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