clang API Documentation

CodeGenFunction.cpp

Go to the documentation of this file.
00001 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This coordinates the per-function state used while generating code.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CodeGenModule.h"
00016 #include "CGDebugInfo.h"
00017 #include "clang/Basic/TargetInfo.h"
00018 #include "clang/AST/APValue.h"
00019 #include "clang/AST/ASTContext.h"
00020 #include "clang/AST/Decl.h"
00021 #include "clang/AST/DeclCXX.h"
00022 #include "clang/AST/StmtCXX.h"
00023 #include "llvm/Target/TargetData.h"
00024 using namespace clang;
00025 using namespace CodeGen;
00026 
00027 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
00028   : BlockFunction(cgm, *this, Builder), CGM(cgm),
00029     Target(CGM.getContext().Target),
00030     Builder(cgm.getModule().getContext()),
00031     DebugInfo(0), IndirectBranch(0),
00032     SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
00033     CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
00034     ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0),
00035     UniqueAggrDestructorCount(0) {
00036   LLVMIntTy = ConvertType(getContext().IntTy);
00037   LLVMPointerWidth = Target.getPointerWidth(0);
00038   Exceptions = getContext().getLangOptions().Exceptions;
00039   CatchUndefined = getContext().getLangOptions().CatchUndefined;
00040 }
00041 
00042 ASTContext &CodeGenFunction::getContext() const {
00043   return CGM.getContext();
00044 }
00045 
00046 
00047 llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
00048   llvm::BasicBlock *&BB = LabelMap[S];
00049   if (BB) return BB;
00050 
00051   // Create, but don't insert, the new block.
00052   return BB = createBasicBlock(S->getName());
00053 }
00054 
00055 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
00056   llvm::Value *Res = LocalDeclMap[VD];
00057   assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
00058   return Res;
00059 }
00060 
00061 llvm::Constant *
00062 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
00063   return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
00064 }
00065 
00066 const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
00067   return CGM.getTypes().ConvertTypeForMem(T);
00068 }
00069 
00070 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
00071   return CGM.getTypes().ConvertType(T);
00072 }
00073 
00074 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
00075   return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
00076     T->isMemberFunctionPointerType();
00077 }
00078 
00079 void CodeGenFunction::EmitReturnBlock() {
00080   // For cleanliness, we try to avoid emitting the return block for
00081   // simple cases.
00082   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00083 
00084   if (CurBB) {
00085     assert(!CurBB->getTerminator() && "Unexpected terminated block.");
00086 
00087     // We have a valid insert point, reuse it if it is empty or there are no
00088     // explicit jumps to the return block.
00089     if (CurBB->empty() || ReturnBlock->use_empty()) {
00090       ReturnBlock->replaceAllUsesWith(CurBB);
00091       delete ReturnBlock;
00092     } else
00093       EmitBlock(ReturnBlock);
00094     return;
00095   }
00096 
00097   // Otherwise, if the return block is the target of a single direct
00098   // branch then we can just put the code in that block instead. This
00099   // cleans up functions which started with a unified return block.
00100   if (ReturnBlock->hasOneUse()) {
00101     llvm::BranchInst *BI =
00102       dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
00103     if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
00104       // Reset insertion point and delete the branch.
00105       Builder.SetInsertPoint(BI->getParent());
00106       BI->eraseFromParent();
00107       delete ReturnBlock;
00108       return;
00109     }
00110   }
00111 
00112   // FIXME: We are at an unreachable point, there is no reason to emit the block
00113   // unless it has uses. However, we still need a place to put the debug
00114   // region.end for now.
00115 
00116   EmitBlock(ReturnBlock);
00117 }
00118 
00119 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
00120   assert(BreakContinueStack.empty() &&
00121          "mismatched push/pop in break/continue stack!");
00122   assert(BlockScopes.empty() &&
00123          "did not remove all blocks from block scope map!");
00124   assert(CleanupEntries.empty() &&
00125          "mismatched push/pop in cleanup stack!");
00126 
00127   // Emit function epilog (to return).
00128   EmitReturnBlock();
00129 
00130   // Emit debug descriptor for function end.
00131   if (CGDebugInfo *DI = getDebugInfo()) {
00132     DI->setLocation(EndLoc);
00133     DI->EmitRegionEnd(CurFn, Builder);
00134   }
00135 
00136   EmitFunctionEpilog(*CurFnInfo, ReturnValue);
00137   EmitEndEHSpec(CurCodeDecl);
00138 
00139   // If someone did an indirect goto, emit the indirect goto block at the end of
00140   // the function.
00141   if (IndirectBranch) {
00142     EmitBlock(IndirectBranch->getParent());
00143     Builder.ClearInsertionPoint();
00144   }
00145   
00146   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
00147   llvm::Instruction *Ptr = AllocaInsertPt;
00148   AllocaInsertPt = 0;
00149   Ptr->eraseFromParent();
00150   
00151   // If someone took the address of a label but never did an indirect goto, we
00152   // made a zero entry PHI node, which is illegal, zap it now.
00153   if (IndirectBranch) {
00154     llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
00155     if (PN->getNumIncomingValues() == 0) {
00156       PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
00157       PN->eraseFromParent();
00158     }
00159   }
00160 }
00161 
00162 void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
00163                                     llvm::Function *Fn,
00164                                     const FunctionArgList &Args,
00165                                     SourceLocation StartLoc) {
00166   const Decl *D = GD.getDecl();
00167   
00168   DidCallStackSave = false;
00169   CurCodeDecl = CurFuncDecl = D;
00170   FnRetTy = RetTy;
00171   CurFn = Fn;
00172   assert(CurFn->isDeclaration() && "Function already has body?");
00173 
00174   // Pass inline keyword to optimizer if it appears explicitly on any
00175   // declaration.
00176   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
00177     for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
00178            RE = FD->redecls_end(); RI != RE; ++RI)
00179       if (RI->isInlineSpecified()) {
00180         Fn->addFnAttr(llvm::Attribute::InlineHint);
00181         break;
00182       }
00183 
00184   llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
00185 
00186   // Create a marker to make it easy to insert allocas into the entryblock
00187   // later.  Don't create this with the builder, because we don't want it
00188   // folded.
00189   llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext));
00190   AllocaInsertPt = new llvm::BitCastInst(Undef,
00191                                          llvm::Type::getInt32Ty(VMContext), "",
00192                                          EntryBB);
00193   if (Builder.isNamePreserving())
00194     AllocaInsertPt->setName("allocapt");
00195 
00196   ReturnBlock = createBasicBlock("return");
00197 
00198   Builder.SetInsertPoint(EntryBB);
00199 
00200   QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0,
00201                                                  false, false, 0, 0,
00202                                                  /*FIXME?*/
00203                                                  FunctionType::ExtInfo());
00204 
00205   // Emit subprogram debug descriptor.
00206   if (CGDebugInfo *DI = getDebugInfo()) {
00207     DI->setLocation(StartLoc);
00208     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
00209   }
00210 
00211   // FIXME: Leaked.
00212   // CC info is ignored, hopefully?
00213   CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args,
00214                                               FunctionType::ExtInfo());
00215 
00216   if (RetTy->isVoidType()) {
00217     // Void type; nothing to return.
00218     ReturnValue = 0;
00219   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
00220              hasAggregateLLVMType(CurFnInfo->getReturnType())) {
00221     // Indirect aggregate return; emit returned value directly into sret slot.
00222     // This reduces code size, and affects correctness in C++.
00223     ReturnValue = CurFn->arg_begin();
00224   } else {
00225     ReturnValue = CreateIRTemp(RetTy, "retval");
00226   }
00227 
00228   EmitStartEHSpec(CurCodeDecl);
00229   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
00230 
00231   if (CXXThisDecl)
00232     CXXThisValue = Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this");
00233   if (CXXVTTDecl)
00234     CXXVTTValue = Builder.CreateLoad(LocalDeclMap[CXXVTTDecl], "vtt");
00235 
00236   // If any of the arguments have a variably modified type, make sure to
00237   // emit the type size.
00238   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
00239        i != e; ++i) {
00240     QualType Ty = i->second;
00241 
00242     if (Ty->isVariablyModifiedType())
00243       EmitVLASize(Ty);
00244   }
00245 }
00246 
00247 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
00248   const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
00249   assert(FD->getBody());
00250   EmitStmt(FD->getBody());
00251 }
00252 
00253 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn) {
00254   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
00255   
00256   // Check if we should generate debug info for this function.
00257   if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>())
00258     DebugInfo = CGM.getDebugInfo();
00259 
00260   FunctionArgList Args;
00261 
00262   CurGD = GD;
00263   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
00264     if (MD->isInstance()) {
00265       // Create the implicit 'this' decl.
00266       // FIXME: I'm not entirely sure I like using a fake decl just for code
00267       // generation. Maybe we can come up with a better way?
00268       CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0,
00269                                               FD->getLocation(),
00270                                               &getContext().Idents.get("this"),
00271                                               MD->getThisType(getContext()));
00272       Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
00273       
00274       // Check if we need a VTT parameter as well.
00275       if (CodeGenVTables::needsVTTParameter(GD)) {
00276         // FIXME: The comment about using a fake decl above applies here too.
00277         QualType T = getContext().getPointerType(getContext().VoidPtrTy);
00278         CXXVTTDecl = 
00279           ImplicitParamDecl::Create(getContext(), 0, FD->getLocation(),
00280                                     &getContext().Idents.get("vtt"), T);
00281         Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType()));
00282       }
00283     }
00284   }
00285 
00286   if (FD->getNumParams()) {
00287     const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>();
00288     assert(FProto && "Function def must have prototype!");
00289 
00290     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
00291       Args.push_back(std::make_pair(FD->getParamDecl(i),
00292                                     FProto->getArgType(i)));
00293   }
00294 
00295   SourceRange BodyRange;
00296   if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
00297 
00298   // Emit the standard function prologue.
00299   StartFunction(GD, FD->getResultType(), Fn, Args, BodyRange.getBegin());
00300 
00301   // Generate the body of the function.
00302   if (isa<CXXDestructorDecl>(FD))
00303     EmitDestructorBody(Args);
00304   else if (isa<CXXConstructorDecl>(FD))
00305     EmitConstructorBody(Args);
00306   else
00307     EmitFunctionBody(Args);
00308 
00309   // Emit the standard function epilogue.
00310   FinishFunction(BodyRange.getEnd());
00311 
00312   // Destroy the 'this' declaration.
00313   if (CXXThisDecl)
00314     CXXThisDecl->Destroy(getContext());
00315   
00316   // Destroy the VTT declaration.
00317   if (CXXVTTDecl)
00318     CXXVTTDecl->Destroy(getContext());
00319 }
00320 
00321 /// ContainsLabel - Return true if the statement contains a label in it.  If
00322 /// this statement is not executed normally, it not containing a label means
00323 /// that we can just remove the code.
00324 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
00325   // Null statement, not a label!
00326   if (S == 0) return false;
00327 
00328   // If this is a label, we have to emit the code, consider something like:
00329   // if (0) {  ...  foo:  bar(); }  goto foo;
00330   if (isa<LabelStmt>(S))
00331     return true;
00332 
00333   // If this is a case/default statement, and we haven't seen a switch, we have
00334   // to emit the code.
00335   if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
00336     return true;
00337 
00338   // If this is a switch statement, we want to ignore cases below it.
00339   if (isa<SwitchStmt>(S))
00340     IgnoreCaseStmts = true;
00341 
00342   // Scan subexpressions for verboten labels.
00343   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
00344        I != E; ++I)
00345     if (ContainsLabel(*I, IgnoreCaseStmts))
00346       return true;
00347 
00348   return false;
00349 }
00350 
00351 
00352 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
00353 /// a constant, or if it does but contains a label, return 0.  If it constant
00354 /// folds to 'true' and does not contain a label, return 1, if it constant folds
00355 /// to 'false' and does not contain a label, return -1.
00356 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
00357   // FIXME: Rename and handle conversion of other evaluatable things
00358   // to bool.
00359   Expr::EvalResult Result;
00360   if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
00361       Result.HasSideEffects)
00362     return 0;  // Not foldable, not integer or not fully evaluatable.
00363 
00364   if (CodeGenFunction::ContainsLabel(Cond))
00365     return 0;  // Contains a label.
00366 
00367   return Result.Val.getInt().getBoolValue() ? 1 : -1;
00368 }
00369 
00370 
00371 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
00372 /// statement) to the specified blocks.  Based on the condition, this might try
00373 /// to simplify the codegen of the conditional based on the branch.
00374 ///
00375 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
00376                                            llvm::BasicBlock *TrueBlock,
00377                                            llvm::BasicBlock *FalseBlock) {
00378   if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
00379     return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
00380 
00381   if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
00382     // Handle X && Y in a condition.
00383     if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
00384       // If we have "1 && X", simplify the code.  "0 && X" would have constant
00385       // folded if the case was simple enough.
00386       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
00387         // br(1 && X) -> br(X).
00388         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00389       }
00390 
00391       // If we have "X && 1", simplify the code to use an uncond branch.
00392       // "X && 0" would have been constant folded to 0.
00393       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
00394         // br(X && 1) -> br(X).
00395         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
00396       }
00397 
00398       // Emit the LHS as a conditional.  If the LHS conditional is false, we
00399       // want to jump to the FalseBlock.
00400       llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
00401       EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
00402       EmitBlock(LHSTrue);
00403 
00404       // Any temporaries created here are conditional.
00405       BeginConditionalBranch();
00406       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00407       EndConditionalBranch();
00408 
00409       return;
00410     } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
00411       // If we have "0 || X", simplify the code.  "1 || X" would have constant
00412       // folded if the case was simple enough.
00413       if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
00414         // br(0 || X) -> br(X).
00415         return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00416       }
00417 
00418       // If we have "X || 0", simplify the code to use an uncond branch.
00419       // "X || 1" would have been constant folded to 1.
00420       if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
00421         // br(X || 0) -> br(X).
00422         return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
00423       }
00424 
00425       // Emit the LHS as a conditional.  If the LHS conditional is true, we
00426       // want to jump to the TrueBlock.
00427       llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
00428       EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
00429       EmitBlock(LHSFalse);
00430 
00431       // Any temporaries created here are conditional.
00432       BeginConditionalBranch();
00433       EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
00434       EndConditionalBranch();
00435 
00436       return;
00437     }
00438   }
00439 
00440   if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
00441     // br(!x, t, f) -> br(x, f, t)
00442     if (CondUOp->getOpcode() == UnaryOperator::LNot)
00443       return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
00444   }
00445 
00446   if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
00447     // Handle ?: operator.
00448 
00449     // Just ignore GNU ?: extension.
00450     if (CondOp->getLHS()) {
00451       // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
00452       llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
00453       llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
00454       EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
00455       EmitBlock(LHSBlock);
00456       EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
00457       EmitBlock(RHSBlock);
00458       EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
00459       return;
00460     }
00461   }
00462 
00463   // Emit the code with the fully general case.
00464   llvm::Value *CondV = EvaluateExprAsBool(Cond);
00465   Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
00466 }
00467 
00468 /// ErrorUnsupported - Print out an error that codegen doesn't support the
00469 /// specified stmt yet.
00470 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
00471                                        bool OmitOnError) {
00472   CGM.ErrorUnsupported(S, Type, OmitOnError);
00473 }
00474 
00475 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
00476   // Ignore empty classes in C++.
00477   if (getContext().getLangOptions().CPlusPlus) {
00478     if (const RecordType *RT = Ty->getAs<RecordType>()) {
00479       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
00480         return;
00481     }
00482   }
00483   
00484   const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
00485   if (DestPtr->getType() != BP)
00486     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
00487 
00488   // Get size and alignment info for this aggregate.
00489   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
00490 
00491   // Don't bother emitting a zero-byte memset.
00492   if (TypeInfo.first == 0)
00493     return;
00494 
00495   // FIXME: Handle variable sized types.
00496   const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext,
00497                                                     LLVMPointerWidth);
00498 
00499   Builder.CreateCall5(CGM.getMemSetFn(BP, IntPtr), DestPtr,
00500                  llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
00501                       // TypeInfo.first describes size in bits.
00502                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
00503                       llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
00504                                              TypeInfo.second/8),
00505                       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
00506                                              0));
00507 }
00508 
00509 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) {
00510   // Make sure that there is a block for the indirect goto.
00511   if (IndirectBranch == 0)
00512     GetIndirectGotoBlock();
00513   
00514   llvm::BasicBlock *BB = getBasicBlockForLabel(L);
00515   
00516   // Make sure the indirect branch includes all of the address-taken blocks.
00517   IndirectBranch->addDestination(BB);
00518   return llvm::BlockAddress::get(CurFn, BB);
00519 }
00520 
00521 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
00522   // If we already made the indirect branch for indirect goto, return its block.
00523   if (IndirectBranch) return IndirectBranch->getParent();
00524   
00525   CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
00526   
00527   const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
00528 
00529   // Create the PHI node that indirect gotos will add entries to.
00530   llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
00531   
00532   // Create the indirect branch instruction.
00533   IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
00534   return IndirectBranch->getParent();
00535 }
00536 
00537 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
00538   llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
00539 
00540   assert(SizeEntry && "Did not emit size for type");
00541   return SizeEntry;
00542 }
00543 
00544 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
00545   assert(Ty->isVariablyModifiedType() &&
00546          "Must pass variably modified type to EmitVLASizes!");
00547 
00548   EnsureInsertPoint();
00549 
00550   if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
00551     llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
00552 
00553     if (!SizeEntry) {
00554       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
00555 
00556       // Get the element size;
00557       QualType ElemTy = VAT->getElementType();
00558       llvm::Value *ElemSize;
00559       if (ElemTy->isVariableArrayType())
00560         ElemSize = EmitVLASize(ElemTy);
00561       else
00562         ElemSize = llvm::ConstantInt::get(SizeTy,
00563             getContext().getTypeSizeInChars(ElemTy).getQuantity());
00564 
00565       llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
00566       NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
00567 
00568       SizeEntry = Builder.CreateMul(ElemSize, NumElements);
00569     }
00570 
00571     return SizeEntry;
00572   }
00573 
00574   if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
00575     EmitVLASize(AT->getElementType());
00576     return 0;
00577   }
00578 
00579   const PointerType *PT = Ty->getAs<PointerType>();
00580   assert(PT && "unknown VM type!");
00581   EmitVLASize(PT->getPointeeType());
00582   return 0;
00583 }
00584 
00585 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
00586   if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
00587     return EmitScalarExpr(E);
00588   }
00589   return EmitLValue(E).getAddress();
00590 }
00591 
00592 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
00593                                        llvm::BasicBlock *CleanupExitBlock,
00594                                        llvm::BasicBlock *PreviousInvokeDest,
00595                                        bool EHOnly) {
00596   CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock,
00597                                         PreviousInvokeDest, EHOnly));
00598 }
00599 
00600 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) {
00601   assert(CleanupEntries.size() >= OldCleanupStackSize &&
00602          "Cleanup stack mismatch!");
00603 
00604   while (CleanupEntries.size() > OldCleanupStackSize)
00605     EmitCleanupBlock();
00606 }
00607 
00608 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() {
00609   CleanupEntry &CE = CleanupEntries.back();
00610 
00611   llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock;
00612 
00613   std::vector<llvm::BasicBlock *> Blocks;
00614   std::swap(Blocks, CE.Blocks);
00615 
00616   std::vector<llvm::BranchInst *> BranchFixups;
00617   std::swap(BranchFixups, CE.BranchFixups);
00618 
00619   bool EHOnly = CE.EHOnly;
00620 
00621   setInvokeDest(CE.PreviousInvokeDest);
00622 
00623   CleanupEntries.pop_back();
00624 
00625   // Check if any branch fixups pointed to the scope we just popped. If so,
00626   // we can remove them.
00627   for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
00628     llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
00629     BlockScopeMap::iterator I = BlockScopes.find(Dest);
00630 
00631     if (I == BlockScopes.end())
00632       continue;
00633 
00634     assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
00635 
00636     if (I->second == CleanupEntries.size()) {
00637       // We don't need to do this branch fixup.
00638       BranchFixups[i] = BranchFixups.back();
00639       BranchFixups.pop_back();
00640       i--;
00641       e--;
00642       continue;
00643     }
00644   }
00645 
00646   llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock;
00647   llvm::BasicBlock *EndBlock = 0;
00648   if (!BranchFixups.empty()) {
00649     if (!SwitchBlock)
00650       SwitchBlock = createBasicBlock("cleanup.switch");
00651     EndBlock = createBasicBlock("cleanup.end");
00652 
00653     llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00654 
00655     Builder.SetInsertPoint(SwitchBlock);
00656 
00657     llvm::Value *DestCodePtr
00658       = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext),
00659                          "cleanup.dst");
00660     llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
00661 
00662     // Create a switch instruction to determine where to jump next.
00663     llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
00664                                                 BranchFixups.size());
00665 
00666     // Restore the current basic block (if any)
00667     if (CurBB) {
00668       Builder.SetInsertPoint(CurBB);
00669 
00670       // If we had a current basic block, we also need to emit an instruction
00671       // to initialize the cleanup destination.
00672       Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)),
00673                           DestCodePtr);
00674     } else
00675       Builder.ClearInsertionPoint();
00676 
00677     for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
00678       llvm::BranchInst *BI = BranchFixups[i];
00679       llvm::BasicBlock *Dest = BI->getSuccessor(0);
00680 
00681       // Fixup the branch instruction to point to the cleanup block.
00682       BI->setSuccessor(0, CleanupEntryBlock);
00683 
00684       if (CleanupEntries.empty()) {
00685         llvm::ConstantInt *ID;
00686 
00687         // Check if we already have a destination for this block.
00688         if (Dest == SI->getDefaultDest())
00689           ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
00690         else {
00691           ID = SI->findCaseDest(Dest);
00692           if (!ID) {
00693             // No code found, get a new unique one by using the number of
00694             // switch successors.
00695             ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
00696                                         SI->getNumSuccessors());
00697             SI->addCase(ID, Dest);
00698           }
00699         }
00700 
00701         // Store the jump destination before the branch instruction.
00702         new llvm::StoreInst(ID, DestCodePtr, BI);
00703       } else {
00704         // We need to jump through another cleanup block. Create a pad block
00705         // with a branch instruction that jumps to the final destination and add
00706         // it as a branch fixup to the current cleanup scope.
00707 
00708         // Create the pad block.
00709         llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
00710 
00711         // Create a unique case ID.
00712         llvm::ConstantInt *ID
00713           = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
00714                                    SI->getNumSuccessors());
00715 
00716         // Store the jump destination before the branch instruction.
00717         new llvm::StoreInst(ID, DestCodePtr, BI);
00718 
00719         // Add it as the destination.
00720         SI->addCase(ID, CleanupPad);
00721 
00722         // Create the branch to the final destination.
00723         llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
00724         CleanupPad->getInstList().push_back(BI);
00725 
00726         // And add it as a branch fixup.
00727         CleanupEntries.back().BranchFixups.push_back(BI);
00728       }
00729     }
00730   }
00731 
00732   // Remove all blocks from the block scope map.
00733   for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
00734     assert(BlockScopes.count(Blocks[i]) &&
00735            "Did not find block in scope map!");
00736 
00737     BlockScopes.erase(Blocks[i]);
00738   }
00739 
00740   return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly);
00741 }
00742 
00743 void CodeGenFunction::EmitCleanupBlock() {
00744   CleanupBlockInfo Info = PopCleanupBlock();
00745 
00746   if (Info.EHOnly) {
00747     // FIXME: Add this to the exceptional edge
00748     if (Info.CleanupBlock->getNumUses() == 0)
00749       delete Info.CleanupBlock;
00750     return;
00751   }
00752 
00753   //  Scrub debug location info.
00754   for (llvm::BasicBlock::iterator LBI = Info.CleanupBlock->begin(),
00755          LBE = Info.CleanupBlock->end(); LBI != LBE; ++LBI)
00756     Builder.SetInstDebugLocation(LBI);
00757 
00758   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
00759   if (CurBB && !CurBB->getTerminator() &&
00760       Info.CleanupBlock->getNumUses() == 0) {
00761     CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
00762     delete Info.CleanupBlock;
00763   } else
00764     EmitBlock(Info.CleanupBlock);
00765 
00766   if (Info.SwitchBlock)
00767     EmitBlock(Info.SwitchBlock);
00768   if (Info.EndBlock)
00769     EmitBlock(Info.EndBlock);
00770 }
00771 
00772 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) {
00773   assert(!CleanupEntries.empty() &&
00774          "Trying to add branch fixup without cleanup block!");
00775 
00776   // FIXME: We could be more clever here and check if there's already a branch
00777   // fixup for this destination and recycle it.
00778   CleanupEntries.back().BranchFixups.push_back(BI);
00779 }
00780 
00781 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) {
00782   if (!HaveInsertPoint())
00783     return;
00784 
00785   llvm::BranchInst* BI = Builder.CreateBr(Dest);
00786 
00787   Builder.ClearInsertionPoint();
00788 
00789   // The stack is empty, no need to do any cleanup.
00790   if (CleanupEntries.empty())
00791     return;
00792 
00793   if (!Dest->getParent()) {
00794     // We are trying to branch to a block that hasn't been inserted yet.
00795     AddBranchFixup(BI);
00796     return;
00797   }
00798 
00799   BlockScopeMap::iterator I = BlockScopes.find(Dest);
00800   if (I == BlockScopes.end()) {
00801     // We are trying to jump to a block that is outside of any cleanup scope.
00802     AddBranchFixup(BI);
00803     return;
00804   }
00805 
00806   assert(I->second < CleanupEntries.size() &&
00807          "Trying to branch into cleanup region");
00808 
00809   if (I->second == CleanupEntries.size() - 1) {
00810     // We have a branch to a block in the same scope.
00811     return;
00812   }
00813 
00814   AddBranchFixup(BI);
00815 }