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