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