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(); 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(const Decl *D, QualType RetTy, 145 llvm::Function *Fn, 146 const FunctionArgList &Args, 147 SourceLocation StartLoc) { 148 DidCallStackSave = false; 149 CurCodeDecl = CurFuncDecl = D; 150 FnRetTy = RetTy; 151 CurFn = Fn; 152 assert(CurFn->isDeclaration() && "Function already has body?"); 153 154 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 155 156 // Create a marker to make it easy to insert allocas into the entryblock 157 // later. Don't create this with the builder, because we don't want it 158 // folded. 159 llvm::Value *Undef = VMContext.getUndef(llvm::Type::Int32Ty); 160 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "", 161 EntryBB); 162 if (Builder.isNamePreserving()) 163 AllocaInsertPt->setName("allocapt"); 164 165 ReturnBlock = createBasicBlock("return"); 166 ReturnValue = 0; 167 if (!RetTy->isVoidType()) 168 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval"); 169 170 Builder.SetInsertPoint(EntryBB); 171 172 // Emit subprogram debug descriptor. 173 // FIXME: The cast here is a huge hack. 174 if (CGDebugInfo *DI = getDebugInfo()) { 175 DI->setLocation(StartLoc); 176 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 177 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder); 178 } else { 179 // Just use LLVM function name. 180 181 // FIXME: Remove unnecessary conversion to std::string when API settles. 182 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(), 183 RetTy, CurFn, Builder); 184 } 185 } 186 187 // FIXME: Leaked. 188 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args); 189 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 190 191 // If any of the arguments have a variably modified type, make sure to 192 // emit the type size. 193 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 194 i != e; ++i) { 195 QualType Ty = i->second; 196 197 if (Ty->isVariablyModifiedType()) 198 EmitVLASize(Ty); 199 } 200 } 201 202 void CodeGenFunction::GenerateCode(const FunctionDecl *FD, 203 llvm::Function *Fn) { 204 // Check if we should generate debug info for this function. 205 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>()) 206 DebugInfo = CGM.getDebugInfo(); 207 208 FunctionArgList Args; 209 210 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 211 if (MD->isInstance()) { 212 // Create the implicit 'this' decl. 213 // FIXME: I'm not entirely sure I like using a fake decl just for code 214 // generation. Maybe we can come up with a better way? 215 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 216 &getContext().Idents.get("this"), 217 MD->getThisType(getContext())); 218 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType())); 219 } 220 } 221 222 if (FD->getNumParams()) { 223 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType(); 224 assert(FProto && "Function def must have prototype!"); 225 226 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) 227 Args.push_back(std::make_pair(FD->getParamDecl(i), 228 FProto->getArgType(i))); 229 } 230 231 // FIXME: Support CXXTryStmt here, too. 232 if (const CompoundStmt *S = FD->getCompoundBody()) { 233 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc()); 234 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 235 EmitCtorPrologue(CD); 236 EmitStmt(S); 237 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 238 EmitDtorEpilogue(DD); 239 FinishFunction(S->getRBracLoc()); 240 } 241 242 // Destroy the 'this' declaration. 243 if (CXXThisDecl) 244 CXXThisDecl->Destroy(getContext()); 245 } 246 247 /// ContainsLabel - Return true if the statement contains a label in it. If 248 /// this statement is not executed normally, it not containing a label means 249 /// that we can just remove the code. 250 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 251 // Null statement, not a label! 252 if (S == 0) return false; 253 254 // If this is a label, we have to emit the code, consider something like: 255 // if (0) { ... foo: bar(); } goto foo; 256 if (isa<LabelStmt>(S)) 257 return true; 258 259 // If this is a case/default statement, and we haven't seen a switch, we have 260 // to emit the code. 261 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 262 return true; 263 264 // If this is a switch statement, we want to ignore cases below it. 265 if (isa<SwitchStmt>(S)) 266 IgnoreCaseStmts = true; 267 268 // Scan subexpressions for verboten labels. 269 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 270 I != E; ++I) 271 if (ContainsLabel(*I, IgnoreCaseStmts)) 272 return true; 273 274 return false; 275 } 276 277 278 /// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to 279 /// a constant, or if it does but contains a label, return 0. If it constant 280 /// folds to 'true' and does not contain a label, return 1, if it constant folds 281 /// to 'false' and does not contain a label, return -1. 282 int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) { 283 // FIXME: Rename and handle conversion of other evaluatable things 284 // to bool. 285 Expr::EvalResult Result; 286 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() || 287 Result.HasSideEffects) 288 return 0; // Not foldable, not integer or not fully evaluatable. 289 290 if (CodeGenFunction::ContainsLabel(Cond)) 291 return 0; // Contains a label. 292 293 return Result.Val.getInt().getBoolValue() ? 1 : -1; 294 } 295 296 297 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 298 /// statement) to the specified blocks. Based on the condition, this might try 299 /// to simplify the codegen of the conditional based on the branch. 300 /// 301 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 302 llvm::BasicBlock *TrueBlock, 303 llvm::BasicBlock *FalseBlock) { 304 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) 305 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock); 306 307 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 308 // Handle X && Y in a condition. 309 if (CondBOp->getOpcode() == BinaryOperator::LAnd) { 310 // If we have "1 && X", simplify the code. "0 && X" would have constant 311 // folded if the case was simple enough. 312 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) { 313 // br(1 && X) -> br(X). 314 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 315 } 316 317 // If we have "X && 1", simplify the code to use an uncond branch. 318 // "X && 0" would have been constant folded to 0. 319 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) { 320 // br(X && 1) -> br(X). 321 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 322 } 323 324 // Emit the LHS as a conditional. If the LHS conditional is false, we 325 // want to jump to the FalseBlock. 326 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 327 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock); 328 EmitBlock(LHSTrue); 329 330 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 331 return; 332 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) { 333 // If we have "0 || X", simplify the code. "1 || X" would have constant 334 // folded if the case was simple enough. 335 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) { 336 // br(0 || X) -> br(X). 337 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 338 } 339 340 // If we have "X || 0", simplify the code to use an uncond branch. 341 // "X || 1" would have been constant folded to 1. 342 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) { 343 // br(X || 0) -> br(X). 344 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock); 345 } 346 347 // Emit the LHS as a conditional. If the LHS conditional is true, we 348 // want to jump to the TrueBlock. 349 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 350 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse); 351 EmitBlock(LHSFalse); 352 353 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock); 354 return; 355 } 356 } 357 358 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 359 // br(!x, t, f) -> br(x, f, t) 360 if (CondUOp->getOpcode() == UnaryOperator::LNot) 361 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock); 362 } 363 364 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 365 // Handle ?: operator. 366 367 // Just ignore GNU ?: extension. 368 if (CondOp->getLHS()) { 369 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 370 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 371 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 372 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock); 373 EmitBlock(LHSBlock); 374 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock); 375 EmitBlock(RHSBlock); 376 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock); 377 return; 378 } 379 } 380 381 // Emit the code with the fully general case. 382 llvm::Value *CondV = EvaluateExprAsBool(Cond); 383 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock); 384 } 385 386 /// getCGRecordLayout - Return record layout info. 387 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT, 388 QualType Ty) { 389 const RecordType *RTy = Ty->getAs<RecordType>(); 390 assert (RTy && "Unexpected type. RecordType expected here."); 391 392 return CGT.getCGRecordLayout(RTy->getDecl()); 393 } 394 395 /// ErrorUnsupported - Print out an error that codegen doesn't support the 396 /// specified stmt yet. 397 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type, 398 bool OmitOnError) { 399 CGM.ErrorUnsupported(S, Type, OmitOnError); 400 } 401 402 unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) { 403 // Use LabelIDs.size() as the new ID if one hasn't been assigned. 404 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second; 405 } 406 407 void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) { 408 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 409 if (DestPtr->getType() != BP) 410 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 411 412 // Get size and alignment info for this aggregate. 413 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 414 415 // Don't bother emitting a zero-byte memset. 416 if (TypeInfo.first == 0) 417 return; 418 419 // FIXME: Handle variable sized types. 420 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 421 422 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr, 423 getLLVMContext().getNullValue(llvm::Type::Int8Ty), 424 // TypeInfo.first describes size in bits. 425 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 426 llvm::ConstantInt::get(llvm::Type::Int32Ty, 427 TypeInfo.second/8)); 428 } 429 430 void CodeGenFunction::EmitIndirectSwitches() { 431 llvm::BasicBlock *Default; 432 433 if (IndirectSwitches.empty()) 434 return; 435 436 if (!LabelIDs.empty()) { 437 Default = getBasicBlockForLabel(LabelIDs.begin()->first); 438 } else { 439 // No possible targets for indirect goto, just emit an infinite 440 // loop. 441 Default = createBasicBlock("indirectgoto.loop", CurFn); 442 llvm::BranchInst::Create(Default, Default); 443 } 444 445 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(), 446 e = IndirectSwitches.end(); i != e; ++i) { 447 llvm::SwitchInst *I = *i; 448 449 I->setSuccessor(0, Default); 450 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(), 451 LE = LabelIDs.end(); LI != LE; ++LI) { 452 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty, 453 LI->second), 454 getBasicBlockForLabel(LI->first)); 455 } 456 } 457 } 458 459 llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) { 460 llvm::Value *&SizeEntry = VLASizeMap[VAT]; 461 462 assert(SizeEntry && "Did not emit size for type"); 463 return SizeEntry; 464 } 465 466 llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) { 467 assert(Ty->isVariablyModifiedType() && 468 "Must pass variably modified type to EmitVLASizes!"); 469 470 EnsureInsertPoint(); 471 472 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) { 473 llvm::Value *&SizeEntry = VLASizeMap[VAT]; 474 475 if (!SizeEntry) { 476 // Get the element size; 477 llvm::Value *ElemSize; 478 479 QualType ElemTy = VAT->getElementType(); 480 481 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 482 483 if (ElemTy->isVariableArrayType()) 484 ElemSize = EmitVLASize(ElemTy); 485 else { 486 ElemSize = llvm::ConstantInt::get(SizeTy, 487 getContext().getTypeSize(ElemTy) / 8); 488 } 489 490 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr()); 491 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp"); 492 493 SizeEntry = Builder.CreateMul(ElemSize, NumElements); 494 } 495 496 return SizeEntry; 497 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) { 498 EmitVLASize(AT->getElementType()); 499 } else if (const PointerType *PT = Ty->getAs<PointerType>()) 500 EmitVLASize(PT->getPointeeType()); 501 else { 502 assert(0 && "unknown VM type!"); 503 } 504 505 return 0; 506 } 507 508 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 509 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) { 510 return EmitScalarExpr(E); 511 } 512 return EmitLValue(E).getAddress(); 513 } 514 515 void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock) 516 { 517 CleanupEntries.push_back(CleanupEntry(CleanupBlock)); 518 } 519 520 void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize) 521 { 522 assert(CleanupEntries.size() >= OldCleanupStackSize && 523 "Cleanup stack mismatch!"); 524 525 while (CleanupEntries.size() > OldCleanupStackSize) 526 EmitCleanupBlock(); 527 } 528 529 CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock() 530 { 531 CleanupEntry &CE = CleanupEntries.back(); 532 533 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock; 534 535 std::vector<llvm::BasicBlock *> Blocks; 536 std::swap(Blocks, CE.Blocks); 537 538 std::vector<llvm::BranchInst *> BranchFixups; 539 std::swap(BranchFixups, CE.BranchFixups); 540 541 CleanupEntries.pop_back(); 542 543 // Check if any branch fixups pointed to the scope we just popped. If so, 544 // we can remove them. 545 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 546 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0); 547 BlockScopeMap::iterator I = BlockScopes.find(Dest); 548 549 if (I == BlockScopes.end()) 550 continue; 551 552 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!"); 553 554 if (I->second == CleanupEntries.size()) { 555 // We don't need to do this branch fixup. 556 BranchFixups[i] = BranchFixups.back(); 557 BranchFixups.pop_back(); 558 i--; 559 e--; 560 continue; 561 } 562 } 563 564 llvm::BasicBlock *SwitchBlock = 0; 565 llvm::BasicBlock *EndBlock = 0; 566 if (!BranchFixups.empty()) { 567 SwitchBlock = createBasicBlock("cleanup.switch"); 568 EndBlock = createBasicBlock("cleanup.end"); 569 570 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 571 572 Builder.SetInsertPoint(SwitchBlock); 573 574 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty, 575 "cleanup.dst"); 576 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp"); 577 578 // Create a switch instruction to determine where to jump next. 579 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock, 580 BranchFixups.size()); 581 582 // Restore the current basic block (if any) 583 if (CurBB) { 584 Builder.SetInsertPoint(CurBB); 585 586 // If we had a current basic block, we also need to emit an instruction 587 // to initialize the cleanup destination. 588 Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty), 589 DestCodePtr); 590 } else 591 Builder.ClearInsertionPoint(); 592 593 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) { 594 llvm::BranchInst *BI = BranchFixups[i]; 595 llvm::BasicBlock *Dest = BI->getSuccessor(0); 596 597 // Fixup the branch instruction to point to the cleanup block. 598 BI->setSuccessor(0, CleanupBlock); 599 600 if (CleanupEntries.empty()) { 601 llvm::ConstantInt *ID; 602 603 // Check if we already have a destination for this block. 604 if (Dest == SI->getDefaultDest()) 605 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0); 606 else { 607 ID = SI->findCaseDest(Dest); 608 if (!ID) { 609 // No code found, get a new unique one by using the number of 610 // switch successors. 611 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 612 SI->getNumSuccessors()); 613 SI->addCase(ID, Dest); 614 } 615 } 616 617 // Store the jump destination before the branch instruction. 618 new llvm::StoreInst(ID, DestCodePtr, BI); 619 } else { 620 // We need to jump through another cleanup block. Create a pad block 621 // with a branch instruction that jumps to the final destination and 622 // add it as a branch fixup to the current cleanup scope. 623 624 // Create the pad block. 625 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn); 626 627 // Create a unique case ID. 628 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 629 SI->getNumSuccessors()); 630 631 // Store the jump destination before the branch instruction. 632 new llvm::StoreInst(ID, DestCodePtr, BI); 633 634 // Add it as the destination. 635 SI->addCase(ID, CleanupPad); 636 637 // Create the branch to the final destination. 638 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest); 639 CleanupPad->getInstList().push_back(BI); 640 641 // And add it as a branch fixup. 642 CleanupEntries.back().BranchFixups.push_back(BI); 643 } 644 } 645 } 646 647 // Remove all blocks from the block scope map. 648 for (size_t i = 0, e = Blocks.size(); i != e; ++i) { 649 assert(BlockScopes.count(Blocks[i]) && 650 "Did not find block in scope map!"); 651 652 BlockScopes.erase(Blocks[i]); 653 } 654 655 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock); 656 } 657 658 void CodeGenFunction::EmitCleanupBlock() 659 { 660 CleanupBlockInfo Info = PopCleanupBlock(); 661 662 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 663 if (CurBB && !CurBB->getTerminator() && 664 Info.CleanupBlock->getNumUses() == 0) { 665 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList()); 666 delete Info.CleanupBlock; 667 } else 668 EmitBlock(Info.CleanupBlock); 669 670 if (Info.SwitchBlock) 671 EmitBlock(Info.SwitchBlock); 672 if (Info.EndBlock) 673 EmitBlock(Info.EndBlock); 674 } 675 676 void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI) 677 { 678 assert(!CleanupEntries.empty() && 679 "Trying to add branch fixup without cleanup block!"); 680 681 // FIXME: We could be more clever here and check if there's already a branch 682 // fixup for this destination and recycle it. 683 CleanupEntries.back().BranchFixups.push_back(BI); 684 } 685 686 void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest) 687 { 688 if (!HaveInsertPoint()) 689 return; 690 691 llvm::BranchInst* BI = Builder.CreateBr(Dest); 692 693 Builder.ClearInsertionPoint(); 694 695 // The stack is empty, no need to do any cleanup. 696 if (CleanupEntries.empty()) 697 return; 698 699 if (!Dest->getParent()) { 700 // We are trying to branch to a block that hasn't been inserted yet. 701 AddBranchFixup(BI); 702 return; 703 } 704 705 BlockScopeMap::iterator I = BlockScopes.find(Dest); 706 if (I == BlockScopes.end()) { 707 // We are trying to jump to a block that is outside of any cleanup scope. 708 AddBranchFixup(BI); 709 return; 710 } 711 712 assert(I->second < CleanupEntries.size() && 713 "Trying to branch into cleanup region"); 714 715 if (I->second == CleanupEntries.size() - 1) { 716 // We have a branch to a block in the same scope. 717 return; 718 } 719 720 AddBranchFixup(BI); 721 } 722