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