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                                                  false, false, 0, 0,
202                                                  /*FIXME?*/
203                                                  FunctionType::ExtInfo());
204 
205   // Emit subprogram debug descriptor.
206   if (CGDebugInfo *DI = getDebugInfo()) {
207     DI->setLocation(StartLoc);
208     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
209   }
210 
211   // FIXME: Leaked.
212   // CC info is ignored, hopefully?
213   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
214                                               FunctionType::ExtInfo());
215 
216   if (RetTy->isVoidType()) {
217     // Void type; nothing to return.
218     ReturnValue = 0;
219   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
220              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
221     // Indirect aggregate return; emit returned value directly into sret slot.
222     // This reduces code size, and affects correctness in C++.
223     ReturnValue = CurFn->arg_begin();
224   } else {
225     ReturnValue = CreateIRTemp(RetTy, "retval");
226   }
227 
228   EmitStartEHSpec(CurCodeDecl);
229   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
230 
231   if (CXXThisDecl)
232     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
233   if (CXXVTTDecl)
234     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
235 
236   // If any of the arguments have a variably modified type, make sure to
237   // emit the type size.
238   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
239        i != e; ++i) {
240     QualType Ty = i->second;
241 
242     if (Ty->isVariablyModifiedType())
243       EmitVLASize(Ty);
244   }
245 }
246 
247 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
248   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
249   assert(FD->getBody());
250   EmitStmt(FD->getBody());
251 }
252 
253 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
254   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
255 
256   // Check if we should generate debug info for this function.
257   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
258     DebugInfo = CGM.getDebugInfo();
259 
260   FunctionArgList Args;
261 
262   CurGD = GD;
263   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
264     if (MD->isInstance()) {
265       // Create the implicit 'this' decl.
266       // FIXME: I'm not entirely sure I like using a fake decl just for code
267       // generation. Maybe we can come up with a better way?
268       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
269                                               FD->getLocation(),
270                                               &getContext().Idents.get("this"),
271                                               MD->getThisType(getContext()));
272       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
273 
274       // Check if we need a VTT parameter as well.
275       if (CodeGenVTables::needsVTTParameter(GD)) {
276         // FIXME: The comment about using a fake decl above applies here too.
277         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
278         CXXVTTDecl =
279           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
280                                     &getContext().Idents.get("vtt"), T);
281         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
282       }
283     }
284   }
285 
286   if (FD->getNumParams()) {
287     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
288     assert(FProto && "Function def must have prototype!");
289 
290     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
291       Args.push_back(std::make_pair(FD->getParamDecl(i),
292                                     FProto->getArgType(i)));
293   }
294 
295   SourceRange BodyRange;
296   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
297 
298   // Emit the standard function prologue.
299   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
300 
301   // Generate the body of the function.
302   if (isa<CXXDestructorDecl>(FD))
303     EmitDestructorBody(Args);
304   else if (isa<CXXConstructorDecl>(FD))
305     EmitConstructorBody(Args);
306   else
307     EmitFunctionBody(Args);
308 
309   // Emit the standard function epilogue.
310   FinishFunction(BodyRange.getEnd());
311 
312   // Destroy the 'this' declaration.
313   if (CXXThisDecl)
314     CXXThisDecl->Destroy(getContext());
315 
316   // Destroy the VTT declaration.
317   if (CXXVTTDecl)
318     CXXVTTDecl->Destroy(getContext());
319 }
320 
321 /// ContainsLabel - Return true if the statement contains a label in it.  If
322 /// this statement is not executed normally, it not containing a label means
323 /// that we can just remove the code.
324 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
325   // Null statement, not a label!
326   if (S == 0) return false;
327 
328   // If this is a label, we have to emit the code, consider something like:
329   // if (0) {  ...  foo:  bar(); }  goto foo;
330   if (isa<LabelStmt>(S))
331     return true;
332 
333   // If this is a case/default statement, and we haven't seen a switch, we have
334   // to emit the code.
335   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
336     return true;
337 
338   // If this is a switch statement, we want to ignore cases below it.
339   if (isa<SwitchStmt>(S))
340     IgnoreCaseStmts = true;
341 
342   // Scan subexpressions for verboten labels.
343   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
344        I != E; ++I)
345     if (ContainsLabel(*I, IgnoreCaseStmts))
346       return true;
347 
348   return false;
349 }
350 
351 
352 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
353 /// a constant, or if it does but contains a label, return 0.  If it constant
354 /// folds to 'true' and does not contain a label, return 1, if it constant folds
355 /// to 'false' and does not contain a label, return -1.
356 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
357   // FIXME: Rename and handle conversion of other evaluatable things
358   // to bool.
359   Expr::EvalResult Result;
360   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
361       Result.HasSideEffects)
362     return 0;  // Not foldable, not integer or not fully evaluatable.
363 
364   if (CodeGenFunction::ContainsLabel(Cond))
365     return 0;  // Contains a label.
366 
367   return Result.Val.getInt().getBoolValue() ? 1 : -1;
368 }
369 
370 
371 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
372 /// statement) to the specified blocks.  Based on the condition, this might try
373 /// to simplify the codegen of the conditional based on the branch.
374 ///
375 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
376                                            llvm::BasicBlock *TrueBlock,
377                                            llvm::BasicBlock *FalseBlock) {
378   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
379     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
380 
381   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
382     // Handle X && Y in a condition.
383     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
384       // If we have "1 && X", simplify the code.  "0 && X" would have constant
385       // folded if the case was simple enough.
386       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
387         // br(1 && X) -> br(X).
388         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
389       }
390 
391       // If we have "X && 1", simplify the code to use an uncond branch.
392       // "X && 0" would have been constant folded to 0.
393       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
394         // br(X && 1) -> br(X).
395         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
396       }
397 
398       // Emit the LHS as a conditional.  If the LHS conditional is false, we
399       // want to jump to the FalseBlock.
400       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
401       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
402       EmitBlock(LHSTrue);
403 
404       // Any temporaries created here are conditional.
405       BeginConditionalBranch();
406       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
407       EndConditionalBranch();
408 
409       return;
410     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
411       // If we have "0 || X", simplify the code.  "1 || X" would have constant
412       // folded if the case was simple enough.
413       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
414         // br(0 || X) -> br(X).
415         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
416       }
417 
418       // If we have "X || 0", simplify the code to use an uncond branch.
419       // "X || 1" would have been constant folded to 1.
420       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
421         // br(X || 0) -> br(X).
422         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
423       }
424 
425       // Emit the LHS as a conditional.  If the LHS conditional is true, we
426       // want to jump to the TrueBlock.
427       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
428       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
429       EmitBlock(LHSFalse);
430 
431       // Any temporaries created here are conditional.
432       BeginConditionalBranch();
433       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
434       EndConditionalBranch();
435 
436       return;
437     }
438   }
439 
440   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
441     // br(!x, t, f) -> br(x, f, t)
442     if (CondUOp->getOpcode() == UnaryOperator::LNot)
443       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
444   }
445 
446   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
447     // Handle ?: operator.
448 
449     // Just ignore GNU ?: extension.
450     if (CondOp->getLHS()) {
451       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
452       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
453       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
454       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
455       EmitBlock(LHSBlock);
456       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
457       EmitBlock(RHSBlock);
458       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
459       return;
460     }
461   }
462 
463   // Emit the code with the fully general case.
464   llvm::Value *CondV = EvaluateExprAsBool(Cond);
465   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
466 }
467 
468 /// ErrorUnsupported - Print out an error that codegen doesn't support the
469 /// specified stmt yet.
470 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
471                                        bool OmitOnError) {
472   CGM.ErrorUnsupported(S, Type, OmitOnError);
473 }
474 
475 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
476   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
477   if (DestPtr->getType() != BP)
478     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
479 
480   // Get size and alignment info for this aggregate.
481   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
482 
483   // Don't bother emitting a zero-byte memset.
484   if (TypeInfo.first == 0)
485     return;
486 
487   // FIXME: Handle variable sized types.
488   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
489                                                     LLVMPointerWidth);
490 
491   Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
492                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
493                       // TypeInfo.first describes size in bits.
494                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
495                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
496                                              TypeInfo.second/8),
497                       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
498                                              0));
499 }
500 
501 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
502   // Make sure that there is a block for the indirect goto.
503   if (IndirectBranch == 0)
504     GetIndirectGotoBlock();
505 
506   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
507 
508   // Make sure the indirect branch includes all of the address-taken blocks.
509   IndirectBranch->addDestination(BB);
510   return llvm::BlockAddress::get(CurFn, BB);
511 }
512 
513 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
514   // If we already made the indirect branch for indirect goto, return its block.
515   if (IndirectBranch) return IndirectBranch->getParent();
516 
517   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
518 
519   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
520 
521   // Create the PHI node that indirect gotos will add entries to.
522   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
523 
524   // Create the indirect branch instruction.
525   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
526   return IndirectBranch->getParent();
527 }
528 
529 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
530   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
531 
532   assert(SizeEntry && "Did not emit size for type");
533   return SizeEntry;
534 }
535 
536 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
537   assert(Ty->isVariablyModifiedType() &&
538          "Must pass variably modified type to EmitVLASizes!");
539 
540   EnsureInsertPoint();
541 
542   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
543     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
544 
545     if (!SizeEntry) {
546       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
547 
548       // Get the element size;
549       QualType ElemTy = VAT->getElementType();
550       llvm::Value *ElemSize;
551       if (ElemTy->isVariableArrayType())
552         ElemSize = EmitVLASize(ElemTy);
553       else
554         ElemSize = llvm::ConstantInt::get(SizeTy,
555             getContext().getTypeSizeInChars(ElemTy).getQuantity());
556 
557       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
558       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
559 
560       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
561     }
562 
563     return SizeEntry;
564   }
565 
566   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
567     EmitVLASize(AT->getElementType());
568     return 0;
569   }
570 
571   const PointerType *PT = Ty->getAs<PointerType>();
572   assert(PT && "unknown VM type!");
573   EmitVLASize(PT->getPointeeType());
574   return 0;
575 }
576 
577 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
578   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
579     return EmitScalarExpr(E);
580   }
581   return EmitLValue(E).getAddress();
582 }
583 
584 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
585                                        llvm::BasicBlock *CleanupExitBlock,
586                                        llvm::BasicBlock *PreviousInvokeDest,
587                                        bool EHOnly) {
588   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
589                                         PreviousInvokeDest, EHOnly));
590 }
591 
592 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
593   assert(CleanupEntries.size() >= OldCleanupStackSize &&
594          "Cleanup stack mismatch!");
595 
596   while (CleanupEntries.size() > OldCleanupStackSize)
597     EmitCleanupBlock();
598 }
599 
600 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
601   CleanupEntry &CE = CleanupEntries.back();
602 
603   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
604 
605   std::vector<llvm::BasicBlock *> Blocks;
606   std::swap(Blocks, CE.Blocks);
607 
608   std::vector<llvm::BranchInst *> BranchFixups;
609   std::swap(BranchFixups, CE.BranchFixups);
610 
611   bool EHOnly = CE.EHOnly;
612 
613   setInvokeDest(CE.PreviousInvokeDest);
614 
615   CleanupEntries.pop_back();
616 
617   // Check if any branch fixups pointed to the scope we just popped. If so,
618   // we can remove them.
619   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
620     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
621     BlockScopeMap::iterator I = BlockScopes.find(Dest);
622 
623     if (I == BlockScopes.end())
624       continue;
625 
626     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
627 
628     if (I->second == CleanupEntries.size()) {
629       // We don't need to do this branch fixup.
630       BranchFixups[i] = BranchFixups.back();
631       BranchFixups.pop_back();
632       i--;
633       e--;
634       continue;
635     }
636   }
637 
638   llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
639   llvm::BasicBlock *EndBlock = 0;
640   if (!BranchFixups.empty()) {
641     if (!SwitchBlock)
642       SwitchBlock = createBasicBlock("cleanup.switch");
643     EndBlock = createBasicBlock("cleanup.end");
644 
645     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
646 
647     Builder.SetInsertPoint(SwitchBlock);
648 
649     llvm::Value *DestCodePtr
650       = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
651                          "cleanup.dst");
652     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
653 
654     // Create a switch instruction to determine where to jump next.
655     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
656                                                 BranchFixups.size());
657 
658     // Restore the current basic block (if any)
659     if (CurBB) {
660       Builder.SetInsertPoint(CurBB);
661 
662       // If we had a current basic block, we also need to emit an instruction
663       // to initialize the cleanup destination.
664       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
665                           DestCodePtr);
666     } else
667       Builder.ClearInsertionPoint();
668 
669     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
670       llvm::BranchInst *BI = BranchFixups[i];
671       llvm::BasicBlock *Dest = BI->getSuccessor(0);
672 
673       // Fixup the branch instruction to point to the cleanup block.
674       BI->setSuccessor(0, CleanupEntryBlock);
675 
676       if (CleanupEntries.empty()) {
677         llvm::ConstantInt *ID;
678 
679         // Check if we already have a destination for this block.
680         if (Dest == SI->getDefaultDest())
681           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
682         else {
683           ID = SI->findCaseDest(Dest);
684           if (!ID) {
685             // No code found, get a new unique one by using the number of
686             // switch successors.
687             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
688                                         SI->getNumSuccessors());
689             SI->addCase(ID, Dest);
690           }
691         }
692 
693         // Store the jump destination before the branch instruction.
694         new llvm::StoreInst(ID, DestCodePtr, BI);
695       } else {
696         // We need to jump through another cleanup block. Create a pad block
697         // with a branch instruction that jumps to the final destination and add
698         // it as a branch fixup to the current cleanup scope.
699 
700         // Create the pad block.
701         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
702 
703         // Create a unique case ID.
704         llvm::ConstantInt *ID
705           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
706                                    SI->getNumSuccessors());
707 
708         // Store the jump destination before the branch instruction.
709         new llvm::StoreInst(ID, DestCodePtr, BI);
710 
711         // Add it as the destination.
712         SI->addCase(ID, CleanupPad);
713 
714         // Create the branch to the final destination.
715         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
716         CleanupPad->getInstList().push_back(BI);
717 
718         // And add it as a branch fixup.
719         CleanupEntries.back().BranchFixups.push_back(BI);
720       }
721     }
722   }
723 
724   // Remove all blocks from the block scope map.
725   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
726     assert(BlockScopes.count(Blocks[i]) &&
727            "Did not find block in scope map!");
728 
729     BlockScopes.erase(Blocks[i]);
730   }
731 
732   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
733 }
734 
735 void CodeGenFunction::EmitCleanupBlock() {
736   CleanupBlockInfo Info = PopCleanupBlock();
737 
738   if (Info.EHOnly) {
739     // FIXME: Add this to the exceptional edge
740     if (Info.CleanupBlock->getNumUses() == 0)
741       delete Info.CleanupBlock;
742     return;
743   }
744 
745   //  Scrub debug location info.
746   for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
747          LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
748     Builder.SetInstDebugLocation(LBI);
749 
750   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
751   if (CurBB && !CurBB->getTerminator() &&
752       Info.CleanupBlock->getNumUses() == 0) {
753     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
754     delete Info.CleanupBlock;
755   } else
756     EmitBlock(Info.CleanupBlock);
757 
758   if (Info.SwitchBlock)
759     EmitBlock(Info.SwitchBlock);
760   if (Info.EndBlock)
761     EmitBlock(Info.EndBlock);
762 }
763 
764 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
765   assert(!CleanupEntries.empty() &&
766          "Trying to add branch fixup without cleanup block!");
767 
768   // FIXME: We could be more clever here and check if there's already a branch
769   // fixup for this destination and recycle it.
770   CleanupEntries.back().BranchFixups.push_back(BI);
771 }
772 
773 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
774   if (!HaveInsertPoint())
775     return;
776 
777   llvm::BranchInst* BI = Builder.CreateBr(Dest);
778 
779   Builder.ClearInsertionPoint();
780 
781   // The stack is empty, no need to do any cleanup.
782   if (CleanupEntries.empty())
783     return;
784 
785   if (!Dest->getParent()) {
786     // We are trying to branch to a block that hasn't been inserted yet.
787     AddBranchFixup(BI);
788     return;
789   }
790 
791   BlockScopeMap::iterator I = BlockScopes.find(Dest);
792   if (I == BlockScopes.end()) {
793     // We are trying to jump to a block that is outside of any cleanup scope.
794     AddBranchFixup(BI);
795     return;
796   }
797 
798   assert(I->second < CleanupEntries.size() &&
799          "Trying to branch into cleanup region");
800 
801   if (I->second == CleanupEntries.size() - 1) {
802     // We have a branch to a block in the same scope.
803     return;
804   }
805 
806   AddBranchFixup(BI);
807 }
808