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