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