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