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