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