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