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