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