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