xref: /freebsd-src/contrib/llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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::ExtInt:
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, CurFnInfo->getReturnInfo().getIndirectAlign());
1074     if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
1075       ReturnValuePointer =
1076           CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
1077       Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
1078                               ReturnValue.getPointer(), Int8PtrTy),
1079                           ReturnValuePointer);
1080     }
1081   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
1082              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
1083     // Load the sret pointer from the argument struct and return into that.
1084     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
1085     llvm::Function::arg_iterator EI = CurFn->arg_end();
1086     --EI;
1087     llvm::Value *Addr = Builder.CreateStructGEP(
1088         EI->getType()->getPointerElementType(), &*EI, Idx);
1089     llvm::Type *Ty =
1090         cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1091     ReturnValuePointer = Address(Addr, getPointerAlign());
1092     Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
1093     ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
1094   } else {
1095     ReturnValue = CreateIRTemp(RetTy, "retval");
1096 
1097     // Tell the epilog emitter to autorelease the result.  We do this
1098     // now so that various specialized functions can suppress it
1099     // during their IR-generation.
1100     if (getLangOpts().ObjCAutoRefCount &&
1101         !CurFnInfo->isReturnsRetained() &&
1102         RetTy->isObjCRetainableType())
1103       AutoreleaseResult = true;
1104   }
1105 
1106   EmitStartEHSpec(CurCodeDecl);
1107 
1108   PrologueCleanupDepth = EHStack.stable_begin();
1109 
1110   // Emit OpenMP specific initialization of the device functions.
1111   if (getLangOpts().OpenMP && CurCodeDecl)
1112     CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
1113 
1114   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
1115 
1116   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
1117     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
1118     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
1119     if (MD->getParent()->isLambda() &&
1120         MD->getOverloadedOperator() == OO_Call) {
1121       // We're in a lambda; figure out the captures.
1122       MD->getParent()->getCaptureFields(LambdaCaptureFields,
1123                                         LambdaThisCaptureField);
1124       if (LambdaThisCaptureField) {
1125         // If the lambda captures the object referred to by '*this' - either by
1126         // value or by reference, make sure CXXThisValue points to the correct
1127         // object.
1128 
1129         // Get the lvalue for the field (which is a copy of the enclosing object
1130         // or contains the address of the enclosing object).
1131         LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
1132         if (!LambdaThisCaptureField->getType()->isPointerType()) {
1133           // If the enclosing object was captured by value, just use its address.
1134           CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
1135         } else {
1136           // Load the lvalue pointed to by the field, since '*this' was captured
1137           // by reference.
1138           CXXThisValue =
1139               EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
1140         }
1141       }
1142       for (auto *FD : MD->getParent()->fields()) {
1143         if (FD->hasCapturedVLAType()) {
1144           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
1145                                            SourceLocation()).getScalarVal();
1146           auto VAT = FD->getCapturedVLAType();
1147           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1148         }
1149       }
1150     } else {
1151       // Not in a lambda; just use 'this' from the method.
1152       // FIXME: Should we generate a new load for each use of 'this'?  The
1153       // fast register allocator would be happier...
1154       CXXThisValue = CXXABIThisValue;
1155     }
1156 
1157     // Check the 'this' pointer once per function, if it's available.
1158     if (CXXABIThisValue) {
1159       SanitizerSet SkippedChecks;
1160       SkippedChecks.set(SanitizerKind::ObjectSize, true);
1161       QualType ThisTy = MD->getThisType();
1162 
1163       // If this is the call operator of a lambda with no capture-default, it
1164       // may have a static invoker function, which may call this operator with
1165       // a null 'this' pointer.
1166       if (isLambdaCallOperator(MD) &&
1167           MD->getParent()->getLambdaCaptureDefault() == LCD_None)
1168         SkippedChecks.set(SanitizerKind::Null, true);
1169 
1170       EmitTypeCheck(
1171           isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
1172           Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1173     }
1174   }
1175 
1176   // If any of the arguments have a variably modified type, make sure to
1177   // emit the type size.
1178   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1179        i != e; ++i) {
1180     const VarDecl *VD = *i;
1181 
1182     // Dig out the type as written from ParmVarDecls; it's unclear whether
1183     // the standard (C99 6.9.1p10) requires this, but we're following the
1184     // precedent set by gcc.
1185     QualType Ty;
1186     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1187       Ty = PVD->getOriginalType();
1188     else
1189       Ty = VD->getType();
1190 
1191     if (Ty->isVariablyModifiedType())
1192       EmitVariablyModifiedType(Ty);
1193   }
1194   // Emit a location at the end of the prologue.
1195   if (CGDebugInfo *DI = getDebugInfo())
1196     DI->EmitLocation(Builder, StartLoc);
1197 
1198   // TODO: Do we need to handle this in two places like we do with
1199   // target-features/target-cpu?
1200   if (CurFuncDecl)
1201     if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
1202       LargestVectorWidth = VecWidth->getVectorWidth();
1203 }
1204 
1205 void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
1206   incrementProfileCounter(Body);
1207   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1208     EmitCompoundStmtWithoutScope(*S);
1209   else
1210     EmitStmt(Body);
1211 
1212   // This is checked after emitting the function body so we know if there
1213   // are any permitted infinite loops.
1214   if (checkIfFunctionMustProgress())
1215     CurFn->addFnAttr(llvm::Attribute::MustProgress);
1216 }
1217 
1218 /// When instrumenting to collect profile data, the counts for some blocks
1219 /// such as switch cases need to not include the fall-through counts, so
1220 /// emit a branch around the instrumentation code. When not instrumenting,
1221 /// this just calls EmitBlock().
1222 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
1223                                                const Stmt *S) {
1224   llvm::BasicBlock *SkipCountBB = nullptr;
1225   if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
1226     // When instrumenting for profiling, the fallthrough to certain
1227     // statements needs to skip over the instrumentation code so that we
1228     // get an accurate count.
1229     SkipCountBB = createBasicBlock("skipcount");
1230     EmitBranch(SkipCountBB);
1231   }
1232   EmitBlock(BB);
1233   uint64_t CurrentCount = getCurrentProfileCount();
1234   incrementProfileCounter(S);
1235   setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
1236   if (SkipCountBB)
1237     EmitBlock(SkipCountBB);
1238 }
1239 
1240 /// Tries to mark the given function nounwind based on the
1241 /// non-existence of any throwing calls within it.  We believe this is
1242 /// lightweight enough to do at -O0.
1243 static void TryMarkNoThrow(llvm::Function *F) {
1244   // LLVM treats 'nounwind' on a function as part of the type, so we
1245   // can't do this on functions that can be overwritten.
1246   if (F->isInterposable()) return;
1247 
1248   for (llvm::BasicBlock &BB : *F)
1249     for (llvm::Instruction &I : BB)
1250       if (I.mayThrow())
1251         return;
1252 
1253   F->setDoesNotThrow();
1254 }
1255 
1256 QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
1257                                                FunctionArgList &Args) {
1258   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1259   QualType ResTy = FD->getReturnType();
1260 
1261   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1262   if (MD && MD->isInstance()) {
1263     if (CGM.getCXXABI().HasThisReturn(GD))
1264       ResTy = MD->getThisType();
1265     else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
1266       ResTy = CGM.getContext().VoidPtrTy;
1267     CGM.getCXXABI().buildThisParam(*this, Args);
1268   }
1269 
1270   // The base version of an inheriting constructor whose constructed base is a
1271   // virtual base is not passed any arguments (because it doesn't actually call
1272   // the inherited constructor).
1273   bool PassedParams = true;
1274   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
1275     if (auto Inherited = CD->getInheritedConstructor())
1276       PassedParams =
1277           getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
1278 
1279   if (PassedParams) {
1280     for (auto *Param : FD->parameters()) {
1281       Args.push_back(Param);
1282       if (!Param->hasAttr<PassObjectSizeAttr>())
1283         continue;
1284 
1285       auto *Implicit = ImplicitParamDecl::Create(
1286           getContext(), Param->getDeclContext(), Param->getLocation(),
1287           /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
1288       SizeArguments[Param] = Implicit;
1289       Args.push_back(Implicit);
1290     }
1291   }
1292 
1293   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1294     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
1295 
1296   return ResTy;
1297 }
1298 
1299 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1300                                    const CGFunctionInfo &FnInfo) {
1301   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
1302   CurGD = GD;
1303 
1304   FunctionArgList Args;
1305   QualType ResTy = BuildFunctionArgList(GD, Args);
1306 
1307   // When generating code for a builtin with an inline declaration, use a
1308   // mangled name to hold the actual body, while keeping an external definition
1309   // in case the function pointer is referenced somewhere.
1310   if (Fn) {
1311     if (FD->isInlineBuiltinDeclaration()) {
1312       std::string FDInlineName = (Fn->getName() + ".inline").str();
1313       llvm::Module *M = Fn->getParent();
1314       llvm::Function *Clone = M->getFunction(FDInlineName);
1315       if (!Clone) {
1316         Clone = llvm::Function::Create(Fn->getFunctionType(),
1317                                        llvm::GlobalValue::InternalLinkage,
1318                                        Fn->getAddressSpace(), FDInlineName, M);
1319         Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1320       }
1321       Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1322       Fn = Clone;
1323     }
1324 
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     else {
1331       for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
1332            PD = PD->getPreviousDecl()) {
1333         if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1334           std::string FDInlineName = (Fn->getName() + ".inline").str();
1335           llvm::Module *M = Fn->getParent();
1336           if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1337             Clone->replaceAllUsesWith(Fn);
1338             Clone->eraseFromParent();
1339           }
1340           break;
1341         }
1342       }
1343     }
1344   }
1345 
1346   // Check if we should generate debug info for this function.
1347   if (FD->hasAttr<NoDebugAttr>()) {
1348     // Clear non-distinct debug info that was possibly attached to the function
1349     // due to an earlier declaration without the nodebug attribute
1350     if (Fn)
1351       Fn->setSubprogram(nullptr);
1352     // Disable debug info indefinitely for this function
1353     DebugInfo = nullptr;
1354   }
1355 
1356   // The function might not have a body if we're generating thunks for a
1357   // function declaration.
1358   SourceRange BodyRange;
1359   if (Stmt *Body = FD->getBody())
1360     BodyRange = Body->getSourceRange();
1361   else
1362     BodyRange = FD->getLocation();
1363   CurEHLocation = BodyRange.getEnd();
1364 
1365   // Use the location of the start of the function to determine where
1366   // the function definition is located. By default use the location
1367   // of the declaration as the location for the subprogram. A function
1368   // may lack a declaration in the source code if it is created by code
1369   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
1370   SourceLocation Loc = FD->getLocation();
1371 
1372   // If this is a function specialization then use the pattern body
1373   // as the location for the function.
1374   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
1375     if (SpecDecl->hasBody(SpecDecl))
1376       Loc = SpecDecl->getLocation();
1377 
1378   Stmt *Body = FD->getBody();
1379 
1380   if (Body) {
1381     // Coroutines always emit lifetime markers.
1382     if (isa<CoroutineBodyStmt>(Body))
1383       ShouldEmitLifetimeMarkers = true;
1384 
1385     // Initialize helper which will detect jumps which can cause invalid
1386     // lifetime markers.
1387     if (ShouldEmitLifetimeMarkers)
1388       Bypasses.Init(Body);
1389   }
1390 
1391   // Emit the standard function prologue.
1392   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
1393 
1394   // Save parameters for coroutine function.
1395   if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1396     for (const auto *ParamDecl : FD->parameters())
1397       FnArgs.push_back(ParamDecl);
1398 
1399   // Generate the body of the function.
1400   PGO.assignRegionCounters(GD, CurFn);
1401   if (isa<CXXDestructorDecl>(FD))
1402     EmitDestructorBody(Args);
1403   else if (isa<CXXConstructorDecl>(FD))
1404     EmitConstructorBody(Args);
1405   else if (getLangOpts().CUDA &&
1406            !getLangOpts().CUDAIsDevice &&
1407            FD->hasAttr<CUDAGlobalAttr>())
1408     CGM.getCUDARuntime().emitDeviceStub(*this, Args);
1409   else if (isa<CXXMethodDecl>(FD) &&
1410            cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1411     // The lambda static invoker function is special, because it forwards or
1412     // clones the body of the function call operator (but is actually static).
1413     EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
1414   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
1415              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1416               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1417     // Implicit copy-assignment gets the same special treatment as implicit
1418     // copy-constructors.
1419     emitImplicitAssignmentOperatorBody(Args);
1420   } else if (Body) {
1421     EmitFunctionBody(Body);
1422   } else
1423     llvm_unreachable("no definition for emitted function");
1424 
1425   // C++11 [stmt.return]p2:
1426   //   Flowing off the end of a function [...] results in undefined behavior in
1427   //   a value-returning function.
1428   // C11 6.9.1p12:
1429   //   If the '}' that terminates a function is reached, and the value of the
1430   //   function call is used by the caller, the behavior is undefined.
1431   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
1432       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
1433     bool ShouldEmitUnreachable =
1434         CGM.getCodeGenOpts().StrictReturn ||
1435         !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
1436     if (SanOpts.has(SanitizerKind::Return)) {
1437       SanitizerScope SanScope(this);
1438       llvm::Value *IsFalse = Builder.getFalse();
1439       EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1440                 SanitizerHandler::MissingReturn,
1441                 EmitCheckSourceLocation(FD->getLocation()), None);
1442     } else if (ShouldEmitUnreachable) {
1443       if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1444         EmitTrapCall(llvm::Intrinsic::trap);
1445     }
1446     if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1447       Builder.CreateUnreachable();
1448       Builder.ClearInsertionPoint();
1449     }
1450   }
1451 
1452   // Emit the standard function epilogue.
1453   FinishFunction(BodyRange.getEnd());
1454 
1455   // If we haven't marked the function nothrow through other means, do
1456   // a quick pass now to see if we can.
1457   if (!CurFn->doesNotThrow())
1458     TryMarkNoThrow(CurFn);
1459 }
1460 
1461 /// ContainsLabel - Return true if the statement contains a label in it.  If
1462 /// this statement is not executed normally, it not containing a label means
1463 /// that we can just remove the code.
1464 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
1465   // Null statement, not a label!
1466   if (!S) return false;
1467 
1468   // If this is a label, we have to emit the code, consider something like:
1469   // if (0) {  ...  foo:  bar(); }  goto foo;
1470   //
1471   // TODO: If anyone cared, we could track __label__'s, since we know that you
1472   // can't jump to one from outside their declared region.
1473   if (isa<LabelStmt>(S))
1474     return true;
1475 
1476   // If this is a case/default statement, and we haven't seen a switch, we have
1477   // to emit the code.
1478   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1479     return true;
1480 
1481   // If this is a switch statement, we want to ignore cases below it.
1482   if (isa<SwitchStmt>(S))
1483     IgnoreCaseStmts = true;
1484 
1485   // Scan subexpressions for verboten labels.
1486   for (const Stmt *SubStmt : S->children())
1487     if (ContainsLabel(SubStmt, IgnoreCaseStmts))
1488       return true;
1489 
1490   return false;
1491 }
1492 
1493 /// containsBreak - Return true if the statement contains a break out of it.
1494 /// If the statement (recursively) contains a switch or loop with a break
1495 /// inside of it, this is fine.
1496 bool CodeGenFunction::containsBreak(const Stmt *S) {
1497   // Null statement, not a label!
1498   if (!S) return false;
1499 
1500   // If this is a switch or loop that defines its own break scope, then we can
1501   // include it and anything inside of it.
1502   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1503       isa<ForStmt>(S))
1504     return false;
1505 
1506   if (isa<BreakStmt>(S))
1507     return true;
1508 
1509   // Scan subexpressions for verboten breaks.
1510   for (const Stmt *SubStmt : S->children())
1511     if (containsBreak(SubStmt))
1512       return true;
1513 
1514   return false;
1515 }
1516 
1517 bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
1518   if (!S) return false;
1519 
1520   // Some statement kinds add a scope and thus never add a decl to the current
1521   // scope. Note, this list is longer than the list of statements that might
1522   // have an unscoped decl nested within them, but this way is conservatively
1523   // correct even if more statement kinds are added.
1524   if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1525       isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1526       isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1527       isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1528     return false;
1529 
1530   if (isa<DeclStmt>(S))
1531     return true;
1532 
1533   for (const Stmt *SubStmt : S->children())
1534     if (mightAddDeclToScope(SubStmt))
1535       return true;
1536 
1537   return false;
1538 }
1539 
1540 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1541 /// to a constant, or if it does but contains a label, return false.  If it
1542 /// constant folds return true and set the boolean result in Result.
1543 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1544                                                    bool &ResultBool,
1545                                                    bool AllowLabels) {
1546   llvm::APSInt ResultInt;
1547   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
1548     return false;
1549 
1550   ResultBool = ResultInt.getBoolValue();
1551   return true;
1552 }
1553 
1554 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1555 /// to a constant, or if it does but contains a label, return false.  If it
1556 /// constant folds return true and set the folded value.
1557 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
1558                                                    llvm::APSInt &ResultInt,
1559                                                    bool AllowLabels) {
1560   // FIXME: Rename and handle conversion of other evaluatable things
1561   // to bool.
1562   Expr::EvalResult Result;
1563   if (!Cond->EvaluateAsInt(Result, getContext()))
1564     return false;  // Not foldable, not integer or not fully evaluatable.
1565 
1566   llvm::APSInt Int = Result.Val.getInt();
1567   if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
1568     return false;  // Contains a label.
1569 
1570   ResultInt = Int;
1571   return true;
1572 }
1573 
1574 /// Determine whether the given condition is an instrumentable condition
1575 /// (i.e. no "&&" or "||").
1576 bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
1577   // Bypass simplistic logical-NOT operator before determining whether the
1578   // condition contains any other logical operator.
1579   if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
1580     if (UnOp->getOpcode() == UO_LNot)
1581       C = UnOp->getSubExpr();
1582 
1583   const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
1584   return (!BOp || !BOp->isLogicalOp());
1585 }
1586 
1587 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
1588 /// increments a profile counter based on the semantics of the given logical
1589 /// operator opcode.  This is used to instrument branch condition coverage for
1590 /// logical operators.
1591 void CodeGenFunction::EmitBranchToCounterBlock(
1592     const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
1593     llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
1594     Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
1595   // If not instrumenting, just emit a branch.
1596   bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1597   if (!InstrumentRegions || !isInstrumentedCondition(Cond))
1598     return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
1599 
1600   llvm::BasicBlock *ThenBlock = NULL;
1601   llvm::BasicBlock *ElseBlock = NULL;
1602   llvm::BasicBlock *NextBlock = NULL;
1603 
1604   // Create the block we'll use to increment the appropriate counter.
1605   llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
1606 
1607   // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
1608   // means we need to evaluate the condition and increment the counter on TRUE:
1609   //
1610   // if (Cond)
1611   //   goto CounterIncrBlock;
1612   // else
1613   //   goto FalseBlock;
1614   //
1615   // CounterIncrBlock:
1616   //   Counter++;
1617   //   goto TrueBlock;
1618 
1619   if (LOp == BO_LAnd) {
1620     ThenBlock = CounterIncrBlock;
1621     ElseBlock = FalseBlock;
1622     NextBlock = TrueBlock;
1623   }
1624 
1625   // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
1626   // we need to evaluate the condition and increment the counter on FALSE:
1627   //
1628   // if (Cond)
1629   //   goto TrueBlock;
1630   // else
1631   //   goto CounterIncrBlock;
1632   //
1633   // CounterIncrBlock:
1634   //   Counter++;
1635   //   goto FalseBlock;
1636 
1637   else if (LOp == BO_LOr) {
1638     ThenBlock = TrueBlock;
1639     ElseBlock = CounterIncrBlock;
1640     NextBlock = FalseBlock;
1641   } else {
1642     llvm_unreachable("Expected Opcode must be that of a Logical Operator");
1643   }
1644 
1645   // Emit Branch based on condition.
1646   EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
1647 
1648   // Emit the block containing the counter increment(s).
1649   EmitBlock(CounterIncrBlock);
1650 
1651   // Increment corresponding counter; if index not provided, use Cond as index.
1652   incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
1653 
1654   // Go to the next block.
1655   EmitBranch(NextBlock);
1656 }
1657 
1658 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1659 /// statement) to the specified blocks.  Based on the condition, this might try
1660 /// to simplify the codegen of the conditional based on the branch.
1661 /// \param LH The value of the likelihood attribute on the True branch.
1662 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1663                                            llvm::BasicBlock *TrueBlock,
1664                                            llvm::BasicBlock *FalseBlock,
1665                                            uint64_t TrueCount,
1666                                            Stmt::Likelihood LH) {
1667   Cond = Cond->IgnoreParens();
1668 
1669   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1670 
1671     // Handle X && Y in a condition.
1672     if (CondBOp->getOpcode() == BO_LAnd) {
1673       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1674       // folded if the case was simple enough.
1675       bool ConstantBool = false;
1676       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1677           ConstantBool) {
1678         // br(1 && X) -> br(X).
1679         incrementProfileCounter(CondBOp);
1680         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1681                                         FalseBlock, TrueCount, LH);
1682       }
1683 
1684       // If we have "X && 1", simplify the code to use an uncond branch.
1685       // "X && 0" would have been constant folded to 0.
1686       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1687           ConstantBool) {
1688         // br(X && 1) -> br(X).
1689         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
1690                                         FalseBlock, TrueCount, LH, CondBOp);
1691       }
1692 
1693       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1694       // want to jump to the FalseBlock.
1695       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1696       // The counter tells us how often we evaluate RHS, and all of TrueCount
1697       // can be propagated to that branch.
1698       uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
1699 
1700       ConditionalEvaluation eval(*this);
1701       {
1702         ApplyDebugLocation DL(*this, Cond);
1703         // Propagate the likelihood attribute like __builtin_expect
1704         // __builtin_expect(X && Y, 1) -> X and Y are likely
1705         // __builtin_expect(X && Y, 0) -> only Y is unlikely
1706         EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
1707                              LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
1708         EmitBlock(LHSTrue);
1709       }
1710 
1711       incrementProfileCounter(CondBOp);
1712       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1713 
1714       // Any temporaries created here are conditional.
1715       eval.begin(*this);
1716       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
1717                                FalseBlock, TrueCount, LH);
1718       eval.end(*this);
1719 
1720       return;
1721     }
1722 
1723     if (CondBOp->getOpcode() == BO_LOr) {
1724       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1725       // folded if the case was simple enough.
1726       bool ConstantBool = false;
1727       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1728           !ConstantBool) {
1729         // br(0 || X) -> br(X).
1730         incrementProfileCounter(CondBOp);
1731         return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
1732                                         FalseBlock, TrueCount, LH);
1733       }
1734 
1735       // If we have "X || 0", simplify the code to use an uncond branch.
1736       // "X || 1" would have been constant folded to 1.
1737       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1738           !ConstantBool) {
1739         // br(X || 0) -> br(X).
1740         return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
1741                                         FalseBlock, TrueCount, LH, CondBOp);
1742       }
1743 
1744       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1745       // want to jump to the TrueBlock.
1746       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1747       // We have the count for entry to the RHS and for the whole expression
1748       // being true, so we can divy up True count between the short circuit and
1749       // the RHS.
1750       uint64_t LHSCount =
1751           getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
1752       uint64_t RHSCount = TrueCount - LHSCount;
1753 
1754       ConditionalEvaluation eval(*this);
1755       {
1756         // Propagate the likelihood attribute like __builtin_expect
1757         // __builtin_expect(X || Y, 1) -> only Y is likely
1758         // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
1759         ApplyDebugLocation DL(*this, Cond);
1760         EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
1761                              LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
1762         EmitBlock(LHSFalse);
1763       }
1764 
1765       incrementProfileCounter(CondBOp);
1766       setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
1767 
1768       // Any temporaries created here are conditional.
1769       eval.begin(*this);
1770       EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
1771                                RHSCount, LH);
1772 
1773       eval.end(*this);
1774 
1775       return;
1776     }
1777   }
1778 
1779   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1780     // br(!x, t, f) -> br(x, f, t)
1781     if (CondUOp->getOpcode() == UO_LNot) {
1782       // Negate the count.
1783       uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
1784       // The values of the enum are chosen to make this negation possible.
1785       LH = static_cast<Stmt::Likelihood>(-LH);
1786       // Negate the condition and swap the destination blocks.
1787       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1788                                   FalseCount, LH);
1789     }
1790   }
1791 
1792   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1793     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1794     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1795     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1796 
1797     // The ConditionalOperator itself has no likelihood information for its
1798     // true and false branches. This matches the behavior of __builtin_expect.
1799     ConditionalEvaluation cond(*this);
1800     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
1801                          getProfileCount(CondOp), Stmt::LH_None);
1802 
1803     // When computing PGO branch weights, we only know the overall count for
1804     // the true block. This code is essentially doing tail duplication of the
1805     // naive code-gen, introducing new edges for which counts are not
1806     // available. Divide the counts proportionally between the LHS and RHS of
1807     // the conditional operator.
1808     uint64_t LHSScaledTrueCount = 0;
1809     if (TrueCount) {
1810       double LHSRatio =
1811           getProfileCount(CondOp) / (double)getCurrentProfileCount();
1812       LHSScaledTrueCount = TrueCount * LHSRatio;
1813     }
1814 
1815     cond.begin(*this);
1816     EmitBlock(LHSBlock);
1817     incrementProfileCounter(CondOp);
1818     {
1819       ApplyDebugLocation DL(*this, Cond);
1820       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1821                            LHSScaledTrueCount, LH);
1822     }
1823     cond.end(*this);
1824 
1825     cond.begin(*this);
1826     EmitBlock(RHSBlock);
1827     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1828                          TrueCount - LHSScaledTrueCount, LH);
1829     cond.end(*this);
1830 
1831     return;
1832   }
1833 
1834   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1835     // Conditional operator handling can give us a throw expression as a
1836     // condition for a case like:
1837     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1838     // Fold this to:
1839     //   br(c, throw x, br(y, t, f))
1840     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1841     return;
1842   }
1843 
1844   // Emit the code with the fully general case.
1845   llvm::Value *CondV;
1846   {
1847     ApplyDebugLocation DL(*this, Cond);
1848     CondV = EvaluateExprAsBool(Cond);
1849   }
1850 
1851   llvm::MDNode *Weights = nullptr;
1852   llvm::MDNode *Unpredictable = nullptr;
1853 
1854   // If the branch has a condition wrapped by __builtin_unpredictable,
1855   // create metadata that specifies that the branch is unpredictable.
1856   // Don't bother if not optimizing because that metadata would not be used.
1857   auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
1858   if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1859     auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1860     if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1861       llvm::MDBuilder MDHelper(getLLVMContext());
1862       Unpredictable = MDHelper.createUnpredictable();
1863     }
1864   }
1865 
1866   // If there is a Likelihood knowledge for the cond, lower it.
1867   // Note that if not optimizing this won't emit anything.
1868   llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
1869   if (CondV != NewCondV)
1870     CondV = NewCondV;
1871   else {
1872     // Otherwise, lower profile counts. Note that we do this even at -O0.
1873     uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
1874     Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
1875   }
1876 
1877   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
1878 }
1879 
1880 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1881 /// specified stmt yet.
1882 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1883   CGM.ErrorUnsupported(S, Type);
1884 }
1885 
1886 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1887 /// variable-length array whose elements have a non-zero bit-pattern.
1888 ///
1889 /// \param baseType the inner-most element type of the array
1890 /// \param src - a char* pointing to the bit-pattern for a single
1891 /// base element of the array
1892 /// \param sizeInChars - the total size of the VLA, in chars
1893 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1894                                Address dest, Address src,
1895                                llvm::Value *sizeInChars) {
1896   CGBuilderTy &Builder = CGF.Builder;
1897 
1898   CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1899   llvm::Value *baseSizeInChars
1900     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
1901 
1902   Address begin =
1903     Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
1904   llvm::Value *end = Builder.CreateInBoundsGEP(
1905       begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
1906 
1907   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1908   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1909   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1910 
1911   // Make a loop over the VLA.  C99 guarantees that the VLA element
1912   // count must be nonzero.
1913   CGF.EmitBlock(loopBB);
1914 
1915   llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
1916   cur->addIncoming(begin.getPointer(), originBB);
1917 
1918   CharUnits curAlign =
1919     dest.getAlignment().alignmentOfArrayElement(baseSize);
1920 
1921   // memcpy the individual element bit-pattern.
1922   Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
1923                        /*volatile*/ false);
1924 
1925   // Go to the next element.
1926   llvm::Value *next =
1927     Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
1928 
1929   // Leave if that's the end of the VLA.
1930   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1931   Builder.CreateCondBr(done, contBB, loopBB);
1932   cur->addIncoming(next, loopBB);
1933 
1934   CGF.EmitBlock(contBB);
1935 }
1936 
1937 void
1938 CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
1939   // Ignore empty classes in C++.
1940   if (getLangOpts().CPlusPlus) {
1941     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1942       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1943         return;
1944     }
1945   }
1946 
1947   // Cast the dest ptr to the appropriate i8 pointer type.
1948   if (DestPtr.getElementType() != Int8Ty)
1949     DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
1950 
1951   // Get size and alignment info for this aggregate.
1952   CharUnits size = getContext().getTypeSizeInChars(Ty);
1953 
1954   llvm::Value *SizeVal;
1955   const VariableArrayType *vla;
1956 
1957   // Don't bother emitting a zero-byte memset.
1958   if (size.isZero()) {
1959     // But note that getTypeInfo returns 0 for a VLA.
1960     if (const VariableArrayType *vlaType =
1961           dyn_cast_or_null<VariableArrayType>(
1962                                           getContext().getAsArrayType(Ty))) {
1963       auto VlaSize = getVLASize(vlaType);
1964       SizeVal = VlaSize.NumElts;
1965       CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1966       if (!eltSize.isOne())
1967         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1968       vla = vlaType;
1969     } else {
1970       return;
1971     }
1972   } else {
1973     SizeVal = CGM.getSize(size);
1974     vla = nullptr;
1975   }
1976 
1977   // If the type contains a pointer to data member we can't memset it to zero.
1978   // Instead, create a null constant and copy it to the destination.
1979   // TODO: there are other patterns besides zero that we can usefully memset,
1980   // like -1, which happens to be the pattern used by member-pointers.
1981   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1982     // For a VLA, emit a single element, then splat that over the VLA.
1983     if (vla) Ty = getContext().getBaseElementType(vla);
1984 
1985     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1986 
1987     llvm::GlobalVariable *NullVariable =
1988       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1989                                /*isConstant=*/true,
1990                                llvm::GlobalVariable::PrivateLinkage,
1991                                NullConstant, Twine());
1992     CharUnits NullAlign = DestPtr.getAlignment();
1993     NullVariable->setAlignment(NullAlign.getAsAlign());
1994     Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
1995                    NullAlign);
1996 
1997     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1998 
1999     // Get and call the appropriate llvm.memcpy overload.
2000     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
2001     return;
2002   }
2003 
2004   // Otherwise, just memset the whole thing to zero.  This is legal
2005   // because in LLVM, all default initializers (other than the ones we just
2006   // handled above) are guaranteed to have a bit pattern of all zeros.
2007   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
2008 }
2009 
2010 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
2011   // Make sure that there is a block for the indirect goto.
2012   if (!IndirectBranch)
2013     GetIndirectGotoBlock();
2014 
2015   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
2016 
2017   // Make sure the indirect branch includes all of the address-taken blocks.
2018   IndirectBranch->addDestination(BB);
2019   return llvm::BlockAddress::get(CurFn, BB);
2020 }
2021 
2022 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
2023   // If we already made the indirect branch for indirect goto, return its block.
2024   if (IndirectBranch) return IndirectBranch->getParent();
2025 
2026   CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
2027 
2028   // Create the PHI node that indirect gotos will add entries to.
2029   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
2030                                               "indirect.goto.dest");
2031 
2032   // Create the indirect branch instruction.
2033   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2034   return IndirectBranch->getParent();
2035 }
2036 
2037 /// Computes the length of an array in elements, as well as the base
2038 /// element type and a properly-typed first element pointer.
2039 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
2040                                               QualType &baseType,
2041                                               Address &addr) {
2042   const ArrayType *arrayType = origArrayType;
2043 
2044   // If it's a VLA, we have to load the stored size.  Note that
2045   // this is the size of the VLA in bytes, not its size in elements.
2046   llvm::Value *numVLAElements = nullptr;
2047   if (isa<VariableArrayType>(arrayType)) {
2048     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
2049 
2050     // Walk into all VLAs.  This doesn't require changes to addr,
2051     // which has type T* where T is the first non-VLA element type.
2052     do {
2053       QualType elementType = arrayType->getElementType();
2054       arrayType = getContext().getAsArrayType(elementType);
2055 
2056       // If we only have VLA components, 'addr' requires no adjustment.
2057       if (!arrayType) {
2058         baseType = elementType;
2059         return numVLAElements;
2060       }
2061     } while (isa<VariableArrayType>(arrayType));
2062 
2063     // We get out here only if we find a constant array type
2064     // inside the VLA.
2065   }
2066 
2067   // We have some number of constant-length arrays, so addr should
2068   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
2069   // down to the first element of addr.
2070   SmallVector<llvm::Value*, 8> gepIndices;
2071 
2072   // GEP down to the array type.
2073   llvm::ConstantInt *zero = Builder.getInt32(0);
2074   gepIndices.push_back(zero);
2075 
2076   uint64_t countFromCLAs = 1;
2077   QualType eltType;
2078 
2079   llvm::ArrayType *llvmArrayType =
2080     dyn_cast<llvm::ArrayType>(addr.getElementType());
2081   while (llvmArrayType) {
2082     assert(isa<ConstantArrayType>(arrayType));
2083     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
2084              == llvmArrayType->getNumElements());
2085 
2086     gepIndices.push_back(zero);
2087     countFromCLAs *= llvmArrayType->getNumElements();
2088     eltType = arrayType->getElementType();
2089 
2090     llvmArrayType =
2091       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2092     arrayType = getContext().getAsArrayType(arrayType->getElementType());
2093     assert((!llvmArrayType || arrayType) &&
2094            "LLVM and Clang types are out-of-synch");
2095   }
2096 
2097   if (arrayType) {
2098     // From this point onwards, the Clang array type has been emitted
2099     // as some other type (probably a packed struct). Compute the array
2100     // size, and just emit the 'begin' expression as a bitcast.
2101     while (arrayType) {
2102       countFromCLAs *=
2103           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
2104       eltType = arrayType->getElementType();
2105       arrayType = getContext().getAsArrayType(eltType);
2106     }
2107 
2108     llvm::Type *baseType = ConvertType(eltType);
2109     addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
2110   } else {
2111     // Create the actual GEP.
2112     addr = Address(Builder.CreateInBoundsGEP(
2113         addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
2114         addr.getAlignment());
2115   }
2116 
2117   baseType = eltType;
2118 
2119   llvm::Value *numElements
2120     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
2121 
2122   // If we had any VLA dimensions, factor them in.
2123   if (numVLAElements)
2124     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
2125 
2126   return numElements;
2127 }
2128 
2129 CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
2130   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2131   assert(vla && "type was not a variable array type!");
2132   return getVLASize(vla);
2133 }
2134 
2135 CodeGenFunction::VlaSizePair
2136 CodeGenFunction::getVLASize(const VariableArrayType *type) {
2137   // The number of elements so far; always size_t.
2138   llvm::Value *numElements = nullptr;
2139 
2140   QualType elementType;
2141   do {
2142     elementType = type->getElementType();
2143     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
2144     assert(vlaSize && "no size for VLA!");
2145     assert(vlaSize->getType() == SizeTy);
2146 
2147     if (!numElements) {
2148       numElements = vlaSize;
2149     } else {
2150       // It's undefined behavior if this wraps around, so mark it that way.
2151       // FIXME: Teach -fsanitize=undefined to trap this.
2152       numElements = Builder.CreateNUWMul(numElements, vlaSize);
2153     }
2154   } while ((type = getContext().getAsVariableArrayType(elementType)));
2155 
2156   return { numElements, elementType };
2157 }
2158 
2159 CodeGenFunction::VlaSizePair
2160 CodeGenFunction::getVLAElements1D(QualType type) {
2161   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
2162   assert(vla && "type was not a variable array type!");
2163   return getVLAElements1D(vla);
2164 }
2165 
2166 CodeGenFunction::VlaSizePair
2167 CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
2168   llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
2169   assert(VlaSize && "no size for VLA!");
2170   assert(VlaSize->getType() == SizeTy);
2171   return { VlaSize, Vla->getElementType() };
2172 }
2173 
2174 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
2175   assert(type->isVariablyModifiedType() &&
2176          "Must pass variably modified type to EmitVLASizes!");
2177 
2178   EnsureInsertPoint();
2179 
2180   // We're going to walk down into the type and look for VLA
2181   // expressions.
2182   do {
2183     assert(type->isVariablyModifiedType());
2184 
2185     const Type *ty = type.getTypePtr();
2186     switch (ty->getTypeClass()) {
2187 
2188 #define TYPE(Class, Base)
2189 #define ABSTRACT_TYPE(Class, Base)
2190 #define NON_CANONICAL_TYPE(Class, Base)
2191 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2192 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2193 #include "clang/AST/TypeNodes.inc"
2194       llvm_unreachable("unexpected dependent type!");
2195 
2196     // These types are never variably-modified.
2197     case Type::Builtin:
2198     case Type::Complex:
2199     case Type::Vector:
2200     case Type::ExtVector:
2201     case Type::ConstantMatrix:
2202     case Type::Record:
2203     case Type::Enum:
2204     case Type::Elaborated:
2205     case Type::TemplateSpecialization:
2206     case Type::ObjCTypeParam:
2207     case Type::ObjCObject:
2208     case Type::ObjCInterface:
2209     case Type::ObjCObjectPointer:
2210     case Type::ExtInt:
2211       llvm_unreachable("type class is never variably-modified!");
2212 
2213     case Type::Adjusted:
2214       type = cast<AdjustedType>(ty)->getAdjustedType();
2215       break;
2216 
2217     case Type::Decayed:
2218       type = cast<DecayedType>(ty)->getPointeeType();
2219       break;
2220 
2221     case Type::Pointer:
2222       type = cast<PointerType>(ty)->getPointeeType();
2223       break;
2224 
2225     case Type::BlockPointer:
2226       type = cast<BlockPointerType>(ty)->getPointeeType();
2227       break;
2228 
2229     case Type::LValueReference:
2230     case Type::RValueReference:
2231       type = cast<ReferenceType>(ty)->getPointeeType();
2232       break;
2233 
2234     case Type::MemberPointer:
2235       type = cast<MemberPointerType>(ty)->getPointeeType();
2236       break;
2237 
2238     case Type::ConstantArray:
2239     case Type::IncompleteArray:
2240       // Losing element qualification here is fine.
2241       type = cast<ArrayType>(ty)->getElementType();
2242       break;
2243 
2244     case Type::VariableArray: {
2245       // Losing element qualification here is fine.
2246       const VariableArrayType *vat = cast<VariableArrayType>(ty);
2247 
2248       // Unknown size indication requires no size computation.
2249       // Otherwise, evaluate and record it.
2250       if (const Expr *size = vat->getSizeExpr()) {
2251         // It's possible that we might have emitted this already,
2252         // e.g. with a typedef and a pointer to it.
2253         llvm::Value *&entry = VLASizeMap[size];
2254         if (!entry) {
2255           llvm::Value *Size = EmitScalarExpr(size);
2256 
2257           // C11 6.7.6.2p5:
2258           //   If the size is an expression that is not an integer constant
2259           //   expression [...] each time it is evaluated it shall have a value
2260           //   greater than zero.
2261           if (SanOpts.has(SanitizerKind::VLABound) &&
2262               size->getType()->isSignedIntegerType()) {
2263             SanitizerScope SanScope(this);
2264             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
2265             llvm::Constant *StaticArgs[] = {
2266                 EmitCheckSourceLocation(size->getBeginLoc()),
2267                 EmitCheckTypeDescriptor(size->getType())};
2268             EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
2269                                      SanitizerKind::VLABound),
2270                       SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
2271           }
2272 
2273           // Always zexting here would be wrong if it weren't
2274           // undefined behavior to have a negative bound.
2275           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
2276         }
2277       }
2278       type = vat->getElementType();
2279       break;
2280     }
2281 
2282     case Type::FunctionProto:
2283     case Type::FunctionNoProto:
2284       type = cast<FunctionType>(ty)->getReturnType();
2285       break;
2286 
2287     case Type::Paren:
2288     case Type::TypeOf:
2289     case Type::UnaryTransform:
2290     case Type::Attributed:
2291     case Type::SubstTemplateTypeParm:
2292     case Type::MacroQualified:
2293       // Keep walking after single level desugaring.
2294       type = type.getSingleStepDesugaredType(getContext());
2295       break;
2296 
2297     case Type::Typedef:
2298     case Type::Decltype:
2299     case Type::Auto:
2300     case Type::DeducedTemplateSpecialization:
2301       // Stop walking: nothing to do.
2302       return;
2303 
2304     case Type::TypeOfExpr:
2305       // Stop walking: emit typeof expression.
2306       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
2307       return;
2308 
2309     case Type::Atomic:
2310       type = cast<AtomicType>(ty)->getValueType();
2311       break;
2312 
2313     case Type::Pipe:
2314       type = cast<PipeType>(ty)->getElementType();
2315       break;
2316     }
2317   } while (type->isVariablyModifiedType());
2318 }
2319 
2320 Address CodeGenFunction::EmitVAListRef(const Expr* E) {
2321   if (getContext().getBuiltinVaListType()->isArrayType())
2322     return EmitPointerWithAlignment(E);
2323   return EmitLValue(E).getAddress(*this);
2324 }
2325 
2326 Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
2327   return EmitLValue(E).getAddress(*this);
2328 }
2329 
2330 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
2331                                               const APValue &Init) {
2332   assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
2333   if (CGDebugInfo *Dbg = getDebugInfo())
2334     if (CGM.getCodeGenOpts().hasReducedDebugInfo())
2335       Dbg->EmitGlobalVariable(E->getDecl(), Init);
2336 }
2337 
2338 CodeGenFunction::PeepholeProtection
2339 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
2340   // At the moment, the only aggressive peephole we do in IR gen
2341   // is trunc(zext) folding, but if we add more, we can easily
2342   // extend this protection.
2343 
2344   if (!rvalue.isScalar()) return PeepholeProtection();
2345   llvm::Value *value = rvalue.getScalarVal();
2346   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
2347 
2348   // Just make an extra bitcast.
2349   assert(HaveInsertPoint());
2350   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
2351                                                   Builder.GetInsertBlock());
2352 
2353   PeepholeProtection protection;
2354   protection.Inst = inst;
2355   return protection;
2356 }
2357 
2358 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
2359   if (!protection.Inst) return;
2360 
2361   // In theory, we could try to duplicate the peepholes now, but whatever.
2362   protection.Inst->eraseFromParent();
2363 }
2364 
2365 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2366                                               QualType Ty, SourceLocation Loc,
2367                                               SourceLocation AssumptionLoc,
2368                                               llvm::Value *Alignment,
2369                                               llvm::Value *OffsetValue) {
2370   if (Alignment->getType() != IntPtrTy)
2371     Alignment =
2372         Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
2373   if (OffsetValue && OffsetValue->getType() != IntPtrTy)
2374     OffsetValue =
2375         Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
2376   llvm::Value *TheCheck = nullptr;
2377   if (SanOpts.has(SanitizerKind::Alignment)) {
2378     llvm::Value *PtrIntValue =
2379         Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2380 
2381     if (OffsetValue) {
2382       bool IsOffsetZero = false;
2383       if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2384         IsOffsetZero = CI->isZero();
2385 
2386       if (!IsOffsetZero)
2387         PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2388     }
2389 
2390     llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
2391     llvm::Value *Mask =
2392         Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
2393     llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
2394     TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2395   }
2396   llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
2397       CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
2398 
2399   if (!SanOpts.has(SanitizerKind::Alignment))
2400     return;
2401   emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2402                                OffsetValue, TheCheck, Assumption);
2403 }
2404 
2405 void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
2406                                               const Expr *E,
2407                                               SourceLocation AssumptionLoc,
2408                                               llvm::Value *Alignment,
2409                                               llvm::Value *OffsetValue) {
2410   if (auto *CE = dyn_cast<CastExpr>(E))
2411     E = CE->getSubExprAsWritten();
2412   QualType Ty = E->getType();
2413   SourceLocation Loc = E->getExprLoc();
2414 
2415   emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
2416                           OffsetValue);
2417 }
2418 
2419 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
2420                                                  llvm::Value *AnnotatedVal,
2421                                                  StringRef AnnotationStr,
2422                                                  SourceLocation Location,
2423                                                  const AnnotateAttr *Attr) {
2424   SmallVector<llvm::Value *, 5> Args = {
2425       AnnotatedVal,
2426       Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
2427       Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
2428       CGM.EmitAnnotationLineNo(Location),
2429   };
2430   if (Attr)
2431     Args.push_back(CGM.EmitAnnotationArgs(Attr));
2432   return Builder.CreateCall(AnnotationFn, Args);
2433 }
2434 
2435 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
2436   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2437   // FIXME We create a new bitcast for every annotation because that's what
2438   // llvm-gcc was doing.
2439   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2440     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
2441                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
2442                        I->getAnnotation(), D->getLocation(), I);
2443 }
2444 
2445 Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
2446                                               Address Addr) {
2447   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2448   llvm::Value *V = Addr.getPointer();
2449   llvm::Type *VTy = V->getType();
2450   auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2451   unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2452   llvm::PointerType *IntrinTy =
2453       llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
2454   llvm::Function *F =
2455       CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
2456 
2457   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2458     // FIXME Always emit the cast inst so we can differentiate between
2459     // annotation on the first field of a struct and annotation on the struct
2460     // itself.
2461     if (VTy != IntrinTy)
2462       V = Builder.CreateBitCast(V, IntrinTy);
2463     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
2464     V = Builder.CreateBitCast(V, VTy);
2465   }
2466 
2467   return Address(V, Addr.getAlignment());
2468 }
2469 
2470 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
2471 
2472 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
2473     : CGF(CGF) {
2474   assert(!CGF->IsSanitizerScope);
2475   CGF->IsSanitizerScope = true;
2476 }
2477 
2478 CodeGenFunction::SanitizerScope::~SanitizerScope() {
2479   CGF->IsSanitizerScope = false;
2480 }
2481 
2482 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
2483                                    const llvm::Twine &Name,
2484                                    llvm::BasicBlock *BB,
2485                                    llvm::BasicBlock::iterator InsertPt) const {
2486   LoopStack.InsertHelper(I);
2487   if (IsSanitizerScope)
2488     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
2489 }
2490 
2491 void CGBuilderInserter::InsertHelper(
2492     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
2493     llvm::BasicBlock::iterator InsertPt) const {
2494   llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
2495   if (CGF)
2496     CGF->InsertHelper(I, Name, BB, InsertPt);
2497 }
2498 
2499 // Emits an error if we don't have a valid set of target features for the
2500 // called function.
2501 void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
2502                                           const FunctionDecl *TargetDecl) {
2503   return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
2504 }
2505 
2506 // Emits an error if we don't have a valid set of target features for the
2507 // called function.
2508 void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
2509                                           const FunctionDecl *TargetDecl) {
2510   // Early exit if this is an indirect call.
2511   if (!TargetDecl)
2512     return;
2513 
2514   // Get the current enclosing function if it exists. If it doesn't
2515   // we can't check the target features anyhow.
2516   const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
2517   if (!FD)
2518     return;
2519 
2520   // Grab the required features for the call. For a builtin this is listed in
2521   // the td file with the default cpu, for an always_inline function this is any
2522   // listed cpu and any listed features.
2523   unsigned BuiltinID = TargetDecl->getBuiltinID();
2524   std::string MissingFeature;
2525   llvm::StringMap<bool> CallerFeatureMap;
2526   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
2527   if (BuiltinID) {
2528     StringRef FeatureList(
2529         CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
2530     // Return if the builtin doesn't have any required features.
2531     if (FeatureList.empty())
2532       return;
2533     assert(!FeatureList.contains(' ') && "Space in feature list");
2534     TargetFeatures TF(CallerFeatureMap);
2535     if (!TF.hasRequiredFeatures(FeatureList))
2536       CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
2537           << TargetDecl->getDeclName() << FeatureList;
2538   } else if (!TargetDecl->isMultiVersion() &&
2539              TargetDecl->hasAttr<TargetAttr>()) {
2540     // Get the required features for the callee.
2541 
2542     const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
2543     ParsedTargetAttr ParsedAttr =
2544         CGM.getContext().filterFunctionTargetAttrs(TD);
2545 
2546     SmallVector<StringRef, 1> ReqFeatures;
2547     llvm::StringMap<bool> CalleeFeatureMap;
2548     CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
2549 
2550     for (const auto &F : ParsedAttr.Features) {
2551       if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
2552         ReqFeatures.push_back(StringRef(F).substr(1));
2553     }
2554 
2555     for (const auto &F : CalleeFeatureMap) {
2556       // Only positive features are "required".
2557       if (F.getValue())
2558         ReqFeatures.push_back(F.getKey());
2559     }
2560     if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2561       if (!CallerFeatureMap.lookup(Feature)) {
2562         MissingFeature = Feature.str();
2563         return false;
2564       }
2565       return true;
2566     }))
2567       CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
2568           << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
2569   }
2570 }
2571 
2572 void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
2573   if (!CGM.getCodeGenOpts().SanitizeStats)
2574     return;
2575 
2576   llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
2577   IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
2578   CGM.getSanStats().create(IRB, SSK);
2579 }
2580 
2581 llvm::Value *
2582 CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
2583   llvm::Value *Condition = nullptr;
2584 
2585   if (!RO.Conditions.Architecture.empty())
2586     Condition = EmitX86CpuIs(RO.Conditions.Architecture);
2587 
2588   if (!RO.Conditions.Features.empty()) {
2589     llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
2590     Condition =
2591         Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
2592   }
2593   return Condition;
2594 }
2595 
2596 static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
2597                                              llvm::Function *Resolver,
2598                                              CGBuilderTy &Builder,
2599                                              llvm::Function *FuncToReturn,
2600                                              bool SupportsIFunc) {
2601   if (SupportsIFunc) {
2602     Builder.CreateRet(FuncToReturn);
2603     return;
2604   }
2605 
2606   llvm::SmallVector<llvm::Value *, 10> Args;
2607   llvm::for_each(Resolver->args(),
2608                  [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
2609 
2610   llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
2611   Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2612 
2613   if (Resolver->getReturnType()->isVoidTy())
2614     Builder.CreateRetVoid();
2615   else
2616     Builder.CreateRet(Result);
2617 }
2618 
2619 void CodeGenFunction::EmitMultiVersionResolver(
2620     llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
2621   assert(getContext().getTargetInfo().getTriple().isX86() &&
2622          "Only implemented for x86 targets");
2623 
2624   bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
2625 
2626   // Main function's basic block.
2627   llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
2628   Builder.SetInsertPoint(CurBlock);
2629   EmitX86CpuInit();
2630 
2631   for (const MultiVersionResolverOption &RO : Options) {
2632     Builder.SetInsertPoint(CurBlock);
2633     llvm::Value *Condition = FormResolverCondition(RO);
2634 
2635     // The 'default' or 'generic' case.
2636     if (!Condition) {
2637       assert(&RO == Options.end() - 1 &&
2638              "Default or Generic case must be last");
2639       CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
2640                                        SupportsIFunc);
2641       return;
2642     }
2643 
2644     llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
2645     CGBuilderTy RetBuilder(*this, RetBlock);
2646     CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
2647                                      SupportsIFunc);
2648     CurBlock = createBasicBlock("resolver_else", Resolver);
2649     Builder.CreateCondBr(Condition, RetBlock, CurBlock);
2650   }
2651 
2652   // If no generic/default, emit an unreachable.
2653   Builder.SetInsertPoint(CurBlock);
2654   llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2655   TrapCall->setDoesNotReturn();
2656   TrapCall->setDoesNotThrow();
2657   Builder.CreateUnreachable();
2658   Builder.ClearInsertionPoint();
2659 }
2660 
2661 // Loc - where the diagnostic will point, where in the source code this
2662 //  alignment has failed.
2663 // SecondaryLoc - if present (will be present if sufficiently different from
2664 //  Loc), the diagnostic will additionally point a "Note:" to this location.
2665 //  It should be the location where the __attribute__((assume_aligned))
2666 //  was written e.g.
2667 void CodeGenFunction::emitAlignmentAssumptionCheck(
2668     llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
2669     SourceLocation SecondaryLoc, llvm::Value *Alignment,
2670     llvm::Value *OffsetValue, llvm::Value *TheCheck,
2671     llvm::Instruction *Assumption) {
2672   assert(Assumption && isa<llvm::CallInst>(Assumption) &&
2673          cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
2674              llvm::Intrinsic::getDeclaration(
2675                  Builder.GetInsertBlock()->getParent()->getParent(),
2676                  llvm::Intrinsic::assume) &&
2677          "Assumption should be a call to llvm.assume().");
2678   assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
2679          "Assumption should be the last instruction of the basic block, "
2680          "since the basic block is still being generated.");
2681 
2682   if (!SanOpts.has(SanitizerKind::Alignment))
2683     return;
2684 
2685   // Don't check pointers to volatile data. The behavior here is implementation-
2686   // defined.
2687   if (Ty->getPointeeType().isVolatileQualified())
2688     return;
2689 
2690   // We need to temorairly remove the assumption so we can insert the
2691   // sanitizer check before it, else the check will be dropped by optimizations.
2692   Assumption->removeFromParent();
2693 
2694   {
2695     SanitizerScope SanScope(this);
2696 
2697     if (!OffsetValue)
2698       OffsetValue = Builder.getInt1(0); // no offset.
2699 
2700     llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
2701                                     EmitCheckSourceLocation(SecondaryLoc),
2702                                     EmitCheckTypeDescriptor(Ty)};
2703     llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
2704                                   EmitCheckValue(Alignment),
2705                                   EmitCheckValue(OffsetValue)};
2706     EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
2707               SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
2708   }
2709 
2710   // We are now in the (new, empty) "cont" basic block.
2711   // Reintroduce the assumption.
2712   Builder.Insert(Assumption);
2713   // FIXME: Assumption still has it's original basic block as it's Parent.
2714 }
2715 
2716 llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
2717   if (CGDebugInfo *DI = getDebugInfo())
2718     return DI->SourceLocToDebugLoc(Location);
2719 
2720   return llvm::DebugLoc();
2721 }
2722 
2723 llvm::Value *
2724 CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
2725                                                       Stmt::Likelihood LH) {
2726   switch (LH) {
2727   case Stmt::LH_None:
2728     return Cond;
2729   case Stmt::LH_Likely:
2730   case Stmt::LH_Unlikely:
2731     // Don't generate llvm.expect on -O0 as the backend won't use it for
2732     // anything.
2733     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2734       return Cond;
2735     llvm::Type *CondTy = Cond->getType();
2736     assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
2737     llvm::Function *FnExpect =
2738         CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
2739     llvm::Value *ExpectedValueOfCond =
2740         llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
2741     return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
2742                               Cond->getName() + ".expval");
2743   }
2744   llvm_unreachable("Unknown Likelihood");
2745 }
2746