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