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 "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGException.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
32   : BlockFunction(cgm, *this, Builder), CGM(cgm),
33     Target(CGM.getContext().Target),
34     Builder(cgm.getModule().getContext()),
35     NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
36     ExceptionSlot(0), DebugInfo(0), IndirectBranch(0),
37     SwitchInsn(0), CaseRangeBlock(0),
38     DidCallStackSave(false), UnreachableBlock(0),
39     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
40     OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
41     TrapBB(0) {
42 
43   // Get some frequently used types.
44   LLVMPointerWidth = Target.getPointerWidth(0);
45   llvm::LLVMContext &LLVMContext = CGM.getLLVMContext();
46   IntPtrTy = llvm::IntegerType::get(LLVMContext, LLVMPointerWidth);
47   Int32Ty  = llvm::Type::getInt32Ty(LLVMContext);
48   Int64Ty  = llvm::Type::getInt64Ty(LLVMContext);
49 
50   Exceptions = getContext().getLangOptions().Exceptions;
51   CatchUndefined = getContext().getLangOptions().CatchUndefined;
52   CGM.getCXXABI().getMangleContext().startNewFunction();
53 }
54 
55 ASTContext &CodeGenFunction::getContext() const {
56   return CGM.getContext();
57 }
58 
59 
60 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61   return CGM.getTypes().ConvertTypeForMem(T);
62 }
63 
64 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65   return CGM.getTypes().ConvertType(T);
66 }
67 
68 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
69   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
70     T->isObjCObjectType();
71 }
72 
73 void CodeGenFunction::EmitReturnBlock() {
74   // For cleanliness, we try to avoid emitting the return block for
75   // simple cases.
76   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
77 
78   if (CurBB) {
79     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
80 
81     // We have a valid insert point, reuse it if it is empty or there are no
82     // explicit jumps to the return block.
83     if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
84       ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
85       delete ReturnBlock.getBlock();
86     } else
87       EmitBlock(ReturnBlock.getBlock());
88     return;
89   }
90 
91   // Otherwise, if the return block is the target of a single direct
92   // branch then we can just put the code in that block instead. This
93   // cleans up functions which started with a unified return block.
94   if (ReturnBlock.getBlock()->hasOneUse()) {
95     llvm::BranchInst *BI =
96       dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
97     if (BI && BI->isUnconditional() &&
98         BI->getSuccessor(0) == ReturnBlock.getBlock()) {
99       // Reset insertion point and delete the branch.
100       Builder.SetInsertPoint(BI->getParent());
101       BI->eraseFromParent();
102       delete ReturnBlock.getBlock();
103       return;
104     }
105   }
106 
107   // FIXME: We are at an unreachable point, there is no reason to emit the block
108   // unless it has uses. However, we still need a place to put the debug
109   // region.end for now.
110 
111   EmitBlock(ReturnBlock.getBlock());
112 }
113 
114 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
115   if (!BB) return;
116   if (!BB->use_empty())
117     return CGF.CurFn->getBasicBlockList().push_back(BB);
118   delete BB;
119 }
120 
121 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
122   assert(BreakContinueStack.empty() &&
123          "mismatched push/pop in break/continue stack!");
124 
125   // Emit function epilog (to return).
126   EmitReturnBlock();
127 
128   EmitFunctionInstrumentation("__cyg_profile_func_exit");
129 
130   // Emit debug descriptor for function end.
131   if (CGDebugInfo *DI = getDebugInfo()) {
132     DI->setLocation(EndLoc);
133     DI->EmitFunctionEnd(Builder);
134   }
135 
136   EmitFunctionEpilog(*CurFnInfo);
137   EmitEndEHSpec(CurCodeDecl);
138 
139   assert(EHStack.empty() &&
140          "did not remove all scopes from cleanup stack!");
141 
142   // If someone did an indirect goto, emit the indirect goto block at the end of
143   // the function.
144   if (IndirectBranch) {
145     EmitBlock(IndirectBranch->getParent());
146     Builder.ClearInsertionPoint();
147   }
148 
149   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
150   llvm::Instruction *Ptr = AllocaInsertPt;
151   AllocaInsertPt = 0;
152   Ptr->eraseFromParent();
153 
154   // If someone took the address of a label but never did an indirect goto, we
155   // made a zero entry PHI node, which is illegal, zap it now.
156   if (IndirectBranch) {
157     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
158     if (PN->getNumIncomingValues() == 0) {
159       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
160       PN->eraseFromParent();
161     }
162   }
163 
164   EmitIfUsed(*this, RethrowBlock.getBlock());
165   EmitIfUsed(*this, TerminateLandingPad);
166   EmitIfUsed(*this, TerminateHandler);
167   EmitIfUsed(*this, UnreachableBlock);
168 
169   if (CGM.getCodeGenOpts().EmitDeclMetadata)
170     EmitDeclMetadata();
171 }
172 
173 /// ShouldInstrumentFunction - Return true if the current function should be
174 /// instrumented with __cyg_profile_func_* calls
175 bool CodeGenFunction::ShouldInstrumentFunction() {
176   if (!CGM.getCodeGenOpts().InstrumentFunctions)
177     return false;
178   if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
179     return false;
180   return true;
181 }
182 
183 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
184 /// instrumentation function with the current function and the call site, if
185 /// function instrumentation is enabled.
186 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
187   if (!ShouldInstrumentFunction())
188     return;
189 
190   const llvm::PointerType *PointerTy;
191   const llvm::FunctionType *FunctionTy;
192   std::vector<const llvm::Type*> ProfileFuncArgs;
193 
194   // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
195   PointerTy = llvm::Type::getInt8PtrTy(VMContext);
196   ProfileFuncArgs.push_back(PointerTy);
197   ProfileFuncArgs.push_back(PointerTy);
198   FunctionTy = llvm::FunctionType::get(
199     llvm::Type::getVoidTy(VMContext),
200     ProfileFuncArgs, false);
201 
202   llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
203   llvm::CallInst *CallSite = Builder.CreateCall(
204     CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
205     llvm::ConstantInt::get(Int32Ty, 0),
206     "callsite");
207 
208   Builder.CreateCall2(F,
209                       llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
210                       CallSite);
211 }
212 
213 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
214                                     llvm::Function *Fn,
215                                     const FunctionArgList &Args,
216                                     SourceLocation StartLoc) {
217   const Decl *D = GD.getDecl();
218 
219   DidCallStackSave = false;
220   CurCodeDecl = CurFuncDecl = D;
221   FnRetTy = RetTy;
222   CurFn = Fn;
223   assert(CurFn->isDeclaration() && "Function already has body?");
224 
225   // Pass inline keyword to optimizer if it appears explicitly on any
226   // declaration.
227   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
228     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
229            RE = FD->redecls_end(); RI != RE; ++RI)
230       if (RI->isInlineSpecified()) {
231         Fn->addFnAttr(llvm::Attribute::InlineHint);
232         break;
233       }
234 
235   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
236 
237   // Create a marker to make it easy to insert allocas into the entryblock
238   // later.  Don't create this with the builder, because we don't want it
239   // folded.
240   llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
241   AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
242   if (Builder.isNamePreserving())
243     AllocaInsertPt->setName("allocapt");
244 
245   ReturnBlock = getJumpDestInCurrentScope("return");
246 
247   Builder.SetInsertPoint(EntryBB);
248 
249   // Emit subprogram debug descriptor.
250   if (CGDebugInfo *DI = getDebugInfo()) {
251     // FIXME: what is going on here and why does it ignore all these
252     // interesting type properties?
253     QualType FnType =
254       getContext().getFunctionType(RetTy, 0, 0,
255                                    FunctionProtoType::ExtProtoInfo());
256 
257     DI->setLocation(StartLoc);
258     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
259   }
260 
261   EmitFunctionInstrumentation("__cyg_profile_func_enter");
262 
263   // FIXME: Leaked.
264   // CC info is ignored, hopefully?
265   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
266                                               FunctionType::ExtInfo());
267 
268   if (RetTy->isVoidType()) {
269     // Void type; nothing to return.
270     ReturnValue = 0;
271   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
272              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
273     // Indirect aggregate return; emit returned value directly into sret slot.
274     // This reduces code size, and affects correctness in C++.
275     ReturnValue = CurFn->arg_begin();
276   } else {
277     ReturnValue = CreateIRTemp(RetTy, "retval");
278   }
279 
280   EmitStartEHSpec(CurCodeDecl);
281   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
282 
283   if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
284     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
285 
286   // If any of the arguments have a variably modified type, make sure to
287   // emit the type size.
288   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
289        i != e; ++i) {
290     QualType Ty = i->second;
291 
292     if (Ty->isVariablyModifiedType())
293       EmitVLASize(Ty);
294   }
295 }
296 
297 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
298   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
299   assert(FD->getBody());
300   EmitStmt(FD->getBody());
301 }
302 
303 /// Tries to mark the given function nounwind based on the
304 /// non-existence of any throwing calls within it.  We believe this is
305 /// lightweight enough to do at -O0.
306 static void TryMarkNoThrow(llvm::Function *F) {
307   // LLVM treats 'nounwind' on a function as part of the type, so we
308   // can't do this on functions that can be overwritten.
309   if (F->mayBeOverridden()) return;
310 
311   for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
312     for (llvm::BasicBlock::iterator
313            BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
314       if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
315         if (!Call->doesNotThrow())
316           return;
317   F->setDoesNotThrow(true);
318 }
319 
320 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
321   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
322 
323   // Check if we should generate debug info for this function.
324   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
325     DebugInfo = CGM.getDebugInfo();
326 
327   FunctionArgList Args;
328   QualType ResTy = FD->getResultType();
329 
330   CurGD = GD;
331   if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
332     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
333 
334   if (FD->getNumParams()) {
335     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
336     assert(FProto && "Function def must have prototype!");
337 
338     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
339       Args.push_back(std::make_pair(FD->getParamDecl(i),
340                                     FProto->getArgType(i)));
341   }
342 
343   SourceRange BodyRange;
344   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
345 
346   // Emit the standard function prologue.
347   StartFunction(GD, ResTy, Fn, Args, BodyRange.getBegin());
348 
349   // Generate the body of the function.
350   if (isa<CXXDestructorDecl>(FD))
351     EmitDestructorBody(Args);
352   else if (isa<CXXConstructorDecl>(FD))
353     EmitConstructorBody(Args);
354   else
355     EmitFunctionBody(Args);
356 
357   // Emit the standard function epilogue.
358   FinishFunction(BodyRange.getEnd());
359 
360   // If we haven't marked the function nothrow through other means, do
361   // a quick pass now to see if we can.
362   if (!CurFn->doesNotThrow())
363     TryMarkNoThrow(CurFn);
364 }
365 
366 /// ContainsLabel - Return true if the statement contains a label in it.  If
367 /// this statement is not executed normally, it not containing a label means
368 /// that we can just remove the code.
369 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
370   // Null statement, not a label!
371   if (S == 0) return false;
372 
373   // If this is a label, we have to emit the code, consider something like:
374   // if (0) {  ...  foo:  bar(); }  goto foo;
375   if (isa<LabelStmt>(S))
376     return true;
377 
378   // If this is a case/default statement, and we haven't seen a switch, we have
379   // to emit the code.
380   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
381     return true;
382 
383   // If this is a switch statement, we want to ignore cases below it.
384   if (isa<SwitchStmt>(S))
385     IgnoreCaseStmts = true;
386 
387   // Scan subexpressions for verboten labels.
388   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
389        I != E; ++I)
390     if (ContainsLabel(*I, IgnoreCaseStmts))
391       return true;
392 
393   return false;
394 }
395 
396 
397 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
398 /// a constant, or if it does but contains a label, return 0.  If it constant
399 /// folds to 'true' and does not contain a label, return 1, if it constant folds
400 /// to 'false' and does not contain a label, return -1.
401 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
402   // FIXME: Rename and handle conversion of other evaluatable things
403   // to bool.
404   Expr::EvalResult Result;
405   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
406       Result.HasSideEffects)
407     return 0;  // Not foldable, not integer or not fully evaluatable.
408 
409   if (CodeGenFunction::ContainsLabel(Cond))
410     return 0;  // Contains a label.
411 
412   return Result.Val.getInt().getBoolValue() ? 1 : -1;
413 }
414 
415 
416 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
417 /// statement) to the specified blocks.  Based on the condition, this might try
418 /// to simplify the codegen of the conditional based on the branch.
419 ///
420 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
421                                            llvm::BasicBlock *TrueBlock,
422                                            llvm::BasicBlock *FalseBlock) {
423   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
424     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
425 
426   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
427     // Handle X && Y in a condition.
428     if (CondBOp->getOpcode() == BO_LAnd) {
429       // If we have "1 && X", simplify the code.  "0 && X" would have constant
430       // folded if the case was simple enough.
431       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
432         // br(1 && X) -> br(X).
433         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
434       }
435 
436       // If we have "X && 1", simplify the code to use an uncond branch.
437       // "X && 0" would have been constant folded to 0.
438       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
439         // br(X && 1) -> br(X).
440         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
441       }
442 
443       // Emit the LHS as a conditional.  If the LHS conditional is false, we
444       // want to jump to the FalseBlock.
445       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
446 
447       ConditionalEvaluation eval(*this);
448       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
449       EmitBlock(LHSTrue);
450 
451       // Any temporaries created here are conditional.
452       eval.begin(*this);
453       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
454       eval.end(*this);
455 
456       return;
457     } else if (CondBOp->getOpcode() == BO_LOr) {
458       // If we have "0 || X", simplify the code.  "1 || X" would have constant
459       // folded if the case was simple enough.
460       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
461         // br(0 || X) -> br(X).
462         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
463       }
464 
465       // If we have "X || 0", simplify the code to use an uncond branch.
466       // "X || 1" would have been constant folded to 1.
467       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
468         // br(X || 0) -> br(X).
469         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
470       }
471 
472       // Emit the LHS as a conditional.  If the LHS conditional is true, we
473       // want to jump to the TrueBlock.
474       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
475 
476       ConditionalEvaluation eval(*this);
477       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
478       EmitBlock(LHSFalse);
479 
480       // Any temporaries created here are conditional.
481       eval.begin(*this);
482       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
483       eval.end(*this);
484 
485       return;
486     }
487   }
488 
489   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
490     // br(!x, t, f) -> br(x, f, t)
491     if (CondUOp->getOpcode() == UO_LNot)
492       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
493   }
494 
495   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
496     // Handle ?: operator.
497 
498     // Just ignore GNU ?: extension.
499     if (CondOp->getLHS()) {
500       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
501       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
502       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
503 
504       ConditionalEvaluation cond(*this);
505       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
506 
507       cond.begin(*this);
508       EmitBlock(LHSBlock);
509       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
510       cond.end(*this);
511 
512       cond.begin(*this);
513       EmitBlock(RHSBlock);
514       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
515       cond.end(*this);
516 
517       return;
518     }
519   }
520 
521   // Emit the code with the fully general case.
522   llvm::Value *CondV = EvaluateExprAsBool(Cond);
523   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
524 }
525 
526 /// ErrorUnsupported - Print out an error that codegen doesn't support the
527 /// specified stmt yet.
528 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
529                                        bool OmitOnError) {
530   CGM.ErrorUnsupported(S, Type, OmitOnError);
531 }
532 
533 /// emitNonZeroVLAInit - Emit the "zero" initialization of a
534 /// variable-length array whose elements have a non-zero bit-pattern.
535 ///
536 /// \param src - a char* pointing to the bit-pattern for a single
537 /// base element of the array
538 /// \param sizeInChars - the total size of the VLA, in chars
539 /// \param align - the total alignment of the VLA
540 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
541                                llvm::Value *dest, llvm::Value *src,
542                                llvm::Value *sizeInChars) {
543   std::pair<CharUnits,CharUnits> baseSizeAndAlign
544     = CGF.getContext().getTypeInfoInChars(baseType);
545 
546   CGBuilderTy &Builder = CGF.Builder;
547 
548   llvm::Value *baseSizeInChars
549     = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
550 
551   const llvm::Type *i8p = Builder.getInt8PtrTy();
552 
553   llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
554   llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
555 
556   llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
557   llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
558   llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
559 
560   // Make a loop over the VLA.  C99 guarantees that the VLA element
561   // count must be nonzero.
562   CGF.EmitBlock(loopBB);
563 
564   llvm::PHINode *cur = Builder.CreatePHI(i8p, "vla.cur");
565   cur->reserveOperandSpace(2);
566   cur->addIncoming(begin, originBB);
567 
568   // memcpy the individual element bit-pattern.
569   Builder.CreateMemCpy(cur, src, baseSizeInChars,
570                        baseSizeAndAlign.second.getQuantity(),
571                        /*volatile*/ false);
572 
573   // Go to the next element.
574   llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
575 
576   // Leave if that's the end of the VLA.
577   llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
578   Builder.CreateCondBr(done, contBB, loopBB);
579   cur->addIncoming(next, loopBB);
580 
581   CGF.EmitBlock(contBB);
582 }
583 
584 void
585 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
586   // Ignore empty classes in C++.
587   if (getContext().getLangOptions().CPlusPlus) {
588     if (const RecordType *RT = Ty->getAs<RecordType>()) {
589       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
590         return;
591     }
592   }
593 
594   // Cast the dest ptr to the appropriate i8 pointer type.
595   unsigned DestAS =
596     cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
597   const llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
598   if (DestPtr->getType() != BP)
599     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
600 
601   // Get size and alignment info for this aggregate.
602   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
603   uint64_t Size = TypeInfo.first / 8;
604   unsigned Align = TypeInfo.second / 8;
605 
606   llvm::Value *SizeVal;
607   const VariableArrayType *vla;
608 
609   // Don't bother emitting a zero-byte memset.
610   if (Size == 0) {
611     // But note that getTypeInfo returns 0 for a VLA.
612     if (const VariableArrayType *vlaType =
613           dyn_cast_or_null<VariableArrayType>(
614                                           getContext().getAsArrayType(Ty))) {
615       SizeVal = GetVLASize(vlaType);
616       vla = vlaType;
617     } else {
618       return;
619     }
620   } else {
621     SizeVal = llvm::ConstantInt::get(IntPtrTy, Size);
622     vla = 0;
623   }
624 
625   // If the type contains a pointer to data member we can't memset it to zero.
626   // Instead, create a null constant and copy it to the destination.
627   // TODO: there are other patterns besides zero that we can usefully memset,
628   // like -1, which happens to be the pattern used by member-pointers.
629   if (!CGM.getTypes().isZeroInitializable(Ty)) {
630     // For a VLA, emit a single element, then splat that over the VLA.
631     if (vla) Ty = getContext().getBaseElementType(vla);
632 
633     llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
634 
635     llvm::GlobalVariable *NullVariable =
636       new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
637                                /*isConstant=*/true,
638                                llvm::GlobalVariable::PrivateLinkage,
639                                NullConstant, llvm::Twine());
640     llvm::Value *SrcPtr =
641       Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
642 
643     if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
644 
645     // Get and call the appropriate llvm.memcpy overload.
646     Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false);
647     return;
648   }
649 
650   // Otherwise, just memset the whole thing to zero.  This is legal
651   // because in LLVM, all default initializers (other than the ones we just
652   // handled above) are guaranteed to have a bit pattern of all zeros.
653   Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false);
654 }
655 
656 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
657   // Make sure that there is a block for the indirect goto.
658   if (IndirectBranch == 0)
659     GetIndirectGotoBlock();
660 
661   llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
662 
663   // Make sure the indirect branch includes all of the address-taken blocks.
664   IndirectBranch->addDestination(BB);
665   return llvm::BlockAddress::get(CurFn, BB);
666 }
667 
668 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
669   // If we already made the indirect branch for indirect goto, return its block.
670   if (IndirectBranch) return IndirectBranch->getParent();
671 
672   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
673 
674   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
675 
676   // Create the PHI node that indirect gotos will add entries to.
677   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
678 
679   // Create the indirect branch instruction.
680   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
681   return IndirectBranch->getParent();
682 }
683 
684 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
685   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
686 
687   assert(SizeEntry && "Did not emit size for type");
688   return SizeEntry;
689 }
690 
691 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
692   assert(Ty->isVariablyModifiedType() &&
693          "Must pass variably modified type to EmitVLASizes!");
694 
695   EnsureInsertPoint();
696 
697   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
698     // unknown size indication requires no size computation.
699     if (!VAT->getSizeExpr())
700       return 0;
701     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
702 
703     if (!SizeEntry) {
704       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
705 
706       // Get the element size;
707       QualType ElemTy = VAT->getElementType();
708       llvm::Value *ElemSize;
709       if (ElemTy->isVariableArrayType())
710         ElemSize = EmitVLASize(ElemTy);
711       else
712         ElemSize = llvm::ConstantInt::get(SizeTy,
713             getContext().getTypeSizeInChars(ElemTy).getQuantity());
714 
715       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
716       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
717 
718       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
719     }
720 
721     return SizeEntry;
722   }
723 
724   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
725     EmitVLASize(AT->getElementType());
726     return 0;
727   }
728 
729   if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
730     EmitVLASize(PT->getInnerType());
731     return 0;
732   }
733 
734   const PointerType *PT = Ty->getAs<PointerType>();
735   assert(PT && "unknown VM type!");
736   EmitVLASize(PT->getPointeeType());
737   return 0;
738 }
739 
740 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
741   if (getContext().getBuiltinVaListType()->isArrayType())
742     return EmitScalarExpr(E);
743   return EmitLValue(E).getAddress();
744 }
745 
746 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
747                                               llvm::Constant *Init) {
748   assert (Init && "Invalid DeclRefExpr initializer!");
749   if (CGDebugInfo *Dbg = getDebugInfo())
750     Dbg->EmitGlobalVariable(E->getDecl(), Init);
751 }
752