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