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