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