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 "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/APValue.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 "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
28   : BlockFunction(cgm, *this, Builder), CGM(cgm),
29     Target(CGM.getContext().Target),
30     Builder(cgm.getModule().getContext()),
31     DebugInfo(0), IndirectBranch(0),
32     SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
33     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
34     ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
35     UniqueAggrDestructorCount(0) {
36   LLVMIntTy = ConvertType(getContext().IntTy);
37   LLVMPointerWidth = Target.getPointerWidth(0);
38   Exceptions = getContext().getLangOptions().Exceptions;
39   CatchUndefined = getContext().getLangOptions().CatchUndefined;
40 }
41 
42 ASTContext &CodeGenFunction::getContext() const {
43   return CGM.getContext();
44 }
45 
46 
47 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48   llvm::BasicBlock *&BB = LabelMap[S];
49   if (BB) return BB;
50 
51   // Create, but don't insert, the new block.
52   return BB = createBasicBlock(S->getName());
53 }
54 
55 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56   llvm::Value *Res = LocalDeclMap[VD];
57   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58   return Res;
59 }
60 
61 llvm::Constant *
62 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
64 }
65 
66 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67   return CGM.getTypes().ConvertTypeForMem(T);
68 }
69 
70 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71   return CGM.getTypes().ConvertType(T);
72 }
73 
74 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
75   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76     T->isMemberFunctionPointerType();
77 }
78 
79 void CodeGenFunction::EmitReturnBlock() {
80   // For cleanliness, we try to avoid emitting the return block for
81   // simple cases.
82   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83 
84   if (CurBB) {
85     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86 
87     // We have a valid insert point, reuse it if it is empty or there are no
88     // explicit jumps to the return block.
89     if (CurBB->empty() || ReturnBlock->use_empty()) {
90       ReturnBlock->replaceAllUsesWith(CurBB);
91       delete ReturnBlock;
92     } else
93       EmitBlock(ReturnBlock);
94     return;
95   }
96 
97   // Otherwise, if the return block is the target of a single direct
98   // branch then we can just put the code in that block instead. This
99   // cleans up functions which started with a unified return block.
100   if (ReturnBlock->hasOneUse()) {
101     llvm::BranchInst *BI =
102       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104       // Reset insertion point and delete the branch.
105       Builder.SetInsertPoint(BI->getParent());
106       BI->eraseFromParent();
107       delete ReturnBlock;
108       return;
109     }
110   }
111 
112   // FIXME: We are at an unreachable point, there is no reason to emit the block
113   // unless it has uses. However, we still need a place to put the debug
114   // region.end for now.
115 
116   EmitBlock(ReturnBlock);
117 }
118 
119 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
120   assert(BreakContinueStack.empty() &&
121          "mismatched push/pop in break/continue stack!");
122   assert(BlockScopes.empty() &&
123          "did not remove all blocks from block scope map!");
124   assert(CleanupEntries.empty() &&
125          "mismatched push/pop in cleanup stack!");
126 
127   // Emit function epilog (to return).
128   EmitReturnBlock();
129 
130   // Emit debug descriptor for function end.
131   if (CGDebugInfo *DI = getDebugInfo()) {
132     DI->setLocation(EndLoc);
133     DI->EmitRegionEnd(CurFn, Builder);
134   }
135 
136   EmitFunctionEpilog(*CurFnInfo, ReturnValue);
137   EmitEndEHSpec(CurCodeDecl);
138 
139   // If someone did an indirect goto, emit the indirect goto block at the end of
140   // the function.
141   if (IndirectBranch) {
142     EmitBlock(IndirectBranch->getParent());
143     Builder.ClearInsertionPoint();
144   }
145 
146   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
147   llvm::Instruction *Ptr = AllocaInsertPt;
148   AllocaInsertPt = 0;
149   Ptr->eraseFromParent();
150 
151   // If someone took the address of a label but never did an indirect goto, we
152   // made a zero entry PHI node, which is illegal, zap it now.
153   if (IndirectBranch) {
154     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155     if (PN->getNumIncomingValues() == 0) {
156       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157       PN->eraseFromParent();
158     }
159   }
160 }
161 
162 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
163                                     llvm::Function *Fn,
164                                     const FunctionArgList &Args,
165                                     SourceLocation StartLoc) {
166   const Decl *D = GD.getDecl();
167 
168   DidCallStackSave = false;
169   CurCodeDecl = CurFuncDecl = D;
170   FnRetTy = RetTy;
171   CurFn = Fn;
172   assert(CurFn->isDeclaration() && "Function already has body?");
173 
174   // Pass inline keyword to optimizer if it appears explicitly on any
175   // declaration.
176   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178            RE = FD->redecls_end(); RI != RE; ++RI)
179       if (RI->isInlineSpecified()) {
180         Fn->addFnAttr(llvm::Attribute::InlineHint);
181         break;
182       }
183 
184   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
185 
186   // Create a marker to make it easy to insert allocas into the entryblock
187   // later.  Don't create this with the builder, because we don't want it
188   // folded.
189   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
190   AllocaInsertPt = new llvm::BitCastInst(Undef,
191                                          llvm::Type::getInt32Ty(VMContext), "",
192                                          EntryBB);
193   if (Builder.isNamePreserving())
194     AllocaInsertPt->setName("allocapt");
195 
196   ReturnBlock = createBasicBlock("return");
197 
198   Builder.SetInsertPoint(EntryBB);
199 
200   QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
201 
202   // Emit subprogram debug descriptor.
203   if (CGDebugInfo *DI = getDebugInfo()) {
204     DI->setLocation(StartLoc);
205     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
206   }
207 
208   // FIXME: Leaked.
209   // CC info is ignored, hopefully?
210   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
211                                               CC_Default, false);
212 
213   if (RetTy->isVoidType()) {
214     // Void type; nothing to return.
215     ReturnValue = 0;
216   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
217              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
218     // Indirect aggregate return; emit returned value directly into sret slot.
219     // This reduces code size, and affects correctness in C++.
220     ReturnValue = CurFn->arg_begin();
221   } else {
222     ReturnValue = CreateIRTemp(RetTy, "retval");
223   }
224 
225   EmitStartEHSpec(CurCodeDecl);
226   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
227 
228   if (CXXThisDecl)
229     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
230   if (CXXVTTDecl)
231     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
232 
233   // If any of the arguments have a variably modified type, make sure to
234   // emit the type size.
235   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
236        i != e; ++i) {
237     QualType Ty = i->second;
238 
239     if (Ty->isVariablyModifiedType())
240       EmitVLASize(Ty);
241   }
242 }
243 
244 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
245   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
246 
247   Stmt *Body = FD->getBody();
248   if (Body)
249     EmitStmt(Body);
250   else {
251     assert(FD->isImplicit() && "non-implicit function def has no body");
252     assert(FD->isCopyAssignment() && "implicit function not copy assignment");
253     SynthesizeCXXCopyAssignment(Args);
254   }
255 }
256 
257 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
258   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
259 
260   // Check if we should generate debug info for this function.
261   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
262     DebugInfo = CGM.getDebugInfo();
263 
264   FunctionArgList Args;
265 
266   CurGD = GD;
267   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
268     if (MD->isInstance()) {
269       // Create the implicit 'this' decl.
270       // FIXME: I'm not entirely sure I like using a fake decl just for code
271       // generation. Maybe we can come up with a better way?
272       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
273                                               FD->getLocation(),
274                                               &getContext().Idents.get("this"),
275                                               MD->getThisType(getContext()));
276       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
277 
278       // Check if we need a VTT parameter as well.
279       if (CGVtableInfo::needsVTTParameter(GD)) {
280         // FIXME: The comment about using a fake decl above applies here too.
281         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
282         CXXVTTDecl =
283           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
284                                     &getContext().Idents.get("vtt"), T);
285         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
286       }
287     }
288   }
289 
290   if (FD->getNumParams()) {
291     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
292     assert(FProto && "Function def must have prototype!");
293 
294     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
295       Args.push_back(std::make_pair(FD->getParamDecl(i),
296                                     FProto->getArgType(i)));
297   }
298 
299   SourceRange BodyRange;
300   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
301 
302   // Emit the standard function prologue.
303   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
304 
305   // Generate the body of the function.
306   if (isa<CXXDestructorDecl>(FD))
307     EmitDestructorBody(Args);
308   else if (isa<CXXConstructorDecl>(FD))
309     EmitConstructorBody(Args);
310   else
311     EmitFunctionBody(Args);
312 
313   // Emit the standard function epilogue.
314   FinishFunction(BodyRange.getEnd());
315 
316   // Destroy the 'this' declaration.
317   if (CXXThisDecl)
318     CXXThisDecl->Destroy(getContext());
319 
320   // Destroy the VTT declaration.
321   if (CXXVTTDecl)
322     CXXVTTDecl->Destroy(getContext());
323 }
324 
325 /// ContainsLabel - Return true if the statement contains a label in it.  If
326 /// this statement is not executed normally, it not containing a label means
327 /// that we can just remove the code.
328 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
329   // Null statement, not a label!
330   if (S == 0) return false;
331 
332   // If this is a label, we have to emit the code, consider something like:
333   // if (0) {  ...  foo:  bar(); }  goto foo;
334   if (isa<LabelStmt>(S))
335     return true;
336 
337   // If this is a case/default statement, and we haven't seen a switch, we have
338   // to emit the code.
339   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
340     return true;
341 
342   // If this is a switch statement, we want to ignore cases below it.
343   if (isa<SwitchStmt>(S))
344     IgnoreCaseStmts = true;
345 
346   // Scan subexpressions for verboten labels.
347   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
348        I != E; ++I)
349     if (ContainsLabel(*I, IgnoreCaseStmts))
350       return true;
351 
352   return false;
353 }
354 
355 
356 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
357 /// a constant, or if it does but contains a label, return 0.  If it constant
358 /// folds to 'true' and does not contain a label, return 1, if it constant folds
359 /// to 'false' and does not contain a label, return -1.
360 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
361   // FIXME: Rename and handle conversion of other evaluatable things
362   // to bool.
363   Expr::EvalResult Result;
364   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
365       Result.HasSideEffects)
366     return 0;  // Not foldable, not integer or not fully evaluatable.
367 
368   if (CodeGenFunction::ContainsLabel(Cond))
369     return 0;  // Contains a label.
370 
371   return Result.Val.getInt().getBoolValue() ? 1 : -1;
372 }
373 
374 
375 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
376 /// statement) to the specified blocks.  Based on the condition, this might try
377 /// to simplify the codegen of the conditional based on the branch.
378 ///
379 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
380                                            llvm::BasicBlock *TrueBlock,
381                                            llvm::BasicBlock *FalseBlock) {
382   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
383     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
384 
385   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
386     // Handle X && Y in a condition.
387     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
388       // If we have "1 && X", simplify the code.  "0 && X" would have constant
389       // folded if the case was simple enough.
390       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
391         // br(1 && X) -> br(X).
392         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
393       }
394 
395       // If we have "X && 1", simplify the code to use an uncond branch.
396       // "X && 0" would have been constant folded to 0.
397       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
398         // br(X && 1) -> br(X).
399         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
400       }
401 
402       // Emit the LHS as a conditional.  If the LHS conditional is false, we
403       // want to jump to the FalseBlock.
404       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
405       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
406       EmitBlock(LHSTrue);
407 
408       // Any temporaries created here are conditional.
409       BeginConditionalBranch();
410       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
411       EndConditionalBranch();
412 
413       return;
414     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
415       // If we have "0 || X", simplify the code.  "1 || X" would have constant
416       // folded if the case was simple enough.
417       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
418         // br(0 || X) -> br(X).
419         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
420       }
421 
422       // If we have "X || 0", simplify the code to use an uncond branch.
423       // "X || 1" would have been constant folded to 1.
424       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
425         // br(X || 0) -> br(X).
426         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
427       }
428 
429       // Emit the LHS as a conditional.  If the LHS conditional is true, we
430       // want to jump to the TrueBlock.
431       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
432       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
433       EmitBlock(LHSFalse);
434 
435       // Any temporaries created here are conditional.
436       BeginConditionalBranch();
437       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
438       EndConditionalBranch();
439 
440       return;
441     }
442   }
443 
444   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
445     // br(!x, t, f) -> br(x, f, t)
446     if (CondUOp->getOpcode() == UnaryOperator::LNot)
447       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
448   }
449 
450   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
451     // Handle ?: operator.
452 
453     // Just ignore GNU ?: extension.
454     if (CondOp->getLHS()) {
455       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
456       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
457       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
458       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
459       EmitBlock(LHSBlock);
460       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
461       EmitBlock(RHSBlock);
462       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
463       return;
464     }
465   }
466 
467   // Emit the code with the fully general case.
468   llvm::Value *CondV = EvaluateExprAsBool(Cond);
469   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
470 }
471 
472 /// ErrorUnsupported - Print out an error that codegen doesn't support the
473 /// specified stmt yet.
474 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
475                                        bool OmitOnError) {
476   CGM.ErrorUnsupported(S, Type, OmitOnError);
477 }
478 
479 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
480   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
481   if (DestPtr->getType() != BP)
482     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
483 
484   // Get size and alignment info for this aggregate.
485   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
486 
487   // Don't bother emitting a zero-byte memset.
488   if (TypeInfo.first == 0)
489     return;
490 
491   // FIXME: Handle variable sized types.
492   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
493                                                     LLVMPointerWidth);
494 
495   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
496                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
497                       // TypeInfo.first describes size in bits.
498                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
499                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
500                                              TypeInfo.second/8));
501 }
502 
503 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
504   // Make sure that there is a block for the indirect goto.
505   if (IndirectBranch == 0)
506     GetIndirectGotoBlock();
507 
508   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
509 
510   // Make sure the indirect branch includes all of the address-taken blocks.
511   IndirectBranch->addDestination(BB);
512   return llvm::BlockAddress::get(CurFn, BB);
513 }
514 
515 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
516   // If we already made the indirect branch for indirect goto, return its block.
517   if (IndirectBranch) return IndirectBranch->getParent();
518 
519   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
520 
521   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
522 
523   // Create the PHI node that indirect gotos will add entries to.
524   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
525 
526   // Create the indirect branch instruction.
527   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
528   return IndirectBranch->getParent();
529 }
530 
531 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
532   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
533 
534   assert(SizeEntry && "Did not emit size for type");
535   return SizeEntry;
536 }
537 
538 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
539   assert(Ty->isVariablyModifiedType() &&
540          "Must pass variably modified type to EmitVLASizes!");
541 
542   EnsureInsertPoint();
543 
544   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
545     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
546 
547     if (!SizeEntry) {
548       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
549 
550       // Get the element size;
551       QualType ElemTy = VAT->getElementType();
552       llvm::Value *ElemSize;
553       if (ElemTy->isVariableArrayType())
554         ElemSize = EmitVLASize(ElemTy);
555       else
556         ElemSize = llvm::ConstantInt::get(SizeTy,
557             getContext().getTypeSizeInChars(ElemTy).getQuantity());
558 
559       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
560       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
561 
562       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
563     }
564 
565     return SizeEntry;
566   }
567 
568   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
569     EmitVLASize(AT->getElementType());
570     return 0;
571   }
572 
573   const PointerType *PT = Ty->getAs<PointerType>();
574   assert(PT && "unknown VM type!");
575   EmitVLASize(PT->getPointeeType());
576   return 0;
577 }
578 
579 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
580   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
581     return EmitScalarExpr(E);
582   }
583   return EmitLValue(E).getAddress();
584 }
585 
586 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
587                                        llvm::BasicBlock *CleanupExitBlock,
588                                        llvm::BasicBlock *PreviousInvokeDest,
589                                        bool EHOnly) {
590   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
591                                         PreviousInvokeDest, EHOnly));
592 }
593 
594 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
595   assert(CleanupEntries.size() >= OldCleanupStackSize &&
596          "Cleanup stack mismatch!");
597 
598   while (CleanupEntries.size() > OldCleanupStackSize)
599     EmitCleanupBlock();
600 }
601 
602 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
603   CleanupEntry &CE = CleanupEntries.back();
604 
605   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
606 
607   std::vector<llvm::BasicBlock *> Blocks;
608   std::swap(Blocks, CE.Blocks);
609 
610   std::vector<llvm::BranchInst *> BranchFixups;
611   std::swap(BranchFixups, CE.BranchFixups);
612 
613   bool EHOnly = CE.EHOnly;
614 
615   setInvokeDest(CE.PreviousInvokeDest);
616 
617   CleanupEntries.pop_back();
618 
619   // Check if any branch fixups pointed to the scope we just popped. If so,
620   // we can remove them.
621   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
622     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
623     BlockScopeMap::iterator I = BlockScopes.find(Dest);
624 
625     if (I == BlockScopes.end())
626       continue;
627 
628     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
629 
630     if (I->second == CleanupEntries.size()) {
631       // We don't need to do this branch fixup.
632       BranchFixups[i] = BranchFixups.back();
633       BranchFixups.pop_back();
634       i--;
635       e--;
636       continue;
637     }
638   }
639 
640   llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
641   llvm::BasicBlock *EndBlock = 0;
642   if (!BranchFixups.empty()) {
643     if (!SwitchBlock)
644       SwitchBlock = createBasicBlock("cleanup.switch");
645     EndBlock = createBasicBlock("cleanup.end");
646 
647     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
648 
649     Builder.SetInsertPoint(SwitchBlock);
650 
651     llvm::Value *DestCodePtr
652       = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
653                          "cleanup.dst");
654     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
655 
656     // Create a switch instruction to determine where to jump next.
657     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
658                                                 BranchFixups.size());
659 
660     // Restore the current basic block (if any)
661     if (CurBB) {
662       Builder.SetInsertPoint(CurBB);
663 
664       // If we had a current basic block, we also need to emit an instruction
665       // to initialize the cleanup destination.
666       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
667                           DestCodePtr);
668     } else
669       Builder.ClearInsertionPoint();
670 
671     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
672       llvm::BranchInst *BI = BranchFixups[i];
673       llvm::BasicBlock *Dest = BI->getSuccessor(0);
674 
675       // Fixup the branch instruction to point to the cleanup block.
676       BI->setSuccessor(0, CleanupEntryBlock);
677 
678       if (CleanupEntries.empty()) {
679         llvm::ConstantInt *ID;
680 
681         // Check if we already have a destination for this block.
682         if (Dest == SI->getDefaultDest())
683           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
684         else {
685           ID = SI->findCaseDest(Dest);
686           if (!ID) {
687             // No code found, get a new unique one by using the number of
688             // switch successors.
689             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
690                                         SI->getNumSuccessors());
691             SI->addCase(ID, Dest);
692           }
693         }
694 
695         // Store the jump destination before the branch instruction.
696         new llvm::StoreInst(ID, DestCodePtr, BI);
697       } else {
698         // We need to jump through another cleanup block. Create a pad block
699         // with a branch instruction that jumps to the final destination and add
700         // it as a branch fixup to the current cleanup scope.
701 
702         // Create the pad block.
703         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
704 
705         // Create a unique case ID.
706         llvm::ConstantInt *ID
707           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
708                                    SI->getNumSuccessors());
709 
710         // Store the jump destination before the branch instruction.
711         new llvm::StoreInst(ID, DestCodePtr, BI);
712 
713         // Add it as the destination.
714         SI->addCase(ID, CleanupPad);
715 
716         // Create the branch to the final destination.
717         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
718         CleanupPad->getInstList().push_back(BI);
719 
720         // And add it as a branch fixup.
721         CleanupEntries.back().BranchFixups.push_back(BI);
722       }
723     }
724   }
725 
726   // Remove all blocks from the block scope map.
727   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
728     assert(BlockScopes.count(Blocks[i]) &&
729            "Did not find block in scope map!");
730 
731     BlockScopes.erase(Blocks[i]);
732   }
733 
734   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
735 }
736 
737 void CodeGenFunction::EmitCleanupBlock() {
738   CleanupBlockInfo Info = PopCleanupBlock();
739 
740   if (Info.EHOnly) {
741     // FIXME: Add this to the exceptional edge
742     if (Info.CleanupBlock->getNumUses() == 0)
743       delete Info.CleanupBlock;
744     return;
745   }
746 
747   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
748   if (CurBB && !CurBB->getTerminator() &&
749       Info.CleanupBlock->getNumUses() == 0) {
750     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
751     delete Info.CleanupBlock;
752   } else
753     EmitBlock(Info.CleanupBlock);
754 
755   if (Info.SwitchBlock)
756     EmitBlock(Info.SwitchBlock);
757   if (Info.EndBlock)
758     EmitBlock(Info.EndBlock);
759 }
760 
761 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
762   assert(!CleanupEntries.empty() &&
763          "Trying to add branch fixup without cleanup block!");
764 
765   // FIXME: We could be more clever here and check if there's already a branch
766   // fixup for this destination and recycle it.
767   CleanupEntries.back().BranchFixups.push_back(BI);
768 }
769 
770 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
771   if (!HaveInsertPoint())
772     return;
773 
774   llvm::BranchInst* BI = Builder.CreateBr(Dest);
775 
776   Builder.ClearInsertionPoint();
777 
778   // The stack is empty, no need to do any cleanup.
779   if (CleanupEntries.empty())
780     return;
781 
782   if (!Dest->getParent()) {
783     // We are trying to branch to a block that hasn't been inserted yet.
784     AddBranchFixup(BI);
785     return;
786   }
787 
788   BlockScopeMap::iterator I = BlockScopes.find(Dest);
789   if (I == BlockScopes.end()) {
790     // We are trying to jump to a block that is outside of any cleanup scope.
791     AddBranchFixup(BI);
792     return;
793   }
794 
795   assert(I->second < CleanupEntries.size() &&
796          "Trying to branch into cleanup region");
797 
798   if (I->second == CleanupEntries.size() - 1) {
799     // We have a branch to a block in the same scope.
800     return;
801   }
802 
803   AddBranchFixup(BI);
804 }
805