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