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