1 //===-- DwarfEHPrepare - Prepare exception handling for code generation ---===// 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 pass mulches exception handling code into a form adapted to code 11 // generation. Required if using dwarf exception handling. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #define DEBUG_TYPE "dwarfehprepare" 16 #include "llvm/Function.h" 17 #include "llvm/Instructions.h" 18 #include "llvm/IntrinsicInst.h" 19 #include "llvm/Module.h" 20 #include "llvm/Pass.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/Dominators.h" 23 #include "llvm/CodeGen/Passes.h" 24 #include "llvm/MC/MCAsmInfo.h" 25 #include "llvm/Support/CallSite.h" 26 #include "llvm/Target/TargetLowering.h" 27 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 28 #include "llvm/Transforms/Utils/SSAUpdater.h" 29 using namespace llvm; 30 31 STATISTIC(NumLandingPadsSplit, "Number of landing pads split"); 32 STATISTIC(NumUnwindsLowered, "Number of unwind instructions lowered"); 33 STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved"); 34 35 namespace { 36 class DwarfEHPrepare : public FunctionPass { 37 const TargetMachine *TM; 38 const TargetLowering *TLI; 39 40 // The eh.exception intrinsic. 41 Function *ExceptionValueIntrinsic; 42 43 // The eh.selector intrinsic. 44 Function *SelectorIntrinsic; 45 46 // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call. 47 Constant *URoR; 48 49 // The EH language-specific catch-all type. 50 GlobalVariable *EHCatchAllValue; 51 52 // _Unwind_Resume or the target equivalent. 53 Constant *RewindFunction; 54 55 // We both use and preserve dominator info. 56 DominatorTree *DT; 57 58 // The function we are running on. 59 Function *F; 60 61 // The landing pads for this function. 62 typedef SmallPtrSet<BasicBlock*, 8> BBSet; 63 BBSet LandingPads; 64 65 bool NormalizeLandingPads(); 66 bool LowerUnwinds(); 67 bool MoveExceptionValueCalls(); 68 69 Instruction *CreateExceptionValueCall(BasicBlock *BB); 70 71 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still 72 /// use the "llvm.eh.catch.all.value" call need to convert to using its 73 /// initializer instead. 74 bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels); 75 76 bool HasCatchAllInSelector(IntrinsicInst *); 77 78 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups. 79 void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels, 80 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels); 81 82 /// FindAllURoRInvokes - Find all URoR invokes in the function. 83 void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes); 84 85 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or 86 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to 87 /// a landing pad within the current function. This is a candidate to merge 88 /// the selector associated with the URoR invoke with the one from the 89 /// URoR's landing pad. 90 bool HandleURoRInvokes(); 91 92 /// FindSelectorAndURoR - Find the eh.selector call and URoR call associated 93 /// with the eh.exception call. This recursively looks past instructions 94 /// which don't change the EH pointer value, like casts or PHI nodes. 95 bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke, 96 SmallPtrSet<IntrinsicInst*, 8> &SelCalls); 97 98 public: 99 static char ID; // Pass identification, replacement for typeid. 100 DwarfEHPrepare(const TargetMachine *tm) : 101 FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()), 102 ExceptionValueIntrinsic(0), SelectorIntrinsic(0), 103 URoR(0), EHCatchAllValue(0), RewindFunction(0) { 104 initializeDominatorTreePass(*PassRegistry::getPassRegistry()); 105 } 106 107 virtual bool runOnFunction(Function &Fn); 108 109 // getAnalysisUsage - We need the dominator tree for handling URoR. 110 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 111 AU.addRequired<DominatorTree>(); 112 AU.addPreserved<DominatorTree>(); 113 } 114 115 const char *getPassName() const { 116 return "Exception handling preparation"; 117 } 118 119 }; 120 } // end anonymous namespace 121 122 char DwarfEHPrepare::ID = 0; 123 124 FunctionPass *llvm::createDwarfEHPass(const TargetMachine *tm) { 125 return new DwarfEHPrepare(tm); 126 } 127 128 /// HasCatchAllInSelector - Return true if the intrinsic instruction has a 129 /// catch-all. 130 bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) { 131 if (!EHCatchAllValue) return false; 132 133 unsigned ArgIdx = II->getNumArgOperands() - 1; 134 GlobalVariable *GV = dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx)); 135 return GV == EHCatchAllValue; 136 } 137 138 /// FindAllCleanupSelectors - Find all eh.selector calls that are clean-ups. 139 void DwarfEHPrepare:: 140 FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels, 141 SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) { 142 for (Value::use_iterator 143 I = SelectorIntrinsic->use_begin(), 144 E = SelectorIntrinsic->use_end(); I != E; ++I) { 145 IntrinsicInst *II = cast<IntrinsicInst>(*I); 146 147 if (II->getParent()->getParent() != F) 148 continue; 149 150 if (!HasCatchAllInSelector(II)) 151 Sels.insert(II); 152 else 153 CatchAllSels.insert(II); 154 } 155 } 156 157 /// FindAllURoRInvokes - Find all URoR invokes in the function. 158 void DwarfEHPrepare:: 159 FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) { 160 for (Value::use_iterator 161 I = URoR->use_begin(), 162 E = URoR->use_end(); I != E; ++I) { 163 if (InvokeInst *II = dyn_cast<InvokeInst>(*I)) 164 URoRInvokes.insert(II); 165 } 166 } 167 168 /// CleanupSelectors - Any remaining eh.selector intrinsic calls which still use 169 /// the "llvm.eh.catch.all.value" call need to convert to using its 170 /// initializer instead. 171 bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels) { 172 if (!EHCatchAllValue) return false; 173 174 if (!SelectorIntrinsic) { 175 SelectorIntrinsic = 176 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector); 177 if (!SelectorIntrinsic) return false; 178 } 179 180 bool Changed = false; 181 for (SmallPtrSet<IntrinsicInst*, 32>::iterator 182 I = Sels.begin(), E = Sels.end(); I != E; ++I) { 183 IntrinsicInst *Sel = *I; 184 185 // Index of the "llvm.eh.catch.all.value" variable. 186 unsigned OpIdx = Sel->getNumArgOperands() - 1; 187 GlobalVariable *GV = dyn_cast<GlobalVariable>(Sel->getArgOperand(OpIdx)); 188 if (GV != EHCatchAllValue) continue; 189 Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer()); 190 Changed = true; 191 } 192 193 return Changed; 194 } 195 196 /// FindSelectorAndURoR - Find the eh.selector call associated with the 197 /// eh.exception call. And indicate if there is a URoR "invoke" associated with 198 /// the eh.exception call. This recursively looks past instructions which don't 199 /// change the EH pointer value, like casts or PHI nodes. 200 bool 201 DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke, 202 SmallPtrSet<IntrinsicInst*, 8> &SelCalls) { 203 SmallPtrSet<PHINode*, 32> SeenPHIs; 204 bool Changed = false; 205 206 for (Value::use_iterator 207 I = Inst->use_begin(), E = Inst->use_end(); I != E; ++I) { 208 Instruction *II = dyn_cast<Instruction>(*I); 209 if (!II || II->getParent()->getParent() != F) continue; 210 211 if (IntrinsicInst *Sel = dyn_cast<IntrinsicInst>(II)) { 212 if (Sel->getIntrinsicID() == Intrinsic::eh_selector) 213 SelCalls.insert(Sel); 214 } else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(II)) { 215 if (Invoke->getCalledFunction() == URoR) 216 URoRInvoke = true; 217 } else if (CastInst *CI = dyn_cast<CastInst>(II)) { 218 Changed |= FindSelectorAndURoR(CI, URoRInvoke, SelCalls); 219 } else if (PHINode *PN = dyn_cast<PHINode>(II)) { 220 if (SeenPHIs.insert(PN)) 221 // Don't process a PHI node more than once. 222 Changed |= FindSelectorAndURoR(PN, URoRInvoke, SelCalls); 223 } 224 } 225 226 return Changed; 227 } 228 229 /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or 230 /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump to a 231 /// landing pad within the current function. This is a candidate to merge the 232 /// selector associated with the URoR invoke with the one from the URoR's 233 /// landing pad. 234 bool DwarfEHPrepare::HandleURoRInvokes() { 235 if (!EHCatchAllValue) { 236 EHCatchAllValue = 237 F->getParent()->getNamedGlobal("llvm.eh.catch.all.value"); 238 if (!EHCatchAllValue) return false; 239 } 240 241 if (!SelectorIntrinsic) { 242 SelectorIntrinsic = 243 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector); 244 if (!SelectorIntrinsic) return false; 245 } 246 247 SmallPtrSet<IntrinsicInst*, 32> Sels; 248 SmallPtrSet<IntrinsicInst*, 32> CatchAllSels; 249 FindAllCleanupSelectors(Sels, CatchAllSels); 250 251 if (!URoR) { 252 URoR = F->getParent()->getFunction("_Unwind_Resume_or_Rethrow"); 253 if (!URoR) { 254 URoR = F->getParent()->getFunction("_Unwind_SjLj_Resume"); 255 if (!URoR) return CleanupSelectors(CatchAllSels); 256 } 257 } 258 259 SmallPtrSet<InvokeInst*, 32> URoRInvokes; 260 FindAllURoRInvokes(URoRInvokes); 261 262 SmallPtrSet<IntrinsicInst*, 32> SelsToConvert; 263 264 for (SmallPtrSet<IntrinsicInst*, 32>::iterator 265 SI = Sels.begin(), SE = Sels.end(); SI != SE; ++SI) { 266 const BasicBlock *SelBB = (*SI)->getParent(); 267 for (SmallPtrSet<InvokeInst*, 32>::iterator 268 UI = URoRInvokes.begin(), UE = URoRInvokes.end(); UI != UE; ++UI) { 269 const BasicBlock *URoRBB = (*UI)->getParent(); 270 if (DT->dominates(SelBB, URoRBB)) { 271 SelsToConvert.insert(*SI); 272 break; 273 } 274 } 275 } 276 277 bool Changed = false; 278 279 if (Sels.size() != SelsToConvert.size()) { 280 // If we haven't been able to convert all of the clean-up selectors, then 281 // loop through the slow way to see if they still need to be converted. 282 if (!ExceptionValueIntrinsic) { 283 ExceptionValueIntrinsic = 284 Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception); 285 if (!ExceptionValueIntrinsic) 286 return CleanupSelectors(CatchAllSels); 287 } 288 289 for (Value::use_iterator 290 I = ExceptionValueIntrinsic->use_begin(), 291 E = ExceptionValueIntrinsic->use_end(); I != E; ++I) { 292 IntrinsicInst *EHPtr = dyn_cast<IntrinsicInst>(*I); 293 if (!EHPtr || EHPtr->getParent()->getParent() != F) continue; 294 295 bool URoRInvoke = false; 296 SmallPtrSet<IntrinsicInst*, 8> SelCalls; 297 Changed |= FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls); 298 299 if (URoRInvoke) { 300 // This EH pointer is being used by an invoke of an URoR instruction and 301 // an eh.selector intrinsic call. If the eh.selector is a 'clean-up', we 302 // need to convert it to a 'catch-all'. 303 for (SmallPtrSet<IntrinsicInst*, 8>::iterator 304 SI = SelCalls.begin(), SE = SelCalls.end(); SI != SE; ++SI) 305 if (!HasCatchAllInSelector(*SI)) 306 SelsToConvert.insert(*SI); 307 } 308 } 309 } 310 311 if (!SelsToConvert.empty()) { 312 // Convert all clean-up eh.selectors, which are associated with "invokes" of 313 // URoR calls, into catch-all eh.selectors. 314 Changed = true; 315 316 for (SmallPtrSet<IntrinsicInst*, 8>::iterator 317 SI = SelsToConvert.begin(), SE = SelsToConvert.end(); 318 SI != SE; ++SI) { 319 IntrinsicInst *II = *SI; 320 321 // Use the exception object pointer and the personality function 322 // from the original selector. 323 CallSite CS(II); 324 IntrinsicInst::op_iterator I = CS.arg_begin(); 325 IntrinsicInst::op_iterator E = CS.arg_end(); 326 IntrinsicInst::op_iterator B = prior(E); 327 328 // Exclude last argument if it is an integer. 329 if (isa<ConstantInt>(B)) E = B; 330 331 // Add exception object pointer (front). 332 // Add personality function (next). 333 // Add in any filter IDs (rest). 334 SmallVector<Value*, 8> Args(I, E); 335 336 Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indicator. 337 338 CallInst *NewSelector = 339 CallInst::Create(SelectorIntrinsic, Args.begin(), Args.end(), 340 "eh.sel.catch.all", II); 341 342 NewSelector->setTailCall(II->isTailCall()); 343 NewSelector->setAttributes(II->getAttributes()); 344 NewSelector->setCallingConv(II->getCallingConv()); 345 346 II->replaceAllUsesWith(NewSelector); 347 II->eraseFromParent(); 348 } 349 } 350 351 Changed |= CleanupSelectors(CatchAllSels); 352 return Changed; 353 } 354 355 /// NormalizeLandingPads - Normalize and discover landing pads, noting them 356 /// in the LandingPads set. A landing pad is normal if the only CFG edges 357 /// that end at it are unwind edges from invoke instructions. If we inlined 358 /// through an invoke we could have a normal branch from the previous 359 /// unwind block through to the landing pad for the original invoke. 360 /// Abnormal landing pads are fixed up by redirecting all unwind edges to 361 /// a new basic block which falls through to the original. 362 bool DwarfEHPrepare::NormalizeLandingPads() { 363 bool Changed = false; 364 365 const MCAsmInfo *MAI = TM->getMCAsmInfo(); 366 bool usingSjLjEH = MAI->getExceptionHandlingType() == ExceptionHandling::SjLj; 367 368 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { 369 TerminatorInst *TI = I->getTerminator(); 370 if (!isa<InvokeInst>(TI)) 371 continue; 372 BasicBlock *LPad = TI->getSuccessor(1); 373 // Skip landing pads that have already been normalized. 374 if (LandingPads.count(LPad)) 375 continue; 376 377 // Check that only invoke unwind edges end at the landing pad. 378 bool OnlyUnwoundTo = true; 379 bool SwitchOK = usingSjLjEH; 380 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); 381 PI != PE; ++PI) { 382 TerminatorInst *PT = (*PI)->getTerminator(); 383 // The SjLj dispatch block uses a switch instruction. This is effectively 384 // an unwind edge, so we can disregard it here. There will only ever 385 // be one dispatch, however, so if there are multiple switches, one 386 // of them truly is a normal edge, not an unwind edge. 387 if (SwitchOK && isa<SwitchInst>(PT)) { 388 SwitchOK = false; 389 continue; 390 } 391 if (!isa<InvokeInst>(PT) || LPad == PT->getSuccessor(0)) { 392 OnlyUnwoundTo = false; 393 break; 394 } 395 } 396 397 if (OnlyUnwoundTo) { 398 // Only unwind edges lead to the landing pad. Remember the landing pad. 399 LandingPads.insert(LPad); 400 continue; 401 } 402 403 // At least one normal edge ends at the landing pad. Redirect the unwind 404 // edges to a new basic block which falls through into this one. 405 406 // Create the new basic block. 407 BasicBlock *NewBB = BasicBlock::Create(F->getContext(), 408 LPad->getName() + "_unwind_edge"); 409 410 // Insert it into the function right before the original landing pad. 411 LPad->getParent()->getBasicBlockList().insert(LPad, NewBB); 412 413 // Redirect unwind edges from the original landing pad to NewBB. 414 for (pred_iterator PI = pred_begin(LPad), PE = pred_end(LPad); PI != PE; ) { 415 TerminatorInst *PT = (*PI++)->getTerminator(); 416 if (isa<InvokeInst>(PT) && PT->getSuccessor(1) == LPad) 417 // Unwind to the new block. 418 PT->setSuccessor(1, NewBB); 419 } 420 421 // If there are any PHI nodes in LPad, we need to update them so that they 422 // merge incoming values from NewBB instead. 423 for (BasicBlock::iterator II = LPad->begin(); isa<PHINode>(II); ++II) { 424 PHINode *PN = cast<PHINode>(II); 425 pred_iterator PB = pred_begin(NewBB), PE = pred_end(NewBB); 426 427 // Check to see if all of the values coming in via unwind edges are the 428 // same. If so, we don't need to create a new PHI node. 429 Value *InVal = PN->getIncomingValueForBlock(*PB); 430 for (pred_iterator PI = PB; PI != PE; ++PI) { 431 if (PI != PB && InVal != PN->getIncomingValueForBlock(*PI)) { 432 InVal = 0; 433 break; 434 } 435 } 436 437 if (InVal == 0) { 438 // Different unwind edges have different values. Create a new PHI node 439 // in NewBB. 440 PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".unwind", 441 NewBB); 442 // Add an entry for each unwind edge, using the value from the old PHI. 443 for (pred_iterator PI = PB; PI != PE; ++PI) 444 NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI); 445 446 // Now use this new PHI as the common incoming value for NewBB in PN. 447 InVal = NewPN; 448 } 449 450 // Revector exactly one entry in the PHI node to come from NewBB 451 // and delete all other entries that come from unwind edges. If 452 // there are both normal and unwind edges from the same predecessor, 453 // this leaves an entry for the normal edge. 454 for (pred_iterator PI = PB; PI != PE; ++PI) 455 PN->removeIncomingValue(*PI); 456 PN->addIncoming(InVal, NewBB); 457 } 458 459 // Add a fallthrough from NewBB to the original landing pad. 460 BranchInst::Create(LPad, NewBB); 461 462 // Now update DominatorTree analysis information. 463 DT->splitBlock(NewBB); 464 465 // Remember the newly constructed landing pad. The original landing pad 466 // LPad is no longer a landing pad now that all unwind edges have been 467 // revectored to NewBB. 468 LandingPads.insert(NewBB); 469 ++NumLandingPadsSplit; 470 Changed = true; 471 } 472 473 return Changed; 474 } 475 476 /// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume, 477 /// rethrowing any previously caught exception. This will crash horribly 478 /// at runtime if there is no such exception: using unwind to throw a new 479 /// exception is currently not supported. 480 bool DwarfEHPrepare::LowerUnwinds() { 481 SmallVector<TerminatorInst*, 16> UnwindInsts; 482 483 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) { 484 TerminatorInst *TI = I->getTerminator(); 485 if (isa<UnwindInst>(TI)) 486 UnwindInsts.push_back(TI); 487 } 488 489 if (UnwindInsts.empty()) return false; 490 491 // Find the rewind function if we didn't already. 492 if (!RewindFunction) { 493 LLVMContext &Ctx = UnwindInsts[0]->getContext(); 494 std::vector<const Type*> 495 Params(1, Type::getInt8PtrTy(Ctx)); 496 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), 497 Params, false); 498 const char *RewindName = TLI->getLibcallName(RTLIB::UNWIND_RESUME); 499 RewindFunction = F->getParent()->getOrInsertFunction(RewindName, FTy); 500 } 501 502 bool Changed = false; 503 504 for (SmallVectorImpl<TerminatorInst*>::iterator 505 I = UnwindInsts.begin(), E = UnwindInsts.end(); I != E; ++I) { 506 TerminatorInst *TI = *I; 507 508 // Replace the unwind instruction with a call to _Unwind_Resume (or the 509 // appropriate target equivalent) followed by an UnreachableInst. 510 511 // Create the call... 512 CallInst *CI = CallInst::Create(RewindFunction, 513 CreateExceptionValueCall(TI->getParent()), 514 "", TI); 515 CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME)); 516 // ...followed by an UnreachableInst. 517 new UnreachableInst(TI->getContext(), TI); 518 519 // Nuke the unwind instruction. 520 TI->eraseFromParent(); 521 ++NumUnwindsLowered; 522 Changed = true; 523 } 524 525 return Changed; 526 } 527 528 /// MoveExceptionValueCalls - Ensure that eh.exception is only ever called from 529 /// landing pads by replacing calls outside of landing pads with direct use of 530 /// a register holding the appropriate value; this requires adding calls inside 531 /// all landing pads to initialize the register. Also, move eh.exception calls 532 /// inside landing pads to the start of the landing pad (optional, but may make 533 /// things simpler for later passes). 534 bool DwarfEHPrepare::MoveExceptionValueCalls() { 535 // If the eh.exception intrinsic is not declared in the module then there is 536 // nothing to do. Speed up compilation by checking for this common case. 537 if (!ExceptionValueIntrinsic && 538 !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_exception))) 539 return false; 540 541 bool Changed = false; 542 543 // Move calls to eh.exception that are inside a landing pad to the start of 544 // the landing pad. 545 for (BBSet::const_iterator LI = LandingPads.begin(), LE = LandingPads.end(); 546 LI != LE; ++LI) { 547 BasicBlock *LP = *LI; 548 for (BasicBlock::iterator II = LP->getFirstNonPHIOrDbg(), IE = LP->end(); 549 II != IE;) 550 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) { 551 // Found a call to eh.exception. 552 if (!EI->use_empty()) { 553 // If there is already a call to eh.exception at the start of the 554 // landing pad, then get hold of it; otherwise create such a call. 555 Value *CallAtStart = CreateExceptionValueCall(LP); 556 557 // If the call was at the start of a landing pad then leave it alone. 558 if (EI == CallAtStart) 559 continue; 560 EI->replaceAllUsesWith(CallAtStart); 561 } 562 EI->eraseFromParent(); 563 ++NumExceptionValuesMoved; 564 Changed = true; 565 } 566 } 567 568 // Look for calls to eh.exception that are not in a landing pad. If one is 569 // found, then a register that holds the exception value will be created in 570 // each landing pad, and the SSAUpdater will be used to compute the values 571 // returned by eh.exception calls outside of landing pads. 572 SSAUpdater SSA; 573 574 // Remember where we found the eh.exception call, to avoid rescanning earlier 575 // basic blocks which we already know contain no eh.exception calls. 576 bool FoundCallOutsideLandingPad = false; 577 Function::iterator BB = F->begin(); 578 for (Function::iterator BE = F->end(); BB != BE; ++BB) { 579 // Skip over landing pads. 580 if (LandingPads.count(BB)) 581 continue; 582 583 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 584 II != IE; ++II) 585 if (isa<EHExceptionInst>(II)) { 586 SSA.Initialize(II->getType(), II->getName()); 587 FoundCallOutsideLandingPad = true; 588 break; 589 } 590 591 if (FoundCallOutsideLandingPad) 592 break; 593 } 594 595 // If all calls to eh.exception are in landing pads then we are done. 596 if (!FoundCallOutsideLandingPad) 597 return Changed; 598 599 // Add a call to eh.exception at the start of each landing pad, and tell the 600 // SSAUpdater that this is the value produced by the landing pad. 601 for (BBSet::iterator LI = LandingPads.begin(), LE = LandingPads.end(); 602 LI != LE; ++LI) 603 SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI)); 604 605 // Now turn all calls to eh.exception that are not in a landing pad into a use 606 // of the appropriate register. 607 for (Function::iterator BE = F->end(); BB != BE; ++BB) { 608 // Skip over landing pads. 609 if (LandingPads.count(BB)) 610 continue; 611 612 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 613 II != IE;) 614 if (EHExceptionInst *EI = dyn_cast<EHExceptionInst>(II++)) { 615 // Found a call to eh.exception, replace it with the value from any 616 // upstream landing pad(s). 617 EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB)); 618 EI->eraseFromParent(); 619 ++NumExceptionValuesMoved; 620 } 621 } 622 623 return true; 624 } 625 626 /// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic at 627 /// the start of the basic block (unless there already is one, in which case 628 /// the existing call is returned). 629 Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) { 630 Instruction *Start = BB->getFirstNonPHIOrDbg(); 631 // Is this a call to eh.exception? 632 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(Start)) 633 if (CI->getIntrinsicID() == Intrinsic::eh_exception) 634 // Reuse the existing call. 635 return Start; 636 637 // Find the eh.exception intrinsic if we didn't already. 638 if (!ExceptionValueIntrinsic) 639 ExceptionValueIntrinsic = Intrinsic::getDeclaration(F->getParent(), 640 Intrinsic::eh_exception); 641 642 // Create the call. 643 return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start); 644 } 645 646 bool DwarfEHPrepare::runOnFunction(Function &Fn) { 647 bool Changed = false; 648 649 // Initialize internal state. 650 DT = &getAnalysis<DominatorTree>(); 651 F = &Fn; 652 653 // Ensure that only unwind edges end at landing pads (a landing pad is a 654 // basic block where an invoke unwind edge ends). 655 Changed |= NormalizeLandingPads(); 656 657 // Turn unwind instructions into libcalls. 658 Changed |= LowerUnwinds(); 659 660 // TODO: Move eh.selector calls to landing pads and combine them. 661 662 // Move eh.exception calls to landing pads. 663 Changed |= MoveExceptionValueCalls(); 664 665 Changed |= HandleURoRInvokes(); 666 667 LandingPads.clear(); 668 669 return Changed; 670 } 671