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