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