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