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