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