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