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