xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision c7a39c833af173a7797692757b13b4b8eb801acd)
1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This coordinates the per-function state used while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CGBlocks.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenPGO.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/ASTLambda.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/Decl.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Basic/Builtins.h"
32 #include "clang/Basic/CodeGenOptions.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/CodeGen/CGFunctionInfo.h"
35 #include "clang/Frontend/FrontendDiagnostic.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/FPEnv.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/MDBuilder.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/Support/CRC.h"
46 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
47 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
48 using namespace clang;
49 using namespace CodeGen;
50 
51 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
52 /// markers.
53 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
54                                       const LangOptions &LangOpts) {
55   if (CGOpts.DisableLifetimeMarkers)
56     return false;
57 
58   // Sanitizers may use markers.
59   if (CGOpts.SanitizeAddressUseAfterScope ||
60       LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
61       LangOpts.Sanitize.has(SanitizerKind::Memory))
62     return true;
63 
64   // For now, only in optimized builds.
65   return CGOpts.OptimizationLevel != 0;
66 }
67 
68 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
69     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
70       Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
71               CGBuilderInserterTy(this)),
72       SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
73       DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
74       ShouldEmitLifetimeMarkers(
75           shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
76   if (!suppressNewContext)
77     CGM.getCXXABI().getMangleContext().startNewFunction();
78 
79   SetFastMathFlags(CurFPFeatures);
80   SetFPModel();
81 }
82 
83 CodeGenFunction::~CodeGenFunction() {
84   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
85 
86   if (getLangOpts().OpenMP && CurFn)
87     CGM.getOpenMPRuntime().functionFinished(*this);
88 
89   // If we have an OpenMPIRBuilder we want to finalize functions (incl.
90   // outlining etc) at some point. Doing it once the function codegen is done
91   // seems to be a reasonable spot. We do it here, as opposed to the deletion
92   // time of the CodeGenModule, because we have to ensure the IR has not yet
93   // been "emitted" to the outside, thus, modifications are still sensible.
94   if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
95     CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
96 }
97 
98 // Map the LangOption for exception behavior into
99 // the corresponding enum in the IR.
100 llvm::fp::ExceptionBehavior
101 clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
102 
103   switch (Kind) {
104   case LangOptions::FPE_Ignore:  return llvm::fp::ebIgnore;
105   case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
106   case LangOptions::FPE_Strict:  return llvm::fp::ebStrict;
107   }
108   llvm_unreachable("Unsupported FP Exception Behavior");
109 }
110 
111 void CodeGenFunction::SetFPModel() {
112   llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
113   auto fpExceptionBehavior = ToConstrainedExceptMD(
114                                getLangOpts().getFPExceptionMode());
115 
116   Builder.setDefaultConstrainedRounding(RM);
117   Builder.setDefaultConstrainedExcept(fpExceptionBehavior);
118   Builder.setIsFPConstrained(fpExceptionBehavior != llvm::fp::ebIgnore ||
119                              RM != llvm::RoundingMode::NearestTiesToEven);
120 }
121 
122 void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
123   llvm::FastMathFlags FMF;
124   FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
125   FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
126   FMF.setNoInfs(FPFeatures.getNoHonorInfs());
127   FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
128   FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
129   FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
130   FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
131   Builder.setFastMathFlags(FMF);
132 }
133 
134 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
135                                                   const Expr *E)
136     : CGF(CGF) {
137   ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
138 }
139 
140 CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
141                                                   FPOptions FPFeatures)
142     : CGF(CGF) {
143   ConstructorHelper(FPFeatures);
144 }
145 
146 void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
147   OldFPFeatures = CGF.CurFPFeatures;
148   CGF.CurFPFeatures = FPFeatures;
149 
150   OldExcept = CGF.Builder.getDefaultConstrainedExcept();
151   OldRounding = CGF.Builder.getDefaultConstrainedRounding();
152 
153   if (OldFPFeatures == FPFeatures)
154     return;
155 
156   FMFGuard.emplace(CGF.Builder);
157 
158   llvm::RoundingMode NewRoundingBehavior =
159       static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
160   CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
161   auto NewExceptionBehavior =
162       ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
163           FPFeatures.getFPExceptionMode()));
164   CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
165 
166   CGF.SetFastMathFlags(FPFeatures);
167 
168   assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
169           isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
170           isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
171           (NewExceptionBehavior == llvm::fp::ebIgnore &&
172            NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
173          "FPConstrained should be enabled on entire function");
174 
175   auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
176     auto OldValue =
177         CGF.CurFn->getFnAttribute(Name).getValueAsString() == "true";
178     auto NewValue = OldValue & Value;
179     if (OldValue != NewValue)
180       CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
181   };
182   mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
183   mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
184   mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
185   mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
186                                          FPFeatures.getAllowReciprocal() &&
187                                          FPFeatures.getAllowApproxFunc() &&
188                                          FPFeatures.getNoSignedZero());
189 }
190 
191 CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
192   CGF.CurFPFeatures = OldFPFeatures;
193   CGF.Builder.setDefaultConstrainedExcept(OldExcept);
194   CGF.Builder.setDefaultConstrainedRounding(OldRounding);
195 }
196 
197 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
198   LValueBaseInfo BaseInfo;
199   TBAAAccessInfo TBAAInfo;
200   CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
201   return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
202                           TBAAInfo);
203 }
204 
205 /// Given a value of type T* that may not be to a complete object,
206 /// construct an l-value with the natural pointee alignment of T.
207 LValue
208 CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
209   LValueBaseInfo BaseInfo;
210   TBAAAccessInfo TBAAInfo;
211   CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
212                                                 /* forPointeeType= */ true);
213   return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
214 }
215 
216 
217 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
218   return CGM.getTypes().ConvertTypeForMem(T);
219 }
220 
221 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
222   return CGM.getTypes().ConvertType(T);
223 }
224 
225 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
226   type = type.getCanonicalType();
227   while (true) {
228     switch (type->getTypeClass()) {
229 #define TYPE(name, parent)
230 #define ABSTRACT_TYPE(name, parent)
231 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
232 #define DEPENDENT_TYPE(name, parent) case Type::name:
233 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
234 #include "clang/AST/TypeNodes.inc"
235       llvm_unreachable("non-canonical or dependent type in IR-generation");
236 
237     case Type::Auto:
238     case Type::DeducedTemplateSpecialization:
239       llvm_unreachable("undeduced type in IR-generation");
240 
241     // Various scalar types.
242     case Type::Builtin:
243     case Type::Pointer:
244     case Type::BlockPointer:
245     case Type::LValueReference:
246     case Type::RValueReference:
247     case Type::MemberPointer:
248     case Type::Vector:
249     case Type::ExtVector:
250     case Type::ConstantMatrix:
251     case Type::FunctionProto:
252     case Type::FunctionNoProto:
253     case Type::Enum:
254     case Type::ObjCObjectPointer:
255     case Type::Pipe:
256     case Type::ExtInt:
257       return TEK_Scalar;
258 
259     // Complexes.
260     case Type::Complex:
261       return TEK_Complex;
262 
263     // Arrays, records, and Objective-C objects.
264     case Type::ConstantArray:
265     case Type::IncompleteArray:
266     case Type::VariableArray:
267     case Type::Record:
268     case Type::ObjCObject:
269     case Type::ObjCInterface:
270       return TEK_Aggregate;
271 
272     // We operate on atomic values according to their underlying type.
273     case Type::Atomic:
274       type = cast<AtomicType>(type)->getValueType();
275       continue;
276     }
277     llvm_unreachable("unknown type kind!");
278   }
279 }
280 
281 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
282   // For cleanliness, we try to avoid emitting the return block for
283   // simple cases.
284   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
285 
286   if (CurBB) {
287     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
288 
289     // We have a valid insert point, reuse it if it is empty or there are no
290     // explicit jumps to the return block.
291     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
292       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
293       delete ReturnBlock.getBlock();
294       ReturnBlock = JumpDest();
295     } else
296       EmitBlock(ReturnBlock.getBlock());
297     return llvm::DebugLoc();
298   }
299 
300   // Otherwise, if the return block is the target of a single direct
301   // branch then we can just put the code in that block instead. This
302   // cleans up functions which started with a unified return block.
303   if (ReturnBlock.getBlock()->hasOneUse()) {
304     llvm::BranchInst *BI =
305       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
306     if (BI && BI->isUnconditional() &&
307         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
308       // Record/return the DebugLoc of the simple 'return' expression to be used
309       // later by the actual 'ret' instruction.
310       llvm::DebugLoc Loc = BI->getDebugLoc();
311       Builder.SetInsertPoint(BI->getParent());
312       BI->eraseFromParent();
313       delete ReturnBlock.getBlock();
314       ReturnBlock = JumpDest();
315       return Loc;
316     }
317   }
318 
319   // FIXME: We are at an unreachable point, there is no reason to emit the block
320   // unless it has uses. However, we still need a place to put the debug
321   // region.end for now.
322 
323   EmitBlock(ReturnBlock.getBlock());
324   return llvm::DebugLoc();
325 }
326 
327 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
328   if (!BB) return;
329   if (!BB->use_empty())
330     return CGF.CurFn->getBasicBlockList().push_back(BB);
331   delete BB;
332 }
333 
334 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
335   assert(BreakContinueStack.empty() &&
336          "mismatched push/pop in break/continue stack!");
337 
338   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
339     && NumSimpleReturnExprs == NumReturnExprs
340     && ReturnBlock.getBlock()->use_empty();
341   // Usually the return expression is evaluated before the cleanup
342   // code.  If the function contains only a simple return statement,
343   // such as a constant, the location before the cleanup code becomes
344   // the last useful breakpoint in the function, because the simple
345   // return expression will be evaluated after the cleanup code. To be
346   // safe, set the debug location for cleanup code to the location of
347   // the return statement.  Otherwise the cleanup code should be at the
348   // end of the function's lexical scope.
349   //
350   // If there are multiple branches to the return block, the branch
351   // instructions will get the location of the return statements and
352   // all will be fine.
353   if (CGDebugInfo *DI = getDebugInfo()) {
354     if (OnlySimpleReturnStmts)
355       DI->EmitLocation(Builder, LastStopPoint);
356     else
357       DI->EmitLocation(Builder, EndLoc);
358   }
359 
360   // Pop any cleanups that might have been associated with the
361   // parameters.  Do this in whatever block we're currently in; it's
362   // important to do this before we enter the return block or return
363   // edges will be *really* confused.
364   bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
365   bool HasOnlyLifetimeMarkers =
366       HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
367   bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
368   if (HasCleanups) {
369     // Make sure the line table doesn't jump back into the body for
370     // the ret after it's been at EndLoc.
371     Optional<ApplyDebugLocation> AL;
372     if (CGDebugInfo *DI = getDebugInfo()) {
373       if (OnlySimpleReturnStmts)
374         DI->EmitLocation(Builder, EndLoc);
375       else
376         // We may not have a valid end location. Try to apply it anyway, and
377         // fall back to an artificial location if needed.
378         AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
379     }
380 
381     PopCleanupBlocks(PrologueCleanupDepth);
382   }
383 
384   // Emit function epilog (to return).
385   llvm::DebugLoc Loc = EmitReturnBlock();
386 
387   if (ShouldInstrumentFunction()) {
388     if (CGM.getCodeGenOpts().InstrumentFunctions)
389       CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
390     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
391       CurFn->addFnAttr("instrument-function-exit-inlined",
392                        "__cyg_profile_func_exit");
393   }
394 
395   // Emit debug descriptor for function end.
396   if (CGDebugInfo *DI = getDebugInfo())
397     DI->EmitFunctionEnd(Builder, CurFn);
398 
399   // Reset the debug location to that of the simple 'return' expression, if any
400   // rather than that of the end of the function's scope '}'.
401   ApplyDebugLocation AL(*this, Loc);
402   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
403   EmitEndEHSpec(CurCodeDecl);
404 
405   assert(EHStack.empty() &&
406          "did not remove all scopes from cleanup stack!");
407 
408   // If someone did an indirect goto, emit the indirect goto block at the end of
409   // the function.
410   if (IndirectBranch) {
411     EmitBlock(IndirectBranch->getParent());
412     Builder.ClearInsertionPoint();
413   }
414 
415   // If some of our locals escaped, insert a call to llvm.localescape in the
416   // entry block.
417   if (!EscapedLocals.empty()) {
418     // Invert the map from local to index into a simple vector. There should be
419     // no holes.
420     SmallVector<llvm::Value *, 4> EscapeArgs;
421     EscapeArgs.resize(EscapedLocals.size());
422     for (auto &Pair : EscapedLocals)
423       EscapeArgs[Pair.second] = Pair.first;
424     llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
425         &CGM.getModule(), llvm::Intrinsic::localescape);
426     CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
427   }
428 
429   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
430   llvm::Instruction *Ptr = AllocaInsertPt;
431   AllocaInsertPt = nullptr;
432   Ptr->eraseFromParent();
433 
434   // If someone took the address of a label but never did an indirect goto, we
435   // made a zero entry PHI node, which is illegal, zap it now.
436   if (IndirectBranch) {
437     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
438     if (PN->getNumIncomingValues() == 0) {
439       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
440       PN->eraseFromParent();
441     }
442   }
443 
444   EmitIfUsed(*this, EHResumeBlock);
445   EmitIfUsed(*this, TerminateLandingPad);
446   EmitIfUsed(*this, TerminateHandler);
447   EmitIfUsed(*this, UnreachableBlock);
448 
449   for (const auto &FuncletAndParent : TerminateFunclets)
450     EmitIfUsed(*this, FuncletAndParent.second);
451 
452   if (CGM.getCodeGenOpts().EmitDeclMetadata)
453     EmitDeclMetadata();
454 
455   for (const auto &R : DeferredReplacements) {
456     if (llvm::Value *Old = R.first) {
457       Old->replaceAllUsesWith(R.second);
458       cast<llvm::Instruction>(Old)->eraseFromParent();
459     }
460   }
461   DeferredReplacements.clear();
462 
463   // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
464   // PHIs if the current function is a coroutine. We don't do it for all
465   // functions as it may result in slight increase in numbers of instructions
466   // if compiled with no optimizations. We do it for coroutine as the lifetime
467   // of CleanupDestSlot alloca make correct coroutine frame building very
468   // difficult.
469   if (NormalCleanupDest.isValid() && isCoroutine()) {
470     llvm::DominatorTree DT(*CurFn);
471     llvm::PromoteMemToReg(
472         cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
473     NormalCleanupDest = Address::invalid();
474   }
475 
476   // Scan function arguments for vector width.
477   for (llvm::Argument &A : CurFn->args())
478     if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
479       LargestVectorWidth =
480           std::max((uint64_t)LargestVectorWidth,
481                    VT->getPrimitiveSizeInBits().getKnownMinSize());
482 
483   // Update vector width based on return type.
484   if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
485     LargestVectorWidth =
486         std::max((uint64_t)LargestVectorWidth,
487                  VT->getPrimitiveSizeInBits().getKnownMinSize());
488 
489   // Add the required-vector-width attribute. This contains the max width from:
490   // 1. min-vector-width attribute used in the source program.
491   // 2. Any builtins used that have a vector width specified.
492   // 3. Values passed in and out of inline assembly.
493   // 4. Width of vector arguments and return types for this function.
494   // 5. Width of vector aguments and return types for functions called by this
495   //    function.
496   if (LargestVectorWidth)
497     CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
498 
499   // Add vscale attribute if appropriate.
500   if (getLangOpts().ArmSveVectorBits) {
501     unsigned VScale = getLangOpts().ArmSveVectorBits / 128;
502     CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(getLLVMContext(),
503                                                              VScale, VScale));
504   }
505 
506   // If we generated an unreachable return block, delete it now.
507   if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
508     Builder.ClearInsertionPoint();
509     ReturnBlock.getBlock()->eraseFromParent();
510   }
511   if (ReturnValue.isValid()) {
512     auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
513     if (RetAlloca && RetAlloca->use_empty()) {
514       RetAlloca->eraseFromParent();
515       ReturnValue = Address::invalid();
516     }
517   }
518 }
519 
520 /// ShouldInstrumentFunction - Return true if the current function should be
521 /// instrumented with __cyg_profile_func_* calls
522 bool CodeGenFunction::ShouldInstrumentFunction() {
523   if (!CGM.getCodeGenOpts().InstrumentFunctions &&
524       !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
525       !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
526     return false;
527   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
528     return false;
529   return true;
530 }
531 
532 /// ShouldXRayInstrument - Return true if the current function should be
533 /// instrumented with XRay nop sleds.
534 bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
535   return CGM.getCodeGenOpts().XRayInstrumentFunctions;
536 }
537 
538 /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
539 /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
540 bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
541   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
542          (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
543           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
544               XRayInstrKind::Custom);
545 }
546 
547 bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
548   return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
549          (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
550           CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
551               XRayInstrKind::Typed);
552 }
553 
554 llvm::Constant *
555 CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
556                                             llvm::Constant *Addr) {
557   // Addresses stored in prologue data can't require run-time fixups and must
558   // be PC-relative. Run-time fixups are undesirable because they necessitate
559   // writable text segments, which are unsafe. And absolute addresses are
560   // undesirable because they break PIE mode.
561 
562   // Add a layer of indirection through a private global. Taking its address
563   // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
564   auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
565                                       /*isConstant=*/true,
566                                       llvm::GlobalValue::PrivateLinkage, Addr);
567 
568   // Create a PC-relative address.
569   auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
570   auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
571   auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
572   return (IntPtrTy == Int32Ty)
573              ? PCRelAsInt
574              : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
575 }
576 
577 llvm::Value *
578 CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
579                                           llvm::Value *EncodedAddr) {
580   // Reconstruct the address of the global.
581   auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
582   auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
583   auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
584   auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
585 
586   // Load the original pointer through the global.
587   return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
588                             "decoded_addr");
589 }
590 
591 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
592                                                llvm::Function *Fn)
593 {
594   if (!FD->hasAttr<OpenCLKernelAttr>())
595     return;
596 
597   llvm::LLVMContext &Context = getLLVMContext();
598 
599   CGM.GenOpenCLArgMetadata(Fn, FD, this);
600 
601   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
602     QualType HintQTy = A->getTypeHint();
603     const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
604     bool IsSignedInteger =
605         HintQTy->isSignedIntegerType() ||
606         (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
607     llvm::Metadata *AttrMDArgs[] = {
608         llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
609             CGM.getTypes().ConvertType(A->getTypeHint()))),
610         llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
611             llvm::IntegerType::get(Context, 32),
612             llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
613     Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
614   }
615 
616   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
617     llvm::Metadata *AttrMDArgs[] = {
618         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
619         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
620         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
621     Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
622   }
623 
624   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
625     llvm::Metadata *AttrMDArgs[] = {
626         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
627         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
628         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
629     Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
630   }
631 
632   if (const OpenCLIntelReqdSubGroupSizeAttr *A =
633           FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
634     llvm::Metadata *AttrMDArgs[] = {
635         llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
636     Fn->setMetadata("intel_reqd_sub_group_size",
637                     llvm::MDNode::get(Context, AttrMDArgs));
638   }
639 }
640 
641 /// Determine whether the function F ends with a return stmt.
642 static bool endsWithReturn(const Decl* F) {
643   const Stmt *Body = nullptr;
644   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
645     Body = FD->getBody();
646   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
647     Body = OMD->getBody();
648 
649   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
650     auto LastStmt = CS->body_rbegin();
651     if (LastStmt != CS->body_rend())
652       return isa<ReturnStmt>(*LastStmt);
653   }
654   return false;
655 }
656 
657 void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
658   if (SanOpts.has(SanitizerKind::Thread)) {
659     Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
660     Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
661   }
662 }
663 
664 /// Check if the return value of this function requires sanitization.
665 bool CodeGenFunction::requiresReturnValueCheck() const {
666   return requiresReturnValueNullabilityCheck() ||
667          (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
668           CurCodeDecl->getAttr<ReturnsNonNullAttr>());
669 }
670 
671 static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
672   auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
673   if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
674       !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
675       (MD->getNumParams() != 1 && MD->getNumParams() != 2))
676     return false;
677 
678   if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
679     return false;
680 
681   if (MD->getNumParams() == 2) {
682     auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
683     if (!PT || !PT->isVoidPointerType() ||
684         !PT->getPointeeType().isConstQualified())
685       return false;
686   }
687 
688   return true;
689 }
690 
691 /// Return the UBSan prologue signature for \p FD if one is available.
692 static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
693                                             const FunctionDecl *FD) {
694   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
695     if (!MD->isStatic())
696       return nullptr;
697   return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
698 }
699 
700 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
701                                     llvm::Function *Fn,
702                                     const CGFunctionInfo &FnInfo,
703                                     const FunctionArgList &Args,
704                                     SourceLocation Loc,
705                                     SourceLocation StartLoc) {
706   assert(!CurFn &&
707          "Do not use a CodeGenFunction object for more than one function");
708 
709   const Decl *D = GD.getDecl();
710 
711   DidCallStackSave = false;
712   CurCodeDecl = D;
713   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
714     if (FD->usesSEHTry())
715       CurSEHParent = FD;
716   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
717   FnRetTy = RetTy;
718   CurFn = Fn;
719   CurFnInfo = &FnInfo;
720   assert(CurFn->isDeclaration() && "Function already has body?");
721 
722   // If this function is ignored for any of the enabled sanitizers,
723   // disable the sanitizer for the function.
724   do {
725 #define SANITIZER(NAME, ID)                                                    \
726   if (SanOpts.empty())                                                         \
727     break;                                                                     \
728   if (SanOpts.has(SanitizerKind::ID))                                          \
729     if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc))                    \
730       SanOpts.set(SanitizerKind::ID, false);
731 
732 #include "clang/Basic/Sanitizers.def"
733 #undef SANITIZER
734   } while (0);
735 
736   if (D) {
737     // Apply the no_sanitize* attributes to SanOpts.
738     for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
739       SanitizerMask mask = Attr->getMask();
740       SanOpts.Mask &= ~mask;
741       if (mask & SanitizerKind::Address)
742         SanOpts.set(SanitizerKind::KernelAddress, false);
743       if (mask & SanitizerKind::KernelAddress)
744         SanOpts.set(SanitizerKind::Address, false);
745       if (mask & SanitizerKind::HWAddress)
746         SanOpts.set(SanitizerKind::KernelHWAddress, false);
747       if (mask & SanitizerKind::KernelHWAddress)
748         SanOpts.set(SanitizerKind::HWAddress, false);
749     }
750   }
751 
752   // Apply sanitizer attributes to the function.
753   if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
754     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
755   if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
756     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
757   if (SanOpts.has(SanitizerKind::MemTag))
758     Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
759   if (SanOpts.has(SanitizerKind::Thread))
760     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
761   if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
762     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
763   if (SanOpts.has(SanitizerKind::SafeStack))
764     Fn->addFnAttr(llvm::Attribute::SafeStack);
765   if (SanOpts.has(SanitizerKind::ShadowCallStack))
766     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
767 
768   // Apply fuzzing attribute to the function.
769   if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
770     Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
771 
772   // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
773   // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
774   if (SanOpts.has(SanitizerKind::Thread)) {
775     if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
776       IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
777       if (OMD->getMethodFamily() == OMF_dealloc ||
778           OMD->getMethodFamily() == OMF_initialize ||
779           (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
780         markAsIgnoreThreadCheckingAtRuntime(Fn);
781       }
782     }
783   }
784 
785   // Ignore unrelated casts in STL allocate() since the allocator must cast
786   // from void* to T* before object initialization completes. Don't match on the
787   // namespace because not all allocators are in std::
788   if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
789     if (matchesStlAllocatorFn(D, getContext()))
790       SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
791   }
792 
793   // Ignore null checks in coroutine functions since the coroutines passes
794   // are not aware of how to move the extra UBSan instructions across the split
795   // coroutine boundaries.
796   if (D && SanOpts.has(SanitizerKind::Null))
797     if (const auto *FD = dyn_cast<FunctionDecl>(D))
798       if (FD->getBody() &&
799           FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
800         SanOpts.Mask &= ~SanitizerKind::Null;
801 
802   // Apply xray attributes to the function (as a string, for now)
803   bool AlwaysXRayAttr = false;
804   if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
805     if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
806             XRayInstrKind::FunctionEntry) ||
807         CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
808             XRayInstrKind::FunctionExit)) {
809       if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
810         Fn->addFnAttr("function-instrument", "xray-always");
811         AlwaysXRayAttr = true;
812       }
813       if (XRayAttr->neverXRayInstrument())
814         Fn->addFnAttr("function-instrument", "xray-never");
815       if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
816         if (ShouldXRayInstrumentFunction())
817           Fn->addFnAttr("xray-log-args",
818                         llvm::utostr(LogArgs->getArgumentCount()));
819     }
820   } else {
821     if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
822       Fn->addFnAttr(
823           "xray-instruction-threshold",
824           llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
825   }
826 
827   if (ShouldXRayInstrumentFunction()) {
828     if (CGM.getCodeGenOpts().XRayIgnoreLoops)
829       Fn->addFnAttr("xray-ignore-loops");
830 
831     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
832             XRayInstrKind::FunctionExit))
833       Fn->addFnAttr("xray-skip-exit");
834 
835     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
836             XRayInstrKind::FunctionEntry))
837       Fn->addFnAttr("xray-skip-entry");
838 
839     auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
840     if (FuncGroups > 1) {
841       auto FuncName = llvm::makeArrayRef<uint8_t>(
842           CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
843       auto Group = crc32(FuncName) % FuncGroups;
844       if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
845           !AlwaysXRayAttr)
846         Fn->addFnAttr("function-instrument", "xray-never");
847     }
848   }
849 
850   if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
851     if (CGM.isProfileInstrExcluded(Fn, Loc))
852       Fn->addFnAttr(llvm::Attribute::NoProfile);
853 
854   unsigned Count, Offset;
855   if (const auto *Attr =
856           D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
857     Count = Attr->getCount();
858     Offset = Attr->getOffset();
859   } else {
860     Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
861     Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
862   }
863   if (Count && Offset <= Count) {
864     Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
865     if (Offset)
866       Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
867   }
868 
869   // Add no-jump-tables value.
870   if (CGM.getCodeGenOpts().NoUseJumpTables)
871     Fn->addFnAttr("no-jump-tables", "true");
872 
873   // Add no-inline-line-tables value.
874   if (CGM.getCodeGenOpts().NoInlineLineTables)
875     Fn->addFnAttr("no-inline-line-tables");
876 
877   // Add profile-sample-accurate value.
878   if (CGM.getCodeGenOpts().ProfileSampleAccurate)
879     Fn->addFnAttr("profile-sample-accurate");
880 
881   if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
882     Fn->addFnAttr("use-sample-profile");
883 
884   if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
885     Fn->addFnAttr("cfi-canonical-jump-table");
886 
887   if (getLangOpts().OpenCL) {
888     // Add metadata for a kernel function.
889     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
890       EmitOpenCLKernelMetadata(FD, Fn);
891   }
892 
893   // If we are checking function types, emit a function type signature as
894   // prologue data.
895   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
896     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
897       if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
898         // Remove any (C++17) exception specifications, to allow calling e.g. a
899         // noexcept function through a non-noexcept pointer.
900         auto ProtoTy =
901           getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
902                                                         EST_None);
903         llvm::Constant *FTRTTIConst =
904             CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
905         llvm::Constant *FTRTTIConstEncoded =
906             EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
907         llvm::Constant *PrologueStructElems[] = {PrologueSig,
908                                                  FTRTTIConstEncoded};
909         llvm::Constant *PrologueStructConst =
910             llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
911         Fn->setPrologueData(PrologueStructConst);
912       }
913     }
914   }
915 
916   // If we're checking nullability, we need to know whether we can check the
917   // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
918   if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
919     auto Nullability = FnRetTy->getNullability(getContext());
920     if (Nullability && *Nullability == NullabilityKind::NonNull) {
921       if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
922             CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
923         RetValNullabilityPrecondition =
924             llvm::ConstantInt::getTrue(getLLVMContext());
925     }
926   }
927 
928   // If we're in C++ mode and the function name is "main", it is guaranteed
929   // to be norecurse by the standard (3.6.1.3 "The function main shall not be
930   // used within a program").
931   //
932   // OpenCL C 2.0 v2.2-11 s6.9.i:
933   //     Recursion is not supported.
934   //
935   // SYCL v1.2.1 s3.10:
936   //     kernels cannot include RTTI information, exception classes,
937   //     recursive code, virtual functions or make use of C++ libraries that
938   //     are not compiled for the device.
939   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
940     if ((getLangOpts().CPlusPlus && FD->isMain()) || getLangOpts().OpenCL ||
941         getLangOpts().SYCLIsDevice ||
942         (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>()))
943       Fn->addFnAttr(llvm::Attribute::NoRecurse);
944   }
945 
946   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
947     Builder.setIsFPConstrained(FD->hasAttr<StrictFPAttr>());
948     if (FD->hasAttr<StrictFPAttr>())
949       Fn->addFnAttr(llvm::Attribute::StrictFP);
950   }
951 
952   // If a custom alignment is used, force realigning to this alignment on
953   // any main function which certainly will need it.
954   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
955     if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
956         CGM.getCodeGenOpts().StackAlignment)
957       Fn->addFnAttr("stackrealign");
958 
959   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
960 
961   // Create a marker to make it easy to insert allocas into the entryblock
962   // later.  Don't create this with the builder, because we don't want it
963   // folded.
964   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
965   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
966 
967   ReturnBlock = getJumpDestInCurrentScope("return");
968 
969   Builder.SetInsertPoint(EntryBB);
970 
971   // If we're checking the return value, allocate space for a pointer to a
972   // precise source location of the checked return statement.
973   if (requiresReturnValueCheck()) {
974     ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
975     InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
976   }
977 
978   // Emit subprogram debug descriptor.
979   if (CGDebugInfo *DI = getDebugInfo()) {
980     // Reconstruct the type from the argument list so that implicit parameters,
981     // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
982     // convention.
983     CallingConv CC = CallingConv::CC_C;
984     if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
985       if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
986         CC = SrcFnTy->getCallConv();
987     SmallVector<QualType, 16> ArgTypes;
988     for (const VarDecl *VD : Args)
989       ArgTypes.push_back(VD->getType());
990     QualType FnType = getContext().getFunctionType(
991         RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
992     DI->emitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk);
993   }
994 
995   if (ShouldInstrumentFunction()) {
996     if (CGM.getCodeGenOpts().InstrumentFunctions)
997       CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
998     if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
999       CurFn->addFnAttr("instrument-function-entry-inlined",
1000                        "__cyg_profile_func_enter");
1001     if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
1002       CurFn->addFnAttr("instrument-function-entry-inlined",
1003                        "__cyg_profile_func_enter_bare");
1004   }
1005 
1006   // Since emitting the mcount call here impacts optimizations such as function
1007   // inlining, we just add an attribute to insert a mcount call in backend.
1008   // The attribute "counting-function" is set to mcount function name which is
1009   // architecture dependent.
1010   if (CGM.getCodeGenOpts().InstrumentForProfiling) {
1011     // Calls to fentry/mcount should not be generated if function has
1012     // the no_instrument_function attribute.
1013     if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
1014       if (CGM.getCodeGenOpts().CallFEntry)
1015         Fn->addFnAttr("fentry-call", "true");
1016       else {
1017         Fn->addFnAttr("instrument-function-entry-inlined",
1018                       getTarget().getMCountName());
1019       }
1020       if (CGM.getCodeGenOpts().MNopMCount) {
1021         if (!CGM.getCodeGenOpts().CallFEntry)
1022           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1023             << "-mnop-mcount" << "-mfentry";
1024         Fn->addFnAttr("mnop-mcount");
1025       }
1026 
1027       if (CGM.getCodeGenOpts().RecordMCount) {
1028         if (!CGM.getCodeGenOpts().CallFEntry)
1029           CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
1030             << "-mrecord-mcount" << "-mfentry";
1031         Fn->addFnAttr("mrecord-mcount");
1032       }
1033     }
1034   }
1035 
1036   if (CGM.getCodeGenOpts().PackedStack) {
1037     if (getContext().getTargetInfo().getTriple().getArch() !=
1038         llvm::Triple::systemz)
1039       CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
1040         << "-mpacked-stack";
1041     Fn->addFnAttr("packed-stack");
1042   }
1043 
1044   if (RetTy->isVoidType()) {
1045     // Void type; nothing to return.
1046     ReturnValue = Address::invalid();
1047 
1048     // Count the implicit return.
1049     if (!endsWithReturn(D))
1050       ++NumReturnExprs;
1051   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
1052     // Indirect return; emit returned value directly into sret slot.
1053     // This reduces code size, and affects correctness in C++.
1054     auto AI = CurFn->arg_begin();
1055     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
1056       ++AI;
1057     ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
1058     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1059       ReturnValuePointer =
1060           CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
1061       Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
1062                               ReturnValue.getPointer(), Int8PtrTy),
1063                           ReturnValuePointer);
1064     }
1065   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1066              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1067     // Load the sret pointer from the argument struct and return into that.
1068     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1069     llvm::Function::arg_iterator EI = CurFn->arg_end();
1070     --EI;
1071     llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
1072     llvm::Type *Ty =
1073         cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1074     ReturnValuePointer = Address(Addr, getPointerAlign());
1075     Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1076     ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
1077   } else {
1078     ReturnValue = CreateIRTemp(RetTy, "retval");
1079 
1080     // Tell the epilog emitter to autorelease the result.  We do this
1081     // now so that various specialized functions can suppress it
1082     // during their IR-generation.
1083     if (getLangOpts().ObjCAutoRefCount &&
1084         !CurFnInfo->isReturnsRetained() &&
1085         RetTy->isObjCRetainableType())
1086       AutoreleaseResult = true;
1087   }
1088 
1089   EmitStartEHSpec(CurCodeDecl);
1090 
1091   PrologueCleanupDepth = EHStack.stable_begin();
1092 
1093   // Emit OpenMP specific initialization of the device functions.
1094   if (getLangOpts().OpenMP && CurCodeDecl)
1095     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1096 
1097   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1098 
1099   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1100     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1101     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1102     if (MD->getParent()->isLambda() &&
1103         MD->getOverloadedOperator() == OO_Call) {
1104       // We're in a lambda; figure out the captures.
1105       MD->getParent()->getCaptureFields(LambdaCaptureFields,
1106                                         LambdaThisCaptureField);
1107       if (LambdaThisCaptureField) {
1108         // If the lambda captures the object referred to by '*this' - either by
1109         // value or by reference, make sure CXXThisValue points to the correct
1110         // object.
1111 
1112         // Get the lvalue for the field (which is a copy of the enclosing object
1113         // or contains the address of the enclosing object).
1114         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1115         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1116           // If the enclosing object was captured by value, just use its address.
1117           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1118         } else {
1119           // Load the lvalue pointed to by the field, since '*this' was captured
1120           // by reference.
1121           CXXThisValue =
1122               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1123         }
1124       }
1125       for (auto *FD : MD->getParent()->fields()) {
1126         if (FD->hasCapturedVLAType()) {
1127           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1128                                            SourceLocation()).getScalarVal();
1129           auto VAT = FD->getCapturedVLAType();
1130           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1131         }
1132       }
1133     } else {
1134       // Not in a lambda; just use 'this' from the method.
1135       // FIXME: Should we generate a new load for each use of 'this'?  The
1136       // fast register allocator would be happier...
1137       CXXThisValue = CXXABIThisValue;
1138     }
1139 
1140     // Check the 'this' pointer once per function, if it's available.
1141     if (CXXABIThisValue) {
1142       SanitizerSet SkippedChecks;
1143       SkippedChecks.set(SanitizerKind::ObjectSize, true);
1144       QualType ThisTy = MD->getThisType();
1145 
1146       // If this is the call operator of a lambda with no capture-default, it
1147       // may have a static invoker function, which may call this operator with
1148       // a null 'this' pointer.
1149       if (isLambdaCallOperator(MD) &&
1150           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
1151         SkippedChecks.set(SanitizerKind::Null, true);
1152 
1153       EmitTypeCheck(
1154           isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1155           Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1156     }
1157   }
1158 
1159   // If any of the arguments have a variably modified type, make sure to
1160   // emit the type size.
1161   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1162        i != e; ++i) {
1163     const VarDecl *VD = *i;
1164 
1165     // Dig out the type as written from ParmVarDecls; it's unclear whether
1166     // the standard (C99 6.9.1p10) requires this, but we're following the
1167     // precedent set by gcc.
1168     QualType Ty;
1169     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1170       Ty = PVD->getOriginalType();
1171     else
1172       Ty = VD->getType();
1173 
1174     if (Ty->isVariablyModifiedType())
1175       EmitVariablyModifiedType(Ty);
1176   }
1177   // Emit a location at the end of the prologue.
1178   if (CGDebugInfo *DI = getDebugInfo())
1179     DI->EmitLocation(Builder, StartLoc);
1180 
1181   // TODO: Do we need to handle this in two places like we do with
1182   // target-features/target-cpu?
1183   if (CurFuncDecl)
1184     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1185       LargestVectorWidth = VecWidth->getVectorWidth();
1186 }
1187 
1188 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1189   incrementProfileCounter(Body);
1190   if (CPlusPlusWithProgress())
1191     FnIsMustProgress = true;
1192 
1193   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1194     EmitCompoundStmtWithoutScope(*S);
1195   else
1196     EmitStmt(Body);
1197 
1198   // This is checked after emitting the function body so we know if there
1199   // are any permitted infinite loops.
1200   if (FnIsMustProgress)
1201     CurFn->addFnAttr(llvm::Attribute::MustProgress);
1202 }
1203 
1204 /// When instrumenting to collect profile data, the counts for some blocks
1205 /// such as switch cases need to not include the fall-through counts, so
1206 /// emit a branch around the instrumentation code. When not instrumenting,
1207 /// this just calls EmitBlock().
1208 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1209                                                const Stmt *S) {
1210   llvm::BasicBlock *SkipCountBB = nullptr;
1211   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1212     // When instrumenting for profiling, the fallthrough to certain
1213     // statements needs to skip over the instrumentation code so that we
1214     // get an accurate count.
1215     SkipCountBB = createBasicBlock("skipcount");
1216     EmitBranch(SkipCountBB);
1217   }
1218   EmitBlock(BB);
1219   uint64_t CurrentCount = getCurrentProfileCount();
1220   incrementProfileCounter(S);
1221   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1222   if (SkipCountBB)
1223     EmitBlock(SkipCountBB);
1224 }
1225 
1226 /// Tries to mark the given function nounwind based on the
1227 /// non-existence of any throwing calls within it.  We believe this is
1228 /// lightweight enough to do at -O0.
1229 static void TryMarkNoThrow(llvm::Function *F) {
1230   // LLVM treats 'nounwind' on a function as part of the type, so we
1231   // can't do this on functions that can be overwritten.
1232   if (F->isInterposable()) return;
1233 
1234   for (llvm::BasicBlock &BB : *F)
1235     for (llvm::Instruction &I : BB)
1236       if (I.mayThrow())
1237         return;
1238 
1239   F->setDoesNotThrow();
1240 }
1241 
1242 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1243                                                FunctionArgList &Args) {
1244   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1245   QualType ResTy = FD->getReturnType();
1246 
1247   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1248   if (MD && MD->isInstance()) {
1249     if (CGM.getCXXABI().HasThisReturn(GD))
1250       ResTy = MD->getThisType();
1251     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1252       ResTy = CGM.getContext().VoidPtrTy;
1253     CGM.getCXXABI().buildThisParam(*this, Args);
1254   }
1255 
1256   // The base version of an inheriting constructor whose constructed base is a
1257   // virtual base is not passed any arguments (because it doesn't actually call
1258   // the inherited constructor).
1259   bool PassedParams = true;
1260   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1261     if (auto Inherited = CD->getInheritedConstructor())
1262       PassedParams =
1263           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1264 
1265   if (PassedParams) {
1266     for (auto *Param : FD->parameters()) {
1267       Args.push_back(Param);
1268       if (!Param->hasAttr<PassObjectSizeAttr>())
1269         continue;
1270 
1271       auto *Implicit = ImplicitParamDecl::Create(
1272           getContext(), Param->getDeclContext(), Param->getLocation(),
1273           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1274       SizeArguments[Param] = Implicit;
1275       Args.push_back(Implicit);
1276     }
1277   }
1278 
1279   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1280     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1281 
1282   return ResTy;
1283 }
1284 
1285 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1286                                    const CGFunctionInfo &FnInfo) {
1287   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1288   CurGD = GD;
1289 
1290   FunctionArgList Args;
1291   QualType ResTy = BuildFunctionArgList(GD, Args);
1292 
1293   // Check if we should generate debug info for this function.
1294   if (FD->hasAttr<NoDebugAttr>())
1295     DebugInfo = nullptr; // disable debug info indefinitely for this function
1296 
1297   // The function might not have a body if we're generating thunks for a
1298   // function declaration.
1299   SourceRange BodyRange;
1300   if (Stmt *Body = FD->getBody())
1301     BodyRange = Body->getSourceRange();
1302   else
1303     BodyRange = FD->getLocation();
1304   CurEHLocation = BodyRange.getEnd();
1305 
1306   // Use the location of the start of the function to determine where
1307   // the function definition is located. By default use the location
1308   // of the declaration as the location for the subprogram. A function
1309   // may lack a declaration in the source code if it is created by code
1310   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1311   SourceLocation Loc = FD->getLocation();
1312 
1313   // If this is a function specialization then use the pattern body
1314   // as the location for the function.
1315   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1316     if (SpecDecl->hasBody(SpecDecl))
1317       Loc = SpecDecl->getLocation();
1318 
1319   Stmt *Body = FD->getBody();
1320 
1321   if (Body) {
1322     // Coroutines always emit lifetime markers.
1323     if (isa<CoroutineBodyStmt>(Body))
1324       ShouldEmitLifetimeMarkers = true;
1325 
1326     // Initialize helper which will detect jumps which can cause invalid
1327     // lifetime markers.
1328     if (ShouldEmitLifetimeMarkers)
1329       Bypasses.Init(Body);
1330   }
1331 
1332   // Emit the standard function prologue.
1333   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1334 
1335   // Generate the body of the function.
1336   PGO.assignRegionCounters(GD, CurFn);
1337   if (isa<CXXDestructorDecl>(FD))
1338     EmitDestructorBody(Args);
1339   else if (isa<CXXConstructorDecl>(FD))
1340     EmitConstructorBody(Args);
1341   else if (getLangOpts().CUDA &&
1342            !getLangOpts().CUDAIsDevice &&
1343            FD->hasAttr<CUDAGlobalAttr>())
1344     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1345   else if (isa<CXXMethodDecl>(FD) &&
1346            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1347     // The lambda static invoker function is special, because it forwards or
1348     // clones the body of the function call operator (but is actually static).
1349     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1350   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1351              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1352               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1353     // Implicit copy-assignment gets the same special treatment as implicit
1354     // copy-constructors.
1355     emitImplicitAssignmentOperatorBody(Args);
1356   } else if (Body) {
1357     EmitFunctionBody(Body);
1358   } else
1359     llvm_unreachable("no definition for emitted function");
1360 
1361   // C++11 [stmt.return]p2:
1362   //   Flowing off the end of a function [...] results in undefined behavior in
1363   //   a value-returning function.
1364   // C11 6.9.1p12:
1365   //   If the '}' that terminates a function is reached, and the value of the
1366   //   function call is used by the caller, the behavior is undefined.
1367   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1368       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1369     bool ShouldEmitUnreachable =
1370         CGM.getCodeGenOpts().StrictReturn ||
1371         !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1372     if (SanOpts.has(SanitizerKind::Return)) {
1373       SanitizerScope SanScope(this);
1374       llvm::Value *IsFalse = Builder.getFalse();
1375       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1376                 SanitizerHandler::MissingReturn,
1377                 EmitCheckSourceLocation(FD->getLocation()), None);
1378     } else if (ShouldEmitUnreachable) {
1379       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1380         EmitTrapCall(llvm::Intrinsic::trap);
1381     }
1382     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1383       Builder.CreateUnreachable();
1384       Builder.ClearInsertionPoint();
1385     }
1386   }
1387 
1388   // Emit the standard function epilogue.
1389   FinishFunction(BodyRange.getEnd());
1390 
1391   // If we haven't marked the function nothrow through other means, do
1392   // a quick pass now to see if we can.
1393   if (!CurFn->doesNotThrow())
1394     TryMarkNoThrow(CurFn);
1395 }
1396 
1397 /// ContainsLabel - Return true if the statement contains a label in it.  If
1398 /// this statement is not executed normally, it not containing a label means
1399 /// that we can just remove the code.
1400 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1401   // Null statement, not a label!
1402   if (!S) return false;
1403 
1404   // If this is a label, we have to emit the code, consider something like:
1405   // if (0) {  ...  foo:  bar(); }  goto foo;
1406   //
1407   // TODO: If anyone cared, we could track __label__'s, since we know that you
1408   // can't jump to one from outside their declared region.
1409   if (isa<LabelStmt>(S))
1410     return true;
1411 
1412   // If this is a case/default statement, and we haven't seen a switch, we have
1413   // to emit the code.
1414   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1415     return true;
1416 
1417   // If this is a switch statement, we want to ignore cases below it.
1418   if (isa<SwitchStmt>(S))
1419     IgnoreCaseStmts = true;
1420 
1421   // Scan subexpressions for verboten labels.
1422   for (const Stmt *SubStmt : S->children())
1423     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1424       return true;
1425 
1426   return false;
1427 }
1428 
1429 /// containsBreak - Return true if the statement contains a break out of it.
1430 /// If the statement (recursively) contains a switch or loop with a break
1431 /// inside of it, this is fine.
1432 bool CodeGenFunction::containsBreak(const Stmt *S) {
1433   // Null statement, not a label!
1434   if (!S) return false;
1435 
1436   // If this is a switch or loop that defines its own break scope, then we can
1437   // include it and anything inside of it.
1438   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1439       isa<ForStmt>(S))
1440     return false;
1441 
1442   if (isa<BreakStmt>(S))
1443     return true;
1444 
1445   // Scan subexpressions for verboten breaks.
1446   for (const Stmt *SubStmt : S->children())
1447     if (containsBreak(SubStmt))
1448       return true;
1449 
1450   return false;
1451 }
1452 
1453 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1454   if (!S) return false;
1455 
1456   // Some statement kinds add a scope and thus never add a decl to the current
1457   // scope. Note, this list is longer than the list of statements that might
1458   // have an unscoped decl nested within them, but this way is conservatively
1459   // correct even if more statement kinds are added.
1460   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1461       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1462       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1463       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1464     return false;
1465 
1466   if (isa<DeclStmt>(S))
1467     return true;
1468 
1469   for (const Stmt *SubStmt : S->children())
1470     if (mightAddDeclToScope(SubStmt))
1471       return true;
1472 
1473   return false;
1474 }
1475 
1476 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1477 /// to a constant, or if it does but contains a label, return false.  If it
1478 /// constant folds return true and set the boolean result in Result.
1479 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1480                                                    bool &ResultBool,
1481                                                    bool AllowLabels) {
1482   llvm::APSInt ResultInt;
1483   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1484     return false;
1485 
1486   ResultBool = ResultInt.getBoolValue();
1487   return true;
1488 }
1489 
1490 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1491 /// to a constant, or if it does but contains a label, return false.  If it
1492 /// constant folds return true and set the folded value.
1493 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1494                                                    llvm::APSInt &ResultInt,
1495                                                    bool AllowLabels) {
1496   // FIXME: Rename and handle conversion of other evaluatable things
1497   // to bool.
1498   Expr::EvalResult Result;
1499   if (!Cond->EvaluateAsInt(Result, getContext()))
1500     return false;  // Not foldable, not integer or not fully evaluatable.
1501 
1502   llvm::APSInt Int = Result.Val.getInt();
1503   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1504     return false;  // Contains a label.
1505 
1506   ResultInt = Int;
1507   return true;
1508 }
1509 
1510 /// Determine whether the given condition is an instrumentable condition
1511 /// (i.e. no "&&" or "||").
1512 bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1513   // Bypass simplistic logical-NOT operator before determining whether the
1514   // condition contains any other logical operator.
1515   if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1516     if (UnOp->getOpcode() == UO_LNot)
1517       C = UnOp->getSubExpr();
1518 
1519   const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1520   return (!BOp || !BOp->isLogicalOp());
1521 }
1522 
1523 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1524 /// increments a profile counter based on the semantics of the given logical
1525 /// operator opcode.  This is used to instrument branch condition coverage for
1526 /// logical operators.
1527 void CodeGenFunction::EmitBranchToCounterBlock(
1528     const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1529     llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1530     Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1531   // If not instrumenting, just emit a branch.
1532   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1533   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1534     return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1535 
1536   llvm::BasicBlock *ThenBlock = NULL;
1537   llvm::BasicBlock *ElseBlock = NULL;
1538   llvm::BasicBlock *NextBlock = NULL;
1539 
1540   // Create the block we'll use to increment the appropriate counter.
1541   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1542 
1543   // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1544   // means we need to evaluate the condition and increment the counter on TRUE:
1545   //
1546   // if (Cond)
1547   //   goto CounterIncrBlock;
1548   // else
1549   //   goto FalseBlock;
1550   //
1551   // CounterIncrBlock:
1552   //   Counter++;
1553   //   goto TrueBlock;
1554 
1555   if (LOp == BO_LAnd) {
1556     ThenBlock = CounterIncrBlock;
1557     ElseBlock = FalseBlock;
1558     NextBlock = TrueBlock;
1559   }
1560 
1561   // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1562   // we need to evaluate the condition and increment the counter on FALSE:
1563   //
1564   // if (Cond)
1565   //   goto TrueBlock;
1566   // else
1567   //   goto CounterIncrBlock;
1568   //
1569   // CounterIncrBlock:
1570   //   Counter++;
1571   //   goto FalseBlock;
1572 
1573   else if (LOp == BO_LOr) {
1574     ThenBlock = TrueBlock;
1575     ElseBlock = CounterIncrBlock;
1576     NextBlock = FalseBlock;
1577   } else {
1578     llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1579   }
1580 
1581   // Emit Branch based on condition.
1582   EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1583 
1584   // Emit the block containing the counter increment(s).
1585   EmitBlock(CounterIncrBlock);
1586 
1587   // Increment corresponding counter; if index not provided, use Cond as index.
1588   incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1589 
1590   // Go to the next block.
1591   EmitBranch(NextBlock);
1592 }
1593 
1594 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1595 /// statement) to the specified blocks.  Based on the condition, this might try
1596 /// to simplify the codegen of the conditional based on the branch.
1597 /// \param LH The value of the likelihood attribute on the True branch.
1598 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1599                                            llvm::BasicBlock *TrueBlock,
1600                                            llvm::BasicBlock *FalseBlock,
1601                                            uint64_t TrueCount,
1602                                            Stmt::Likelihood LH) {
1603   Cond = Cond->IgnoreParens();
1604 
1605   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1606 
1607     // Handle X && Y in a condition.
1608     if (CondBOp->getOpcode() == BO_LAnd) {
1609       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1610       // folded if the case was simple enough.
1611       bool ConstantBool = false;
1612       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1613           ConstantBool) {
1614         // br(1 && X) -> br(X).
1615         incrementProfileCounter(CondBOp);
1616         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1617                                         FalseBlock, TrueCount, LH);
1618       }
1619 
1620       // If we have "X && 1", simplify the code to use an uncond branch.
1621       // "X && 0" would have been constant folded to 0.
1622       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1623           ConstantBool) {
1624         // br(X && 1) -> br(X).
1625         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1626                                         FalseBlock, TrueCount, LH, CondBOp);
1627       }
1628 
1629       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1630       // want to jump to the FalseBlock.
1631       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1632       // The counter tells us how often we evaluate RHS, and all of TrueCount
1633       // can be propagated to that branch.
1634       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1635 
1636       ConditionalEvaluation eval(*this);
1637       {
1638         ApplyDebugLocation DL(*this, Cond);
1639         // Propagate the likelihood attribute like __builtin_expect
1640         // __builtin_expect(X && Y, 1) -> X and Y are likely
1641         // __builtin_expect(X && Y, 0) -> only Y is unlikely
1642         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1643                              LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1644         EmitBlock(LHSTrue);
1645       }
1646 
1647       incrementProfileCounter(CondBOp);
1648       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1649 
1650       // Any temporaries created here are conditional.
1651       eval.begin(*this);
1652       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1653                                FalseBlock, TrueCount, LH);
1654       eval.end(*this);
1655 
1656       return;
1657     }
1658 
1659     if (CondBOp->getOpcode() == BO_LOr) {
1660       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1661       // folded if the case was simple enough.
1662       bool ConstantBool = false;
1663       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1664           !ConstantBool) {
1665         // br(0 || X) -> br(X).
1666         incrementProfileCounter(CondBOp);
1667         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1668                                         FalseBlock, TrueCount, LH);
1669       }
1670 
1671       // If we have "X || 0", simplify the code to use an uncond branch.
1672       // "X || 1" would have been constant folded to 1.
1673       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1674           !ConstantBool) {
1675         // br(X || 0) -> br(X).
1676         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1677                                         FalseBlock, TrueCount, LH, CondBOp);
1678       }
1679 
1680       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1681       // want to jump to the TrueBlock.
1682       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1683       // We have the count for entry to the RHS and for the whole expression
1684       // being true, so we can divy up True count between the short circuit and
1685       // the RHS.
1686       uint64_t LHSCount =
1687           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1688       uint64_t RHSCount = TrueCount - LHSCount;
1689 
1690       ConditionalEvaluation eval(*this);
1691       {
1692         // Propagate the likelihood attribute like __builtin_expect
1693         // __builtin_expect(X || Y, 1) -> only Y is likely
1694         // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1695         ApplyDebugLocation DL(*this, Cond);
1696         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1697                              LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1698         EmitBlock(LHSFalse);
1699       }
1700 
1701       incrementProfileCounter(CondBOp);
1702       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1703 
1704       // Any temporaries created here are conditional.
1705       eval.begin(*this);
1706       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1707                                RHSCount, LH);
1708 
1709       eval.end(*this);
1710 
1711       return;
1712     }
1713   }
1714 
1715   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1716     // br(!x, t, f) -> br(x, f, t)
1717     if (CondUOp->getOpcode() == UO_LNot) {
1718       // Negate the count.
1719       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1720       // The values of the enum are chosen to make this negation possible.
1721       LH = static_cast<Stmt::Likelihood>(-LH);
1722       // Negate the condition and swap the destination blocks.
1723       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1724                                   FalseCount, LH);
1725     }
1726   }
1727 
1728   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1729     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1730     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1731     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1732 
1733     // The ConditionalOperator itself has no likelihood information for its
1734     // true and false branches. This matches the behavior of __builtin_expect.
1735     ConditionalEvaluation cond(*this);
1736     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1737                          getProfileCount(CondOp), Stmt::LH_None);
1738 
1739     // When computing PGO branch weights, we only know the overall count for
1740     // the true block. This code is essentially doing tail duplication of the
1741     // naive code-gen, introducing new edges for which counts are not
1742     // available. Divide the counts proportionally between the LHS and RHS of
1743     // the conditional operator.
1744     uint64_t LHSScaledTrueCount = 0;
1745     if (TrueCount) {
1746       double LHSRatio =
1747           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1748       LHSScaledTrueCount = TrueCount * LHSRatio;
1749     }
1750 
1751     cond.begin(*this);
1752     EmitBlock(LHSBlock);
1753     incrementProfileCounter(CondOp);
1754     {
1755       ApplyDebugLocation DL(*this, Cond);
1756       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1757                            LHSScaledTrueCount, LH);
1758     }
1759     cond.end(*this);
1760 
1761     cond.begin(*this);
1762     EmitBlock(RHSBlock);
1763     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1764                          TrueCount - LHSScaledTrueCount, LH);
1765     cond.end(*this);
1766 
1767     return;
1768   }
1769 
1770   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1771     // Conditional operator handling can give us a throw expression as a
1772     // condition for a case like:
1773     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1774     // Fold this to:
1775     //   br(c, throw x, br(y, t, f))
1776     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1777     return;
1778   }
1779 
1780   // Emit the code with the fully general case.
1781   llvm::Value *CondV;
1782   {
1783     ApplyDebugLocation DL(*this, Cond);
1784     CondV = EvaluateExprAsBool(Cond);
1785   }
1786 
1787   llvm::MDNode *Weights = nullptr;
1788   llvm::MDNode *Unpredictable = nullptr;
1789 
1790   // If the branch has a condition wrapped by __builtin_unpredictable,
1791   // create metadata that specifies that the branch is unpredictable.
1792   // Don't bother if not optimizing because that metadata would not be used.
1793   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1794   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1795     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1796     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1797       llvm::MDBuilder MDHelper(getLLVMContext());
1798       Unpredictable = MDHelper.createUnpredictable();
1799     }
1800   }
1801 
1802   // If there is a Likelihood knowledge for the cond, lower it.
1803   // Note that if not optimizing this won't emit anything.
1804   llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1805   if (CondV != NewCondV)
1806     CondV = NewCondV;
1807   else {
1808     // Otherwise, lower profile counts. Note that we do this even at -O0.
1809     uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1810     Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1811   }
1812 
1813   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1814 }
1815 
1816 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1817 /// specified stmt yet.
1818 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1819   CGM.ErrorUnsupported(S, Type);
1820 }
1821 
1822 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1823 /// variable-length array whose elements have a non-zero bit-pattern.
1824 ///
1825 /// \param baseType the inner-most element type of the array
1826 /// \param src - a char* pointing to the bit-pattern for a single
1827 /// base element of the array
1828 /// \param sizeInChars - the total size of the VLA, in chars
1829 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1830                                Address dest, Address src,
1831                                llvm::Value *sizeInChars) {
1832   CGBuilderTy &Builder = CGF.Builder;
1833 
1834   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1835   llvm::Value *baseSizeInChars
1836     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1837 
1838   Address begin =
1839     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1840   llvm::Value *end = Builder.CreateInBoundsGEP(
1841       begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
1842 
1843   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1844   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1845   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1846 
1847   // Make a loop over the VLA.  C99 guarantees that the VLA element
1848   // count must be nonzero.
1849   CGF.EmitBlock(loopBB);
1850 
1851   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1852   cur->addIncoming(begin.getPointer(), originBB);
1853 
1854   CharUnits curAlign =
1855     dest.getAlignment().alignmentOfArrayElement(baseSize);
1856 
1857   // memcpy the individual element bit-pattern.
1858   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1859                        /*volatile*/ false);
1860 
1861   // Go to the next element.
1862   llvm::Value *next =
1863     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1864 
1865   // Leave if that's the end of the VLA.
1866   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1867   Builder.CreateCondBr(done, contBB, loopBB);
1868   cur->addIncoming(next, loopBB);
1869 
1870   CGF.EmitBlock(contBB);
1871 }
1872 
1873 void
1874 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1875   // Ignore empty classes in C++.
1876   if (getLangOpts().CPlusPlus) {
1877     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1878       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1879         return;
1880     }
1881   }
1882 
1883   // Cast the dest ptr to the appropriate i8 pointer type.
1884   if (DestPtr.getElementType() != Int8Ty)
1885     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1886 
1887   // Get size and alignment info for this aggregate.
1888   CharUnits size = getContext().getTypeSizeInChars(Ty);
1889 
1890   llvm::Value *SizeVal;
1891   const VariableArrayType *vla;
1892 
1893   // Don't bother emitting a zero-byte memset.
1894   if (size.isZero()) {
1895     // But note that getTypeInfo returns 0 for a VLA.
1896     if (const VariableArrayType *vlaType =
1897           dyn_cast_or_null<VariableArrayType>(
1898                                           getContext().getAsArrayType(Ty))) {
1899       auto VlaSize = getVLASize(vlaType);
1900       SizeVal = VlaSize.NumElts;
1901       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1902       if (!eltSize.isOne())
1903         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1904       vla = vlaType;
1905     } else {
1906       return;
1907     }
1908   } else {
1909     SizeVal = CGM.getSize(size);
1910     vla = nullptr;
1911   }
1912 
1913   // If the type contains a pointer to data member we can't memset it to zero.
1914   // Instead, create a null constant and copy it to the destination.
1915   // TODO: there are other patterns besides zero that we can usefully memset,
1916   // like -1, which happens to be the pattern used by member-pointers.
1917   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1918     // For a VLA, emit a single element, then splat that over the VLA.
1919     if (vla) Ty = getContext().getBaseElementType(vla);
1920 
1921     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1922 
1923     llvm::GlobalVariable *NullVariable =
1924       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1925                                /*isConstant=*/true,
1926                                llvm::GlobalVariable::PrivateLinkage,
1927                                NullConstant, Twine());
1928     CharUnits NullAlign = DestPtr.getAlignment();
1929     NullVariable->setAlignment(NullAlign.getAsAlign());
1930     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1931                    NullAlign);
1932 
1933     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1934 
1935     // Get and call the appropriate llvm.memcpy overload.
1936     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
1937     return;
1938   }
1939 
1940   // Otherwise, just memset the whole thing to zero.  This is legal
1941   // because in LLVM, all default initializers (other than the ones we just
1942   // handled above) are guaranteed to have a bit pattern of all zeros.
1943   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
1944 }
1945 
1946 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1947   // Make sure that there is a block for the indirect goto.
1948   if (!IndirectBranch)
1949     GetIndirectGotoBlock();
1950 
1951   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1952 
1953   // Make sure the indirect branch includes all of the address-taken blocks.
1954   IndirectBranch->addDestination(BB);
1955   return llvm::BlockAddress::get(CurFn, BB);
1956 }
1957 
1958 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1959   // If we already made the indirect branch for indirect goto, return its block.
1960   if (IndirectBranch) return IndirectBranch->getParent();
1961 
1962   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
1963 
1964   // Create the PHI node that indirect gotos will add entries to.
1965   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1966                                               "indirect.goto.dest");
1967 
1968   // Create the indirect branch instruction.
1969   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1970   return IndirectBranch->getParent();
1971 }
1972 
1973 /// Computes the length of an array in elements, as well as the base
1974 /// element type and a properly-typed first element pointer.
1975 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1976                                               QualType &baseType,
1977                                               Address &addr) {
1978   const ArrayType *arrayType = origArrayType;
1979 
1980   // If it's a VLA, we have to load the stored size.  Note that
1981   // this is the size of the VLA in bytes, not its size in elements.
1982   llvm::Value *numVLAElements = nullptr;
1983   if (isa<VariableArrayType>(arrayType)) {
1984     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
1985 
1986     // Walk into all VLAs.  This doesn't require changes to addr,
1987     // which has type T* where T is the first non-VLA element type.
1988     do {
1989       QualType elementType = arrayType->getElementType();
1990       arrayType = getContext().getAsArrayType(elementType);
1991 
1992       // If we only have VLA components, 'addr' requires no adjustment.
1993       if (!arrayType) {
1994         baseType = elementType;
1995         return numVLAElements;
1996       }
1997     } while (isa<VariableArrayType>(arrayType));
1998 
1999     // We get out here only if we find a constant array type
2000     // inside the VLA.
2001   }
2002 
2003   // We have some number of constant-length arrays, so addr should
2004   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2005   // down to the first element of addr.
2006   SmallVector<llvm::Value*, 8> gepIndices;
2007 
2008   // GEP down to the array type.
2009   llvm::ConstantInt *zero = Builder.getInt32(0);
2010   gepIndices.push_back(zero);
2011 
2012   uint64_t countFromCLAs = 1;
2013   QualType eltType;
2014 
2015   llvm::ArrayType *llvmArrayType =
2016     dyn_cast<llvm::ArrayType>(addr.getElementType());
2017   while (llvmArrayType) {
2018     assert(isa<ConstantArrayType>(arrayType));
2019     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
2020              == llvmArrayType->getNumElements());
2021 
2022     gepIndices.push_back(zero);
2023     countFromCLAs *= llvmArrayType->getNumElements();
2024     eltType = arrayType->getElementType();
2025 
2026     llvmArrayType =
2027       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2028     arrayType = getContext().getAsArrayType(arrayType->getElementType());
2029     assert((!llvmArrayType || arrayType) &&
2030            "LLVM and Clang types are out-of-synch");
2031   }
2032 
2033   if (arrayType) {
2034     // From this point onwards, the Clang array type has been emitted
2035     // as some other type (probably a packed struct). Compute the array
2036     // size, and just emit the 'begin' expression as a bitcast.
2037     while (arrayType) {
2038       countFromCLAs *=
2039           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
2040       eltType = arrayType->getElementType();
2041       arrayType = getContext().getAsArrayType(eltType);
2042     }
2043 
2044     llvm::Type *baseType = ConvertType(eltType);
2045     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
2046   } else {
2047     // Create the actual GEP.
2048     addr = Address(Builder.CreateInBoundsGEP(
2049         addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
2050         addr.getAlignment());
2051   }
2052 
2053   baseType = eltType;
2054 
2055   llvm::Value *numElements
2056     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2057 
2058   // If we had any VLA dimensions, factor them in.
2059   if (numVLAElements)
2060     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2061 
2062   return numElements;
2063 }
2064 
2065 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2066   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2067   assert(vla && "type was not a variable array type!");
2068   return getVLASize(vla);
2069 }
2070 
2071 CodeGenFunction::VlaSizePair
2072 CodeGenFunction::getVLASize(const VariableArrayType *type) {
2073   // The number of elements so far; always size_t.
2074   llvm::Value *numElements = nullptr;
2075 
2076   QualType elementType;
2077   do {
2078     elementType = type->getElementType();
2079     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2080     assert(vlaSize && "no size for VLA!");
2081     assert(vlaSize->getType() == SizeTy);
2082 
2083     if (!numElements) {
2084       numElements = vlaSize;
2085     } else {
2086       // It's undefined behavior if this wraps around, so mark it that way.
2087       // FIXME: Teach -fsanitize=undefined to trap this.
2088       numElements = Builder.CreateNUWMul(numElements, vlaSize);
2089     }
2090   } while ((type = getContext().getAsVariableArrayType(elementType)));
2091 
2092   return { numElements, elementType };
2093 }
2094 
2095 CodeGenFunction::VlaSizePair
2096 CodeGenFunction::getVLAElements1D(QualType type) {
2097   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2098   assert(vla && "type was not a variable array type!");
2099   return getVLAElements1D(vla);
2100 }
2101 
2102 CodeGenFunction::VlaSizePair
2103 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2104   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2105   assert(VlaSize && "no size for VLA!");
2106   assert(VlaSize->getType() == SizeTy);
2107   return { VlaSize, Vla->getElementType() };
2108 }
2109 
2110 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2111   assert(type->isVariablyModifiedType() &&
2112          "Must pass variably modified type to EmitVLASizes!");
2113 
2114   EnsureInsertPoint();
2115 
2116   // We're going to walk down into the type and look for VLA
2117   // expressions.
2118   do {
2119     assert(type->isVariablyModifiedType());
2120 
2121     const Type *ty = type.getTypePtr();
2122     switch (ty->getTypeClass()) {
2123 
2124 #define TYPE(Class, Base)
2125 #define ABSTRACT_TYPE(Class, Base)
2126 #define NON_CANONICAL_TYPE(Class, Base)
2127 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2128 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2129 #include "clang/AST/TypeNodes.inc"
2130       llvm_unreachable("unexpected dependent type!");
2131 
2132     // These types are never variably-modified.
2133     case Type::Builtin:
2134     case Type::Complex:
2135     case Type::Vector:
2136     case Type::ExtVector:
2137     case Type::ConstantMatrix:
2138     case Type::Record:
2139     case Type::Enum:
2140     case Type::Elaborated:
2141     case Type::TemplateSpecialization:
2142     case Type::ObjCTypeParam:
2143     case Type::ObjCObject:
2144     case Type::ObjCInterface:
2145     case Type::ObjCObjectPointer:
2146     case Type::ExtInt:
2147       llvm_unreachable("type class is never variably-modified!");
2148 
2149     case Type::Adjusted:
2150       type = cast<AdjustedType>(ty)->getAdjustedType();
2151       break;
2152 
2153     case Type::Decayed:
2154       type = cast<DecayedType>(ty)->getPointeeType();
2155       break;
2156 
2157     case Type::Pointer:
2158       type = cast<PointerType>(ty)->getPointeeType();
2159       break;
2160 
2161     case Type::BlockPointer:
2162       type = cast<BlockPointerType>(ty)->getPointeeType();
2163       break;
2164 
2165     case Type::LValueReference:
2166     case Type::RValueReference:
2167       type = cast<ReferenceType>(ty)->getPointeeType();
2168       break;
2169 
2170     case Type::MemberPointer:
2171       type = cast<MemberPointerType>(ty)->getPointeeType();
2172       break;
2173 
2174     case Type::ConstantArray:
2175     case Type::IncompleteArray:
2176       // Losing element qualification here is fine.
2177       type = cast<ArrayType>(ty)->getElementType();
2178       break;
2179 
2180     case Type::VariableArray: {
2181       // Losing element qualification here is fine.
2182       const VariableArrayType *vat = cast<VariableArrayType>(ty);
2183 
2184       // Unknown size indication requires no size computation.
2185       // Otherwise, evaluate and record it.
2186       if (const Expr *size = vat->getSizeExpr()) {
2187         // It's possible that we might have emitted this already,
2188         // e.g. with a typedef and a pointer to it.
2189         llvm::Value *&entry = VLASizeMap[size];
2190         if (!entry) {
2191           llvm::Value *Size = EmitScalarExpr(size);
2192 
2193           // C11 6.7.6.2p5:
2194           //   If the size is an expression that is not an integer constant
2195           //   expression [...] each time it is evaluated it shall have a value
2196           //   greater than zero.
2197           if (SanOpts.has(SanitizerKind::VLABound) &&
2198               size->getType()->isSignedIntegerType()) {
2199             SanitizerScope SanScope(this);
2200             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
2201             llvm::Constant *StaticArgs[] = {
2202                 EmitCheckSourceLocation(size->getBeginLoc()),
2203                 EmitCheckTypeDescriptor(size->getType())};
2204             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
2205                                      SanitizerKind::VLABound),
2206                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2207           }
2208 
2209           // Always zexting here would be wrong if it weren't
2210           // undefined behavior to have a negative bound.
2211           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
2212         }
2213       }
2214       type = vat->getElementType();
2215       break;
2216     }
2217 
2218     case Type::FunctionProto:
2219     case Type::FunctionNoProto:
2220       type = cast<FunctionType>(ty)->getReturnType();
2221       break;
2222 
2223     case Type::Paren:
2224     case Type::TypeOf:
2225     case Type::UnaryTransform:
2226     case Type::Attributed:
2227     case Type::SubstTemplateTypeParm:
2228     case Type::MacroQualified:
2229       // Keep walking after single level desugaring.
2230       type = type.getSingleStepDesugaredType(getContext());
2231       break;
2232 
2233     case Type::Typedef:
2234     case Type::Decltype:
2235     case Type::Auto:
2236     case Type::DeducedTemplateSpecialization:
2237       // Stop walking: nothing to do.
2238       return;
2239 
2240     case Type::TypeOfExpr:
2241       // Stop walking: emit typeof expression.
2242       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2243       return;
2244 
2245     case Type::Atomic:
2246       type = cast<AtomicType>(ty)->getValueType();
2247       break;
2248 
2249     case Type::Pipe:
2250       type = cast<PipeType>(ty)->getElementType();
2251       break;
2252     }
2253   } while (type->isVariablyModifiedType());
2254 }
2255 
2256 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2257   if (getContext().getBuiltinVaListType()->isArrayType())
2258     return EmitPointerWithAlignment(E);
2259   return EmitLValue(E).getAddress(*this);
2260 }
2261 
2262 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2263   return EmitLValue(E).getAddress(*this);
2264 }
2265 
2266 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2267                                               const APValue &Init) {
2268   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2269   if (CGDebugInfo *Dbg = getDebugInfo())
2270     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2271       Dbg->EmitGlobalVariable(E->getDecl(), Init);
2272 }
2273 
2274 CodeGenFunction::PeepholeProtection
2275 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2276   // At the moment, the only aggressive peephole we do in IR gen
2277   // is trunc(zext) folding, but if we add more, we can easily
2278   // extend this protection.
2279 
2280   if (!rvalue.isScalar()) return PeepholeProtection();
2281   llvm::Value *value = rvalue.getScalarVal();
2282   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2283 
2284   // Just make an extra bitcast.
2285   assert(HaveInsertPoint());
2286   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2287                                                   Builder.GetInsertBlock());
2288 
2289   PeepholeProtection protection;
2290   protection.Inst = inst;
2291   return protection;
2292 }
2293 
2294 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2295   if (!protection.Inst) return;
2296 
2297   // In theory, we could try to duplicate the peepholes now, but whatever.
2298   protection.Inst->eraseFromParent();
2299 }
2300 
2301 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2302                                               QualType Ty, SourceLocation Loc,
2303                                               SourceLocation AssumptionLoc,
2304                                               llvm::Value *Alignment,
2305                                               llvm::Value *OffsetValue) {
2306   if (Alignment->getType() != IntPtrTy)
2307     Alignment =
2308         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2309   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2310     OffsetValue =
2311         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2312   llvm::Value *TheCheck = nullptr;
2313   if (SanOpts.has(SanitizerKind::Alignment)) {
2314     llvm::Value *PtrIntValue =
2315         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2316 
2317     if (OffsetValue) {
2318       bool IsOffsetZero = false;
2319       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2320         IsOffsetZero = CI->isZero();
2321 
2322       if (!IsOffsetZero)
2323         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2324     }
2325 
2326     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2327     llvm::Value *Mask =
2328         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2329     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2330     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2331   }
2332   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2333       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2334 
2335   if (!SanOpts.has(SanitizerKind::Alignment))
2336     return;
2337   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2338                                OffsetValue, TheCheck, Assumption);
2339 }
2340 
2341 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2342                                               const Expr *E,
2343                                               SourceLocation AssumptionLoc,
2344                                               llvm::Value *Alignment,
2345                                               llvm::Value *OffsetValue) {
2346   if (auto *CE = dyn_cast<CastExpr>(E))
2347     E = CE->getSubExprAsWritten();
2348   QualType Ty = E->getType();
2349   SourceLocation Loc = E->getExprLoc();
2350 
2351   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2352                           OffsetValue);
2353 }
2354 
2355 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2356                                                  llvm::Value *AnnotatedVal,
2357                                                  StringRef AnnotationStr,
2358                                                  SourceLocation Location,
2359                                                  const AnnotateAttr *Attr) {
2360   SmallVector<llvm::Value *, 5> Args = {
2361       AnnotatedVal,
2362       Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2363       Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2364       CGM.EmitAnnotationLineNo(Location),
2365   };
2366   if (Attr)
2367     Args.push_back(CGM.EmitAnnotationArgs(Attr));
2368   return Builder.CreateCall(AnnotationFn, Args);
2369 }
2370 
2371 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2372   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2373   // FIXME We create a new bitcast for every annotation because that's what
2374   // llvm-gcc was doing.
2375   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2376     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2377                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2378                        I->getAnnotation(), D->getLocation(), I);
2379 }
2380 
2381 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2382                                               Address Addr) {
2383   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2384   llvm::Value *V = Addr.getPointer();
2385   llvm::Type *VTy = V->getType();
2386   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
2387                                     CGM.Int8PtrTy);
2388 
2389   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2390     // FIXME Always emit the cast inst so we can differentiate between
2391     // annotation on the first field of a struct and annotation on the struct
2392     // itself.
2393     if (VTy != CGM.Int8PtrTy)
2394       V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
2395     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2396     V = Builder.CreateBitCast(V, VTy);
2397   }
2398 
2399   return Address(V, Addr.getAlignment());
2400 }
2401 
2402 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2403 
2404 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2405     : CGF(CGF) {
2406   assert(!CGF->IsSanitizerScope);
2407   CGF->IsSanitizerScope = true;
2408 }
2409 
2410 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2411   CGF->IsSanitizerScope = false;
2412 }
2413 
2414 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2415                                    const llvm::Twine &Name,
2416                                    llvm::BasicBlock *BB,
2417                                    llvm::BasicBlock::iterator InsertPt) const {
2418   LoopStack.InsertHelper(I);
2419   if (IsSanitizerScope)
2420     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2421 }
2422 
2423 void CGBuilderInserter::InsertHelper(
2424     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2425     llvm::BasicBlock::iterator InsertPt) const {
2426   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2427   if (CGF)
2428     CGF->InsertHelper(I, Name, BB, InsertPt);
2429 }
2430 
2431 // Emits an error if we don't have a valid set of target features for the
2432 // called function.
2433 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2434                                           const FunctionDecl *TargetDecl) {
2435   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2436 }
2437 
2438 // Emits an error if we don't have a valid set of target features for the
2439 // called function.
2440 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2441                                           const FunctionDecl *TargetDecl) {
2442   // Early exit if this is an indirect call.
2443   if (!TargetDecl)
2444     return;
2445 
2446   // Get the current enclosing function if it exists. If it doesn't
2447   // we can't check the target features anyhow.
2448   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2449   if (!FD)
2450     return;
2451 
2452   // Grab the required features for the call. For a builtin this is listed in
2453   // the td file with the default cpu, for an always_inline function this is any
2454   // listed cpu and any listed features.
2455   unsigned BuiltinID = TargetDecl->getBuiltinID();
2456   std::string MissingFeature;
2457   llvm::StringMap<bool> CallerFeatureMap;
2458   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2459   if (BuiltinID) {
2460     StringRef FeatureList(
2461         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2462     // Return if the builtin doesn't have any required features.
2463     if (FeatureList.empty())
2464       return;
2465     assert(FeatureList.find(' ') == StringRef::npos &&
2466            "Space in feature list");
2467     TargetFeatures TF(CallerFeatureMap);
2468     if (!TF.hasRequiredFeatures(FeatureList))
2469       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2470           << TargetDecl->getDeclName() << FeatureList;
2471   } else if (!TargetDecl->isMultiVersion() &&
2472              TargetDecl->hasAttr<TargetAttr>()) {
2473     // Get the required features for the callee.
2474 
2475     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2476     ParsedTargetAttr ParsedAttr =
2477         CGM.getContext().filterFunctionTargetAttrs(TD);
2478 
2479     SmallVector<StringRef, 1> ReqFeatures;
2480     llvm::StringMap<bool> CalleeFeatureMap;
2481     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2482 
2483     for (const auto &F : ParsedAttr.Features) {
2484       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2485         ReqFeatures.push_back(StringRef(F).substr(1));
2486     }
2487 
2488     for (const auto &F : CalleeFeatureMap) {
2489       // Only positive features are "required".
2490       if (F.getValue())
2491         ReqFeatures.push_back(F.getKey());
2492     }
2493     if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2494       if (!CallerFeatureMap.lookup(Feature)) {
2495         MissingFeature = Feature.str();
2496         return false;
2497       }
2498       return true;
2499     }))
2500       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2501           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2502   }
2503 }
2504 
2505 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2506   if (!CGM.getCodeGenOpts().SanitizeStats)
2507     return;
2508 
2509   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2510   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2511   CGM.getSanStats().create(IRB, SSK);
2512 }
2513 
2514 llvm::Value *
2515 CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2516   llvm::Value *Condition = nullptr;
2517 
2518   if (!RO.Conditions.Architecture.empty())
2519     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2520 
2521   if (!RO.Conditions.Features.empty()) {
2522     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2523     Condition =
2524         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2525   }
2526   return Condition;
2527 }
2528 
2529 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2530                                              llvm::Function *Resolver,
2531                                              CGBuilderTy &Builder,
2532                                              llvm::Function *FuncToReturn,
2533                                              bool SupportsIFunc) {
2534   if (SupportsIFunc) {
2535     Builder.CreateRet(FuncToReturn);
2536     return;
2537   }
2538 
2539   llvm::SmallVector<llvm::Value *, 10> Args;
2540   llvm::for_each(Resolver->args(),
2541                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2542 
2543   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2544   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2545 
2546   if (Resolver->getReturnType()->isVoidTy())
2547     Builder.CreateRetVoid();
2548   else
2549     Builder.CreateRet(Result);
2550 }
2551 
2552 void CodeGenFunction::EmitMultiVersionResolver(
2553     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2554   assert(getContext().getTargetInfo().getTriple().isX86() &&
2555          "Only implemented for x86 targets");
2556 
2557   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2558 
2559   // Main function's basic block.
2560   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2561   Builder.SetInsertPoint(CurBlock);
2562   EmitX86CpuInit();
2563 
2564   for (const MultiVersionResolverOption &RO : Options) {
2565     Builder.SetInsertPoint(CurBlock);
2566     llvm::Value *Condition = FormResolverCondition(RO);
2567 
2568     // The 'default' or 'generic' case.
2569     if (!Condition) {
2570       assert(&RO == Options.end() - 1 &&
2571              "Default or Generic case must be last");
2572       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2573                                        SupportsIFunc);
2574       return;
2575     }
2576 
2577     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2578     CGBuilderTy RetBuilder(*this, RetBlock);
2579     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2580                                      SupportsIFunc);
2581     CurBlock = createBasicBlock("resolver_else", Resolver);
2582     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2583   }
2584 
2585   // If no generic/default, emit an unreachable.
2586   Builder.SetInsertPoint(CurBlock);
2587   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2588   TrapCall->setDoesNotReturn();
2589   TrapCall->setDoesNotThrow();
2590   Builder.CreateUnreachable();
2591   Builder.ClearInsertionPoint();
2592 }
2593 
2594 // Loc - where the diagnostic will point, where in the source code this
2595 //  alignment has failed.
2596 // SecondaryLoc - if present (will be present if sufficiently different from
2597 //  Loc), the diagnostic will additionally point a "Note:" to this location.
2598 //  It should be the location where the __attribute__((assume_aligned))
2599 //  was written e.g.
2600 void CodeGenFunction::emitAlignmentAssumptionCheck(
2601     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2602     SourceLocation SecondaryLoc, llvm::Value *Alignment,
2603     llvm::Value *OffsetValue, llvm::Value *TheCheck,
2604     llvm::Instruction *Assumption) {
2605   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2606          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2607              llvm::Intrinsic::getDeclaration(
2608                  Builder.GetInsertBlock()->getParent()->getParent(),
2609                  llvm::Intrinsic::assume) &&
2610          "Assumption should be a call to llvm.assume().");
2611   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2612          "Assumption should be the last instruction of the basic block, "
2613          "since the basic block is still being generated.");
2614 
2615   if (!SanOpts.has(SanitizerKind::Alignment))
2616     return;
2617 
2618   // Don't check pointers to volatile data. The behavior here is implementation-
2619   // defined.
2620   if (Ty->getPointeeType().isVolatileQualified())
2621     return;
2622 
2623   // We need to temorairly remove the assumption so we can insert the
2624   // sanitizer check before it, else the check will be dropped by optimizations.
2625   Assumption->removeFromParent();
2626 
2627   {
2628     SanitizerScope SanScope(this);
2629 
2630     if (!OffsetValue)
2631       OffsetValue = Builder.getInt1(0); // no offset.
2632 
2633     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2634                                     EmitCheckSourceLocation(SecondaryLoc),
2635                                     EmitCheckTypeDescriptor(Ty)};
2636     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2637                                   EmitCheckValue(Alignment),
2638                                   EmitCheckValue(OffsetValue)};
2639     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2640               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2641   }
2642 
2643   // We are now in the (new, empty) "cont" basic block.
2644   // Reintroduce the assumption.
2645   Builder.Insert(Assumption);
2646   // FIXME: Assumption still has it's original basic block as it's Parent.
2647 }
2648 
2649 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2650   if (CGDebugInfo *DI = getDebugInfo())
2651     return DI->SourceLocToDebugLoc(Location);
2652 
2653   return llvm::DebugLoc();
2654 }
2655 
2656 llvm::Value *
2657 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2658                                                       Stmt::Likelihood LH) {
2659   switch (LH) {
2660   case Stmt::LH_None:
2661     return Cond;
2662   case Stmt::LH_Likely:
2663   case Stmt::LH_Unlikely:
2664     // Don't generate llvm.expect on -O0 as the backend won't use it for
2665     // anything.
2666     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2667       return Cond;
2668     llvm::Type *CondTy = Cond->getType();
2669     assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2670     llvm::Function *FnExpect =
2671         CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2672     llvm::Value *ExpectedValueOfCond =
2673         llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2674     return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2675                               Cond->getName() + ".expval");
2676   }
2677   llvm_unreachable("Unknown Likelihood");
2678 }
2679