xref: /llvm-project/clang/lib/CodeGen/CodeGenFunction.cpp (revision cc2ab0cdc97a72fd5efe0ada69d8094eabddf1be)
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                                                  false, false, 0, 0,
202                                                  /*FIXME?*/
203                                                  FunctionType::ExtInfo());
204 
205   // Emit subprogram debug descriptor.
206   if (CGDebugInfo *DI = getDebugInfo()) {
207     DI->setLocation(StartLoc);
208     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
209   }
210 
211   // FIXME: Leaked.
212   // CC info is ignored, hopefully?
213   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
214                                               FunctionType::ExtInfo());
215 
216   if (RetTy->isVoidType()) {
217     // Void type; nothing to return.
218     ReturnValue = 0;
219   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
220              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
221     // Indirect aggregate return; emit returned value directly into sret slot.
222     // This reduces code size, and affects correctness in C++.
223     ReturnValue = CurFn->arg_begin();
224   } else {
225     ReturnValue = CreateIRTemp(RetTy, "retval");
226   }
227 
228   EmitStartEHSpec(CurCodeDecl);
229   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
230 
231   if (CXXThisDecl)
232     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
233   if (CXXVTTDecl)
234     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
235 
236   // If any of the arguments have a variably modified type, make sure to
237   // emit the type size.
238   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
239        i != e; ++i) {
240     QualType Ty = i->second;
241 
242     if (Ty->isVariablyModifiedType())
243       EmitVLASize(Ty);
244   }
245 }
246 
247 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
248   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
249 
250   Stmt *Body = FD->getBody();
251   if (Body)
252     EmitStmt(Body);
253   else {
254     assert(FD->isImplicit() && "non-implicit function def has no body");
255     assert(FD->isCopyAssignment() && "implicit function not copy assignment");
256     SynthesizeCXXCopyAssignment(Args);
257   }
258 }
259 
260 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
261   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
262 
263   // Check if we should generate debug info for this function.
264   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
265     DebugInfo = CGM.getDebugInfo();
266 
267   FunctionArgList Args;
268 
269   CurGD = GD;
270   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
271     if (MD->isInstance()) {
272       // Create the implicit 'this' decl.
273       // FIXME: I'm not entirely sure I like using a fake decl just for code
274       // generation. Maybe we can come up with a better way?
275       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
276                                               FD->getLocation(),
277                                               &getContext().Idents.get("this"),
278                                               MD->getThisType(getContext()));
279       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
280 
281       // Check if we need a VTT parameter as well.
282       if (CodeGenVTables::needsVTTParameter(GD)) {
283         // FIXME: The comment about using a fake decl above applies here too.
284         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
285         CXXVTTDecl =
286           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
287                                     &getContext().Idents.get("vtt"), T);
288         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
289       }
290     }
291   }
292 
293   if (FD->getNumParams()) {
294     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
295     assert(FProto && "Function def must have prototype!");
296 
297     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
298       Args.push_back(std::make_pair(FD->getParamDecl(i),
299                                     FProto->getArgType(i)));
300   }
301 
302   SourceRange BodyRange;
303   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
304 
305   // Emit the standard function prologue.
306   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
307 
308   // Generate the body of the function.
309   if (isa<CXXDestructorDecl>(FD))
310     EmitDestructorBody(Args);
311   else if (isa<CXXConstructorDecl>(FD))
312     EmitConstructorBody(Args);
313   else
314     EmitFunctionBody(Args);
315 
316   // Emit the standard function epilogue.
317   FinishFunction(BodyRange.getEnd());
318 
319   // Destroy the 'this' declaration.
320   if (CXXThisDecl)
321     CXXThisDecl->Destroy(getContext());
322 
323   // Destroy the VTT declaration.
324   if (CXXVTTDecl)
325     CXXVTTDecl->Destroy(getContext());
326 }
327 
328 /// ContainsLabel - Return true if the statement contains a label in it.  If
329 /// this statement is not executed normally, it not containing a label means
330 /// that we can just remove the code.
331 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
332   // Null statement, not a label!
333   if (S == 0) return false;
334 
335   // If this is a label, we have to emit the code, consider something like:
336   // if (0) {  ...  foo:  bar(); }  goto foo;
337   if (isa<LabelStmt>(S))
338     return true;
339 
340   // If this is a case/default statement, and we haven't seen a switch, we have
341   // to emit the code.
342   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
343     return true;
344 
345   // If this is a switch statement, we want to ignore cases below it.
346   if (isa<SwitchStmt>(S))
347     IgnoreCaseStmts = true;
348 
349   // Scan subexpressions for verboten labels.
350   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
351        I != E; ++I)
352     if (ContainsLabel(*I, IgnoreCaseStmts))
353       return true;
354 
355   return false;
356 }
357 
358 
359 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
360 /// a constant, or if it does but contains a label, return 0.  If it constant
361 /// folds to 'true' and does not contain a label, return 1, if it constant folds
362 /// to 'false' and does not contain a label, return -1.
363 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
364   // FIXME: Rename and handle conversion of other evaluatable things
365   // to bool.
366   Expr::EvalResult Result;
367   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
368       Result.HasSideEffects)
369     return 0;  // Not foldable, not integer or not fully evaluatable.
370 
371   if (CodeGenFunction::ContainsLabel(Cond))
372     return 0;  // Contains a label.
373 
374   return Result.Val.getInt().getBoolValue() ? 1 : -1;
375 }
376 
377 
378 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
379 /// statement) to the specified blocks.  Based on the condition, this might try
380 /// to simplify the codegen of the conditional based on the branch.
381 ///
382 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
383                                            llvm::BasicBlock *TrueBlock,
384                                            llvm::BasicBlock *FalseBlock) {
385   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
386     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
387 
388   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
389     // Handle X && Y in a condition.
390     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
391       // If we have "1 && X", simplify the code.  "0 && X" would have constant
392       // folded if the case was simple enough.
393       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
394         // br(1 && X) -> br(X).
395         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
396       }
397 
398       // If we have "X && 1", simplify the code to use an uncond branch.
399       // "X && 0" would have been constant folded to 0.
400       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
401         // br(X && 1) -> br(X).
402         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
403       }
404 
405       // Emit the LHS as a conditional.  If the LHS conditional is false, we
406       // want to jump to the FalseBlock.
407       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
408       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
409       EmitBlock(LHSTrue);
410 
411       // Any temporaries created here are conditional.
412       BeginConditionalBranch();
413       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
414       EndConditionalBranch();
415 
416       return;
417     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
418       // If we have "0 || X", simplify the code.  "1 || X" would have constant
419       // folded if the case was simple enough.
420       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
421         // br(0 || X) -> br(X).
422         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
423       }
424 
425       // If we have "X || 0", simplify the code to use an uncond branch.
426       // "X || 1" would have been constant folded to 1.
427       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
428         // br(X || 0) -> br(X).
429         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
430       }
431 
432       // Emit the LHS as a conditional.  If the LHS conditional is true, we
433       // want to jump to the TrueBlock.
434       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
435       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
436       EmitBlock(LHSFalse);
437 
438       // Any temporaries created here are conditional.
439       BeginConditionalBranch();
440       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
441       EndConditionalBranch();
442 
443       return;
444     }
445   }
446 
447   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
448     // br(!x, t, f) -> br(x, f, t)
449     if (CondUOp->getOpcode() == UnaryOperator::LNot)
450       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
451   }
452 
453   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
454     // Handle ?: operator.
455 
456     // Just ignore GNU ?: extension.
457     if (CondOp->getLHS()) {
458       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
459       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
460       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
461       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
462       EmitBlock(LHSBlock);
463       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
464       EmitBlock(RHSBlock);
465       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
466       return;
467     }
468   }
469 
470   // Emit the code with the fully general case.
471   llvm::Value *CondV = EvaluateExprAsBool(Cond);
472   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
473 }
474 
475 /// ErrorUnsupported - Print out an error that codegen doesn't support the
476 /// specified stmt yet.
477 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
478                                        bool OmitOnError) {
479   CGM.ErrorUnsupported(S, Type, OmitOnError);
480 }
481 
482 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
483   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
484   if (DestPtr->getType() != BP)
485     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
486 
487   // Get size and alignment info for this aggregate.
488   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
489 
490   // Don't bother emitting a zero-byte memset.
491   if (TypeInfo.first == 0)
492     return;
493 
494   // FIXME: Handle variable sized types.
495   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
496                                                     LLVMPointerWidth);
497 
498   Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
499                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
500                       // TypeInfo.first describes size in bits.
501                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
502                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
503                                              TypeInfo.second/8),
504                       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
505                                              0));
506 }
507 
508 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
509   // Make sure that there is a block for the indirect goto.
510   if (IndirectBranch == 0)
511     GetIndirectGotoBlock();
512 
513   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
514 
515   // Make sure the indirect branch includes all of the address-taken blocks.
516   IndirectBranch->addDestination(BB);
517   return llvm::BlockAddress::get(CurFn, BB);
518 }
519 
520 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
521   // If we already made the indirect branch for indirect goto, return its block.
522   if (IndirectBranch) return IndirectBranch->getParent();
523 
524   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
525 
526   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
527 
528   // Create the PHI node that indirect gotos will add entries to.
529   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
530 
531   // Create the indirect branch instruction.
532   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
533   return IndirectBranch->getParent();
534 }
535 
536 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
537   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
538 
539   assert(SizeEntry && "Did not emit size for type");
540   return SizeEntry;
541 }
542 
543 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
544   assert(Ty->isVariablyModifiedType() &&
545          "Must pass variably modified type to EmitVLASizes!");
546 
547   EnsureInsertPoint();
548 
549   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
550     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
551 
552     if (!SizeEntry) {
553       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
554 
555       // Get the element size;
556       QualType ElemTy = VAT->getElementType();
557       llvm::Value *ElemSize;
558       if (ElemTy->isVariableArrayType())
559         ElemSize = EmitVLASize(ElemTy);
560       else
561         ElemSize = llvm::ConstantInt::get(SizeTy,
562             getContext().getTypeSizeInChars(ElemTy).getQuantity());
563 
564       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
565       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
566 
567       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
568     }
569 
570     return SizeEntry;
571   }
572 
573   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
574     EmitVLASize(AT->getElementType());
575     return 0;
576   }
577 
578   const PointerType *PT = Ty->getAs<PointerType>();
579   assert(PT && "unknown VM type!");
580   EmitVLASize(PT->getPointeeType());
581   return 0;
582 }
583 
584 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
585   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
586     return EmitScalarExpr(E);
587   }
588   return EmitLValue(E).getAddress();
589 }
590 
591 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
592                                        llvm::BasicBlock *CleanupExitBlock,
593                                        llvm::BasicBlock *PreviousInvokeDest,
594                                        bool EHOnly) {
595   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
596                                         PreviousInvokeDest, EHOnly));
597 }
598 
599 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
600   assert(CleanupEntries.size() >= OldCleanupStackSize &&
601          "Cleanup stack mismatch!");
602 
603   while (CleanupEntries.size() > OldCleanupStackSize)
604     EmitCleanupBlock();
605 }
606 
607 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
608   CleanupEntry &CE = CleanupEntries.back();
609 
610   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
611 
612   std::vector<llvm::BasicBlock *> Blocks;
613   std::swap(Blocks, CE.Blocks);
614 
615   std::vector<llvm::BranchInst *> BranchFixups;
616   std::swap(BranchFixups, CE.BranchFixups);
617 
618   bool EHOnly = CE.EHOnly;
619 
620   setInvokeDest(CE.PreviousInvokeDest);
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 = CE.CleanupExitBlock;
646   llvm::BasicBlock *EndBlock = 0;
647   if (!BranchFixups.empty()) {
648     if (!SwitchBlock)
649       SwitchBlock = createBasicBlock("cleanup.switch");
650     EndBlock = createBasicBlock("cleanup.end");
651 
652     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
653 
654     Builder.SetInsertPoint(SwitchBlock);
655 
656     llvm::Value *DestCodePtr
657       = 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, CleanupEntryBlock);
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 add
705         // 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
712           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
713                                    SI->getNumSuccessors());
714 
715         // Store the jump destination before the branch instruction.
716         new llvm::StoreInst(ID, DestCodePtr, BI);
717 
718         // Add it as the destination.
719         SI->addCase(ID, CleanupPad);
720 
721         // Create the branch to the final destination.
722         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
723         CleanupPad->getInstList().push_back(BI);
724 
725         // And add it as a branch fixup.
726         CleanupEntries.back().BranchFixups.push_back(BI);
727       }
728     }
729   }
730 
731   // Remove all blocks from the block scope map.
732   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
733     assert(BlockScopes.count(Blocks[i]) &&
734            "Did not find block in scope map!");
735 
736     BlockScopes.erase(Blocks[i]);
737   }
738 
739   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
740 }
741 
742 void CodeGenFunction::EmitCleanupBlock() {
743   CleanupBlockInfo Info = PopCleanupBlock();
744 
745   if (Info.EHOnly) {
746     // FIXME: Add this to the exceptional edge
747     if (Info.CleanupBlock->getNumUses() == 0)
748       delete Info.CleanupBlock;
749     return;
750   }
751 
752   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
753   if (CurBB && !CurBB->getTerminator() &&
754       Info.CleanupBlock->getNumUses() == 0) {
755     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
756     delete Info.CleanupBlock;
757   } else
758     EmitBlock(Info.CleanupBlock);
759 
760   if (Info.SwitchBlock)
761     EmitBlock(Info.SwitchBlock);
762   if (Info.EndBlock)
763     EmitBlock(Info.EndBlock);
764 }
765 
766 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
767   assert(!CleanupEntries.empty() &&
768          "Trying to add branch fixup without cleanup block!");
769 
770   // FIXME: We could be more clever here and check if there's already a branch
771   // fixup for this destination and recycle it.
772   CleanupEntries.back().BranchFixups.push_back(BI);
773 }
774 
775 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
776   if (!HaveInsertPoint())
777     return;
778 
779   llvm::BranchInst* BI = Builder.CreateBr(Dest);
780 
781   Builder.ClearInsertionPoint();
782 
783   // The stack is empty, no need to do any cleanup.
784   if (CleanupEntries.empty())
785     return;
786 
787   if (!Dest->getParent()) {
788     // We are trying to branch to a block that hasn't been inserted yet.
789     AddBranchFixup(BI);
790     return;
791   }
792 
793   BlockScopeMap::iterator I = BlockScopes.find(Dest);
794   if (I == BlockScopes.end()) {
795     // We are trying to jump to a block that is outside of any cleanup scope.
796     AddBranchFixup(BI);
797     return;
798   }
799 
800   assert(I->second < CleanupEntries.size() &&
801          "Trying to branch into cleanup region");
802 
803   if (I->second == CleanupEntries.size() - 1) {
804     // We have a branch to a block in the same scope.
805     return;
806   }
807 
808   AddBranchFixup(BI);
809 }
810