CodeGenFunction.cpp revision 198398
1238104Sdes//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2238104Sdes// 3238104Sdes// The LLVM Compiler Infrastructure 4238104Sdes// 5238104Sdes// This file is distributed under the University of Illinois Open Source 6238104Sdes// License. See LICENSE.TXT for details. 7238104Sdes// 8238104Sdes//===----------------------------------------------------------------------===// 9238104Sdes// 10238104Sdes// This coordinates the per-function state used while generating code. 11238104Sdes// 12238104Sdes//===----------------------------------------------------------------------===// 13238104Sdes 14238104Sdes#include "CodeGenFunction.h" 15238104Sdes#include "CodeGenModule.h" 16238104Sdes#include "CGDebugInfo.h" 17238104Sdes#include "clang/Basic/TargetInfo.h" 18238104Sdes#include "clang/AST/APValue.h" 19238104Sdes#include "clang/AST/ASTContext.h" 20238104Sdes#include "clang/AST/Decl.h" 21238104Sdes#include "clang/AST/DeclCXX.h" 22238104Sdes#include "llvm/Target/TargetData.h" 23238104Sdesusing namespace clang; 24238104Sdesusing namespace CodeGen; 25238104Sdes 26238104SdesCodeGenFunction::CodeGenFunction(CodeGenModule &cgm) 27238104Sdes : BlockFunction(cgm, *this, Builder), CGM(cgm), 28238104Sdes Target(CGM.getContext().Target), 29238104Sdes Builder(cgm.getModule().getContext()), 30238104Sdes DebugInfo(0), IndirectGotoSwitch(0), 31238104Sdes SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0), 32238104Sdes CXXThisDecl(0) { 33238104Sdes LLVMIntTy = ConvertType(getContext().IntTy); 34238104Sdes LLVMPointerWidth = Target.getPointerWidth(0); 35238104Sdes} 36238104Sdes 37238104SdesASTContext &CodeGenFunction::getContext() const { 38238104Sdes return CGM.getContext(); 39238104Sdes} 40238104Sdes 41238104Sdes 42238104Sdesllvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) { 43238104Sdes llvm::BasicBlock *&BB = LabelMap[S]; 44238104Sdes if (BB) return BB; 45238104Sdes 46238104Sdes // Create, but don't insert, the new block. 47238104Sdes return BB = createBasicBlock(S->getName()); 48238104Sdes} 49238104Sdes 50238104Sdesllvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) { 51238104Sdes llvm::Value *Res = LocalDeclMap[VD]; 52238104Sdes assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 53238104Sdes return Res; 54238104Sdes} 55238104Sdes 56238104Sdesllvm::Constant * 57238104SdesCodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) { 58238104Sdes return cast<llvm::Constant>(GetAddrOfLocalVar(BVD)); 59238104Sdes} 60238104Sdes 61238104Sdesconst llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 62238104Sdes return CGM.getTypes().ConvertTypeForMem(T); 63238104Sdes} 64238104Sdes 65238104Sdesconst llvm::Type *CodeGenFunction::ConvertType(QualType T) { 66238104Sdes return CGM.getTypes().ConvertType(T); 67238104Sdes} 68238104Sdes 69238104Sdesbool CodeGenFunction::hasAggregateLLVMType(QualType T) { 70238104Sdes return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() || 71238104Sdes T->isMemberFunctionPointerType(); 72238104Sdes} 73238104Sdes 74238104Sdesvoid CodeGenFunction::EmitReturnBlock() { 75238104Sdes // For cleanliness, we try to avoid emitting the return block for 76238104Sdes // simple cases. 77238104Sdes llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 78238104Sdes 79238104Sdes if (CurBB) { 80238104Sdes assert(!CurBB->getTerminator() && "Unexpected terminated block."); 81238104Sdes 82238104Sdes // We have a valid insert point, reuse it if it is empty or there are no 83238104Sdes // explicit jumps to the return block. 84238104Sdes if (CurBB->empty() || ReturnBlock->use_empty()) { 85238104Sdes ReturnBlock->replaceAllUsesWith(CurBB); 86238104Sdes delete ReturnBlock; 87238104Sdes } else 88238104Sdes EmitBlock(ReturnBlock); 89238104Sdes return; 90238104Sdes } 91238104Sdes 92238104Sdes // Otherwise, if the return block is the target of a single direct 93238104Sdes // branch then we can just put the code in that block instead. This 94238104Sdes // cleans up functions which started with a unified return block. 95238104Sdes if (ReturnBlock->hasOneUse()) { 96238104Sdes llvm::BranchInst *BI = 97238104Sdes dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin()); 98238104Sdes if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) { 99238104Sdes // Reset insertion point and delete the branch. 100238104Sdes Builder.SetInsertPoint(BI->getParent()); 101238104Sdes BI->eraseFromParent(); 102238104Sdes delete ReturnBlock; 103238104Sdes return; 104238104Sdes } 105238104Sdes } 106238104Sdes 107238104Sdes // FIXME: We are at an unreachable point, there is no reason to emit the block 108238104Sdes // unless it has uses. However, we still need a place to put the debug 109238104Sdes // region.end for now. 110238104Sdes 111238104Sdes EmitBlock(ReturnBlock); 112238104Sdes} 113238104Sdes 114238104Sdesvoid CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 115238104Sdes assert(BreakContinueStack.empty() && 116238104Sdes "mismatched push/pop in break/continue stack!"); 117238104Sdes assert(BlockScopes.empty() && 118238104Sdes "did not remove all blocks from block scope map!"); 119238104Sdes assert(CleanupEntries.empty() && 120238104Sdes "mismatched push/pop in cleanup stack!"); 121238104Sdes 122238104Sdes // Emit function epilog (to return). 123238104Sdes EmitReturnBlock(); 124238104Sdes 125238104Sdes // Emit debug descriptor for function end. 126238104Sdes if (CGDebugInfo *DI = getDebugInfo()) { 127238104Sdes DI->setLocation(EndLoc); 128238104Sdes DI->EmitRegionEnd(CurFn, Builder); 129238104Sdes } 130238104Sdes 131238104Sdes EmitFunctionEpilog(*CurFnInfo, ReturnValue); 132238104Sdes 133238104Sdes // Remove the AllocaInsertPt instruction, which is just a convenience for us. 134238104Sdes llvm::Instruction *Ptr = AllocaInsertPt; 135238104Sdes AllocaInsertPt = 0; 136238104Sdes Ptr->eraseFromParent(); 137238104Sdes} 138238104Sdes 139238104Sdesvoid CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 140238104Sdes llvm::Function *Fn, 141238104Sdes const FunctionArgList &Args, 142238104Sdes SourceLocation StartLoc) { 143238104Sdes const Decl *D = GD.getDecl(); 144238104Sdes 145238104Sdes DidCallStackSave = false; 146238104Sdes CurCodeDecl = CurFuncDecl = D; 147238104Sdes FnRetTy = RetTy; 148238104Sdes CurFn = Fn; 149238104Sdes assert(CurFn->isDeclaration() && "Function already has body?"); 150238104Sdes 151238104Sdes llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 152238104Sdes 153238104Sdes // Create a marker to make it easy to insert allocas into the entryblock 154238104Sdes // later. Don't create this with the builder, because we don't want it 155238104Sdes // folded. 156238104Sdes llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)); 157238104Sdes AllocaInsertPt = new llvm::BitCastInst(Undef, 158238104Sdes llvm::Type::getInt32Ty(VMContext), "", 159238104Sdes EntryBB); 160238104Sdes if (Builder.isNamePreserving()) 161238104Sdes AllocaInsertPt->setName("allocapt"); 162238104Sdes 163238104Sdes ReturnBlock = createBasicBlock("return"); 164238104Sdes ReturnValue = 0; 165238104Sdes if (!RetTy->isVoidType()) 166238104Sdes ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 167238104Sdes 168238104Sdes Builder.SetInsertPoint(EntryBB); 169238104Sdes 170238104Sdes QualType FnType = getContext().getFunctionType(RetTy, 0, 0, false, 0); 171238104Sdes 172238104Sdes // Emit subprogram debug descriptor. 173238104Sdes // FIXME: The cast here is a huge hack. 174238104Sdes if (CGDebugInfo *DI = getDebugInfo()) { 175238104Sdes DI->setLocation(StartLoc); 176238104Sdes if (isa<FunctionDecl>(D)) { 177238104Sdes DI->EmitFunctionStart(CGM.getMangledName(GD), FnType, CurFn, Builder); 178238104Sdes } else { 179238104Sdes // Just use LLVM function name. 180238104Sdes 181238104Sdes // FIXME: Remove unnecessary conversion to std::string when API settles. 182238104Sdes DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), 183238104Sdes FnType, CurFn, Builder); 184238104Sdes } 185238104Sdes } 186238104Sdes 187238104Sdes // FIXME: Leaked. 188238104Sdes CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 189238104Sdes EmitFunctionProlog(*CurFnInfo, CurFn, Args); 190238104Sdes 191238104Sdes // If any of the arguments have a variably modified type, make sure to 192238104Sdes // emit the type size. 193238104Sdes for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 194238104Sdes i != e; ++i) { 195238104Sdes QualType Ty = i->second; 196238104Sdes 197238104Sdes if (Ty->isVariablyModifiedType()) 198238104Sdes EmitVLASize(Ty); 199238104Sdes } 200238104Sdes} 201238104Sdes 202238104Sdesvoid CodeGenFunction::GenerateCode(GlobalDecl GD, 203238104Sdes llvm::Function *Fn) { 204238104Sdes const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 205238104Sdes 206238104Sdes // Check if we should generate debug info for this function. 207238104Sdes if (CGM.getDebugInfo() && !FD->hasAttr<NoDebugAttr>()) 208238104Sdes DebugInfo = CGM.getDebugInfo(); 209238104Sdes 210238104Sdes FunctionArgList Args; 211238104Sdes 212238104Sdes if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 213238104Sdes if (MD->isInstance()) { 214238104Sdes // Create the implicit 'this' decl. 215238104Sdes // FIXME: I'm not entirely sure I like using a fake decl just for code 216238104Sdes // generation. Maybe we can come up with a better way? 217238104Sdes CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 218238104Sdes &getContext().Idents.get("this"), 219238104Sdes MD->getThisType(getContext())); 220238104Sdes Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 221238104Sdes } 222238104Sdes } 223238104Sdes 224238104Sdes if (FD->getNumParams()) { 225238104Sdes const FunctionProtoType* FProto = FD->getType()->getAs<FunctionProtoType>(); 226238104Sdes assert(FProto && "Function def must have prototype!"); 227238104Sdes 228238104Sdes for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 229238104Sdes Args.push_back(std::make_pair(FD->getParamDecl(i), 230238104Sdes FProto->getArgType(i))); 231238104Sdes } 232238104Sdes 233238104Sdes // FIXME: Support CXXTryStmt here, too. 234238104Sdes if (const CompoundStmt *S = FD->getCompoundBody()) { 235238104Sdes StartFunction(GD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 236238104Sdes const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD); 237238104Sdes llvm::BasicBlock *DtorEpilogue = 0; 238238104Sdes if (DD) { 239238104Sdes DtorEpilogue = createBasicBlock("dtor.epilogue"); 240238104Sdes 241238104Sdes PushCleanupBlock(DtorEpilogue); 242238104Sdes } 243238104Sdes 244238104Sdes if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 245238104Sdes EmitCtorPrologue(CD, GD.getCtorType()); 246238104Sdes EmitStmt(S); 247238104Sdes 248238104Sdes if (DD) { 249238104Sdes CleanupBlockInfo Info = PopCleanupBlock(); 250238104Sdes 251238104Sdes assert(Info.CleanupBlock == DtorEpilogue && "Block mismatch!"); 252238104Sdes EmitBlock(DtorEpilogue); 253238104Sdes EmitDtorEpilogue(DD, GD.getDtorType()); 254238104Sdes 255238104Sdes if (Info.SwitchBlock) 256238104Sdes EmitBlock(Info.SwitchBlock); 257238104Sdes if (Info.EndBlock) 258238104Sdes EmitBlock(Info.EndBlock); 259238104Sdes } 260238104Sdes FinishFunction(S->getRBracLoc()); 261238104Sdes } else if (FD->isImplicit()) { 262238104Sdes const CXXRecordDecl *ClassDecl = 263238104Sdes cast<CXXRecordDecl>(FD->getDeclContext()); 264238104Sdes (void) ClassDecl; 265238104Sdes if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 266238104Sdes // FIXME: For C++0x, we want to look for implicit *definitions* of 267238104Sdes // these special member functions, rather than implicit *declarations*. 268238104Sdes if (CD->isCopyConstructor(getContext())) { 269238104Sdes assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 270238104Sdes "Cannot synthesize a non-implicit copy constructor"); 271238104Sdes SynthesizeCXXCopyConstructor(CD, GD.getCtorType(), Fn, Args); 272238104Sdes } else if (CD->isDefaultConstructor()) { 273238104Sdes assert(!ClassDecl->hasUserDeclaredConstructor() && 274238104Sdes "Cannot synthesize a non-implicit default constructor."); 275238104Sdes SynthesizeDefaultConstructor(CD, GD.getCtorType(), Fn, Args); 276238104Sdes } else { 277238104Sdes assert(false && "Implicit constructor cannot be synthesized"); 278238104Sdes } 279238104Sdes } else if (const CXXDestructorDecl *CD = dyn_cast<CXXDestructorDecl>(FD)) { 280238104Sdes assert(!ClassDecl->hasUserDeclaredDestructor() && 281238104Sdes "Cannot synthesize a non-implicit destructor"); 282238104Sdes SynthesizeDefaultDestructor(CD, GD.getDtorType(), Fn, Args); 283238104Sdes } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 284238104Sdes assert(MD->isCopyAssignment() && 285238104Sdes !ClassDecl->hasUserDeclaredCopyAssignment() && 286238104Sdes "Cannot synthesize a method that is not an implicit-defined " 287238104Sdes "copy constructor"); 288238104Sdes SynthesizeCXXCopyAssignment(MD, Fn, Args); 289238104Sdes } else { 290238104Sdes assert(false && "Cannot synthesize unknown implicit function"); 291238104Sdes } 292238104Sdes } 293238104Sdes 294238104Sdes // Destroy the 'this' declaration. 295238104Sdes if (CXXThisDecl) 296238104Sdes CXXThisDecl->Destroy(getContext()); 297238104Sdes} 298238104Sdes 299238104Sdes/// ContainsLabel - Return true if the statement contains a label in it. If 300238104Sdes/// this statement is not executed normally, it not containing a label means 301238104Sdes/// that we can just remove the code. 302238104Sdesbool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 303238104Sdes // Null statement, not a label! 304238104Sdes if (S == 0) return false; 305238104Sdes 306238104Sdes // If this is a label, we have to emit the code, consider something like: 307238104Sdes // if (0) { ... foo: bar(); } goto foo; 308238104Sdes if (isa<LabelStmt>(S)) 309238104Sdes return true; 310238104Sdes 311238104Sdes // If this is a case/default statement, and we haven't seen a switch, we have 312238104Sdes // to emit the code. 313238104Sdes if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 314238104Sdes return true; 315238104Sdes 316238104Sdes // If this is a switch statement, we want to ignore cases below it. 317238104Sdes if (isa<SwitchStmt>(S)) 318238104Sdes IgnoreCaseStmts = true; 319 320 // Scan subexpressions for verboten labels. 321 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 322 I != E; ++I) 323 if (ContainsLabel(*I, IgnoreCaseStmts)) 324 return true; 325 326 return false; 327} 328 329 330/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 331/// a constant, or if it does but contains a label, return 0. If it constant 332/// folds to 'true' and does not contain a label, return 1, if it constant folds 333/// to 'false' and does not contain a label, return -1. 334int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 335 // FIXME: Rename and handle conversion of other evaluatable things 336 // to bool. 337 Expr::EvalResult Result; 338 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 339 Result.HasSideEffects) 340 return 0; // Not foldable, not integer or not fully evaluatable. 341 342 if (CodeGenFunction::ContainsLabel(Cond)) 343 return 0; // Contains a label. 344 345 return Result.Val.getInt().getBoolValue() ? 1 : -1; 346} 347 348 349/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 350/// statement) to the specified blocks. Based on the condition, this might try 351/// to simplify the codegen of the conditional based on the branch. 352/// 353void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 354 llvm::BasicBlock *TrueBlock, 355 llvm::BasicBlock *FalseBlock) { 356 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 357 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 358 359 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 360 // Handle X && Y in a condition. 361 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 362 // If we have "1 && X", simplify the code. "0 && X" would have constant 363 // folded if the case was simple enough. 364 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 365 // br(1 && X) -> br(X). 366 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 367 } 368 369 // If we have "X && 1", simplify the code to use an uncond branch. 370 // "X && 0" would have been constant folded to 0. 371 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 372 // br(X && 1) -> br(X). 373 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 374 } 375 376 // Emit the LHS as a conditional. If the LHS conditional is false, we 377 // want to jump to the FalseBlock. 378 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 379 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 380 EmitBlock(LHSTrue); 381 382 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 383 return; 384 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 385 // If we have "0 || X", simplify the code. "1 || X" would have constant 386 // folded if the case was simple enough. 387 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 388 // br(0 || X) -> br(X). 389 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 390 } 391 392 // If we have "X || 0", simplify the code to use an uncond branch. 393 // "X || 1" would have been constant folded to 1. 394 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 395 // br(X || 0) -> br(X). 396 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 397 } 398 399 // Emit the LHS as a conditional. If the LHS conditional is true, we 400 // want to jump to the TrueBlock. 401 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 402 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 403 EmitBlock(LHSFalse); 404 405 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 406 return; 407 } 408 } 409 410 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 411 // br(!x, t, f) -> br(x, f, t) 412 if (CondUOp->getOpcode() == UnaryOperator::LNot) 413 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 414 } 415 416 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 417 // Handle ?: operator. 418 419 // Just ignore GNU ?: extension. 420 if (CondOp->getLHS()) { 421 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 422 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 423 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 424 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 425 EmitBlock(LHSBlock); 426 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 427 EmitBlock(RHSBlock); 428 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 429 return; 430 } 431 } 432 433 // Emit the code with the fully general case. 434 llvm::Value *CondV = EvaluateExprAsBool(Cond); 435 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 436} 437 438/// ErrorUnsupported - Print out an error that codegen doesn't support the 439/// specified stmt yet. 440void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 441 bool OmitOnError) { 442 CGM.ErrorUnsupported(S, Type, OmitOnError); 443} 444 445void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 446 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 447 if (DestPtr->getType() != BP) 448 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 449 450 // Get size and alignment info for this aggregate. 451 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 452 453 // Don't bother emitting a zero-byte memset. 454 if (TypeInfo.first == 0) 455 return; 456 457 // FIXME: Handle variable sized types. 458 const llvm::Type *IntPtr = llvm::IntegerType::get(VMContext, 459 LLVMPointerWidth); 460 461 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 462 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)), 463 // TypeInfo.first describes size in bits. 464 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 465 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 466 TypeInfo.second/8)); 467} 468 469unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 470 // Use LabelIDs.size()+1 as the new ID if one hasn't been assigned. 471 unsigned &Entry = LabelIDs[L]; 472 if (Entry) return Entry; 473 474 Entry = LabelIDs.size(); 475 476 // If this is the first "address taken" of a label and the indirect goto has 477 // already been seen, add this to it. 478 if (IndirectGotoSwitch) { 479 // If this is the first address-taken label, set it as the default dest. 480 if (Entry == 1) 481 IndirectGotoSwitch->setSuccessor(0, getBasicBlockForLabel(L)); 482 else { 483 // Otherwise add it to the switch as a new dest. 484 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext); 485 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, Entry), 486 getBasicBlockForLabel(L)); 487 } 488 } 489 490 return Entry; 491} 492 493llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 494 // If we already made the switch stmt for indirect goto, return its block. 495 if (IndirectGotoSwitch) return IndirectGotoSwitch->getParent(); 496 497 EmitBlock(createBasicBlock("indirectgoto")); 498 499 // Create the PHI node that indirect gotos will add entries to. 500 llvm::Value *DestVal = 501 Builder.CreatePHI(llvm::Type::getInt32Ty(VMContext), "indirect.goto.dest"); 502 503 // Create the switch instruction. For now, set the insert block to this block 504 // which will be fixed as labels are added. 505 IndirectGotoSwitch = Builder.CreateSwitch(DestVal, Builder.GetInsertBlock()); 506 507 // Clear the insertion point to indicate we are in unreachable code. 508 Builder.ClearInsertionPoint(); 509 510 // If we already have labels created, add them. 511 if (!LabelIDs.empty()) { 512 // Invert LabelID's so that the order is determinstic. 513 std::vector<const LabelStmt*> AddrTakenLabelsByID; 514 AddrTakenLabelsByID.resize(LabelIDs.size()); 515 516 for (std::map<const LabelStmt*,unsigned>::iterator 517 LI = LabelIDs.begin(), LE = LabelIDs.end(); LI != LE; ++LI) { 518 assert(LI->second-1 < AddrTakenLabelsByID.size() && 519 "Numbering inconsistent"); 520 AddrTakenLabelsByID[LI->second-1] = LI->first; 521 } 522 523 // Set the default entry as the first block. 524 IndirectGotoSwitch->setSuccessor(0, 525 getBasicBlockForLabel(AddrTakenLabelsByID[0])); 526 527 const llvm::IntegerType *Int32Ty = llvm::Type::getInt32Ty(VMContext); 528 529 // FIXME: The iteration order of this is nondeterminstic! 530 for (unsigned i = 1, e = AddrTakenLabelsByID.size(); i != e; ++i) 531 IndirectGotoSwitch->addCase(llvm::ConstantInt::get(Int32Ty, i+1), 532 getBasicBlockForLabel(AddrTakenLabelsByID[i])); 533 } else { 534 // Otherwise, create a dead block and set it as the default dest. This will 535 // be removed by the optimizers after the indirect goto is set up. 536 llvm::BasicBlock *Dummy = createBasicBlock("indgoto.dummy"); 537 EmitBlock(Dummy); 538 IndirectGotoSwitch->setSuccessor(0, Dummy); 539 Builder.CreateUnreachable(); 540 Builder.ClearInsertionPoint(); 541 } 542 543 return IndirectGotoSwitch->getParent(); 544} 545 546llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 547 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 548 549 assert(SizeEntry && "Did not emit size for type"); 550 return SizeEntry; 551} 552 553llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 554 assert(Ty->isVariablyModifiedType() && 555 "Must pass variably modified type to EmitVLASizes!"); 556 557 EnsureInsertPoint(); 558 559 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 560 llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()]; 561 562 if (!SizeEntry) { 563 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 564 565 // Get the element size; 566 QualType ElemTy = VAT->getElementType(); 567 llvm::Value *ElemSize; 568 if (ElemTy->isVariableArrayType()) 569 ElemSize = EmitVLASize(ElemTy); 570 else 571 ElemSize = llvm::ConstantInt::get(SizeTy, 572 getContext().getTypeSize(ElemTy) / 8); 573 574 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 575 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 576 577 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 578 } 579 580 return SizeEntry; 581 } 582 583 if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 584 EmitVLASize(AT->getElementType()); 585 return 0; 586 } 587 588 const PointerType *PT = Ty->getAs<PointerType>(); 589 assert(PT && "unknown VM type!"); 590 EmitVLASize(PT->getPointeeType()); 591 return 0; 592} 593 594llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 595 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 596 return EmitScalarExpr(E); 597 } 598 return EmitLValue(E).getAddress(); 599} 600 601void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) { 602 CleanupEntries.push_back(CleanupEntry(CleanupBlock)); 603} 604 605void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) { 606 assert(CleanupEntries.size() >= OldCleanupStackSize && 607 "Cleanup stack mismatch!"); 608 609 while (CleanupEntries.size() > OldCleanupStackSize) 610 EmitCleanupBlock(); 611} 612 613CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() { 614 CleanupEntry &CE = CleanupEntries.back(); 615 616 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; 617 618 std::vector<llvm::BasicBlock *> Blocks; 619 std::swap(Blocks, CE.Blocks); 620 621 std::vector<llvm::BranchInst *> BranchFixups; 622 std::swap(BranchFixups, CE.BranchFixups); 623 624 CleanupEntries.pop_back(); 625 626 // Check if any branch fixups pointed to the scope we just popped. If so, 627 // we can remove them. 628 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 629 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 630 BlockScopeMap::iterator I = BlockScopes.find(Dest); 631 632 if (I == BlockScopes.end()) 633 continue; 634 635 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 636 637 if (I->second == CleanupEntries.size()) { 638 // We don't need to do this branch fixup. 639 BranchFixups[i] = BranchFixups.back(); 640 BranchFixups.pop_back(); 641 i--; 642 e--; 643 continue; 644 } 645 } 646 647 llvm::BasicBlock *SwitchBlock = 0; 648 llvm::BasicBlock *EndBlock = 0; 649 if (!BranchFixups.empty()) { 650 SwitchBlock = createBasicBlock("cleanup.switch"); 651 EndBlock = createBasicBlock("cleanup.end"); 652 653 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 654 655 Builder.SetInsertPoint(SwitchBlock); 656 657 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::getInt32Ty(VMContext), 658 "cleanup.dst"); 659 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 660 661 // Create a switch instruction to determine where to jump next. 662 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 663 BranchFixups.size()); 664 665 // Restore the current basic block (if any) 666 if (CurBB) { 667 Builder.SetInsertPoint(CurBB); 668 669 // If we had a current basic block, we also need to emit an instruction 670 // to initialize the cleanup destination. 671 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)), 672 DestCodePtr); 673 } else 674 Builder.ClearInsertionPoint(); 675 676 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 677 llvm::BranchInst *BI = BranchFixups[i]; 678 llvm::BasicBlock *Dest = BI->getSuccessor(0); 679 680 // Fixup the branch instruction to point to the cleanup block. 681 BI->setSuccessor(0, CleanupBlock); 682 683 if (CleanupEntries.empty()) { 684 llvm::ConstantInt *ID; 685 686 // Check if we already have a destination for this block. 687 if (Dest == SI->getDefaultDest()) 688 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0); 689 else { 690 ID = SI->findCaseDest(Dest); 691 if (!ID) { 692 // No code found, get a new unique one by using the number of 693 // switch successors. 694 ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 695 SI->getNumSuccessors()); 696 SI->addCase(ID, Dest); 697 } 698 } 699 700 // Store the jump destination before the branch instruction. 701 new llvm::StoreInst(ID, DestCodePtr, BI); 702 } else { 703 // We need to jump through another cleanup block. Create a pad block 704 // with a branch instruction that jumps to the final destination and 705 // add it as a branch fixup to the current cleanup scope. 706 707 // Create the pad block. 708 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 709 710 // Create a unique case ID. 711 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 712 SI->getNumSuccessors()); 713 714 // Store the jump destination before the branch instruction. 715 new llvm::StoreInst(ID, DestCodePtr, BI); 716 717 // Add it as the destination. 718 SI->addCase(ID, CleanupPad); 719 720 // Create the branch to the final destination. 721 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 722 CleanupPad->getInstList().push_back(BI); 723 724 // And add it as a branch fixup. 725 CleanupEntries.back().BranchFixups.push_back(BI); 726 } 727 } 728 } 729 730 // Remove all blocks from the block scope map. 731 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 732 assert(BlockScopes.count(Blocks[i]) && 733 "Did not find block in scope map!"); 734 735 BlockScopes.erase(Blocks[i]); 736 } 737 738 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock); 739} 740 741void CodeGenFunction::EmitCleanupBlock() { 742 CleanupBlockInfo Info = PopCleanupBlock(); 743 744 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 745 if (CurBB && !CurBB->getTerminator() && 746 Info.CleanupBlock->getNumUses() == 0) { 747 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 748 delete Info.CleanupBlock; 749 } else 750 EmitBlock(Info.CleanupBlock); 751 752 if (Info.SwitchBlock) 753 EmitBlock(Info.SwitchBlock); 754 if (Info.EndBlock) 755 EmitBlock(Info.EndBlock); 756} 757 758void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) { 759 assert(!CleanupEntries.empty() && 760 "Trying to add branch fixup without cleanup block!"); 761 762 // FIXME: We could be more clever here and check if there's already a branch 763 // fixup for this destination and recycle it. 764 CleanupEntries.back().BranchFixups.push_back(BI); 765} 766 767void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) { 768 if (!HaveInsertPoint()) 769 return; 770 771 llvm::BranchInst* BI = Builder.CreateBr(Dest); 772 773 Builder.ClearInsertionPoint(); 774 775 // The stack is empty, no need to do any cleanup. 776 if (CleanupEntries.empty()) 777 return; 778 779 if (!Dest->getParent()) { 780 // We are trying to branch to a block that hasn't been inserted yet. 781 AddBranchFixup(BI); 782 return; 783 } 784 785 BlockScopeMap::iterator I = BlockScopes.find(Dest); 786 if (I == BlockScopes.end()) { 787 // We are trying to jump to a block that is outside of any cleanup scope. 788 AddBranchFixup(BI); 789 return; 790 } 791 792 assert(I->second < CleanupEntries.size() && 793 "Trying to branch into cleanup region"); 794 795 if (I->second == CleanupEntries.size() - 1) { 796 // We have a branch to a block in the same scope. 797 return; 798 } 799 800 AddBranchFixup(BI); 801} 802