xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision 89b12b34f6bdb715eaad3996d22e2a49ab912692)
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 "clang/AST/StmtCXX.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
28   : BlockFunction(cgm, *this, Builder), CGM(cgm),
29     Target(CGM.getContext().Target),
30     Builder(cgm.getModule().getContext()),
31     DebugInfo(0), IndirectBranch(0),
32     SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
33     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
34     ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
35     UniqueAggrDestructorCount(0) {
36   LLVMIntTy = ConvertType(getContext().IntTy);
37   LLVMPointerWidth = Target.getPointerWidth(0);
38   Exceptions = getContext().getLangOptions().Exceptions;
39   CatchUndefined = getContext().getLangOptions().CatchUndefined;
40 }
41 
42 ASTContext &CodeGenFunction::getContext() const {
43   return CGM.getContext();
44 }
45 
46 
47 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
48   llvm::BasicBlock *&BB = LabelMap[S];
49   if (BB) return BB;
50 
51   // Create, but don't insert, the new block.
52   return BB = createBasicBlock(S->getName());
53 }
54 
55 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
56   llvm::Value *Res = LocalDeclMap[VD];
57   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
58   return Res;
59 }
60 
61 llvm::Constant *
62 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
63   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
64 }
65 
66 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
67   return CGM.getTypes().ConvertTypeForMem(T);
68 }
69 
70 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
71   return CGM.getTypes().ConvertType(T);
72 }
73 
74 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
75   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
76     T->isMemberFunctionPointerType();
77 }
78 
79 void CodeGenFunction::EmitReturnBlock() {
80   // For cleanliness, we try to avoid emitting the return block for
81   // simple cases.
82   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
83 
84   if (CurBB) {
85     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
86 
87     // We have a valid insert point, reuse it if it is empty or there are no
88     // explicit jumps to the return block.
89     if (CurBB->empty() || ReturnBlock->use_empty()) {
90       ReturnBlock->replaceAllUsesWith(CurBB);
91       delete ReturnBlock;
92     } else
93       EmitBlock(ReturnBlock);
94     return;
95   }
96 
97   // Otherwise, if the return block is the target of a single direct
98   // branch then we can just put the code in that block instead. This
99   // cleans up functions which started with a unified return block.
100   if (ReturnBlock->hasOneUse()) {
101     llvm::BranchInst *BI =
102       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
103     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
104       // Reset insertion point and delete the branch.
105       Builder.SetInsertPoint(BI->getParent());
106       BI->eraseFromParent();
107       delete ReturnBlock;
108       return;
109     }
110   }
111 
112   // FIXME: We are at an unreachable point, there is no reason to emit the block
113   // unless it has uses. However, we still need a place to put the debug
114   // region.end for now.
115 
116   EmitBlock(ReturnBlock);
117 }
118 
119 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
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   EmitEndEHSpec(CurCodeDecl);
138 
139   // If someone did an indirect goto, emit the indirect goto block at the end of
140   // the function.
141   if (IndirectBranch) {
142     EmitBlock(IndirectBranch->getParent());
143     Builder.ClearInsertionPoint();
144   }
145 
146   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
147   llvm::Instruction *Ptr = AllocaInsertPt;
148   AllocaInsertPt = 0;
149   Ptr->eraseFromParent();
150 
151   // If someone took the address of a label but never did an indirect goto, we
152   // made a zero entry PHI node, which is illegal, zap it now.
153   if (IndirectBranch) {
154     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
155     if (PN->getNumIncomingValues() == 0) {
156       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
157       PN->eraseFromParent();
158     }
159   }
160 }
161 
162 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
163                                     llvm::Function *Fn,
164                                     const FunctionArgList &Args,
165                                     SourceLocation StartLoc) {
166   const Decl *D = GD.getDecl();
167 
168   DidCallStackSave = false;
169   CurCodeDecl = CurFuncDecl = D;
170   FnRetTy = RetTy;
171   CurFn = Fn;
172   assert(CurFn->isDeclaration() && "Function already has body?");
173 
174   // Pass inline keyword to optimizer if it appears explicitly on any
175   // declaration.
176   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
177     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
178            RE = FD->redecls_end(); RI != RE; ++RI)
179       if (RI->isInlineSpecified()) {
180         Fn->addFnAttr(llvm::Attribute::InlineHint);
181         break;
182       }
183 
184   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
185 
186   // Create a marker to make it easy to insert allocas into the entryblock
187   // later.  Don't create this with the builder, because we don't want it
188   // folded.
189   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
190   AllocaInsertPt = new llvm::BitCastInst(Undef,
191                                          llvm::Type::getInt32Ty(VMContext), "",
192                                          EntryBB);
193   if (Builder.isNamePreserving())
194     AllocaInsertPt->setName("allocapt");
195 
196   ReturnBlock = createBasicBlock("return");
197 
198   Builder.SetInsertPoint(EntryBB);
199 
200   QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0);
201 
202   // Emit subprogram debug descriptor.
203   if (CGDebugInfo *DI = getDebugInfo()) {
204     DI->setLocation(StartLoc);
205     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
206   }
207 
208   // FIXME: Leaked.
209   // CC info is ignored, hopefully?
210   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
211                                               CC_Default, false);
212 
213   if (RetTy->isVoidType()) {
214     // Void type; nothing to return.
215     ReturnValue = 0;
216   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
217              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
218     // Indirect aggregate return; emit returned value directly into sret slot.
219     // This reduces code size, and affects correctness in C++.
220     ReturnValue = CurFn->arg_begin();
221   } else {
222     ReturnValue = CreateIRTemp(RetTy, "retval");
223   }
224 
225   EmitStartEHSpec(CurCodeDecl);
226   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
227 
228   if (CXXThisDecl)
229     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
230   if (CXXVTTDecl)
231     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
232 
233   // If any of the arguments have a variably modified type, make sure to
234   // emit the type size.
235   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
236        i != e; ++i) {
237     QualType Ty = i->second;
238 
239     if (Ty->isVariablyModifiedType())
240       EmitVLASize(Ty);
241   }
242 }
243 
244 void CodeGenFunction::GenerateBody(GlobalDecl GD, llvm::Function *Fn,
245                                    FunctionArgList &Args) {
246   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
247 
248   Stmt *Body = FD->getBody();
249   assert((Body || FD->isImplicit()) && "non-implicit function def has no body");
250 
251   // Emit special ctor/dtor prologues.
252   llvm::BasicBlock *DtorEpilogue = 0;
253   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
254     EmitCtorPrologue(CD, GD.getCtorType());
255   } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
256     DtorEpilogue = createBasicBlock("dtor.epilogue");
257     PushCleanupBlock(DtorEpilogue);
258 
259     InitializeVtablePtrs(DD->getParent());
260   }
261 
262   // Emit the body of the function.
263   if (!Body)
264     SynthesizeImplicitFunctionBody(GD, Fn, Args);
265   else {
266     if (isa<CXXTryStmt>(Body))
267       OuterTryBlock = cast<CXXTryStmt>(Body);
268 
269     EmitStmt(Body);
270   }
271 
272   // Emit special ctor/ctor epilogues.
273   if (isa<CXXConstructorDecl>(FD)) {
274     // If any of the member initializers are temporaries bound to references
275     // make sure to emit their destructors.
276     EmitCleanupBlocks(0);
277   } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
278     CleanupBlockInfo Info = PopCleanupBlock();
279     assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!");
280 
281     EmitBlock(DtorEpilogue);
282     EmitDtorEpilogue(DD, GD.getDtorType());
283 
284     if (Info.SwitchBlock)
285       EmitBlock(Info.SwitchBlock);
286     if (Info.EndBlock)
287       EmitBlock(Info.EndBlock);
288   }
289 }
290 
291 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
292   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
293 
294   // Check if we should generate debug info for this function.
295   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
296     DebugInfo = CGM.getDebugInfo();
297 
298   FunctionArgList Args;
299 
300   CurGD = GD;
301   OuterTryBlock = 0;
302   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
303     if (MD->isInstance()) {
304       // Create the implicit 'this' decl.
305       // FIXME: I'm not entirely sure I like using a fake decl just for code
306       // generation. Maybe we can come up with a better way?
307       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
308                                               FD->getLocation(),
309                                               &getContext().Idents.get("this"),
310                                               MD->getThisType(getContext()));
311       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
312 
313       // Check if we need a VTT parameter as well.
314       if (CGVtableInfo::needsVTTParameter(GD)) {
315         // FIXME: The comment about using a fake decl above applies here too.
316         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
317         CXXVTTDecl =
318           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
319                                     &getContext().Idents.get("vtt"), T);
320         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
321       }
322     }
323   }
324 
325   if (FD->getNumParams()) {
326     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
327     assert(FProto && "Function def must have prototype!");
328 
329     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
330       Args.push_back(std::make_pair(FD->getParamDecl(i),
331                                     FProto->getArgType(i)));
332   }
333 
334   SourceRange BodyRange;
335   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
336 
337   // Emit the standard function prologue.
338   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
339 
340   // Generate the body of the function.
341   GenerateBody(GD, Fn, Args);
342 
343   // Emit the standard function epilogue.
344   FinishFunction(BodyRange.getEnd());
345 
346   // Destroy the 'this' declaration.
347   if (CXXThisDecl)
348     CXXThisDecl->Destroy(getContext());
349 
350   // Destroy the VTT declaration.
351   if (CXXVTTDecl)
352     CXXVTTDecl->Destroy(getContext());
353 }
354 
355 /// ContainsLabel - Return true if the statement contains a label in it.  If
356 /// this statement is not executed normally, it not containing a label means
357 /// that we can just remove the code.
358 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
359   // Null statement, not a label!
360   if (S == 0) return false;
361 
362   // If this is a label, we have to emit the code, consider something like:
363   // if (0) {  ...  foo:  bar(); }  goto foo;
364   if (isa<LabelStmt>(S))
365     return true;
366 
367   // If this is a case/default statement, and we haven't seen a switch, we have
368   // to emit the code.
369   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
370     return true;
371 
372   // If this is a switch statement, we want to ignore cases below it.
373   if (isa<SwitchStmt>(S))
374     IgnoreCaseStmts = true;
375 
376   // Scan subexpressions for verboten labels.
377   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
378        I != E; ++I)
379     if (ContainsLabel(*I, IgnoreCaseStmts))
380       return true;
381 
382   return false;
383 }
384 
385 
386 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
387 /// a constant, or if it does but contains a label, return 0.  If it constant
388 /// folds to 'true' and does not contain a label, return 1, if it constant folds
389 /// to 'false' and does not contain a label, return -1.
390 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
391   // FIXME: Rename and handle conversion of other evaluatable things
392   // to bool.
393   Expr::EvalResult Result;
394   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
395       Result.HasSideEffects)
396     return 0;  // Not foldable, not integer or not fully evaluatable.
397 
398   if (CodeGenFunction::ContainsLabel(Cond))
399     return 0;  // Contains a label.
400 
401   return Result.Val.getInt().getBoolValue() ? 1 : -1;
402 }
403 
404 
405 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
406 /// statement) to the specified blocks.  Based on the condition, this might try
407 /// to simplify the codegen of the conditional based on the branch.
408 ///
409 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
410                                            llvm::BasicBlock *TrueBlock,
411                                            llvm::BasicBlock *FalseBlock) {
412   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
413     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
414 
415   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
416     // Handle X && Y in a condition.
417     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
418       // If we have "1 && X", simplify the code.  "0 && X" would have constant
419       // folded if the case was simple enough.
420       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
421         // br(1 && X) -> br(X).
422         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
423       }
424 
425       // If we have "X && 1", simplify the code to use an uncond branch.
426       // "X && 0" would have been constant folded to 0.
427       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
428         // br(X && 1) -> br(X).
429         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
430       }
431 
432       // Emit the LHS as a conditional.  If the LHS conditional is false, we
433       // want to jump to the FalseBlock.
434       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
435       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
436       EmitBlock(LHSTrue);
437 
438       // Any temporaries created here are conditional.
439       BeginConditionalBranch();
440       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
441       EndConditionalBranch();
442 
443       return;
444     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
445       // If we have "0 || X", simplify the code.  "1 || X" would have constant
446       // folded if the case was simple enough.
447       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
448         // br(0 || X) -> br(X).
449         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
450       }
451 
452       // If we have "X || 0", simplify the code to use an uncond branch.
453       // "X || 1" would have been constant folded to 1.
454       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
455         // br(X || 0) -> br(X).
456         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
457       }
458 
459       // Emit the LHS as a conditional.  If the LHS conditional is true, we
460       // want to jump to the TrueBlock.
461       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
462       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
463       EmitBlock(LHSFalse);
464 
465       // Any temporaries created here are conditional.
466       BeginConditionalBranch();
467       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
468       EndConditionalBranch();
469 
470       return;
471     }
472   }
473 
474   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
475     // br(!x, t, f) -> br(x, f, t)
476     if (CondUOp->getOpcode() == UnaryOperator::LNot)
477       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
478   }
479 
480   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
481     // Handle ?: operator.
482 
483     // Just ignore GNU ?: extension.
484     if (CondOp->getLHS()) {
485       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
486       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
487       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
488       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
489       EmitBlock(LHSBlock);
490       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
491       EmitBlock(RHSBlock);
492       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
493       return;
494     }
495   }
496 
497   // Emit the code with the fully general case.
498   llvm::Value *CondV = EvaluateExprAsBool(Cond);
499   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
500 }
501 
502 /// ErrorUnsupported - Print out an error that codegen doesn't support the
503 /// specified stmt yet.
504 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
505                                        bool OmitOnError) {
506   CGM.ErrorUnsupported(S, Type, OmitOnError);
507 }
508 
509 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
510   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
511   if (DestPtr->getType() != BP)
512     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
513 
514   // Get size and alignment info for this aggregate.
515   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
516 
517   // Don't bother emitting a zero-byte memset.
518   if (TypeInfo.first == 0)
519     return;
520 
521   // FIXME: Handle variable sized types.
522   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
523                                                     LLVMPointerWidth);
524 
525   Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
526                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
527                       // TypeInfo.first describes size in bits.
528                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
529                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
530                                              TypeInfo.second/8));
531 }
532 
533 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
534   // Make sure that there is a block for the indirect goto.
535   if (IndirectBranch == 0)
536     GetIndirectGotoBlock();
537 
538   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
539 
540   // Make sure the indirect branch includes all of the address-taken blocks.
541   IndirectBranch->addDestination(BB);
542   return llvm::BlockAddress::get(CurFn, BB);
543 }
544 
545 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
546   // If we already made the indirect branch for indirect goto, return its block.
547   if (IndirectBranch) return IndirectBranch->getParent();
548 
549   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
550 
551   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
552 
553   // Create the PHI node that indirect gotos will add entries to.
554   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
555 
556   // Create the indirect branch instruction.
557   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
558   return IndirectBranch->getParent();
559 }
560 
561 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
562   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
563 
564   assert(SizeEntry && "Did not emit size for type");
565   return SizeEntry;
566 }
567 
568 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
569   assert(Ty->isVariablyModifiedType() &&
570          "Must pass variably modified type to EmitVLASizes!");
571 
572   EnsureInsertPoint();
573 
574   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
575     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
576 
577     if (!SizeEntry) {
578       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
579 
580       // Get the element size;
581       QualType ElemTy = VAT->getElementType();
582       llvm::Value *ElemSize;
583       if (ElemTy->isVariableArrayType())
584         ElemSize = EmitVLASize(ElemTy);
585       else
586         ElemSize = llvm::ConstantInt::get(SizeTy,
587             getContext().getTypeSizeInChars(ElemTy).getQuantity());
588 
589       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
590       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
591 
592       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
593     }
594 
595     return SizeEntry;
596   }
597 
598   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
599     EmitVLASize(AT->getElementType());
600     return 0;
601   }
602 
603   const PointerType *PT = Ty->getAs<PointerType>();
604   assert(PT && "unknown VM type!");
605   EmitVLASize(PT->getPointeeType());
606   return 0;
607 }
608 
609 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
610   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
611     return EmitScalarExpr(E);
612   }
613   return EmitLValue(E).getAddress();
614 }
615 
616 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
617                                        llvm::BasicBlock *CleanupExitBlock,
618                                        llvm::BasicBlock *PreviousInvokeDest,
619                                        bool EHOnly) {
620   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
621                                         PreviousInvokeDest, EHOnly));
622 }
623 
624 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
625   assert(CleanupEntries.size() >= OldCleanupStackSize &&
626          "Cleanup stack mismatch!");
627 
628   while (CleanupEntries.size() > OldCleanupStackSize)
629     EmitCleanupBlock();
630 }
631 
632 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
633   CleanupEntry &CE = CleanupEntries.back();
634 
635   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
636 
637   std::vector<llvm::BasicBlock *> Blocks;
638   std::swap(Blocks, CE.Blocks);
639 
640   std::vector<llvm::BranchInst *> BranchFixups;
641   std::swap(BranchFixups, CE.BranchFixups);
642 
643   bool EHOnly = CE.EHOnly;
644 
645   setInvokeDest(CE.PreviousInvokeDest);
646 
647   CleanupEntries.pop_back();
648 
649   // Check if any branch fixups pointed to the scope we just popped. If so,
650   // we can remove them.
651   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
652     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
653     BlockScopeMap::iterator I = BlockScopes.find(Dest);
654 
655     if (I == BlockScopes.end())
656       continue;
657 
658     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
659 
660     if (I->second == CleanupEntries.size()) {
661       // We don't need to do this branch fixup.
662       BranchFixups[i] = BranchFixups.back();
663       BranchFixups.pop_back();
664       i--;
665       e--;
666       continue;
667     }
668   }
669 
670   llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
671   llvm::BasicBlock *EndBlock = 0;
672   if (!BranchFixups.empty()) {
673     if (!SwitchBlock)
674       SwitchBlock = createBasicBlock("cleanup.switch");
675     EndBlock = createBasicBlock("cleanup.end");
676 
677     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
678 
679     Builder.SetInsertPoint(SwitchBlock);
680 
681     llvm::Value *DestCodePtr
682       = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
683                          "cleanup.dst");
684     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
685 
686     // Create a switch instruction to determine where to jump next.
687     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
688                                                 BranchFixups.size());
689 
690     // Restore the current basic block (if any)
691     if (CurBB) {
692       Builder.SetInsertPoint(CurBB);
693 
694       // If we had a current basic block, we also need to emit an instruction
695       // to initialize the cleanup destination.
696       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
697                           DestCodePtr);
698     } else
699       Builder.ClearInsertionPoint();
700 
701     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
702       llvm::BranchInst *BI = BranchFixups[i];
703       llvm::BasicBlock *Dest = BI->getSuccessor(0);
704 
705       // Fixup the branch instruction to point to the cleanup block.
706       BI->setSuccessor(0, CleanupEntryBlock);
707 
708       if (CleanupEntries.empty()) {
709         llvm::ConstantInt *ID;
710 
711         // Check if we already have a destination for this block.
712         if (Dest == SI->getDefaultDest())
713           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
714         else {
715           ID = SI->findCaseDest(Dest);
716           if (!ID) {
717             // No code found, get a new unique one by using the number of
718             // switch successors.
719             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
720                                         SI->getNumSuccessors());
721             SI->addCase(ID, Dest);
722           }
723         }
724 
725         // Store the jump destination before the branch instruction.
726         new llvm::StoreInst(ID, DestCodePtr, BI);
727       } else {
728         // We need to jump through another cleanup block. Create a pad block
729         // with a branch instruction that jumps to the final destination and add
730         // it as a branch fixup to the current cleanup scope.
731 
732         // Create the pad block.
733         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
734 
735         // Create a unique case ID.
736         llvm::ConstantInt *ID
737           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
738                                    SI->getNumSuccessors());
739 
740         // Store the jump destination before the branch instruction.
741         new llvm::StoreInst(ID, DestCodePtr, BI);
742 
743         // Add it as the destination.
744         SI->addCase(ID, CleanupPad);
745 
746         // Create the branch to the final destination.
747         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
748         CleanupPad->getInstList().push_back(BI);
749 
750         // And add it as a branch fixup.
751         CleanupEntries.back().BranchFixups.push_back(BI);
752       }
753     }
754   }
755 
756   // Remove all blocks from the block scope map.
757   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
758     assert(BlockScopes.count(Blocks[i]) &&
759            "Did not find block in scope map!");
760 
761     BlockScopes.erase(Blocks[i]);
762   }
763 
764   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
765 }
766 
767 void CodeGenFunction::EmitCleanupBlock() {
768   CleanupBlockInfo Info = PopCleanupBlock();
769 
770   if (Info.EHOnly) {
771     // FIXME: Add this to the exceptional edge
772     if (Info.CleanupBlock->getNumUses() == 0)
773       delete Info.CleanupBlock;
774     return;
775   }
776 
777   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
778   if (CurBB && !CurBB->getTerminator() &&
779       Info.CleanupBlock->getNumUses() == 0) {
780     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
781     delete Info.CleanupBlock;
782   } else
783     EmitBlock(Info.CleanupBlock);
784 
785   if (Info.SwitchBlock)
786     EmitBlock(Info.SwitchBlock);
787   if (Info.EndBlock)
788     EmitBlock(Info.EndBlock);
789 }
790 
791 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
792   assert(!CleanupEntries.empty() &&
793          "Trying to add branch fixup without cleanup block!");
794 
795   // FIXME: We could be more clever here and check if there's already a branch
796   // fixup for this destination and recycle it.
797   CleanupEntries.back().BranchFixups.push_back(BI);
798 }
799 
800 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
801   if (!HaveInsertPoint())
802     return;
803 
804   llvm::BranchInst* BI = Builder.CreateBr(Dest);
805 
806   Builder.ClearInsertionPoint();
807 
808   // The stack is empty, no need to do any cleanup.
809   if (CleanupEntries.empty())
810     return;
811 
812   if (!Dest->getParent()) {
813     // We are trying to branch to a block that hasn't been inserted yet.
814     AddBranchFixup(BI);
815     return;
816   }
817 
818   BlockScopeMap::iterator I = BlockScopes.find(Dest);
819   if (I == BlockScopes.end()) {
820     // We are trying to jump to a block that is outside of any cleanup scope.
821     AddBranchFixup(BI);
822     return;
823   }
824 
825   assert(I->second < CleanupEntries.size() &&
826          "Trying to branch into cleanup region");
827 
828   if (I->second == CleanupEntries.size() - 1) {
829     // We have a branch to a block in the same scope.
830     return;
831   }
832 
833   AddBranchFixup(BI);
834 }
835