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