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