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 "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGOpenMPRuntime.h"
19 #include "CodeGenModule.h"
20 #include "CodeGenPGO.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/CodeGen/CGFunctionInfo.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Operator.h"
33 using namespace clang;
34 using namespace CodeGen;
35 
36 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
37     : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
38       Builder(cgm.getModule().getContext(), llvm::ConstantFolder(),
39               CGBuilderInserterTy(this)),
40       CapturedStmtInfo(nullptr), SanOpts(&CGM.getLangOpts().Sanitize),
41       IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
42       SawAsmBlock(false), BlockInfo(nullptr), BlockPointer(nullptr),
43       LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr),
44       NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr),
45       ExceptionSlot(nullptr), EHSelectorSlot(nullptr),
46       DebugInfo(CGM.getModuleDebugInfo()), DisableDebugInfo(false),
47       DidCallStackSave(false), IndirectBranch(nullptr), PGO(cgm),
48       SwitchInsn(nullptr), SwitchWeights(nullptr), CaseRangeBlock(nullptr),
49       UnreachableBlock(nullptr), NumReturnExprs(0), NumSimpleReturnExprs(0),
50       CXXABIThisDecl(nullptr), CXXABIThisValue(nullptr), CXXThisValue(nullptr),
51       CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr),
52       CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
53       CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
54       TerminateHandler(nullptr), TrapBB(nullptr) {
55   if (!suppressNewContext)
56     CGM.getCXXABI().getMangleContext().startNewFunction();
57 
58   llvm::FastMathFlags FMF;
59   if (CGM.getLangOpts().FastMath)
60     FMF.setUnsafeAlgebra();
61   if (CGM.getLangOpts().FiniteMathOnly) {
62     FMF.setNoNaNs();
63     FMF.setNoInfs();
64   }
65   Builder.SetFastMathFlags(FMF);
66 }
67 
68 CodeGenFunction::~CodeGenFunction() {
69   assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
70 
71   // If there are any unclaimed block infos, go ahead and destroy them
72   // now.  This can happen if IR-gen gets clever and skips evaluating
73   // something.
74   if (FirstBlockInfo)
75     destroyBlockInfos(FirstBlockInfo);
76 
77   if (getLangOpts().OpenMP) {
78     CGM.getOpenMPRuntime().FunctionFinished(*this);
79   }
80 }
81 
82 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
83   CharUnits Alignment;
84   if (CGM.getCXXABI().isTypeInfoCalculable(T)) {
85     Alignment = getContext().getTypeAlignInChars(T);
86     unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign;
87     if (MaxAlign && Alignment.getQuantity() > MaxAlign &&
88         !getContext().isAlignmentRequired(T))
89       Alignment = CharUnits::fromQuantity(MaxAlign);
90   }
91   return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T));
92 }
93 
94 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
95   return CGM.getTypes().ConvertTypeForMem(T);
96 }
97 
98 llvm::Type *CodeGenFunction::ConvertType(QualType T) {
99   return CGM.getTypes().ConvertType(T);
100 }
101 
102 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
103   type = type.getCanonicalType();
104   while (true) {
105     switch (type->getTypeClass()) {
106 #define TYPE(name, parent)
107 #define ABSTRACT_TYPE(name, parent)
108 #define NON_CANONICAL_TYPE(name, parent) case Type::name:
109 #define DEPENDENT_TYPE(name, parent) case Type::name:
110 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
111 #include "clang/AST/TypeNodes.def"
112       llvm_unreachable("non-canonical or dependent type in IR-generation");
113 
114     case Type::Auto:
115       llvm_unreachable("undeduced auto type in IR-generation");
116 
117     // Various scalar types.
118     case Type::Builtin:
119     case Type::Pointer:
120     case Type::BlockPointer:
121     case Type::LValueReference:
122     case Type::RValueReference:
123     case Type::MemberPointer:
124     case Type::Vector:
125     case Type::ExtVector:
126     case Type::FunctionProto:
127     case Type::FunctionNoProto:
128     case Type::Enum:
129     case Type::ObjCObjectPointer:
130       return TEK_Scalar;
131 
132     // Complexes.
133     case Type::Complex:
134       return TEK_Complex;
135 
136     // Arrays, records, and Objective-C objects.
137     case Type::ConstantArray:
138     case Type::IncompleteArray:
139     case Type::VariableArray:
140     case Type::Record:
141     case Type::ObjCObject:
142     case Type::ObjCInterface:
143       return TEK_Aggregate;
144 
145     // We operate on atomic values according to their underlying type.
146     case Type::Atomic:
147       type = cast<AtomicType>(type)->getValueType();
148       continue;
149     }
150     llvm_unreachable("unknown type kind!");
151   }
152 }
153 
154 void CodeGenFunction::EmitReturnBlock() {
155   // For cleanliness, we try to avoid emitting the return block for
156   // simple cases.
157   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
158 
159   if (CurBB) {
160     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
161 
162     // We have a valid insert point, reuse it if it is empty or there are no
163     // explicit jumps to the return block.
164     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
165       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
166       delete ReturnBlock.getBlock();
167     } else
168       EmitBlock(ReturnBlock.getBlock());
169     return;
170   }
171 
172   // Otherwise, if the return block is the target of a single direct
173   // branch then we can just put the code in that block instead. This
174   // cleans up functions which started with a unified return block.
175   if (ReturnBlock.getBlock()->hasOneUse()) {
176     llvm::BranchInst *BI =
177       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
178     if (BI && BI->isUnconditional() &&
179         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
180       // Reset insertion point, including debug location, and delete the
181       // branch.  This is really subtle and only works because the next change
182       // in location will hit the caching in CGDebugInfo::EmitLocation and not
183       // override this.
184       Builder.SetCurrentDebugLocation(BI->getDebugLoc());
185       Builder.SetInsertPoint(BI->getParent());
186       BI->eraseFromParent();
187       delete ReturnBlock.getBlock();
188       return;
189     }
190   }
191 
192   // FIXME: We are at an unreachable point, there is no reason to emit the block
193   // unless it has uses. However, we still need a place to put the debug
194   // region.end for now.
195 
196   EmitBlock(ReturnBlock.getBlock());
197 }
198 
199 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
200   if (!BB) return;
201   if (!BB->use_empty())
202     return CGF.CurFn->getBasicBlockList().push_back(BB);
203   delete BB;
204 }
205 
206 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
207   assert(BreakContinueStack.empty() &&
208          "mismatched push/pop in break/continue stack!");
209 
210   bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
211     && NumSimpleReturnExprs == NumReturnExprs
212     && ReturnBlock.getBlock()->use_empty();
213   // Usually the return expression is evaluated before the cleanup
214   // code.  If the function contains only a simple return statement,
215   // such as a constant, the location before the cleanup code becomes
216   // the last useful breakpoint in the function, because the simple
217   // return expression will be evaluated after the cleanup code. To be
218   // safe, set the debug location for cleanup code to the location of
219   // the return statement.  Otherwise the cleanup code should be at the
220   // end of the function's lexical scope.
221   //
222   // If there are multiple branches to the return block, the branch
223   // instructions will get the location of the return statements and
224   // all will be fine.
225   if (CGDebugInfo *DI = getDebugInfo()) {
226     if (OnlySimpleReturnStmts)
227       DI->EmitLocation(Builder, LastStopPoint);
228     else
229       DI->EmitLocation(Builder, EndLoc);
230   }
231 
232   // Pop any cleanups that might have been associated with the
233   // parameters.  Do this in whatever block we're currently in; it's
234   // important to do this before we enter the return block or return
235   // edges will be *really* confused.
236   bool EmitRetDbgLoc = true;
237   if (EHStack.stable_begin() != PrologueCleanupDepth) {
238     PopCleanupBlocks(PrologueCleanupDepth);
239 
240     // Make sure the line table doesn't jump back into the body for
241     // the ret after it's been at EndLoc.
242     EmitRetDbgLoc = false;
243 
244     if (CGDebugInfo *DI = getDebugInfo())
245       if (OnlySimpleReturnStmts)
246         DI->EmitLocation(Builder, EndLoc);
247   }
248 
249   // Emit function epilog (to return).
250   EmitReturnBlock();
251 
252   if (ShouldInstrumentFunction())
253     EmitFunctionInstrumentation("__cyg_profile_func_exit");
254 
255   // Emit debug descriptor for function end.
256   if (CGDebugInfo *DI = getDebugInfo()) {
257     DI->EmitFunctionEnd(Builder);
258   }
259 
260   EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
261   EmitEndEHSpec(CurCodeDecl);
262 
263   assert(EHStack.empty() &&
264          "did not remove all scopes from cleanup stack!");
265 
266   // If someone did an indirect goto, emit the indirect goto block at the end of
267   // the function.
268   if (IndirectBranch) {
269     EmitBlock(IndirectBranch->getParent());
270     Builder.ClearInsertionPoint();
271   }
272 
273   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
274   llvm::Instruction *Ptr = AllocaInsertPt;
275   AllocaInsertPt = nullptr;
276   Ptr->eraseFromParent();
277 
278   // If someone took the address of a label but never did an indirect goto, we
279   // made a zero entry PHI node, which is illegal, zap it now.
280   if (IndirectBranch) {
281     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
282     if (PN->getNumIncomingValues() == 0) {
283       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
284       PN->eraseFromParent();
285     }
286   }
287 
288   EmitIfUsed(*this, EHResumeBlock);
289   EmitIfUsed(*this, TerminateLandingPad);
290   EmitIfUsed(*this, TerminateHandler);
291   EmitIfUsed(*this, UnreachableBlock);
292 
293   if (CGM.getCodeGenOpts().EmitDeclMetadata)
294     EmitDeclMetadata();
295 
296   for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
297            I = DeferredReplacements.begin(),
298            E = DeferredReplacements.end();
299        I != E; ++I) {
300     I->first->replaceAllUsesWith(I->second);
301     I->first->eraseFromParent();
302   }
303 }
304 
305 /// ShouldInstrumentFunction - Return true if the current function should be
306 /// instrumented with __cyg_profile_func_* calls
307 bool CodeGenFunction::ShouldInstrumentFunction() {
308   if (!CGM.getCodeGenOpts().InstrumentFunctions)
309     return false;
310   if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
311     return false;
312   return true;
313 }
314 
315 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
316 /// instrumentation function with the current function and the call site, if
317 /// function instrumentation is enabled.
318 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
319   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
320   llvm::PointerType *PointerTy = Int8PtrTy;
321   llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
322   llvm::FunctionType *FunctionTy =
323     llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
324 
325   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
326   llvm::CallInst *CallSite = Builder.CreateCall(
327     CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
328     llvm::ConstantInt::get(Int32Ty, 0),
329     "callsite");
330 
331   llvm::Value *args[] = {
332     llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
333     CallSite
334   };
335 
336   EmitNounwindRuntimeCall(F, args);
337 }
338 
339 void CodeGenFunction::EmitMCountInstrumentation() {
340   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
341 
342   llvm::Constant *MCountFn =
343     CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
344   EmitNounwindRuntimeCall(MCountFn);
345 }
346 
347 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
348 // information in the program executable. The argument information stored
349 // includes the argument name, its type, the address and access qualifiers used.
350 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
351                                  CodeGenModule &CGM,llvm::LLVMContext &Context,
352                                  SmallVector <llvm::Value*, 5> &kernelMDArgs,
353                                  CGBuilderTy& Builder, ASTContext &ASTCtx) {
354   // Create MDNodes that represent the kernel arg metadata.
355   // Each MDNode is a list in the form of "key", N number of values which is
356   // the same number of values as their are kernel arguments.
357 
358   const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
359 
360   // MDNode for the kernel argument address space qualifiers.
361   SmallVector<llvm::Value*, 8> addressQuals;
362   addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
363 
364   // MDNode for the kernel argument access qualifiers (images only).
365   SmallVector<llvm::Value*, 8> accessQuals;
366   accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
367 
368   // MDNode for the kernel argument type names.
369   SmallVector<llvm::Value*, 8> argTypeNames;
370   argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
371 
372   // MDNode for the kernel argument base type names.
373   SmallVector<llvm::Value*, 8> argBaseTypeNames;
374   argBaseTypeNames.push_back(
375       llvm::MDString::get(Context, "kernel_arg_base_type"));
376 
377   // MDNode for the kernel argument type qualifiers.
378   SmallVector<llvm::Value*, 8> argTypeQuals;
379   argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
380 
381   // MDNode for the kernel argument names.
382   SmallVector<llvm::Value*, 8> argNames;
383   argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
384 
385   for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
386     const ParmVarDecl *parm = FD->getParamDecl(i);
387     QualType ty = parm->getType();
388     std::string typeQuals;
389 
390     if (ty->isPointerType()) {
391       QualType pointeeTy = ty->getPointeeType();
392 
393       // Get address qualifier.
394       addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
395         pointeeTy.getAddressSpace())));
396 
397       // Get argument type name.
398       std::string typeName =
399           pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
400 
401       // Turn "unsigned type" to "utype"
402       std::string::size_type pos = typeName.find("unsigned");
403       if (pointeeTy.isCanonical() && pos != std::string::npos)
404         typeName.erase(pos+1, 8);
405 
406       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
407 
408       std::string baseTypeName =
409           pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
410               Policy) +
411           "*";
412 
413       // Turn "unsigned type" to "utype"
414       pos = baseTypeName.find("unsigned");
415       if (pos != std::string::npos)
416         baseTypeName.erase(pos+1, 8);
417 
418       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
419 
420       // Get argument type qualifiers:
421       if (ty.isRestrictQualified())
422         typeQuals = "restrict";
423       if (pointeeTy.isConstQualified() ||
424           (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
425         typeQuals += typeQuals.empty() ? "const" : " const";
426       if (pointeeTy.isVolatileQualified())
427         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
428     } else {
429       uint32_t AddrSpc = 0;
430       if (ty->isImageType())
431         AddrSpc =
432           CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
433 
434       addressQuals.push_back(Builder.getInt32(AddrSpc));
435 
436       // Get argument type name.
437       std::string typeName = ty.getUnqualifiedType().getAsString(Policy);
438 
439       // Turn "unsigned type" to "utype"
440       std::string::size_type pos = typeName.find("unsigned");
441       if (ty.isCanonical() && pos != std::string::npos)
442         typeName.erase(pos+1, 8);
443 
444       argTypeNames.push_back(llvm::MDString::get(Context, typeName));
445 
446       std::string baseTypeName =
447           ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
448 
449       // Turn "unsigned type" to "utype"
450       pos = baseTypeName.find("unsigned");
451       if (pos != std::string::npos)
452         baseTypeName.erase(pos+1, 8);
453 
454       argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
455 
456       // Get argument type qualifiers:
457       if (ty.isConstQualified())
458         typeQuals = "const";
459       if (ty.isVolatileQualified())
460         typeQuals += typeQuals.empty() ? "volatile" : " volatile";
461     }
462 
463     argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
464 
465     // Get image access qualifier:
466     if (ty->isImageType()) {
467       const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>();
468       if (A && A->isWriteOnly())
469         accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
470       else
471         accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
472       // FIXME: what about read_write?
473     } else
474       accessQuals.push_back(llvm::MDString::get(Context, "none"));
475 
476     // Get argument name.
477     argNames.push_back(llvm::MDString::get(Context, parm->getName()));
478   }
479 
480   kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
481   kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
482   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
483   kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames));
484   kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
485   kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
486 }
487 
488 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
489                                                llvm::Function *Fn)
490 {
491   if (!FD->hasAttr<OpenCLKernelAttr>())
492     return;
493 
494   llvm::LLVMContext &Context = getLLVMContext();
495 
496   SmallVector <llvm::Value*, 5> kernelMDArgs;
497   kernelMDArgs.push_back(Fn);
498 
499   if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
500     GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
501                          Builder, getContext());
502 
503   if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
504     QualType hintQTy = A->getTypeHint();
505     const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
506     bool isSignedInteger =
507         hintQTy->isSignedIntegerType() ||
508         (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
509     llvm::Value *attrMDArgs[] = {
510       llvm::MDString::get(Context, "vec_type_hint"),
511       llvm::UndefValue::get(CGM.getTypes().ConvertType(A->getTypeHint())),
512       llvm::ConstantInt::get(
513           llvm::IntegerType::get(Context, 32),
514           llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
515     };
516     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
517   }
518 
519   if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
520     llvm::Value *attrMDArgs[] = {
521       llvm::MDString::get(Context, "work_group_size_hint"),
522       Builder.getInt32(A->getXDim()),
523       Builder.getInt32(A->getYDim()),
524       Builder.getInt32(A->getZDim())
525     };
526     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
527   }
528 
529   if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
530     llvm::Value *attrMDArgs[] = {
531       llvm::MDString::get(Context, "reqd_work_group_size"),
532       Builder.getInt32(A->getXDim()),
533       Builder.getInt32(A->getYDim()),
534       Builder.getInt32(A->getZDim())
535     };
536     kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
537   }
538 
539   llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
540   llvm::NamedMDNode *OpenCLKernelMetadata =
541     CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
542   OpenCLKernelMetadata->addOperand(kernelMDNode);
543 }
544 
545 /// Determine whether the function F ends with a return stmt.
546 static bool endsWithReturn(const Decl* F) {
547   const Stmt *Body = nullptr;
548   if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
549     Body = FD->getBody();
550   else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
551     Body = OMD->getBody();
552 
553   if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
554     auto LastStmt = CS->body_rbegin();
555     if (LastStmt != CS->body_rend())
556       return isa<ReturnStmt>(*LastStmt);
557   }
558   return false;
559 }
560 
561 void CodeGenFunction::StartFunction(GlobalDecl GD,
562                                     QualType RetTy,
563                                     llvm::Function *Fn,
564                                     const CGFunctionInfo &FnInfo,
565                                     const FunctionArgList &Args,
566                                     SourceLocation Loc,
567                                     SourceLocation StartLoc) {
568   const Decl *D = GD.getDecl();
569 
570   DidCallStackSave = false;
571   CurCodeDecl = D;
572   CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
573   FnRetTy = RetTy;
574   CurFn = Fn;
575   CurFnInfo = &FnInfo;
576   assert(CurFn->isDeclaration() && "Function already has body?");
577 
578   if (CGM.getSanitizerBlacklist().isIn(*Fn))
579     SanOpts = &SanitizerOptions::Disabled;
580 
581   // Pass inline keyword to optimizer if it appears explicitly on any
582   // declaration. Also, in the case of -fno-inline attach NoInline
583   // attribute to all function that are not marked AlwaysInline.
584   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
585     if (!CGM.getCodeGenOpts().NoInline) {
586       for (auto RI : FD->redecls())
587         if (RI->isInlineSpecified()) {
588           Fn->addFnAttr(llvm::Attribute::InlineHint);
589           break;
590         }
591     } else if (!FD->hasAttr<AlwaysInlineAttr>())
592       Fn->addFnAttr(llvm::Attribute::NoInline);
593   }
594 
595   if (getLangOpts().OpenCL) {
596     // Add metadata for a kernel function.
597     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
598       EmitOpenCLKernelMetadata(FD, Fn);
599   }
600 
601   // If we are checking function types, emit a function type signature as
602   // prefix data.
603   if (getLangOpts().CPlusPlus && SanOpts->Function) {
604     if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
605       if (llvm::Constant *PrefixSig =
606               CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
607         llvm::Constant *FTRTTIConst =
608             CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
609         llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
610         llvm::Constant *PrefixStructConst =
611             llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
612         Fn->setPrefixData(PrefixStructConst);
613       }
614     }
615   }
616 
617   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
618 
619   // Create a marker to make it easy to insert allocas into the entryblock
620   // later.  Don't create this with the builder, because we don't want it
621   // folded.
622   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
623   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
624   if (Builder.isNamePreserving())
625     AllocaInsertPt->setName("allocapt");
626 
627   ReturnBlock = getJumpDestInCurrentScope("return");
628 
629   Builder.SetInsertPoint(EntryBB);
630 
631   // Emit subprogram debug descriptor.
632   if (CGDebugInfo *DI = getDebugInfo()) {
633     SmallVector<QualType, 16> ArgTypes;
634     for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
635 	 i != e; ++i) {
636       ArgTypes.push_back((*i)->getType());
637     }
638 
639     QualType FnType =
640       getContext().getFunctionType(RetTy, ArgTypes,
641                                    FunctionProtoType::ExtProtoInfo());
642     DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
643   }
644 
645   if (ShouldInstrumentFunction())
646     EmitFunctionInstrumentation("__cyg_profile_func_enter");
647 
648   if (CGM.getCodeGenOpts().InstrumentForProfiling)
649     EmitMCountInstrumentation();
650 
651   if (RetTy->isVoidType()) {
652     // Void type; nothing to return.
653     ReturnValue = nullptr;
654 
655     // Count the implicit return.
656     if (!endsWithReturn(D))
657       ++NumReturnExprs;
658   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
659              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
660     // Indirect aggregate return; emit returned value directly into sret slot.
661     // This reduces code size, and affects correctness in C++.
662     auto AI = CurFn->arg_begin();
663     if (CurFnInfo->getReturnInfo().isSRetAfterThis())
664       ++AI;
665     ReturnValue = AI;
666   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
667              !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
668     // Load the sret pointer from the argument struct and return into that.
669     unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
670     llvm::Function::arg_iterator EI = CurFn->arg_end();
671     --EI;
672     llvm::Value *Addr = Builder.CreateStructGEP(EI, Idx);
673     ReturnValue = Builder.CreateLoad(Addr, "agg.result");
674   } else {
675     ReturnValue = CreateIRTemp(RetTy, "retval");
676 
677     // Tell the epilog emitter to autorelease the result.  We do this
678     // now so that various specialized functions can suppress it
679     // during their IR-generation.
680     if (getLangOpts().ObjCAutoRefCount &&
681         !CurFnInfo->isReturnsRetained() &&
682         RetTy->isObjCRetainableType())
683       AutoreleaseResult = true;
684   }
685 
686   EmitStartEHSpec(CurCodeDecl);
687 
688   PrologueCleanupDepth = EHStack.stable_begin();
689   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
690 
691   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
692     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
693     const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
694     if (MD->getParent()->isLambda() &&
695         MD->getOverloadedOperator() == OO_Call) {
696       // We're in a lambda; figure out the captures.
697       MD->getParent()->getCaptureFields(LambdaCaptureFields,
698                                         LambdaThisCaptureField);
699       if (LambdaThisCaptureField) {
700         // If this lambda captures this, load it.
701         LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
702         CXXThisValue = EmitLoadOfLValue(ThisLValue,
703                                         SourceLocation()).getScalarVal();
704       }
705       for (auto *FD : MD->getParent()->fields()) {
706         if (FD->hasCapturedVLAType()) {
707           auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
708                                            SourceLocation()).getScalarVal();
709           auto VAT = FD->getCapturedVLAType();
710           VLASizeMap[VAT->getSizeExpr()] = ExprArg;
711         }
712       }
713     } else {
714       // Not in a lambda; just use 'this' from the method.
715       // FIXME: Should we generate a new load for each use of 'this'?  The
716       // fast register allocator would be happier...
717       CXXThisValue = CXXABIThisValue;
718     }
719   }
720 
721   // If any of the arguments have a variably modified type, make sure to
722   // emit the type size.
723   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
724        i != e; ++i) {
725     const VarDecl *VD = *i;
726 
727     // Dig out the type as written from ParmVarDecls; it's unclear whether
728     // the standard (C99 6.9.1p10) requires this, but we're following the
729     // precedent set by gcc.
730     QualType Ty;
731     if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
732       Ty = PVD->getOriginalType();
733     else
734       Ty = VD->getType();
735 
736     if (Ty->isVariablyModifiedType())
737       EmitVariablyModifiedType(Ty);
738   }
739   // Emit a location at the end of the prologue.
740   if (CGDebugInfo *DI = getDebugInfo())
741     DI->EmitLocation(Builder, StartLoc);
742 }
743 
744 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
745                                        const Stmt *Body) {
746   RegionCounter Cnt = getPGORegionCounter(Body);
747   Cnt.beginRegion(Builder);
748   if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
749     EmitCompoundStmtWithoutScope(*S);
750   else
751     EmitStmt(Body);
752 }
753 
754 /// When instrumenting to collect profile data, the counts for some blocks
755 /// such as switch cases need to not include the fall-through counts, so
756 /// emit a branch around the instrumentation code. When not instrumenting,
757 /// this just calls EmitBlock().
758 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
759                                                RegionCounter &Cnt) {
760   llvm::BasicBlock *SkipCountBB = nullptr;
761   if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) {
762     // When instrumenting for profiling, the fallthrough to certain
763     // statements needs to skip over the instrumentation code so that we
764     // get an accurate count.
765     SkipCountBB = createBasicBlock("skipcount");
766     EmitBranch(SkipCountBB);
767   }
768   EmitBlock(BB);
769   Cnt.beginRegion(Builder, /*AddIncomingFallThrough=*/true);
770   if (SkipCountBB)
771     EmitBlock(SkipCountBB);
772 }
773 
774 /// Tries to mark the given function nounwind based on the
775 /// non-existence of any throwing calls within it.  We believe this is
776 /// lightweight enough to do at -O0.
777 static void TryMarkNoThrow(llvm::Function *F) {
778   // LLVM treats 'nounwind' on a function as part of the type, so we
779   // can't do this on functions that can be overwritten.
780   if (F->mayBeOverridden()) return;
781 
782   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
783     for (llvm::BasicBlock::iterator
784            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
785       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
786         if (!Call->doesNotThrow())
787           return;
788       } else if (isa<llvm::ResumeInst>(&*BI)) {
789         return;
790       }
791   F->setDoesNotThrow();
792 }
793 
794 static void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
795                                           const FunctionDecl *UnsizedDealloc) {
796   // This is a weak discardable definition of the sized deallocation function.
797   CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
798 
799   // Call the unsized deallocation function and forward the first argument
800   // unchanged.
801   llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
802   CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
803 }
804 
805 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
806                                    const CGFunctionInfo &FnInfo) {
807   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
808 
809   // Check if we should generate debug info for this function.
810   if (FD->hasAttr<NoDebugAttr>())
811     DebugInfo = nullptr; // disable debug info indefinitely for this function
812 
813   FunctionArgList Args;
814   QualType ResTy = FD->getReturnType();
815 
816   CurGD = GD;
817   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
818   if (MD && MD->isInstance()) {
819     if (CGM.getCXXABI().HasThisReturn(GD))
820       ResTy = MD->getThisType(getContext());
821     CGM.getCXXABI().buildThisParam(*this, Args);
822   }
823 
824   Args.append(FD->param_begin(), FD->param_end());
825 
826   if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
827     CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
828 
829   SourceRange BodyRange;
830   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
831   CurEHLocation = BodyRange.getEnd();
832 
833   // Use the location of the start of the function to determine where
834   // the function definition is located. By default use the location
835   // of the declaration as the location for the subprogram. A function
836   // may lack a declaration in the source code if it is created by code
837   // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
838   SourceLocation Loc = FD->getLocation();
839 
840   // If this is a function specialization then use the pattern body
841   // as the location for the function.
842   if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
843     if (SpecDecl->hasBody(SpecDecl))
844       Loc = SpecDecl->getLocation();
845 
846   // Emit the standard function prologue.
847   StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
848 
849   // Generate the body of the function.
850   PGO.checkGlobalDecl(GD);
851   PGO.assignRegionCounters(GD.getDecl(), CurFn);
852   if (isa<CXXDestructorDecl>(FD))
853     EmitDestructorBody(Args);
854   else if (isa<CXXConstructorDecl>(FD))
855     EmitConstructorBody(Args);
856   else if (getLangOpts().CUDA &&
857            !CGM.getCodeGenOpts().CUDAIsDevice &&
858            FD->hasAttr<CUDAGlobalAttr>())
859     CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
860   else if (isa<CXXConversionDecl>(FD) &&
861            cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
862     // The lambda conversion to block pointer is special; the semantics can't be
863     // expressed in the AST, so IRGen needs to special-case it.
864     EmitLambdaToBlockPointerBody(Args);
865   } else if (isa<CXXMethodDecl>(FD) &&
866              cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
867     // The lambda static invoker function is special, because it forwards or
868     // clones the body of the function call operator (but is actually static).
869     EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
870   } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
871              (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
872               cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
873     // Implicit copy-assignment gets the same special treatment as implicit
874     // copy-constructors.
875     emitImplicitAssignmentOperatorBody(Args);
876   } else if (Stmt *Body = FD->getBody()) {
877     EmitFunctionBody(Args, Body);
878   } else if (FunctionDecl *UnsizedDealloc =
879                  FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
880     // Global sized deallocation functions get an implicit weak definition if
881     // they don't have an explicit definition.
882     EmitSizedDeallocationFunction(*this, UnsizedDealloc);
883   } else
884     llvm_unreachable("no definition for emitted function");
885 
886   // C++11 [stmt.return]p2:
887   //   Flowing off the end of a function [...] results in undefined behavior in
888   //   a value-returning function.
889   // C11 6.9.1p12:
890   //   If the '}' that terminates a function is reached, and the value of the
891   //   function call is used by the caller, the behavior is undefined.
892   if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
893       !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
894     if (SanOpts->Return) {
895       SanitizerScope SanScope(this);
896       EmitCheck(Builder.getFalse(), "missing_return",
897                 EmitCheckSourceLocation(FD->getLocation()),
898                 None, CRK_Unrecoverable);
899     } else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
900       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
901     Builder.CreateUnreachable();
902     Builder.ClearInsertionPoint();
903   }
904 
905   // Emit the standard function epilogue.
906   FinishFunction(BodyRange.getEnd());
907 
908   // If we haven't marked the function nothrow through other means, do
909   // a quick pass now to see if we can.
910   if (!CurFn->doesNotThrow())
911     TryMarkNoThrow(CurFn);
912 
913   PGO.emitInstrumentationData();
914   PGO.destroyRegionCounters();
915 }
916 
917 /// ContainsLabel - Return true if the statement contains a label in it.  If
918 /// this statement is not executed normally, it not containing a label means
919 /// that we can just remove the code.
920 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
921   // Null statement, not a label!
922   if (!S) return false;
923 
924   // If this is a label, we have to emit the code, consider something like:
925   // if (0) {  ...  foo:  bar(); }  goto foo;
926   //
927   // TODO: If anyone cared, we could track __label__'s, since we know that you
928   // can't jump to one from outside their declared region.
929   if (isa<LabelStmt>(S))
930     return true;
931 
932   // If this is a case/default statement, and we haven't seen a switch, we have
933   // to emit the code.
934   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
935     return true;
936 
937   // If this is a switch statement, we want to ignore cases below it.
938   if (isa<SwitchStmt>(S))
939     IgnoreCaseStmts = true;
940 
941   // Scan subexpressions for verboten labels.
942   for (Stmt::const_child_range I = S->children(); I; ++I)
943     if (ContainsLabel(*I, IgnoreCaseStmts))
944       return true;
945 
946   return false;
947 }
948 
949 /// containsBreak - Return true if the statement contains a break out of it.
950 /// If the statement (recursively) contains a switch or loop with a break
951 /// inside of it, this is fine.
952 bool CodeGenFunction::containsBreak(const Stmt *S) {
953   // Null statement, not a label!
954   if (!S) return false;
955 
956   // If this is a switch or loop that defines its own break scope, then we can
957   // include it and anything inside of it.
958   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
959       isa<ForStmt>(S))
960     return false;
961 
962   if (isa<BreakStmt>(S))
963     return true;
964 
965   // Scan subexpressions for verboten breaks.
966   for (Stmt::const_child_range I = S->children(); I; ++I)
967     if (containsBreak(*I))
968       return true;
969 
970   return false;
971 }
972 
973 
974 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
975 /// to a constant, or if it does but contains a label, return false.  If it
976 /// constant folds return true and set the boolean result in Result.
977 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
978                                                    bool &ResultBool) {
979   llvm::APSInt ResultInt;
980   if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
981     return false;
982 
983   ResultBool = ResultInt.getBoolValue();
984   return true;
985 }
986 
987 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
988 /// to a constant, or if it does but contains a label, return false.  If it
989 /// constant folds return true and set the folded value.
990 bool CodeGenFunction::
991 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
992   // FIXME: Rename and handle conversion of other evaluatable things
993   // to bool.
994   llvm::APSInt Int;
995   if (!Cond->EvaluateAsInt(Int, getContext()))
996     return false;  // Not foldable, not integer or not fully evaluatable.
997 
998   if (CodeGenFunction::ContainsLabel(Cond))
999     return false;  // Contains a label.
1000 
1001   ResultInt = Int;
1002   return true;
1003 }
1004 
1005 
1006 
1007 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
1008 /// statement) to the specified blocks.  Based on the condition, this might try
1009 /// to simplify the codegen of the conditional based on the branch.
1010 ///
1011 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
1012                                            llvm::BasicBlock *TrueBlock,
1013                                            llvm::BasicBlock *FalseBlock,
1014                                            uint64_t TrueCount) {
1015   Cond = Cond->IgnoreParens();
1016 
1017   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1018 
1019     // Handle X && Y in a condition.
1020     if (CondBOp->getOpcode() == BO_LAnd) {
1021       RegionCounter Cnt = getPGORegionCounter(CondBOp);
1022 
1023       // If we have "1 && X", simplify the code.  "0 && X" would have constant
1024       // folded if the case was simple enough.
1025       bool ConstantBool = false;
1026       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1027           ConstantBool) {
1028         // br(1 && X) -> br(X).
1029         Cnt.beginRegion(Builder);
1030         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1031                                     TrueCount);
1032       }
1033 
1034       // If we have "X && 1", simplify the code to use an uncond branch.
1035       // "X && 0" would have been constant folded to 0.
1036       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1037           ConstantBool) {
1038         // br(X && 1) -> br(X).
1039         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1040                                     TrueCount);
1041       }
1042 
1043       // Emit the LHS as a conditional.  If the LHS conditional is false, we
1044       // want to jump to the FalseBlock.
1045       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
1046       // The counter tells us how often we evaluate RHS, and all of TrueCount
1047       // can be propagated to that branch.
1048       uint64_t RHSCount = Cnt.getCount();
1049 
1050       ConditionalEvaluation eval(*this);
1051       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
1052       EmitBlock(LHSTrue);
1053 
1054       // Any temporaries created here are conditional.
1055       Cnt.beginRegion(Builder);
1056       eval.begin(*this);
1057       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
1058       eval.end(*this);
1059 
1060       return;
1061     }
1062 
1063     if (CondBOp->getOpcode() == BO_LOr) {
1064       RegionCounter Cnt = getPGORegionCounter(CondBOp);
1065 
1066       // If we have "0 || X", simplify the code.  "1 || X" would have constant
1067       // folded if the case was simple enough.
1068       bool ConstantBool = false;
1069       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
1070           !ConstantBool) {
1071         // br(0 || X) -> br(X).
1072         Cnt.beginRegion(Builder);
1073         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
1074                                     TrueCount);
1075       }
1076 
1077       // If we have "X || 0", simplify the code to use an uncond branch.
1078       // "X || 1" would have been constant folded to 1.
1079       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
1080           !ConstantBool) {
1081         // br(X || 0) -> br(X).
1082         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
1083                                     TrueCount);
1084       }
1085 
1086       // Emit the LHS as a conditional.  If the LHS conditional is true, we
1087       // want to jump to the TrueBlock.
1088       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
1089       // We have the count for entry to the RHS and for the whole expression
1090       // being true, so we can divy up True count between the short circuit and
1091       // the RHS.
1092       uint64_t LHSCount = Cnt.getParentCount() - Cnt.getCount();
1093       uint64_t RHSCount = TrueCount - LHSCount;
1094 
1095       ConditionalEvaluation eval(*this);
1096       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
1097       EmitBlock(LHSFalse);
1098 
1099       // Any temporaries created here are conditional.
1100       Cnt.beginRegion(Builder);
1101       eval.begin(*this);
1102       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
1103 
1104       eval.end(*this);
1105 
1106       return;
1107     }
1108   }
1109 
1110   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1111     // br(!x, t, f) -> br(x, f, t)
1112     if (CondUOp->getOpcode() == UO_LNot) {
1113       // Negate the count.
1114       uint64_t FalseCount = PGO.getCurrentRegionCount() - TrueCount;
1115       // Negate the condition and swap the destination blocks.
1116       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
1117                                   FalseCount);
1118     }
1119   }
1120 
1121   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
1122     // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
1123     llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
1124     llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
1125 
1126     RegionCounter Cnt = getPGORegionCounter(CondOp);
1127     ConditionalEvaluation cond(*this);
1128     EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, Cnt.getCount());
1129 
1130     // When computing PGO branch weights, we only know the overall count for
1131     // the true block. This code is essentially doing tail duplication of the
1132     // naive code-gen, introducing new edges for which counts are not
1133     // available. Divide the counts proportionally between the LHS and RHS of
1134     // the conditional operator.
1135     uint64_t LHSScaledTrueCount = 0;
1136     if (TrueCount) {
1137       double LHSRatio = Cnt.getCount() / (double) Cnt.getParentCount();
1138       LHSScaledTrueCount = TrueCount * LHSRatio;
1139     }
1140 
1141     cond.begin(*this);
1142     EmitBlock(LHSBlock);
1143     Cnt.beginRegion(Builder);
1144     EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
1145                          LHSScaledTrueCount);
1146     cond.end(*this);
1147 
1148     cond.begin(*this);
1149     EmitBlock(RHSBlock);
1150     EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
1151                          TrueCount - LHSScaledTrueCount);
1152     cond.end(*this);
1153 
1154     return;
1155   }
1156 
1157   if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
1158     // Conditional operator handling can give us a throw expression as a
1159     // condition for a case like:
1160     //   br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
1161     // Fold this to:
1162     //   br(c, throw x, br(y, t, f))
1163     EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
1164     return;
1165   }
1166 
1167   // Create branch weights based on the number of times we get here and the
1168   // number of times the condition should be true.
1169   uint64_t CurrentCount = std::max(PGO.getCurrentRegionCount(), TrueCount);
1170   llvm::MDNode *Weights = PGO.createBranchWeights(TrueCount,
1171                                                   CurrentCount - TrueCount);
1172 
1173   // Emit the code with the fully general case.
1174   llvm::Value *CondV = EvaluateExprAsBool(Cond);
1175   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights);
1176 }
1177 
1178 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1179 /// specified stmt yet.
1180 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
1181   CGM.ErrorUnsupported(S, Type);
1182 }
1183 
1184 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
1185 /// variable-length array whose elements have a non-zero bit-pattern.
1186 ///
1187 /// \param baseType the inner-most element type of the array
1188 /// \param src - a char* pointing to the bit-pattern for a single
1189 /// base element of the array
1190 /// \param sizeInChars - the total size of the VLA, in chars
1191 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
1192                                llvm::Value *dest, llvm::Value *src,
1193                                llvm::Value *sizeInChars) {
1194   std::pair<CharUnits,CharUnits> baseSizeAndAlign
1195     = CGF.getContext().getTypeInfoInChars(baseType);
1196 
1197   CGBuilderTy &Builder = CGF.Builder;
1198 
1199   llvm::Value *baseSizeInChars
1200     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
1201 
1202   llvm::Type *i8p = Builder.getInt8PtrTy();
1203 
1204   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
1205   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
1206 
1207   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
1208   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
1209   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
1210 
1211   // Make a loop over the VLA.  C99 guarantees that the VLA element
1212   // count must be nonzero.
1213   CGF.EmitBlock(loopBB);
1214 
1215   llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
1216   cur->addIncoming(begin, originBB);
1217 
1218   // memcpy the individual element bit-pattern.
1219   Builder.CreateMemCpy(cur, src, baseSizeInChars,
1220                        baseSizeAndAlign.second.getQuantity(),
1221                        /*volatile*/ false);
1222 
1223   // Go to the next element.
1224   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
1225 
1226   // Leave if that's the end of the VLA.
1227   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
1228   Builder.CreateCondBr(done, contBB, loopBB);
1229   cur->addIncoming(next, loopBB);
1230 
1231   CGF.EmitBlock(contBB);
1232 }
1233 
1234 void
1235 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
1236   // Ignore empty classes in C++.
1237   if (getLangOpts().CPlusPlus) {
1238     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1239       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
1240         return;
1241     }
1242   }
1243 
1244   // Cast the dest ptr to the appropriate i8 pointer type.
1245   unsigned DestAS =
1246     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
1247   llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
1248   if (DestPtr->getType() != BP)
1249     DestPtr = Builder.CreateBitCast(DestPtr, BP);
1250 
1251   // Get size and alignment info for this aggregate.
1252   std::pair<CharUnits, CharUnits> TypeInfo =
1253     getContext().getTypeInfoInChars(Ty);
1254   CharUnits Size = TypeInfo.first;
1255   CharUnits Align = TypeInfo.second;
1256 
1257   llvm::Value *SizeVal;
1258   const VariableArrayType *vla;
1259 
1260   // Don't bother emitting a zero-byte memset.
1261   if (Size.isZero()) {
1262     // But note that getTypeInfo returns 0 for a VLA.
1263     if (const VariableArrayType *vlaType =
1264           dyn_cast_or_null<VariableArrayType>(
1265                                           getContext().getAsArrayType(Ty))) {
1266       QualType eltType;
1267       llvm::Value *numElts;
1268       std::tie(numElts, eltType) = getVLASize(vlaType);
1269 
1270       SizeVal = numElts;
1271       CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
1272       if (!eltSize.isOne())
1273         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
1274       vla = vlaType;
1275     } else {
1276       return;
1277     }
1278   } else {
1279     SizeVal = CGM.getSize(Size);
1280     vla = nullptr;
1281   }
1282 
1283   // If the type contains a pointer to data member we can't memset it to zero.
1284   // Instead, create a null constant and copy it to the destination.
1285   // TODO: there are other patterns besides zero that we can usefully memset,
1286   // like -1, which happens to be the pattern used by member-pointers.
1287   if (!CGM.getTypes().isZeroInitializable(Ty)) {
1288     // For a VLA, emit a single element, then splat that over the VLA.
1289     if (vla) Ty = getContext().getBaseElementType(vla);
1290 
1291     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
1292 
1293     llvm::GlobalVariable *NullVariable =
1294       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
1295                                /*isConstant=*/true,
1296                                llvm::GlobalVariable::PrivateLinkage,
1297                                NullConstant, Twine());
1298     llvm::Value *SrcPtr =
1299       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
1300 
1301     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
1302 
1303     // Get and call the appropriate llvm.memcpy overload.
1304     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
1305     return;
1306   }
1307 
1308   // Otherwise, just memset the whole thing to zero.  This is legal
1309   // because in LLVM, all default initializers (other than the ones we just
1310   // handled above) are guaranteed to have a bit pattern of all zeros.
1311   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
1312                        Align.getQuantity(), false);
1313 }
1314 
1315 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
1316   // Make sure that there is a block for the indirect goto.
1317   if (!IndirectBranch)
1318     GetIndirectGotoBlock();
1319 
1320   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
1321 
1322   // Make sure the indirect branch includes all of the address-taken blocks.
1323   IndirectBranch->addDestination(BB);
1324   return llvm::BlockAddress::get(CurFn, BB);
1325 }
1326 
1327 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
1328   // If we already made the indirect branch for indirect goto, return its block.
1329   if (IndirectBranch) return IndirectBranch->getParent();
1330 
1331   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
1332 
1333   // Create the PHI node that indirect gotos will add entries to.
1334   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
1335                                               "indirect.goto.dest");
1336 
1337   // Create the indirect branch instruction.
1338   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
1339   return IndirectBranch->getParent();
1340 }
1341 
1342 /// Computes the length of an array in elements, as well as the base
1343 /// element type and a properly-typed first element pointer.
1344 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
1345                                               QualType &baseType,
1346                                               llvm::Value *&addr) {
1347   const ArrayType *arrayType = origArrayType;
1348 
1349   // If it's a VLA, we have to load the stored size.  Note that
1350   // this is the size of the VLA in bytes, not its size in elements.
1351   llvm::Value *numVLAElements = nullptr;
1352   if (isa<VariableArrayType>(arrayType)) {
1353     numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
1354 
1355     // Walk into all VLAs.  This doesn't require changes to addr,
1356     // which has type T* where T is the first non-VLA element type.
1357     do {
1358       QualType elementType = arrayType->getElementType();
1359       arrayType = getContext().getAsArrayType(elementType);
1360 
1361       // If we only have VLA components, 'addr' requires no adjustment.
1362       if (!arrayType) {
1363         baseType = elementType;
1364         return numVLAElements;
1365       }
1366     } while (isa<VariableArrayType>(arrayType));
1367 
1368     // We get out here only if we find a constant array type
1369     // inside the VLA.
1370   }
1371 
1372   // We have some number of constant-length arrays, so addr should
1373   // have LLVM type [M x [N x [...]]]*.  Build a GEP that walks
1374   // down to the first element of addr.
1375   SmallVector<llvm::Value*, 8> gepIndices;
1376 
1377   // GEP down to the array type.
1378   llvm::ConstantInt *zero = Builder.getInt32(0);
1379   gepIndices.push_back(zero);
1380 
1381   uint64_t countFromCLAs = 1;
1382   QualType eltType;
1383 
1384   llvm::ArrayType *llvmArrayType =
1385     dyn_cast<llvm::ArrayType>(
1386       cast<llvm::PointerType>(addr->getType())->getElementType());
1387   while (llvmArrayType) {
1388     assert(isa<ConstantArrayType>(arrayType));
1389     assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1390              == llvmArrayType->getNumElements());
1391 
1392     gepIndices.push_back(zero);
1393     countFromCLAs *= llvmArrayType->getNumElements();
1394     eltType = arrayType->getElementType();
1395 
1396     llvmArrayType =
1397       dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1398     arrayType = getContext().getAsArrayType(arrayType->getElementType());
1399     assert((!llvmArrayType || arrayType) &&
1400            "LLVM and Clang types are out-of-synch");
1401   }
1402 
1403   if (arrayType) {
1404     // From this point onwards, the Clang array type has been emitted
1405     // as some other type (probably a packed struct). Compute the array
1406     // size, and just emit the 'begin' expression as a bitcast.
1407     while (arrayType) {
1408       countFromCLAs *=
1409           cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
1410       eltType = arrayType->getElementType();
1411       arrayType = getContext().getAsArrayType(eltType);
1412     }
1413 
1414     unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
1415     llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
1416     addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
1417   } else {
1418     // Create the actual GEP.
1419     addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
1420   }
1421 
1422   baseType = eltType;
1423 
1424   llvm::Value *numElements
1425     = llvm::ConstantInt::get(SizeTy, countFromCLAs);
1426 
1427   // If we had any VLA dimensions, factor them in.
1428   if (numVLAElements)
1429     numElements = Builder.CreateNUWMul(numVLAElements, numElements);
1430 
1431   return numElements;
1432 }
1433 
1434 std::pair<llvm::Value*, QualType>
1435 CodeGenFunction::getVLASize(QualType type) {
1436   const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
1437   assert(vla && "type was not a variable array type!");
1438   return getVLASize(vla);
1439 }
1440 
1441 std::pair<llvm::Value*, QualType>
1442 CodeGenFunction::getVLASize(const VariableArrayType *type) {
1443   // The number of elements so far; always size_t.
1444   llvm::Value *numElements = nullptr;
1445 
1446   QualType elementType;
1447   do {
1448     elementType = type->getElementType();
1449     llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
1450     assert(vlaSize && "no size for VLA!");
1451     assert(vlaSize->getType() == SizeTy);
1452 
1453     if (!numElements) {
1454       numElements = vlaSize;
1455     } else {
1456       // It's undefined behavior if this wraps around, so mark it that way.
1457       // FIXME: Teach -fsanitize=undefined to trap this.
1458       numElements = Builder.CreateNUWMul(numElements, vlaSize);
1459     }
1460   } while ((type = getContext().getAsVariableArrayType(elementType)));
1461 
1462   return std::pair<llvm::Value*,QualType>(numElements, elementType);
1463 }
1464 
1465 void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
1466   assert(type->isVariablyModifiedType() &&
1467          "Must pass variably modified type to EmitVLASizes!");
1468 
1469   EnsureInsertPoint();
1470 
1471   // We're going to walk down into the type and look for VLA
1472   // expressions.
1473   do {
1474     assert(type->isVariablyModifiedType());
1475 
1476     const Type *ty = type.getTypePtr();
1477     switch (ty->getTypeClass()) {
1478 
1479 #define TYPE(Class, Base)
1480 #define ABSTRACT_TYPE(Class, Base)
1481 #define NON_CANONICAL_TYPE(Class, Base)
1482 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1483 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
1484 #include "clang/AST/TypeNodes.def"
1485       llvm_unreachable("unexpected dependent type!");
1486 
1487     // These types are never variably-modified.
1488     case Type::Builtin:
1489     case Type::Complex:
1490     case Type::Vector:
1491     case Type::ExtVector:
1492     case Type::Record:
1493     case Type::Enum:
1494     case Type::Elaborated:
1495     case Type::TemplateSpecialization:
1496     case Type::ObjCObject:
1497     case Type::ObjCInterface:
1498     case Type::ObjCObjectPointer:
1499       llvm_unreachable("type class is never variably-modified!");
1500 
1501     case Type::Adjusted:
1502       type = cast<AdjustedType>(ty)->getAdjustedType();
1503       break;
1504 
1505     case Type::Decayed:
1506       type = cast<DecayedType>(ty)->getPointeeType();
1507       break;
1508 
1509     case Type::Pointer:
1510       type = cast<PointerType>(ty)->getPointeeType();
1511       break;
1512 
1513     case Type::BlockPointer:
1514       type = cast<BlockPointerType>(ty)->getPointeeType();
1515       break;
1516 
1517     case Type::LValueReference:
1518     case Type::RValueReference:
1519       type = cast<ReferenceType>(ty)->getPointeeType();
1520       break;
1521 
1522     case Type::MemberPointer:
1523       type = cast<MemberPointerType>(ty)->getPointeeType();
1524       break;
1525 
1526     case Type::ConstantArray:
1527     case Type::IncompleteArray:
1528       // Losing element qualification here is fine.
1529       type = cast<ArrayType>(ty)->getElementType();
1530       break;
1531 
1532     case Type::VariableArray: {
1533       // Losing element qualification here is fine.
1534       const VariableArrayType *vat = cast<VariableArrayType>(ty);
1535 
1536       // Unknown size indication requires no size computation.
1537       // Otherwise, evaluate and record it.
1538       if (const Expr *size = vat->getSizeExpr()) {
1539         // It's possible that we might have emitted this already,
1540         // e.g. with a typedef and a pointer to it.
1541         llvm::Value *&entry = VLASizeMap[size];
1542         if (!entry) {
1543           llvm::Value *Size = EmitScalarExpr(size);
1544 
1545           // C11 6.7.6.2p5:
1546           //   If the size is an expression that is not an integer constant
1547           //   expression [...] each time it is evaluated it shall have a value
1548           //   greater than zero.
1549           if (SanOpts->VLABound &&
1550               size->getType()->isSignedIntegerType()) {
1551             SanitizerScope SanScope(this);
1552             llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
1553             llvm::Constant *StaticArgs[] = {
1554               EmitCheckSourceLocation(size->getLocStart()),
1555               EmitCheckTypeDescriptor(size->getType())
1556             };
1557             EmitCheck(Builder.CreateICmpSGT(Size, Zero),
1558                       "vla_bound_not_positive", StaticArgs, Size,
1559                       CRK_Recoverable);
1560           }
1561 
1562           // Always zexting here would be wrong if it weren't
1563           // undefined behavior to have a negative bound.
1564           entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
1565         }
1566       }
1567       type = vat->getElementType();
1568       break;
1569     }
1570 
1571     case Type::FunctionProto:
1572     case Type::FunctionNoProto:
1573       type = cast<FunctionType>(ty)->getReturnType();
1574       break;
1575 
1576     case Type::Paren:
1577     case Type::TypeOf:
1578     case Type::UnaryTransform:
1579     case Type::Attributed:
1580     case Type::SubstTemplateTypeParm:
1581     case Type::PackExpansion:
1582       // Keep walking after single level desugaring.
1583       type = type.getSingleStepDesugaredType(getContext());
1584       break;
1585 
1586     case Type::Typedef:
1587     case Type::Decltype:
1588     case Type::Auto:
1589       // Stop walking: nothing to do.
1590       return;
1591 
1592     case Type::TypeOfExpr:
1593       // Stop walking: emit typeof expression.
1594       EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
1595       return;
1596 
1597     case Type::Atomic:
1598       type = cast<AtomicType>(ty)->getValueType();
1599       break;
1600     }
1601   } while (type->isVariablyModifiedType());
1602 }
1603 
1604 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
1605   if (getContext().getBuiltinVaListType()->isArrayType())
1606     return EmitScalarExpr(E);
1607   return EmitLValue(E).getAddress();
1608 }
1609 
1610 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
1611                                               llvm::Constant *Init) {
1612   assert (Init && "Invalid DeclRefExpr initializer!");
1613   if (CGDebugInfo *Dbg = getDebugInfo())
1614     if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1615       Dbg->EmitGlobalVariable(E->getDecl(), Init);
1616 }
1617 
1618 CodeGenFunction::PeepholeProtection
1619 CodeGenFunction::protectFromPeepholes(RValue rvalue) {
1620   // At the moment, the only aggressive peephole we do in IR gen
1621   // is trunc(zext) folding, but if we add more, we can easily
1622   // extend this protection.
1623 
1624   if (!rvalue.isScalar()) return PeepholeProtection();
1625   llvm::Value *value = rvalue.getScalarVal();
1626   if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
1627 
1628   // Just make an extra bitcast.
1629   assert(HaveInsertPoint());
1630   llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
1631                                                   Builder.GetInsertBlock());
1632 
1633   PeepholeProtection protection;
1634   protection.Inst = inst;
1635   return protection;
1636 }
1637 
1638 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
1639   if (!protection.Inst) return;
1640 
1641   // In theory, we could try to duplicate the peepholes now, but whatever.
1642   protection.Inst->eraseFromParent();
1643 }
1644 
1645 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
1646                                                  llvm::Value *AnnotatedVal,
1647                                                  StringRef AnnotationStr,
1648                                                  SourceLocation Location) {
1649   llvm::Value *Args[4] = {
1650     AnnotatedVal,
1651     Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
1652     Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
1653     CGM.EmitAnnotationLineNo(Location)
1654   };
1655   return Builder.CreateCall(AnnotationFn, Args);
1656 }
1657 
1658 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
1659   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1660   // FIXME We create a new bitcast for every annotation because that's what
1661   // llvm-gcc was doing.
1662   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1663     EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
1664                        Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
1665                        I->getAnnotation(), D->getLocation());
1666 }
1667 
1668 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
1669                                                    llvm::Value *V) {
1670   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1671   llvm::Type *VTy = V->getType();
1672   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
1673                                     CGM.Int8PtrTy);
1674 
1675   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
1676     // FIXME Always emit the cast inst so we can differentiate between
1677     // annotation on the first field of a struct and annotation on the struct
1678     // itself.
1679     if (VTy != CGM.Int8PtrTy)
1680       V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
1681     V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
1682     V = Builder.CreateBitCast(V, VTy);
1683   }
1684 
1685   return V;
1686 }
1687 
1688 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
1689 
1690 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
1691     : CGF(CGF) {
1692   assert(!CGF->IsSanitizerScope);
1693   CGF->IsSanitizerScope = true;
1694 }
1695 
1696 CodeGenFunction::SanitizerScope::~SanitizerScope() {
1697   CGF->IsSanitizerScope = false;
1698 }
1699 
1700 void CodeGenFunction::InsertHelper(llvm::Instruction *I,
1701                                    const llvm::Twine &Name,
1702                                    llvm::BasicBlock *BB,
1703                                    llvm::BasicBlock::iterator InsertPt) const {
1704   LoopStack.InsertHelper(I);
1705   if (IsSanitizerScope)
1706     CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
1707 }
1708 
1709 template <bool PreserveNames>
1710 void CGBuilderInserter<PreserveNames>::InsertHelper(
1711     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1712     llvm::BasicBlock::iterator InsertPt) const {
1713   llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB,
1714                                                               InsertPt);
1715   if (CGF)
1716     CGF->InsertHelper(I, Name, BB, InsertPt);
1717 }
1718 
1719 #ifdef NDEBUG
1720 #define PreserveNames false
1721 #else
1722 #define PreserveNames true
1723 #endif
1724 template void CGBuilderInserter<PreserveNames>::InsertHelper(
1725     llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
1726     llvm::BasicBlock::iterator InsertPt) const;
1727 #undef PreserveNames
1728