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