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