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