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