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