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