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