CodeGenFunction.cpp revision 201361
1193323Sed//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed// 10193323Sed// This coordinates the per-function state used while generating code. 11193323Sed// 12193323Sed//===----------------------------------------------------------------------===// 13193323Sed 14193323Sed#include "CodeGenFunction.h" 15193323Sed#include "CodeGenModule.h" 16205218Srdivacky#include "CGDebugInfo.h" 17193323Sed#include "clang/Basic/TargetInfo.h" 18198090Srdivacky#include "clang/AST/APValue.h" 19193323Sed#include "clang/AST/ASTContext.h" 20193323Sed#include "clang/AST/Decl.h" 21193323Sed#include "clang/AST/DeclCXX.h" 22208599Srdivacky#include "clang/AST/StmtCXX.h" 23193323Sed#include "llvm/Target/TargetData.h" 24198090Srdivackyusing namespace clang; 25202878Srdivackyusing namespace CodeGen; 26202878Srdivacky 27206083SrdivackyCodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 28202878Srdivacky : BlockFunction(cgm, *this, Builder), CGM(cgm), 29202878Srdivacky Target(CGM.getContext().Target), 30193323Sed Builder(cgm.getModule().getContext()), 31193323Sed DebugInfo(0), IndirectBranch(0), 32193323Sed SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), 33193323Sed CXXThisDecl(0), CXXVTTDecl(0), 34202878Srdivacky ConditionalBranchLevel(0), TerminateHandler(0), TrapBB(0), 35202878Srdivacky UniqueAggrDestructorCount(0) { 36193323Sed LLVMIntTy = ConvertType(getContext().IntTy); 37193323Sed LLVMPointerWidth = Target.getPointerWidth(0); 38193323Sed Exceptions = getContext().getLangOptions().Exceptions; 39193323Sed CatchUndefined = getContext().getLangOptions().CatchUndefined; 40193323Sed} 41193323Sed 42193323SedASTContext &CodeGenFunction::getContext() const { 43193323Sed return CGM.getContext(); 44193323Sed} 45193323Sed 46193323Sed 47193323Sedllvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 48208599Srdivacky llvm::BasicBlock *&BB = LabelMap[S]; 49208599Srdivacky if (BB) return BB; 50208599Srdivacky 51208599Srdivacky // Create, but don't insert, the new block. 52208599Srdivacky return BB = createBasicBlock(S->getName()); 53208599Srdivacky} 54208599Srdivacky 55208599Srdivackyllvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 56208599Srdivacky llvm::Value *Res = LocalDeclMap[VD]; 57208599Srdivacky assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 58208599Srdivacky return Res; 59208599Srdivacky} 60208599Srdivacky 61208599Srdivackyllvm::Constant * 62212904SdimCodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 63212904Sdim return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 64212904Sdim} 65210299Sed 66210299Sedconst llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 67210299Sed return CGM.getTypes().ConvertTypeForMem(T); 68208599Srdivacky} 69208599Srdivacky 70208599Srdivackyconst llvm::Type *CodeGenFunction::ConvertType(QualType T) { 71193323Sed return CGM.getTypes().ConvertType(T); 72193323Sed} 73193323Sed 74193323Sedbool CodeGenFunction::hasAggregateLLVMType(QualType T) { 75193323Sed return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 76193323Sed T->isMemberFunctionPointerType(); 77193323Sed} 78193323Sed 79208599Srdivackyvoid CodeGenFunction::EmitReturnBlock() { 80193323Sed // For cleanliness, we try to avoid emitting the return block for 81193323Sed // simple cases. 82193323Sed llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 83193323Sed 84193323Sed if (CurBB) { 85193323Sed assert(!CurBB->getTerminator() && "Unexpected terminated block."); 86193323Sed 87193323Sed // We have a valid insert point, reuse it if it is empty or there are no 88193323Sed // explicit jumps to the return block. 89193323Sed if (CurBB->empty() || ReturnBlock->use_empty()) { 90193323Sed ReturnBlock->replaceAllUsesWith(CurBB); 91193323Sed delete ReturnBlock; 92193323Sed } else 93193323Sed EmitBlock(ReturnBlock); 94193323Sed return; 95193323Sed } 96193323Sed 97193323Sed // Otherwise, if the return block is the target of a single direct 98193323Sed // branch then we can just put the code in that block instead. This 99193323Sed // cleans up functions which started with a unified return block. 100193323Sed if (ReturnBlock->hasOneUse()) { 101193323Sed llvm::BranchInst *BI = 102193323Sed dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); 103193323Sed if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { 104193323Sed // Reset insertion point and delete the branch. 105210299Sed Builder.SetInsertPoint(BI->getParent()); 106193323Sed BI->eraseFromParent(); 107193323Sed delete ReturnBlock; 108193323Sed return; 109193323Sed } 110193323Sed } 111202878Srdivacky 112202878Srdivacky // FIXME: We are at an unreachable point, there is no reason to emit the block 113202878Srdivacky // unless it has uses. However, we still need a place to put the debug 114210299Sed // region.end for now. 115210299Sed 116210299Sed EmitBlock(ReturnBlock); 117210299Sed} 118210299Sed 119210299Sedvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 120210299Sed assert(BreakContinueStack.empty() && 121210299Sed "mismatched push/pop in break/continue stack!"); 122210299Sed assert(BlockScopes.empty() && 123210299Sed "did not remove all blocks from block scope map!"); 124210299Sed assert(CleanupEntries.empty() && 125202878Srdivacky "mismatched push/pop in cleanup stack!"); 126202878Srdivacky 127210299Sed // Emit function epilog (to return). 128202878Srdivacky EmitReturnBlock(); 129210299Sed 130210299Sed // Emit debug descriptor for function end. 131210299Sed if (CGDebugInfo *DI = getDebugInfo()) { 132210299Sed DI->setLocation(EndLoc); 133202878Srdivacky DI->EmitRegionEnd(CurFn, Builder); 134210299Sed } 135202878Srdivacky 136210299Sed EmitFunctionEpilog(*CurFnInfo, ReturnValue); 137210299Sed EmitEndEHSpec(CurCodeDecl); 138210299Sed 139210299Sed // If someone did an indirect goto, emit the indirect goto block at the end of 140210299Sed // the function. 141210299Sed if (IndirectBranch) { 142210299Sed EmitBlock(IndirectBranch->getParent()); 143210299Sed Builder.ClearInsertionPoint(); 144210299Sed } 145202878Srdivacky 146210299Sed // Remove the AllocaInsertPt instruction, which is just a convenience for us. 147210299Sed llvm::Instruction *Ptr = AllocaInsertPt; 148210299Sed AllocaInsertPt = 0; 149210299Sed Ptr->eraseFromParent(); 150202878Srdivacky 151202878Srdivacky // If someone took the address of a label but never did an indirect goto, we 152202878Srdivacky // made a zero entry PHI node, which is illegal, zap it now. 153202878Srdivacky if (IndirectBranch) { 154202878Srdivacky llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 155202878Srdivacky if (PN->getNumIncomingValues() == 0) { 156202878Srdivacky PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 157210299Sed PN->eraseFromParent(); 158210299Sed } 159210299Sed } 160210299Sed} 161210299Sed 162210299Sedvoid CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 163210299Sed llvm::Function *Fn, 164210299Sed const FunctionArgList &Args, 165210299Sed SourceLocation StartLoc) { 166210299Sed const Decl *D = GD.getDecl(); 167202878Srdivacky 168202878Srdivacky DidCallStackSave = false; 169202878Srdivacky CurCodeDecl = CurFuncDecl = D; 170210299Sed FnRetTy = RetTy; 171210299Sed CurFn = Fn; 172210299Sed assert(CurFn->isDeclaration() && "Function already has body?"); 173210299Sed 174210299Sed llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 175210299Sed 176202878Srdivacky // Create a marker to make it easy to insert allocas into the entryblock 177210299Sed // later. Don't create this with the builder, because we don't want it 178210299Sed // folded. 179210299Sed llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)); 180210299Sed AllocaInsertPt = new llvm::BitCastInst(Undef, 181210299Sed llvm::Type::getInt32Ty(VMContext), "", 182202878Srdivacky EntryBB); 183210299Sed if (Builder.isNamePreserving()) 184210299Sed AllocaInsertPt->setName("allocapt"); 185210299Sed 186210299Sed ReturnBlock = createBasicBlock("return"); 187210299Sed 188210299Sed Builder.SetInsertPoint(EntryBB); 189210299Sed 190210299Sed QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0); 191202878Srdivacky 192210299Sed // Emit subprogram debug descriptor. 193210299Sed // FIXME: The cast here is a huge hack. 194202878Srdivacky if (CGDebugInfo *DI = getDebugInfo()) { 195210299Sed DI->setLocation(StartLoc); 196210299Sed if (isa<FunctionDecl>(D)) { 197202878Srdivacky DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder); 198210299Sed } else { 199210299Sed // Just use LLVM function name. 200210299Sed DI->EmitFunctionStart(Fn->getName(), FnType, CurFn, Builder); 201210299Sed } 202210299Sed } 203210299Sed 204210299Sed // FIXME: Leaked. 205210299Sed CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 206210299Sed 207210299Sed if (RetTy->isVoidType()) { 208210299Sed // Void type; nothing to return. 209210299Sed ReturnValue = 0; 210210299Sed } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 211210299Sed hasAggregateLLVMType(CurFnInfo->getReturnType())) { 212202878Srdivacky // Indirect aggregate return; emit returned value directly into sret slot. 213210299Sed // This reduces code size, and is also affects correctness in C++. 214210299Sed ReturnValue = CurFn->arg_begin(); 215202878Srdivacky } else { 216210299Sed ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 217210299Sed } 218210299Sed 219210299Sed EmitStartEHSpec(CurCodeDecl); 220202878Srdivacky EmitFunctionProlog(*CurFnInfo, CurFn, Args); 221210299Sed 222210299Sed // If any of the arguments have a variably modified type, make sure to 223210299Sed // emit the type size. 224210299Sed for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 225210299Sed i != e; ++i) { 226210299Sed QualType Ty = i->second; 227210299Sed 228210299Sed if (Ty->isVariablyModifiedType()) 229210299Sed EmitVLASize(Ty); 230210299Sed } 231210299Sed} 232210299Sed 233210299Sedstatic bool NeedsVTTParameter(GlobalDecl GD) { 234210299Sed const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 235210299Sed 236210299Sed // We don't have any virtual bases, just return early. 237210299Sed if (!MD->getParent()->getNumVBases()) 238210299Sed return false; 239210299Sed 240210299Sed // Check if we have a base constructor. 241210299Sed if (isa<CXXConstructorDecl>(MD) && GD.getCtorType() == Ctor_Base) 242202878Srdivacky return true; 243202878Srdivacky 244210299Sed // Check if we have a base destructor. 245210299Sed if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base) 246210299Sed return true; 247210299Sed 248210299Sed return false; 249202878Srdivacky} 250202878Srdivacky 251202878Srdivackyvoid CodeGenFunction::GenerateCode(GlobalDecl GD, 252193323Sed llvm::Function *Fn) { 253193323Sed const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 254193323Sed 255193323Sed // Check if we should generate debug info for this function. 256193323Sed if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 257193323Sed DebugInfo = CGM.getDebugInfo(); 258193323Sed 259193323Sed FunctionArgList Args; 260193323Sed 261193323Sed CurGD = GD; 262193323Sed OuterTryBlock = 0; 263193323Sed if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 264193323Sed if (MD->isInstance()) { 265193323Sed // Create the implicit 'this' decl. 266193323Sed // FIXME: I'm not entirely sure I like using a fake decl just for code 267193323Sed // generation. Maybe we can come up with a better way? 268193323Sed CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 269193323Sed &getContext().Idents.get("this"), 270204642Srdivacky MD->getThisType(getContext())); 271204642Srdivacky Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 272204642Srdivacky 273204642Srdivacky // Check if we need a VTT parameter as well. 274204642Srdivacky if (NeedsVTTParameter(GD)) { 275204642Srdivacky // FIXME: The comment about using a fake decl above applies here too. 276204642Srdivacky QualType T = getContext().getPointerType(getContext().VoidPtrTy); 277204642Srdivacky CXXVTTDecl = 278204642Srdivacky ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 279204642Srdivacky &getContext().Idents.get("vtt"), T); 280204642Srdivacky Args.push_back(std::make_pair(CXXVTTDecl, CXXVTTDecl->getType())); 281204642Srdivacky } 282204642Srdivacky } 283204642Srdivacky } 284193323Sed 285193323Sed if (FD->getNumParams()) { 286193323Sed const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 287193323Sed assert(FProto && "Function def must have prototype!"); 288193323Sed 289193323Sed for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 290193323Sed Args.push_back(std::make_pair(FD->getParamDecl(i), 291193323Sed FProto->getArgType(i))); 292193323Sed } 293193323Sed 294193323Sed if (const CompoundStmt *S = FD->getCompoundBody()) { 295193323Sed StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 296193323Sed 297193323Sed if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 298193323Sed EmitCtorPrologue(CD, GD.getCtorType()); 299193323Sed EmitStmt(S); 300193323Sed 301193323Sed // If any of the member initializers are temporaries bound to references 302193323Sed // make sure to emit their destructors. 303193323Sed EmitCleanupBlocks(0); 304193323Sed 305193323Sed } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 306193323Sed llvm::BasicBlock *DtorEpilogue = createBasicBlock("dtor.epilogue"); 307193323Sed PushCleanupBlock(DtorEpilogue); 308193323Sed 309193323Sed EmitStmt(S); 310193323Sed 311193323Sed CleanupBlockInfo Info = PopCleanupBlock(); 312193323Sed 313193323Sed assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!"); 314193323Sed EmitBlock(DtorEpilogue); 315193323Sed EmitDtorEpilogue(DD, GD.getDtorType()); 316193323Sed 317193323Sed if (Info.SwitchBlock) 318193323Sed EmitBlock(Info.SwitchBlock); 319193323Sed if (Info.EndBlock) 320193323Sed EmitBlock(Info.EndBlock); 321193323Sed } else { 322193323Sed // Just a regular function, emit its body. 323193323Sed EmitStmt(S); 324193323Sed } 325193323Sed 326193323Sed FinishFunction(S->getRBracLoc()); 327193323Sed } else if (FD->isImplicit()) { 328193323Sed const CXXRecordDecl *ClassDecl = 329193323Sed cast<CXXRecordDecl>(FD->getDeclContext()); 330193323Sed (void) ClassDecl; 331193323Sed if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 332208599Srdivacky // FIXME: For C++0x, we want to look for implicit *definitions* of 333193323Sed // these special member functions, rather than implicit *declarations*. 334193323Sed if (CD->isCopyConstructor()) { 335193323Sed assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 336193323Sed "Cannot synthesize a non-implicit copy constructor"); 337198090Srdivacky SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args); 338198090Srdivacky } else if (CD->isDefaultConstructor()) { 339198090Srdivacky assert(!ClassDecl->hasUserDeclaredConstructor() && 340198090Srdivacky "Cannot synthesize a non-implicit default constructor."); 341198090Srdivacky SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args); 342193323Sed } else { 343193323Sed assert(false && "Implicit constructor cannot be synthesized"); 344193323Sed } 345193323Sed } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) { 346193323Sed assert(!ClassDecl->hasUserDeclaredDestructor() && 347193323Sed "Cannot synthesize a non-implicit destructor"); 348193323Sed SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args); 349193323Sed } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 350193323Sed assert(MD->isCopyAssignment() && 351193323Sed !ClassDecl->hasUserDeclaredCopyAssignment() && 352193323Sed "Cannot synthesize a method that is not an implicit-defined " 353193323Sed "copy constructor"); 354193323Sed SynthesizeCXXCopyAssignment(MD, Fn, Args); 355193323Sed } else { 356193323Sed assert(false && "Cannot synthesize unknown implicit function"); 357193323Sed } 358193323Sed } else if (const Stmt *S = FD->getBody()) { 359193323Sed if (const CXXTryStmt *TS = dyn_cast<CXXTryStmt>(S)) { 360193323Sed OuterTryBlock = TS; 361193323Sed StartFunction(GD, FD->getResultType(), Fn, Args, TS->getTryLoc()); 362193323Sed EmitStmt(TS); 363193323Sed FinishFunction(TS->getEndLoc()); 364193323Sed } 365198090Srdivacky } 366193323Sed 367193323Sed // Destroy the 'this' declaration. 368193323Sed if (CXXThisDecl) 369193323Sed CXXThisDecl->Destroy(getContext()); 370193323Sed 371193323Sed // Destroy the VTT declaration. 372193323Sed if (CXXVTTDecl) 373193323Sed CXXVTTDecl->Destroy(getContext()); 374193323Sed} 375193323Sed 376193323Sed/// ContainsLabel - Return true if the statement contains a label in it. If 377193323Sed/// this statement is not executed normally, it not containing a label means 378193323Sed/// that we can just remove the code. 379198090Srdivackybool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 380193323Sed // Null statement, not a label! 381193323Sed if (S == 0) return false; 382193323Sed 383193323Sed // If this is a label, we have to emit the code, consider something like: 384193323Sed // if (0) { ... foo: bar(); } goto foo; 385193323Sed if (isa<LabelStmt>(S)) 386193323Sed return true; 387193323Sed 388193323Sed // If this is a case/default statement, and we haven't seen a switch, we have 389193323Sed // to emit the code. 390193323Sed if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 391193323Sed return true; 392193323Sed 393193323Sed // If this is a switch statement, we want to ignore cases below it. 394193323Sed if (isa<SwitchStmt>(S)) 395193323Sed IgnoreCaseStmts = true; 396198090Srdivacky 397210299Sed // Scan subexpressions for verboten labels. 398210299Sed for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 399210299Sed I != E; ++I) 400210299Sed if (ContainsLabel(*I, IgnoreCaseStmts)) 401198090Srdivacky return true; 402208599Srdivacky 403207618Srdivacky return false; 404198090Srdivacky} 405198090Srdivacky 406198090Srdivacky 407193323Sed/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 408193323Sed/// a constant, or if it does but contains a label, return 0. If it constant 409193323Sed/// folds to 'true' and does not contain a label, return 1, if it constant folds 410193323Sed/// to 'false' and does not contain a label, return -1. 411193323Sedint CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 412193323Sed // FIXME: Rename and handle conversion of other evaluatable things 413193323Sed // to bool. 414193323Sed Expr::EvalResult Result; 415193323Sed if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 416198090Srdivacky Result.HasSideEffects) 417210299Sed return 0; // Not foldable, not integer or not fully evaluatable. 418210299Sed 419193323Sed if (CodeGenFunction::ContainsLabel(Cond)) 420193323Sed return 0; // Contains a label. 421193323Sed 422193323Sed return Result.Val.getInt().getBoolValue() ? 1 : -1; 423193323Sed} 424193323Sed 425193323Sed 426208599Srdivacky/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 427208599Srdivacky/// statement) to the specified blocks. Based on the condition, this might try 428208599Srdivacky/// to simplify the codegen of the conditional based on the branch. 429208599Srdivacky/// 430208599Srdivackyvoid CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 431208599Srdivacky llvm::BasicBlock *TrueBlock, 432193323Sed llvm::BasicBlock *FalseBlock) { 433208599Srdivacky if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 434208599Srdivacky return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 435208599Srdivacky 436208599Srdivacky if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 437193323Sed // Handle X && Y in a condition. 438193323Sed if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 439193323Sed // If we have "1 && X", simplify the code. "0 && X" would have constant 440193323Sed // folded if the case was simple enough. 441193323Sed if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 442193323Sed // br(1 && X) -> br(X). 443198090Srdivacky return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 444198090Srdivacky } 445193323Sed 446193323Sed // If we have "X && 1", simplify the code to use an uncond branch. 447193323Sed // "X && 0" would have been constant folded to 0. 448208599Srdivacky if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 449208599Srdivacky // br(X && 1) -> br(X). 450208599Srdivacky return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 451208599Srdivacky } 452208599Srdivacky 453208599Srdivacky // Emit the LHS as a conditional. If the LHS conditional is false, we 454208599Srdivacky // want to jump to the FalseBlock. 455208599Srdivacky llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 456208599Srdivacky EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 457208599Srdivacky EmitBlock(LHSTrue); 458208599Srdivacky 459208599Srdivacky EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 460208599Srdivacky return; 461208599Srdivacky } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 462210299Sed // If we have "0 || X", simplify the code. "1 || X" would have constant 463208599Srdivacky // folded if the case was simple enough. 464208599Srdivacky if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 465208599Srdivacky // br(0 || X) -> br(X). 466208599Srdivacky return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 467208599Srdivacky } 468208599Srdivacky 469210299Sed // If we have "X || 0", simplify the code to use an uncond branch. 470210299Sed // "X || 1" would have been constant folded to 1. 471210299Sed if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 472210299Sed // br(X || 0) -> br(X). 473210299Sed return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 474208599Srdivacky } 475208599Srdivacky 476208599Srdivacky // Emit the LHS as a conditional. If the LHS conditional is true, we 477208599Srdivacky // want to jump to the TrueBlock. 478208599Srdivacky llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 479208599Srdivacky EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 480208599Srdivacky EmitBlock(LHSFalse); 481208599Srdivacky 482193323Sed EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 483193323Sed return; 484202375Srdivacky } 485193323Sed } 486193323Sed 487193323Sed if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 488193323Sed // br(!x, t, f) -> br(x, f, t) 489202375Srdivacky if (CondUOp->getOpcode() == UnaryOperator::LNot) 490193323Sed return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 491193323Sed } 492193323Sed 493193323Sed if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 494202375Srdivacky // Handle ?: operator. 495193323Sed 496202375Srdivacky // Just ignore GNU ?: extension. 497193323Sed if (CondOp->getLHS()) { 498193323Sed // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 499193323Sed llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 500198090Srdivacky llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 501206083Srdivacky EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 502206083Srdivacky EmitBlock(LHSBlock); 503206083Srdivacky EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 504206083Srdivacky EmitBlock(RHSBlock); 505206083Srdivacky EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 506206083Srdivacky return; 507206083Srdivacky } 508206083Srdivacky } 509206083Srdivacky 510206083Srdivacky // Emit the code with the fully general case. 511210299Sed llvm::Value *CondV = EvaluateExprAsBool(Cond); 512206083Srdivacky Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 513206083Srdivacky} 514206083Srdivacky 515206083Srdivacky/// ErrorUnsupported - Print out an error that codegen doesn't support the 516206083Srdivacky/// specified stmt yet. 517206083Srdivackyvoid CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 518206083Srdivacky bool OmitOnError) { 519206083Srdivacky CGM.ErrorUnsupported(S, Type, OmitOnError); 520206083Srdivacky} 521206083Srdivacky 522206083Srdivackyvoid CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 523210299Sed const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 524206083Srdivacky if (DestPtr->getType() != BP) 525206083Srdivacky DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 526206083Srdivacky 527206083Srdivacky // Get size and alignment info for this aggregate. 528206083Srdivacky std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 529210299Sed 530206083Srdivacky // Don't bother emitting a zero-byte memset. 531206083Srdivacky if (TypeInfo.first == 0) 532206083Srdivacky return; 533206083Srdivacky 534206083Srdivacky // FIXME: Handle variable sized types. 535206083Srdivacky const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, 536206083Srdivacky LLVMPointerWidth); 537206083Srdivacky 538206083Srdivacky Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 539206083Srdivacky llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), 540206083Srdivacky // TypeInfo.first describes size in bits. 541207618Srdivacky llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 542207618Srdivacky llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 543207618Srdivacky TypeInfo.second/8)); 544207618Srdivacky} 545207618Srdivacky 546206083Srdivackyllvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelStmt *L) { 547206083Srdivacky // Make sure that there is a block for the indirect goto. 548206083Srdivacky if (IndirectBranch == 0) 549206083Srdivacky GetIndirectGotoBlock(); 550206083Srdivacky 551206083Srdivacky llvm::BasicBlock *BB = getBasicBlockForLabel(L); 552198090Srdivacky 553207618Srdivacky // Make sure the indirect branch includes all of the address-taken blocks. 554198090Srdivacky IndirectBranch->addDestination(BB); 555198090Srdivacky return llvm::BlockAddress::get(CurFn, BB); 556198090Srdivacky} 557206083Srdivacky 558206083Srdivackyllvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 559206083Srdivacky // If we already made the indirect branch for indirect goto, return its block. 560205218Srdivacky if (IndirectBranch) return IndirectBranch->getParent(); 561207618Srdivacky 562207618Srdivacky CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 563207618Srdivacky 564207618Srdivacky const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 565207618Srdivacky 566207618Srdivacky // Create the PHI node that indirect gotos will add entries to. 567207618Srdivacky llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest"); 568210299Sed 569207618Srdivacky // Create the indirect branch instruction. 570207618Srdivacky IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 571207618Srdivacky return IndirectBranch->getParent(); 572198090Srdivacky} 573198090Srdivacky 574198090Srdivackyllvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 575198090Srdivacky llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 576198090Srdivacky 577198090Srdivacky assert(SizeEntry && "Did not emit size for type"); 578198090Srdivacky return SizeEntry; 579198090Srdivacky} 580198090Srdivacky 581198090Srdivackyllvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 582198090Srdivacky assert(Ty->isVariablyModifiedType() && 583198090Srdivacky "Must pass variably modified type to EmitVLASizes!"); 584198090Srdivacky 585198090Srdivacky EnsureInsertPoint(); 586198090Srdivacky 587198090Srdivacky if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 588198090Srdivacky llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 589198090Srdivacky 590198090Srdivacky if (!SizeEntry) { 591198090Srdivacky const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 592198090Srdivacky 593206083Srdivacky // Get the element size; 594198090Srdivacky QualType ElemTy = VAT->getElementType(); 595207618Srdivacky llvm::Value *ElemSize; 596207618Srdivacky if (ElemTy->isVariableArrayType()) 597206083Srdivacky ElemSize = EmitVLASize(ElemTy); 598207618Srdivacky else 599198090Srdivacky ElemSize = llvm::ConstantInt::get(SizeTy, 600198090Srdivacky getContext().getTypeSize(ElemTy) / 8); 601198090Srdivacky 602207618Srdivacky llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 603207618Srdivacky NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 604206083Srdivacky 605207618Srdivacky SizeEntry = Builder.CreateMul(ElemSize, NumElements); 606206083Srdivacky } 607206083Srdivacky 608206083Srdivacky return SizeEntry; 609207618Srdivacky } 610206083Srdivacky 611206083Srdivacky if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 612210299Sed EmitVLASize(AT->getElementType()); 613206083Srdivacky return 0; 614206083Srdivacky } 615206083Srdivacky 616206083Srdivacky const PointerType *PT = Ty->getAs<PointerType>(); 617206083Srdivacky assert(PT && "unknown VM type!"); 618206083Srdivacky EmitVLASize(PT->getPointeeType()); 619206083Srdivacky return 0; 620206083Srdivacky} 621206083Srdivacky 622206083Srdivackyllvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 623206083Srdivacky if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 624206083Srdivacky return EmitScalarExpr(E); 625206083Srdivacky } 626206083Srdivacky return EmitLValue(E).getAddress(); 627206083Srdivacky} 628206083Srdivacky 629206083Srdivackyvoid CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock, 630206083Srdivacky llvm::BasicBlock *CleanupExitBlock, 631206083Srdivacky llvm::BasicBlock *PreviousInvokeDest, 632206083Srdivacky bool EHOnly) { 633206083Srdivacky CleanupEntries.push_back(CleanupEntry(CleanupEntryBlock, CleanupExitBlock, 634206083Srdivacky PreviousInvokeDest, EHOnly)); 635206083Srdivacky} 636206083Srdivacky 637206083Srdivackyvoid CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { 638206083Srdivacky assert(CleanupEntries.size() >= OldCleanupStackSize && 639206083Srdivacky "Cleanup stack mismatch!"); 640207618Srdivacky 641207618Srdivacky while (CleanupEntries.size() > OldCleanupStackSize) 642207618Srdivacky EmitCleanupBlock(); 643207618Srdivacky} 644207618Srdivacky 645207618SrdivackyCodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { 646210299Sed CleanupEntry &CE = CleanupEntries.back(); 647210299Sed 648207618Srdivacky llvm::BasicBlock *CleanupEntryBlock = CE.CleanupEntryBlock; 649210299Sed 650207618Srdivacky std::vector<llvm::BasicBlock *> Blocks; 651206083Srdivacky std::swap(Blocks, CE.Blocks); 652205218Srdivacky 653206083Srdivacky std::vector<llvm::BranchInst *> BranchFixups; 654206083Srdivacky std::swap(BranchFixups, CE.BranchFixups); 655206083Srdivacky 656206083Srdivacky bool EHOnly = CE.EHOnly; 657206083Srdivacky 658206083Srdivacky setInvokeDest(CE.PreviousInvokeDest); 659206083Srdivacky 660206083Srdivacky CleanupEntries.pop_back(); 661207618Srdivacky 662207618Srdivacky // Check if any branch fixups pointed to the scope we just popped. If so, 663207618Srdivacky // we can remove them. 664206083Srdivacky for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 665206083Srdivacky llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 666206083Srdivacky BlockScopeMap::iterator I = BlockScopes.find(Dest); 667198090Srdivacky 668198090Srdivacky if (I == BlockScopes.end()) 669198090Srdivacky continue; 670198090Srdivacky 671198090Srdivacky assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 672198090Srdivacky 673 if (I->second == CleanupEntries.size()) { 674 // We don't need to do this branch fixup. 675 BranchFixups[i] = BranchFixups.back(); 676 BranchFixups.pop_back(); 677 i--; 678 e--; 679 continue; 680 } 681 } 682 683 llvm::BasicBlock *SwitchBlock = CE.CleanupExitBlock; 684 llvm::BasicBlock *EndBlock = 0; 685 if (!BranchFixups.empty()) { 686 if (!SwitchBlock) 687 SwitchBlock = createBasicBlock("cleanup.switch"); 688 EndBlock = createBasicBlock("cleanup.end"); 689 690 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 691 692 Builder.SetInsertPoint(SwitchBlock); 693 694 llvm::Value *DestCodePtr 695 = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), 696 "cleanup.dst"); 697 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 698 699 // Create a switch instruction to determine where to jump next. 700 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 701 BranchFixups.size()); 702 703 // Restore the current basic block (if any) 704 if (CurBB) { 705 Builder.SetInsertPoint(CurBB); 706 707 // If we had a current basic block, we also need to emit an instruction 708 // to initialize the cleanup destination. 709 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), 710 DestCodePtr); 711 } else 712 Builder.ClearInsertionPoint(); 713 714 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 715 llvm::BranchInst *BI = BranchFixups[i]; 716 llvm::BasicBlock *Dest = BI->getSuccessor(0); 717 718 // Fixup the branch instruction to point to the cleanup block. 719 BI->setSuccessor(0, CleanupEntryBlock); 720 721 if (CleanupEntries.empty()) { 722 llvm::ConstantInt *ID; 723 724 // Check if we already have a destination for this block. 725 if (Dest == SI->getDefaultDest()) 726 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 727 else { 728 ID = SI->findCaseDest(Dest); 729 if (!ID) { 730 // No code found, get a new unique one by using the number of 731 // switch successors. 732 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 733 SI->getNumSuccessors()); 734 SI->addCase(ID, Dest); 735 } 736 } 737 738 // Store the jump destination before the branch instruction. 739 new llvm::StoreInst(ID, DestCodePtr, BI); 740 } else { 741 // We need to jump through another cleanup block. Create a pad block 742 // with a branch instruction that jumps to the final destination and add 743 // it as a branch fixup to the current cleanup scope. 744 745 // Create the pad block. 746 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 747 748 // Create a unique case ID. 749 llvm::ConstantInt *ID 750 = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 751 SI->getNumSuccessors()); 752 753 // Store the jump destination before the branch instruction. 754 new llvm::StoreInst(ID, DestCodePtr, BI); 755 756 // Add it as the destination. 757 SI->addCase(ID, CleanupPad); 758 759 // Create the branch to the final destination. 760 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 761 CleanupPad->getInstList().push_back(BI); 762 763 // And add it as a branch fixup. 764 CleanupEntries.back().BranchFixups.push_back(BI); 765 } 766 } 767 } 768 769 // Remove all blocks from the block scope map. 770 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 771 assert(BlockScopes.count(Blocks[i]) && 772 "Did not find block in scope map!"); 773 774 BlockScopes.erase(Blocks[i]); 775 } 776 777 return CleanupBlockInfo(CleanupEntryBlock, SwitchBlock, EndBlock, EHOnly); 778} 779 780void CodeGenFunction::EmitCleanupBlock() { 781 CleanupBlockInfo Info = PopCleanupBlock(); 782 783 if (Info.EHOnly) { 784 // FIXME: Add this to the exceptional edge 785 if (Info.CleanupBlock->getNumUses() == 0) 786 delete Info.CleanupBlock; 787 return; 788 } 789 790 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 791 if (CurBB && !CurBB->getTerminator() && 792 Info.CleanupBlock->getNumUses() == 0) { 793 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 794 delete Info.CleanupBlock; 795 } else 796 EmitBlock(Info.CleanupBlock); 797 798 if (Info.SwitchBlock) 799 EmitBlock(Info.SwitchBlock); 800 if (Info.EndBlock) 801 EmitBlock(Info.EndBlock); 802} 803 804void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { 805 assert(!CleanupEntries.empty() && 806 "Trying to add branch fixup without cleanup block!"); 807 808 // FIXME: We could be more clever here and check if there's already a branch 809 // fixup for this destination and recycle it. 810 CleanupEntries.back().BranchFixups.push_back(BI); 811} 812 813void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { 814 if (!HaveInsertPoint()) 815 return; 816 817 llvm::BranchInst* BI = Builder.CreateBr(Dest); 818 819 Builder.ClearInsertionPoint(); 820 821 // The stack is empty, no need to do any cleanup. 822 if (CleanupEntries.empty()) 823 return; 824 825 if (!Dest->getParent()) { 826 // We are trying to branch to a block that hasn't been inserted yet. 827 AddBranchFixup(BI); 828 return; 829 } 830 831 BlockScopeMap::iterator I = BlockScopes.find(Dest); 832 if (I == BlockScopes.end()) { 833 // We are trying to jump to a block that is outside of any cleanup scope. 834 AddBranchFixup(BI); 835 return; 836 } 837 838 assert(I->second < CleanupEntries.size() && 839 "Trying to branch into cleanup region"); 840 841 if (I->second == CleanupEntries.size() - 1) { 842 // We have a branch to a block in the same scope. 843 return; 844 } 845 846 AddBranchFixup(BI); 847} 848