1 //===-- WinEHPrepare - 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 lowers LLVM IR exception handling into something closer to what the 11 // backend wants for functions using a personality function from a runtime 12 // provided by MSVC. Functions with other personality functions are left alone 13 // and may be prepared by other passes. In particular, all supported MSVC 14 // personality functions require cleanup code to be outlined, and the C++ 15 // personality requires catch handler code to be outlined. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/ADT/MapVector.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/SetVector.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/TinyPtrVector.h" 26 #include "llvm/Analysis/CFG.h" 27 #include "llvm/Analysis/LibCallSemantics.h" 28 #include "llvm/Analysis/TargetLibraryInfo.h" 29 #include "llvm/CodeGen/WinEHFuncInfo.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/IR/PatternMatch.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 #include "llvm/Transforms/Utils/Cloning.h" 42 #include "llvm/Transforms/Utils/Local.h" 43 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 44 #include "llvm/Transforms/Utils/SSAUpdater.h" 45 #include <memory> 46 47 using namespace llvm; 48 using namespace llvm::PatternMatch; 49 50 #define DEBUG_TYPE "winehprepare" 51 52 static cl::opt<bool> DisableDemotion( 53 "disable-demotion", cl::Hidden, 54 cl::desc( 55 "Clone multicolor basic blocks but do not demote cross funclet values"), 56 cl::init(false)); 57 58 static cl::opt<bool> DisableCleanups( 59 "disable-cleanups", cl::Hidden, 60 cl::desc("Do not remove implausible terminators or other similar cleanups"), 61 cl::init(false)); 62 63 namespace { 64 65 // This map is used to model frame variable usage during outlining, to 66 // construct a structure type to hold the frame variables in a frame 67 // allocation block, and to remap the frame variable allocas (including 68 // spill locations as needed) to GEPs that get the variable from the 69 // frame allocation structure. 70 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap; 71 72 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't 73 // quite null. 74 AllocaInst *getCatchObjectSentinel() { 75 return static_cast<AllocaInst *>(nullptr) + 1; 76 } 77 78 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet; 79 80 class LandingPadActions; 81 class LandingPadMap; 82 83 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy; 84 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy; 85 86 class WinEHPrepare : public FunctionPass { 87 public: 88 static char ID; // Pass identification, replacement for typeid. 89 WinEHPrepare(const TargetMachine *TM = nullptr) 90 : FunctionPass(ID) { 91 if (TM) 92 TheTriple = TM->getTargetTriple(); 93 } 94 95 bool runOnFunction(Function &Fn) override; 96 97 bool doFinalization(Module &M) override; 98 99 void getAnalysisUsage(AnalysisUsage &AU) const override; 100 101 const char *getPassName() const override { 102 return "Windows exception handling preparation"; 103 } 104 105 private: 106 bool prepareExceptionHandlers(Function &F, 107 SmallVectorImpl<LandingPadInst *> &LPads); 108 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads); 109 void promoteLandingPadValues(LandingPadInst *LPad); 110 void demoteValuesLiveAcrossHandlers(Function &F, 111 SmallVectorImpl<LandingPadInst *> &LPads); 112 void findSEHEHReturnPoints(Function &F, 113 SetVector<BasicBlock *> &EHReturnBlocks); 114 void findCXXEHReturnPoints(Function &F, 115 SetVector<BasicBlock *> &EHReturnBlocks); 116 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF, 117 SetVector<BasicBlock*> &Targets); 118 void completeNestedLandingPad(Function *ParentFn, 119 LandingPadInst *OutlinedLPad, 120 const LandingPadInst *OriginalLPad, 121 FrameVarInfoMap &VarInfo); 122 Function *createHandlerFunc(Function *ParentFn, Type *RetTy, 123 const Twine &Name, Module *M, Value *&ParentFP); 124 bool outlineHandler(ActionHandler *Action, Function *SrcFn, 125 LandingPadInst *LPad, BasicBlock *StartBB, 126 FrameVarInfoMap &VarInfo); 127 void addStubInvokeToHandlerIfNeeded(Function *Handler); 128 129 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions); 130 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB, 131 VisitedBlockSet &VisitedBlocks); 132 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB, 133 BasicBlock *EndBB); 134 135 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB); 136 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot); 137 void 138 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot, 139 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist); 140 AllocaInst *insertPHILoads(PHINode *PN, Function &F); 141 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot, 142 DenseMap<BasicBlock *, Value *> &Loads, Function &F); 143 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB, 144 Function &F); 145 bool prepareExplicitEH(Function &F, 146 SmallVectorImpl<BasicBlock *> &EntryBlocks); 147 void replaceTerminatePadWithCleanup(Function &F); 148 void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks); 149 void demotePHIsOnFunclets(Function &F); 150 void demoteUsesBetweenFunclets(Function &F); 151 void demoteArgumentUses(Function &F); 152 void cloneCommonBlocks(Function &F, 153 SmallVectorImpl<BasicBlock *> &EntryBlocks); 154 void removeImplausibleTerminators(Function &F); 155 void cleanupPreparedFunclets(Function &F); 156 void verifyPreparedFunclets(Function &F); 157 158 Triple TheTriple; 159 160 // All fields are reset by runOnFunction. 161 DominatorTree *DT = nullptr; 162 const TargetLibraryInfo *LibInfo = nullptr; 163 EHPersonality Personality = EHPersonality::Unknown; 164 CatchHandlerMapTy CatchHandlerMap; 165 CleanupHandlerMapTy CleanupHandlerMap; 166 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps; 167 SmallPtrSet<BasicBlock *, 4> NormalBlocks; 168 SmallPtrSet<BasicBlock *, 4> EHBlocks; 169 SetVector<BasicBlock *> EHReturnBlocks; 170 171 // This maps landing pad instructions found in outlined handlers to 172 // the landing pad instruction in the parent function from which they 173 // were cloned. The cloned/nested landing pad is used as the key 174 // because the landing pad may be cloned into multiple handlers. 175 // This map will be used to add the llvm.eh.actions call to the nested 176 // landing pads after all handlers have been outlined. 177 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP; 178 179 // This maps blocks in the parent function which are destinations of 180 // catch handlers to cloned blocks in (other) outlined handlers. This 181 // handles the case where a nested landing pads has a catch handler that 182 // returns to a handler function rather than the parent function. 183 // The original block is used as the key here because there should only 184 // ever be one handler function from which the cloned block is not pruned. 185 // The original block will be pruned from the parent function after all 186 // handlers have been outlined. This map will be used to adjust the 187 // return instructions of handlers which return to the block that was 188 // outlined into a handler. This is done after all handlers have been 189 // outlined but before the outlined code is pruned from the parent function. 190 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks; 191 192 // Map from outlined handler to call to parent local address. Only used for 193 // 32-bit EH. 194 DenseMap<Function *, Value *> HandlerToParentFP; 195 196 AllocaInst *SEHExceptionCodeSlot = nullptr; 197 198 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors; 199 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks; 200 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren; 201 }; 202 203 class WinEHFrameVariableMaterializer : public ValueMaterializer { 204 public: 205 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP, 206 FrameVarInfoMap &FrameVarInfo); 207 ~WinEHFrameVariableMaterializer() override {} 208 209 Value *materializeValueFor(Value *V) override; 210 211 void escapeCatchObject(Value *V); 212 213 private: 214 FrameVarInfoMap &FrameVarInfo; 215 IRBuilder<> Builder; 216 }; 217 218 class LandingPadMap { 219 public: 220 LandingPadMap() : OriginLPad(nullptr) {} 221 void mapLandingPad(const LandingPadInst *LPad); 222 223 bool isInitialized() { return OriginLPad != nullptr; } 224 225 bool isOriginLandingPadBlock(const BasicBlock *BB) const; 226 bool isLandingPadSpecificInst(const Instruction *Inst) const; 227 228 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, 229 Value *SelectorValue) const; 230 231 private: 232 const LandingPadInst *OriginLPad; 233 // We will normally only see one of each of these instructions, but 234 // if more than one occurs for some reason we can handle that. 235 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs; 236 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors; 237 }; 238 239 class WinEHCloningDirectorBase : public CloningDirector { 240 public: 241 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP, 242 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) 243 : Materializer(HandlerFn, ParentFP, VarInfo), 244 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())), 245 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())), 246 LPadMap(LPadMap), ParentFP(ParentFP) {} 247 248 CloningAction handleInstruction(ValueToValueMapTy &VMap, 249 const Instruction *Inst, 250 BasicBlock *NewBB) override; 251 252 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap, 253 const Instruction *Inst, 254 BasicBlock *NewBB) = 0; 255 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap, 256 const Instruction *Inst, 257 BasicBlock *NewBB) = 0; 258 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, 259 const Instruction *Inst, 260 BasicBlock *NewBB) = 0; 261 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap, 262 const IndirectBrInst *IBr, 263 BasicBlock *NewBB) = 0; 264 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap, 265 const InvokeInst *Invoke, 266 BasicBlock *NewBB) = 0; 267 virtual CloningAction handleResume(ValueToValueMapTy &VMap, 268 const ResumeInst *Resume, 269 BasicBlock *NewBB) = 0; 270 virtual CloningAction handleCompare(ValueToValueMapTy &VMap, 271 const CmpInst *Compare, 272 BasicBlock *NewBB) = 0; 273 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap, 274 const LandingPadInst *LPad, 275 BasicBlock *NewBB) = 0; 276 277 ValueMaterializer *getValueMaterializer() override { return &Materializer; } 278 279 protected: 280 WinEHFrameVariableMaterializer Materializer; 281 Type *SelectorIDType; 282 Type *Int8PtrType; 283 LandingPadMap &LPadMap; 284 285 /// The value representing the parent frame pointer. 286 Value *ParentFP; 287 }; 288 289 class WinEHCatchDirector : public WinEHCloningDirectorBase { 290 public: 291 WinEHCatchDirector( 292 Function *CatchFn, Value *ParentFP, Value *Selector, 293 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap, 294 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads, 295 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks) 296 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap), 297 CurrentSelector(Selector->stripPointerCasts()), 298 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads), 299 DT(DT), EHBlocks(EHBlocks) {} 300 301 CloningAction handleBeginCatch(ValueToValueMapTy &VMap, 302 const Instruction *Inst, 303 BasicBlock *NewBB) override; 304 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, 305 BasicBlock *NewBB) override; 306 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, 307 const Instruction *Inst, 308 BasicBlock *NewBB) override; 309 CloningAction handleIndirectBr(ValueToValueMapTy &VMap, 310 const IndirectBrInst *IBr, 311 BasicBlock *NewBB) override; 312 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, 313 BasicBlock *NewBB) override; 314 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, 315 BasicBlock *NewBB) override; 316 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, 317 BasicBlock *NewBB) override; 318 CloningAction handleLandingPad(ValueToValueMapTy &VMap, 319 const LandingPadInst *LPad, 320 BasicBlock *NewBB) override; 321 322 Value *getExceptionVar() { return ExceptionObjectVar; } 323 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; } 324 325 private: 326 Value *CurrentSelector; 327 328 Value *ExceptionObjectVar; 329 TinyPtrVector<BasicBlock *> ReturnTargets; 330 331 // This will be a reference to the field of the same name in the WinEHPrepare 332 // object which instantiates this WinEHCatchDirector object. 333 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP; 334 DominatorTree *DT; 335 SmallPtrSetImpl<BasicBlock *> &EHBlocks; 336 }; 337 338 class WinEHCleanupDirector : public WinEHCloningDirectorBase { 339 public: 340 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP, 341 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) 342 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo, 343 LPadMap) {} 344 345 CloningAction handleBeginCatch(ValueToValueMapTy &VMap, 346 const Instruction *Inst, 347 BasicBlock *NewBB) override; 348 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, 349 BasicBlock *NewBB) override; 350 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, 351 const Instruction *Inst, 352 BasicBlock *NewBB) override; 353 CloningAction handleIndirectBr(ValueToValueMapTy &VMap, 354 const IndirectBrInst *IBr, 355 BasicBlock *NewBB) override; 356 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, 357 BasicBlock *NewBB) override; 358 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, 359 BasicBlock *NewBB) override; 360 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, 361 BasicBlock *NewBB) override; 362 CloningAction handleLandingPad(ValueToValueMapTy &VMap, 363 const LandingPadInst *LPad, 364 BasicBlock *NewBB) override; 365 }; 366 367 class LandingPadActions { 368 public: 369 LandingPadActions() : HasCleanupHandlers(false) {} 370 371 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); } 372 void insertCleanupHandler(CleanupHandler *Action) { 373 Actions.push_back(Action); 374 HasCleanupHandlers = true; 375 } 376 377 bool includesCleanup() const { return HasCleanupHandlers; } 378 379 SmallVectorImpl<ActionHandler *> &actions() { return Actions; } 380 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); } 381 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); } 382 383 private: 384 // Note that this class does not own the ActionHandler objects in this vector. 385 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap 386 // in the WinEHPrepare class. 387 SmallVector<ActionHandler *, 4> Actions; 388 bool HasCleanupHandlers; 389 }; 390 391 } // end anonymous namespace 392 393 char WinEHPrepare::ID = 0; 394 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions", 395 false, false) 396 397 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) { 398 return new WinEHPrepare(TM); 399 } 400 401 bool WinEHPrepare::runOnFunction(Function &Fn) { 402 if (!Fn.hasPersonalityFn()) 403 return false; 404 405 // No need to prepare outlined handlers. 406 if (Fn.hasFnAttribute("wineh-parent")) 407 return false; 408 409 // Classify the personality to see what kind of preparation we need. 410 Personality = classifyEHPersonality(Fn.getPersonalityFn()); 411 412 // Do nothing if this is not an MSVC personality. 413 if (!isMSVCEHPersonality(Personality)) 414 return false; 415 416 SmallVector<LandingPadInst *, 4> LPads; 417 SmallVector<ResumeInst *, 4> Resumes; 418 SmallVector<BasicBlock *, 4> EntryBlocks; 419 bool ForExplicitEH = false; 420 for (BasicBlock &BB : Fn) { 421 Instruction *First = BB.getFirstNonPHI(); 422 if (auto *LP = dyn_cast<LandingPadInst>(First)) { 423 LPads.push_back(LP); 424 } else if (First->isEHPad()) { 425 if (!ForExplicitEH) 426 EntryBlocks.push_back(&Fn.getEntryBlock()); 427 if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First)) 428 EntryBlocks.push_back(&BB); 429 ForExplicitEH = true; 430 } 431 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator())) 432 Resumes.push_back(Resume); 433 } 434 435 if (ForExplicitEH) 436 return prepareExplicitEH(Fn, EntryBlocks); 437 438 // No need to prepare functions that lack landing pads. 439 if (LPads.empty()) 440 return false; 441 442 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 443 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 444 445 // If there were any landing pads, prepareExceptionHandlers will make changes. 446 prepareExceptionHandlers(Fn, LPads); 447 return true; 448 } 449 450 bool WinEHPrepare::doFinalization(Module &M) { return false; } 451 452 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const { 453 AU.addRequired<DominatorTreeWrapperPass>(); 454 AU.addRequired<TargetLibraryInfoWrapperPass>(); 455 } 456 457 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, 458 Constant *&Selector, BasicBlock *&NextBB); 459 460 // Finds blocks reachable from the starting set Worklist. Does not follow unwind 461 // edges or blocks listed in StopPoints. 462 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs, 463 SetVector<BasicBlock *> &Worklist, 464 const SetVector<BasicBlock *> *StopPoints) { 465 while (!Worklist.empty()) { 466 BasicBlock *BB = Worklist.pop_back_val(); 467 468 // Don't cross blocks that we should stop at. 469 if (StopPoints && StopPoints->count(BB)) 470 continue; 471 472 if (!ReachableBBs.insert(BB).second) 473 continue; // Already visited. 474 475 // Don't follow unwind edges of invokes. 476 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { 477 Worklist.insert(II->getNormalDest()); 478 continue; 479 } 480 481 // Otherwise, follow all successors. 482 Worklist.insert(succ_begin(BB), succ_end(BB)); 483 } 484 } 485 486 // Attempt to find an instruction where a block can be split before 487 // a call to llvm.eh.begincatch and its operands. If the block 488 // begins with the begincatch call or one of its adjacent operands 489 // the block will not be split. 490 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB, 491 IntrinsicInst *II) { 492 // If the begincatch call is already the first instruction in the block, 493 // don't split. 494 Instruction *FirstNonPHI = BB->getFirstNonPHI(); 495 if (II == FirstNonPHI) 496 return nullptr; 497 498 // If either operand is in the same basic block as the instruction and 499 // isn't used by another instruction before the begincatch call, include it 500 // in the split block. 501 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0)); 502 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1)); 503 504 Instruction *I = II->getPrevNode(); 505 Instruction *LastI = II; 506 507 while (I == Op0 || I == Op1) { 508 // If the block begins with one of the operands and there are no other 509 // instructions between the operand and the begincatch call, don't split. 510 if (I == FirstNonPHI) 511 return nullptr; 512 513 LastI = I; 514 I = I->getPrevNode(); 515 } 516 517 // If there is at least one instruction in the block before the begincatch 518 // call and its operands, split the block at either the begincatch or 519 // its operand. 520 return LastI; 521 } 522 523 /// Find all points where exceptional control rejoins normal control flow via 524 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist. 525 void WinEHPrepare::findCXXEHReturnPoints( 526 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { 527 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { 528 BasicBlock *BB = BBI; 529 for (Instruction &I : *BB) { 530 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) { 531 Instruction *SplitPt = 532 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I)); 533 if (SplitPt) { 534 // Split the block before the llvm.eh.begincatch call to allow 535 // cleanup and catch code to be distinguished later. 536 // Do not update BBI because we still need to process the 537 // portion of the block that we are splitting off. 538 SplitBlock(BB, SplitPt, DT); 539 break; 540 } 541 } 542 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) { 543 // Split the block after the call to llvm.eh.endcatch if there is 544 // anything other than an unconditional branch, or if the successor 545 // starts with a phi. 546 auto *Br = dyn_cast<BranchInst>(I.getNextNode()); 547 if (!Br || !Br->isUnconditional() || 548 isa<PHINode>(Br->getSuccessor(0)->begin())) { 549 DEBUG(dbgs() << "splitting block " << BB->getName() 550 << " with llvm.eh.endcatch\n"); 551 BBI = SplitBlock(BB, I.getNextNode(), DT); 552 } 553 // The next BB is normal control flow. 554 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0)); 555 break; 556 } 557 } 558 } 559 } 560 561 static bool isCatchAllLandingPad(const BasicBlock *BB) { 562 const LandingPadInst *LP = BB->getLandingPadInst(); 563 if (!LP) 564 return false; 565 unsigned N = LP->getNumClauses(); 566 return (N > 0 && LP->isCatch(N - 1) && 567 isa<ConstantPointerNull>(LP->getClause(N - 1))); 568 } 569 570 /// Find all points where exceptions control rejoins normal control flow via 571 /// selector dispatch. 572 void WinEHPrepare::findSEHEHReturnPoints( 573 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { 574 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { 575 BasicBlock *BB = BBI; 576 // If the landingpad is a catch-all, treat the whole lpad as if it is 577 // reachable from normal control flow. 578 // FIXME: This is imprecise. We need a better way of identifying where a 579 // catch-all starts and cleanups stop. As far as LLVM is concerned, there 580 // is no difference. 581 if (isCatchAllLandingPad(BB)) { 582 EHReturnBlocks.insert(BB); 583 continue; 584 } 585 586 BasicBlock *CatchHandler; 587 BasicBlock *NextBB; 588 Constant *Selector; 589 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) { 590 // Split the edge if there are multiple predecessors. This creates a place 591 // where we can insert EH recovery code. 592 if (!CatchHandler->getSinglePredecessor()) { 593 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName() 594 << " to " << CatchHandler->getName() << '\n'); 595 BBI = CatchHandler = SplitCriticalEdge( 596 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler)); 597 } 598 EHReturnBlocks.insert(CatchHandler); 599 } 600 } 601 } 602 603 void WinEHPrepare::identifyEHBlocks(Function &F, 604 SmallVectorImpl<LandingPadInst *> &LPads) { 605 DEBUG(dbgs() << "Demoting values live across exception handlers in function " 606 << F.getName() << '\n'); 607 608 // Build a set of all non-exceptional blocks and exceptional blocks. 609 // - Non-exceptional blocks are blocks reachable from the entry block while 610 // not following invoke unwind edges. 611 // - Exceptional blocks are blocks reachable from landingpads. Analysis does 612 // not follow llvm.eh.endcatch blocks, which mark a transition from 613 // exceptional to normal control. 614 615 if (Personality == EHPersonality::MSVC_CXX) 616 findCXXEHReturnPoints(F, EHReturnBlocks); 617 else 618 findSEHEHReturnPoints(F, EHReturnBlocks); 619 620 DEBUG({ 621 dbgs() << "identified the following blocks as EH return points:\n"; 622 for (BasicBlock *BB : EHReturnBlocks) 623 dbgs() << " " << BB->getName() << '\n'; 624 }); 625 626 // Join points should not have phis at this point, unless they are a 627 // landingpad, in which case we will demote their phis later. 628 #ifndef NDEBUG 629 for (BasicBlock *BB : EHReturnBlocks) 630 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) && 631 "non-lpad EH return block has phi"); 632 #endif 633 634 // Normal blocks are the blocks reachable from the entry block and all EH 635 // return points. 636 SetVector<BasicBlock *> Worklist; 637 Worklist = EHReturnBlocks; 638 Worklist.insert(&F.getEntryBlock()); 639 findReachableBlocks(NormalBlocks, Worklist, nullptr); 640 DEBUG({ 641 dbgs() << "marked the following blocks as normal:\n"; 642 for (BasicBlock *BB : NormalBlocks) 643 dbgs() << " " << BB->getName() << '\n'; 644 }); 645 646 // Exceptional blocks are the blocks reachable from landingpads that don't 647 // cross EH return points. 648 Worklist.clear(); 649 for (auto *LPI : LPads) 650 Worklist.insert(LPI->getParent()); 651 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks); 652 DEBUG({ 653 dbgs() << "marked the following blocks as exceptional:\n"; 654 for (BasicBlock *BB : EHBlocks) 655 dbgs() << " " << BB->getName() << '\n'; 656 }); 657 658 } 659 660 /// Ensure that all values live into and out of exception handlers are stored 661 /// in memory. 662 /// FIXME: This falls down when values are defined in one handler and live into 663 /// another handler. For example, a cleanup defines a value used only by a 664 /// catch handler. 665 void WinEHPrepare::demoteValuesLiveAcrossHandlers( 666 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { 667 DEBUG(dbgs() << "Demoting values live across exception handlers in function " 668 << F.getName() << '\n'); 669 670 // identifyEHBlocks() should have been called before this function. 671 assert(!NormalBlocks.empty()); 672 673 // Try to avoid demoting EH pointer and selector values. They get in the way 674 // of our pattern matching. 675 SmallPtrSet<Instruction *, 10> EHVals; 676 for (BasicBlock &BB : F) { 677 LandingPadInst *LP = BB.getLandingPadInst(); 678 if (!LP) 679 continue; 680 EHVals.insert(LP); 681 for (User *U : LP->users()) { 682 auto *EI = dyn_cast<ExtractValueInst>(U); 683 if (!EI) 684 continue; 685 EHVals.insert(EI); 686 for (User *U2 : EI->users()) { 687 if (auto *PN = dyn_cast<PHINode>(U2)) 688 EHVals.insert(PN); 689 } 690 } 691 } 692 693 SetVector<Argument *> ArgsToDemote; 694 SetVector<Instruction *> InstrsToDemote; 695 for (BasicBlock &BB : F) { 696 bool IsNormalBB = NormalBlocks.count(&BB); 697 bool IsEHBB = EHBlocks.count(&BB); 698 if (!IsNormalBB && !IsEHBB) 699 continue; // Blocks that are neither normal nor EH are unreachable. 700 for (Instruction &I : BB) { 701 for (Value *Op : I.operands()) { 702 // Don't demote static allocas, constants, and labels. 703 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op)) 704 continue; 705 auto *AI = dyn_cast<AllocaInst>(Op); 706 if (AI && AI->isStaticAlloca()) 707 continue; 708 709 if (auto *Arg = dyn_cast<Argument>(Op)) { 710 if (IsEHBB) { 711 DEBUG(dbgs() << "Demoting argument " << *Arg 712 << " used by EH instr: " << I << "\n"); 713 ArgsToDemote.insert(Arg); 714 } 715 continue; 716 } 717 718 // Don't demote EH values. 719 auto *OpI = cast<Instruction>(Op); 720 if (EHVals.count(OpI)) 721 continue; 722 723 BasicBlock *OpBB = OpI->getParent(); 724 // If a value is produced and consumed in the same BB, we don't need to 725 // demote it. 726 if (OpBB == &BB) 727 continue; 728 bool IsOpNormalBB = NormalBlocks.count(OpBB); 729 bool IsOpEHBB = EHBlocks.count(OpBB); 730 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) { 731 DEBUG({ 732 dbgs() << "Demoting instruction live in-out from EH:\n"; 733 dbgs() << "Instr: " << *OpI << '\n'; 734 dbgs() << "User: " << I << '\n'; 735 }); 736 InstrsToDemote.insert(OpI); 737 } 738 } 739 } 740 } 741 742 // Demote values live into and out of handlers. 743 // FIXME: This demotion is inefficient. We should insert spills at the point 744 // of definition, insert one reload in each handler that uses the value, and 745 // insert reloads in the BB used to rejoin normal control flow. 746 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt(); 747 for (Instruction *I : InstrsToDemote) 748 DemoteRegToStack(*I, false, AllocaInsertPt); 749 750 // Demote arguments separately, and only for uses in EH blocks. 751 for (Argument *Arg : ArgsToDemote) { 752 auto *Slot = new AllocaInst(Arg->getType(), nullptr, 753 Arg->getName() + ".reg2mem", AllocaInsertPt); 754 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end()); 755 for (User *U : Users) { 756 auto *I = dyn_cast<Instruction>(U); 757 if (I && EHBlocks.count(I->getParent())) { 758 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I); 759 U->replaceUsesOfWith(Arg, Reload); 760 } 761 } 762 new StoreInst(Arg, Slot, AllocaInsertPt); 763 } 764 765 // Demote landingpad phis, as the landingpad will be removed from the machine 766 // CFG. 767 for (LandingPadInst *LPI : LPads) { 768 BasicBlock *BB = LPI->getParent(); 769 while (auto *Phi = dyn_cast<PHINode>(BB->begin())) 770 DemotePHIToStack(Phi, AllocaInsertPt); 771 } 772 773 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and " 774 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n"); 775 } 776 777 bool WinEHPrepare::prepareExceptionHandlers( 778 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { 779 // Don't run on functions that are already prepared. 780 for (LandingPadInst *LPad : LPads) { 781 BasicBlock *LPadBB = LPad->getParent(); 782 for (Instruction &Inst : *LPadBB) 783 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) 784 return false; 785 } 786 787 identifyEHBlocks(F, LPads); 788 demoteValuesLiveAcrossHandlers(F, LPads); 789 790 // These containers are used to re-map frame variables that are used in 791 // outlined catch and cleanup handlers. They will be populated as the 792 // handlers are outlined. 793 FrameVarInfoMap FrameVarInfo; 794 795 bool HandlersOutlined = false; 796 797 Module *M = F.getParent(); 798 LLVMContext &Context = M->getContext(); 799 800 // Create a new function to receive the handler contents. 801 PointerType *Int8PtrType = Type::getInt8PtrTy(Context); 802 Type *Int32Type = Type::getInt32Ty(Context); 803 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions); 804 805 if (isAsynchronousEHPersonality(Personality)) { 806 // FIXME: Switch the ehptr type to i32 and then switch this. 807 SEHExceptionCodeSlot = 808 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code", 809 F.getEntryBlock().getFirstInsertionPt()); 810 } 811 812 // In order to handle the case where one outlined catch handler returns 813 // to a block within another outlined catch handler that would otherwise 814 // be unreachable, we need to outline the nested landing pad before we 815 // outline the landing pad which encloses it. 816 if (!isAsynchronousEHPersonality(Personality)) 817 std::sort(LPads.begin(), LPads.end(), 818 [this](LandingPadInst *const &L, LandingPadInst *const &R) { 819 return DT->properlyDominates(R->getParent(), L->getParent()); 820 }); 821 822 // This container stores the llvm.eh.recover and IndirectBr instructions 823 // that make up the body of each landing pad after it has been outlined. 824 // We need to defer the population of the target list for the indirectbr 825 // until all landing pads have been outlined so that we can handle the 826 // case of blocks in the target that are reached only from nested 827 // landing pads. 828 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls; 829 830 for (LandingPadInst *LPad : LPads) { 831 // Look for evidence that this landingpad has already been processed. 832 bool LPadHasActionList = false; 833 BasicBlock *LPadBB = LPad->getParent(); 834 for (Instruction &Inst : *LPadBB) { 835 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) { 836 LPadHasActionList = true; 837 break; 838 } 839 } 840 841 // If we've already outlined the handlers for this landingpad, 842 // there's nothing more to do here. 843 if (LPadHasActionList) 844 continue; 845 846 // If either of the values in the aggregate returned by the landing pad is 847 // extracted and stored to memory, promote the stored value to a register. 848 promoteLandingPadValues(LPad); 849 850 LandingPadActions Actions; 851 mapLandingPadBlocks(LPad, Actions); 852 853 HandlersOutlined |= !Actions.actions().empty(); 854 for (ActionHandler *Action : Actions) { 855 if (Action->hasBeenProcessed()) 856 continue; 857 BasicBlock *StartBB = Action->getStartBlock(); 858 859 // SEH doesn't do any outlining for catches. Instead, pass the handler 860 // basic block addr to llvm.eh.actions and list the block as a return 861 // target. 862 if (isAsynchronousEHPersonality(Personality)) { 863 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { 864 processSEHCatchHandler(CatchAction, StartBB); 865 continue; 866 } 867 } 868 869 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo); 870 } 871 872 // Split the block after the landingpad instruction so that it is just a 873 // call to llvm.eh.actions followed by indirectbr. 874 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed"); 875 SplitBlock(LPadBB, LPad->getNextNode(), DT); 876 // Erase the branch inserted by the split so we can insert indirectbr. 877 LPadBB->getTerminator()->eraseFromParent(); 878 879 // Replace all extracted values with undef and ultimately replace the 880 // landingpad with undef. 881 SmallVector<Instruction *, 4> SEHCodeUses; 882 SmallVector<Instruction *, 4> EHUndefs; 883 for (User *U : LPad->users()) { 884 auto *E = dyn_cast<ExtractValueInst>(U); 885 if (!E) 886 continue; 887 assert(E->getNumIndices() == 1 && 888 "Unexpected operation: extracting both landing pad values"); 889 unsigned Idx = *E->idx_begin(); 890 assert((Idx == 0 || Idx == 1) && "unexpected index"); 891 if (Idx == 0 && isAsynchronousEHPersonality(Personality)) 892 SEHCodeUses.push_back(E); 893 else 894 EHUndefs.push_back(E); 895 } 896 for (Instruction *E : EHUndefs) { 897 E->replaceAllUsesWith(UndefValue::get(E->getType())); 898 E->eraseFromParent(); 899 } 900 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType())); 901 902 // Rewrite uses of the exception pointer to loads of an alloca. 903 while (!SEHCodeUses.empty()) { 904 Instruction *E = SEHCodeUses.pop_back_val(); 905 SmallVector<Use *, 4> Uses; 906 for (Use &U : E->uses()) 907 Uses.push_back(&U); 908 for (Use *U : Uses) { 909 auto *I = cast<Instruction>(U->getUser()); 910 if (isa<ResumeInst>(I)) 911 continue; 912 if (auto *Phi = dyn_cast<PHINode>(I)) 913 SEHCodeUses.push_back(Phi); 914 else 915 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I)); 916 } 917 E->replaceAllUsesWith(UndefValue::get(E->getType())); 918 E->eraseFromParent(); 919 } 920 921 // Add a call to describe the actions for this landing pad. 922 std::vector<Value *> ActionArgs; 923 for (ActionHandler *Action : Actions) { 924 // Action codes from docs are: 0 cleanup, 1 catch. 925 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { 926 ActionArgs.push_back(ConstantInt::get(Int32Type, 1)); 927 ActionArgs.push_back(CatchAction->getSelector()); 928 // Find the frame escape index of the exception object alloca in the 929 // parent. 930 int FrameEscapeIdx = -1; 931 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar()); 932 if (EHObj && !isa<ConstantPointerNull>(EHObj)) { 933 auto I = FrameVarInfo.find(EHObj); 934 assert(I != FrameVarInfo.end() && 935 "failed to map llvm.eh.begincatch var"); 936 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I); 937 } 938 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx)); 939 } else { 940 ActionArgs.push_back(ConstantInt::get(Int32Type, 0)); 941 } 942 ActionArgs.push_back(Action->getHandlerBlockOrFunc()); 943 } 944 CallInst *Recover = 945 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB); 946 947 SetVector<BasicBlock *> ReturnTargets; 948 for (ActionHandler *Action : Actions) { 949 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { 950 const auto &CatchTargets = CatchAction->getReturnTargets(); 951 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end()); 952 } 953 } 954 IndirectBrInst *Branch = 955 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB); 956 for (BasicBlock *Target : ReturnTargets) 957 Branch->addDestination(Target); 958 959 if (!isAsynchronousEHPersonality(Personality)) { 960 // C++ EH must repopulate the targets later to handle the case of 961 // targets that are reached indirectly through nested landing pads. 962 LPadImpls.push_back(std::make_pair(Recover, Branch)); 963 } 964 965 } // End for each landingpad 966 967 // If nothing got outlined, there is no more processing to be done. 968 if (!HandlersOutlined) 969 return false; 970 971 // Replace any nested landing pad stubs with the correct action handler. 972 // This must be done before we remove unreachable blocks because it 973 // cleans up references to outlined blocks that will be deleted. 974 for (auto &LPadPair : NestedLPtoOriginalLP) 975 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo); 976 NestedLPtoOriginalLP.clear(); 977 978 // Update the indirectbr instructions' target lists if necessary. 979 SetVector<BasicBlock*> CheckedTargets; 980 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; 981 for (auto &LPadImplPair : LPadImpls) { 982 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first); 983 IndirectBrInst *Branch = LPadImplPair.second; 984 985 // Get a list of handlers called by 986 parseEHActions(Recover, ActionList); 987 988 // Add an indirect branch listing possible successors of the catch handlers. 989 SetVector<BasicBlock *> ReturnTargets; 990 for (const auto &Action : ActionList) { 991 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) { 992 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc()); 993 getPossibleReturnTargets(&F, Handler, ReturnTargets); 994 } 995 } 996 ActionList.clear(); 997 // Clear any targets we already knew about. 998 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) { 999 BasicBlock *KnownTarget = Branch->getDestination(I); 1000 if (ReturnTargets.count(KnownTarget)) 1001 ReturnTargets.remove(KnownTarget); 1002 } 1003 for (BasicBlock *Target : ReturnTargets) { 1004 Branch->addDestination(Target); 1005 // The target may be a block that we excepted to get pruned. 1006 // If it is, it may contain a call to llvm.eh.endcatch. 1007 if (CheckedTargets.insert(Target)) { 1008 // Earlier preparations guarantee that all calls to llvm.eh.endcatch 1009 // will be followed by an unconditional branch. 1010 auto *Br = dyn_cast<BranchInst>(Target->getTerminator()); 1011 if (Br && Br->isUnconditional() && 1012 Br != Target->getFirstNonPHIOrDbgOrLifetime()) { 1013 Instruction *Prev = Br->getPrevNode(); 1014 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>())) 1015 Prev->eraseFromParent(); 1016 } 1017 } 1018 } 1019 } 1020 LPadImpls.clear(); 1021 1022 F.addFnAttr("wineh-parent", F.getName()); 1023 1024 // Delete any blocks that were only used by handlers that were outlined above. 1025 removeUnreachableBlocks(F); 1026 1027 BasicBlock *Entry = &F.getEntryBlock(); 1028 IRBuilder<> Builder(F.getParent()->getContext()); 1029 Builder.SetInsertPoint(Entry->getFirstInsertionPt()); 1030 1031 Function *FrameEscapeFn = 1032 Intrinsic::getDeclaration(M, Intrinsic::localescape); 1033 Function *RecoverFrameFn = 1034 Intrinsic::getDeclaration(M, Intrinsic::localrecover); 1035 SmallVector<Value *, 8> AllocasToEscape; 1036 1037 // Scan the entry block for an existing call to llvm.localescape. We need to 1038 // keep escaping those objects. 1039 for (Instruction &I : F.front()) { 1040 auto *II = dyn_cast<IntrinsicInst>(&I); 1041 if (II && II->getIntrinsicID() == Intrinsic::localescape) { 1042 auto Args = II->arg_operands(); 1043 AllocasToEscape.append(Args.begin(), Args.end()); 1044 II->eraseFromParent(); 1045 break; 1046 } 1047 } 1048 1049 // Finally, replace all of the temporary allocas for frame variables used in 1050 // the outlined handlers with calls to llvm.localrecover. 1051 for (auto &VarInfoEntry : FrameVarInfo) { 1052 Value *ParentVal = VarInfoEntry.first; 1053 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second; 1054 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal); 1055 1056 // FIXME: We should try to sink unescaped allocas from the parent frame into 1057 // the child frame. If the alloca is escaped, we have to use the lifetime 1058 // markers to ensure that the alloca is only live within the child frame. 1059 1060 // Add this alloca to the list of things to escape. 1061 AllocasToEscape.push_back(ParentAlloca); 1062 1063 // Next replace all outlined allocas that are mapped to it. 1064 for (AllocaInst *TempAlloca : Allocas) { 1065 if (TempAlloca == getCatchObjectSentinel()) 1066 continue; // Skip catch parameter sentinels. 1067 Function *HandlerFn = TempAlloca->getParent()->getParent(); 1068 llvm::Value *FP = HandlerToParentFP[HandlerFn]; 1069 assert(FP); 1070 1071 // FIXME: Sink this localrecover into the blocks where it is used. 1072 Builder.SetInsertPoint(TempAlloca); 1073 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc()); 1074 Value *RecoverArgs[] = { 1075 Builder.CreateBitCast(&F, Int8PtrType, ""), FP, 1076 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)}; 1077 Instruction *RecoveredAlloca = 1078 Builder.CreateCall(RecoverFrameFn, RecoverArgs); 1079 1080 // Add a pointer bitcast if the alloca wasn't an i8. 1081 if (RecoveredAlloca->getType() != TempAlloca->getType()) { 1082 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8"); 1083 RecoveredAlloca = cast<Instruction>( 1084 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType())); 1085 } 1086 TempAlloca->replaceAllUsesWith(RecoveredAlloca); 1087 TempAlloca->removeFromParent(); 1088 RecoveredAlloca->takeName(TempAlloca); 1089 delete TempAlloca; 1090 } 1091 } // End for each FrameVarInfo entry. 1092 1093 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry 1094 // block. 1095 Builder.SetInsertPoint(&F.getEntryBlock().back()); 1096 Builder.CreateCall(FrameEscapeFn, AllocasToEscape); 1097 1098 if (SEHExceptionCodeSlot) { 1099 if (isAllocaPromotable(SEHExceptionCodeSlot)) { 1100 SmallPtrSet<BasicBlock *, 4> UserBlocks; 1101 for (User *U : SEHExceptionCodeSlot->users()) { 1102 if (auto *Inst = dyn_cast<Instruction>(U)) 1103 UserBlocks.insert(Inst->getParent()); 1104 } 1105 PromoteMemToReg(SEHExceptionCodeSlot, *DT); 1106 // After the promotion, kill off dead instructions. 1107 for (BasicBlock *BB : UserBlocks) 1108 SimplifyInstructionsInBlock(BB, LibInfo); 1109 } 1110 } 1111 1112 // Clean up the handler action maps we created for this function 1113 DeleteContainerSeconds(CatchHandlerMap); 1114 CatchHandlerMap.clear(); 1115 DeleteContainerSeconds(CleanupHandlerMap); 1116 CleanupHandlerMap.clear(); 1117 HandlerToParentFP.clear(); 1118 DT = nullptr; 1119 LibInfo = nullptr; 1120 SEHExceptionCodeSlot = nullptr; 1121 EHBlocks.clear(); 1122 NormalBlocks.clear(); 1123 EHReturnBlocks.clear(); 1124 1125 return HandlersOutlined; 1126 } 1127 1128 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) { 1129 // If the return values of the landing pad instruction are extracted and 1130 // stored to memory, we want to promote the store locations to reg values. 1131 SmallVector<AllocaInst *, 2> EHAllocas; 1132 1133 // The landingpad instruction returns an aggregate value. Typically, its 1134 // value will be passed to a pair of extract value instructions and the 1135 // results of those extracts are often passed to store instructions. 1136 // In unoptimized code the stored value will often be loaded and then stored 1137 // again. 1138 for (auto *U : LPad->users()) { 1139 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); 1140 if (!Extract) 1141 continue; 1142 1143 for (auto *EU : Extract->users()) { 1144 if (auto *Store = dyn_cast<StoreInst>(EU)) { 1145 auto *AV = cast<AllocaInst>(Store->getPointerOperand()); 1146 EHAllocas.push_back(AV); 1147 } 1148 } 1149 } 1150 1151 // We can't do this without a dominator tree. 1152 assert(DT); 1153 1154 if (!EHAllocas.empty()) { 1155 PromoteMemToReg(EHAllocas, *DT); 1156 EHAllocas.clear(); 1157 } 1158 1159 // After promotion, some extracts may be trivially dead. Remove them. 1160 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end()); 1161 for (auto *U : Users) 1162 RecursivelyDeleteTriviallyDeadInstructions(U); 1163 } 1164 1165 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF, 1166 Function *HandlerF, 1167 SetVector<BasicBlock*> &Targets) { 1168 for (BasicBlock &BB : *HandlerF) { 1169 // If the handler contains landing pads, check for any 1170 // handlers that may return directly to a block in the 1171 // parent function. 1172 if (auto *LPI = BB.getLandingPadInst()) { 1173 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode()); 1174 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; 1175 parseEHActions(Recover, ActionList); 1176 for (const auto &Action : ActionList) { 1177 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) { 1178 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc()); 1179 getPossibleReturnTargets(ParentF, NestedF, Targets); 1180 } 1181 } 1182 } 1183 1184 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); 1185 if (!Ret) 1186 continue; 1187 1188 // Handler functions must always return a block address. 1189 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); 1190 1191 // If this is the handler for a nested landing pad, the 1192 // return address may have been remapped to a block in the 1193 // parent handler. We're not interested in those. 1194 if (BA->getFunction() != ParentF) 1195 continue; 1196 1197 Targets.insert(BA->getBasicBlock()); 1198 } 1199 } 1200 1201 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn, 1202 LandingPadInst *OutlinedLPad, 1203 const LandingPadInst *OriginalLPad, 1204 FrameVarInfoMap &FrameVarInfo) { 1205 // Get the nested block and erase the unreachable instruction that was 1206 // temporarily inserted as its terminator. 1207 LLVMContext &Context = ParentFn->getContext(); 1208 BasicBlock *OutlinedBB = OutlinedLPad->getParent(); 1209 // If the nested landing pad was outlined before the landing pad that enclosed 1210 // it, it will already be in outlined form. In that case, we just need to see 1211 // if the returns and the enclosing branch instruction need to be updated. 1212 IndirectBrInst *Branch = 1213 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator()); 1214 if (!Branch) { 1215 // If the landing pad wasn't in outlined form, it should be a stub with 1216 // an unreachable terminator. 1217 assert(isa<UnreachableInst>(OutlinedBB->getTerminator())); 1218 OutlinedBB->getTerminator()->eraseFromParent(); 1219 // That should leave OutlinedLPad as the last instruction in its block. 1220 assert(&OutlinedBB->back() == OutlinedLPad); 1221 } 1222 1223 // The original landing pad will have already had its action intrinsic 1224 // built by the outlining loop. We need to clone that into the outlined 1225 // location. It may also be necessary to add references to the exception 1226 // variables to the outlined handler in which this landing pad is nested 1227 // and remap return instructions in the nested handlers that should return 1228 // to an address in the outlined handler. 1229 Function *OutlinedHandlerFn = OutlinedBB->getParent(); 1230 BasicBlock::const_iterator II = OriginalLPad; 1231 ++II; 1232 // The instruction after the landing pad should now be a call to eh.actions. 1233 const Instruction *Recover = II; 1234 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover); 1235 1236 // Remap the return target in the nested handler. 1237 SmallVector<BlockAddress *, 4> ActionTargets; 1238 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; 1239 parseEHActions(EHActions, ActionList); 1240 for (const auto &Action : ActionList) { 1241 auto *Catch = dyn_cast<CatchHandler>(Action.get()); 1242 if (!Catch) 1243 continue; 1244 // The dyn_cast to function here selects C++ catch handlers and skips 1245 // SEH catch handlers. 1246 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc()); 1247 if (!Handler) 1248 continue; 1249 // Visit all the return instructions, looking for places that return 1250 // to a location within OutlinedHandlerFn. 1251 for (BasicBlock &NestedHandlerBB : *Handler) { 1252 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator()); 1253 if (!Ret) 1254 continue; 1255 1256 // Handler functions must always return a block address. 1257 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); 1258 // The original target will have been in the main parent function, 1259 // but if it is the address of a block that has been outlined, it 1260 // should be a block that was outlined into OutlinedHandlerFn. 1261 assert(BA->getFunction() == ParentFn); 1262 1263 // Ignore targets that aren't part of an outlined handler function. 1264 if (!LPadTargetBlocks.count(BA->getBasicBlock())) 1265 continue; 1266 1267 // If the return value is the address ofF a block that we 1268 // previously outlined into the parent handler function, replace 1269 // the return instruction and add the mapped target to the list 1270 // of possible return addresses. 1271 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()]; 1272 assert(MappedBB->getParent() == OutlinedHandlerFn); 1273 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB); 1274 Ret->eraseFromParent(); 1275 ReturnInst::Create(Context, NewBA, &NestedHandlerBB); 1276 ActionTargets.push_back(NewBA); 1277 } 1278 } 1279 ActionList.clear(); 1280 1281 if (Branch) { 1282 // If the landing pad was already in outlined form, just update its targets. 1283 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I) 1284 Branch->removeDestination(I); 1285 // Add the previously collected action targets. 1286 for (auto *Target : ActionTargets) 1287 Branch->addDestination(Target->getBasicBlock()); 1288 } else { 1289 // If the landing pad was previously stubbed out, fill in its outlined form. 1290 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone()); 1291 OutlinedBB->getInstList().push_back(NewEHActions); 1292 1293 // Insert an indirect branch into the outlined landing pad BB. 1294 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB); 1295 // Add the previously collected action targets. 1296 for (auto *Target : ActionTargets) 1297 IBr->addDestination(Target->getBasicBlock()); 1298 } 1299 } 1300 1301 // This function examines a block to determine whether the block ends with a 1302 // conditional branch to a catch handler based on a selector comparison. 1303 // This function is used both by the WinEHPrepare::findSelectorComparison() and 1304 // WinEHCleanupDirector::handleTypeIdFor(). 1305 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, 1306 Constant *&Selector, BasicBlock *&NextBB) { 1307 ICmpInst::Predicate Pred; 1308 BasicBlock *TBB, *FBB; 1309 Value *LHS, *RHS; 1310 1311 if (!match(BB->getTerminator(), 1312 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB))) 1313 return false; 1314 1315 if (!match(LHS, 1316 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) && 1317 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector)))) 1318 return false; 1319 1320 if (Pred == CmpInst::ICMP_EQ) { 1321 CatchHandler = TBB; 1322 NextBB = FBB; 1323 return true; 1324 } 1325 1326 if (Pred == CmpInst::ICMP_NE) { 1327 CatchHandler = FBB; 1328 NextBB = TBB; 1329 return true; 1330 } 1331 1332 return false; 1333 } 1334 1335 static bool isCatchBlock(BasicBlock *BB) { 1336 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 1337 II != IE; ++II) { 1338 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>())) 1339 return true; 1340 } 1341 return false; 1342 } 1343 1344 static BasicBlock *createStubLandingPad(Function *Handler) { 1345 // FIXME: Finish this! 1346 LLVMContext &Context = Handler->getContext(); 1347 BasicBlock *StubBB = BasicBlock::Create(Context, "stub"); 1348 Handler->getBasicBlockList().push_back(StubBB); 1349 IRBuilder<> Builder(StubBB); 1350 LandingPadInst *LPad = Builder.CreateLandingPad( 1351 llvm::StructType::get(Type::getInt8PtrTy(Context), 1352 Type::getInt32Ty(Context), nullptr), 1353 0); 1354 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad. 1355 Function *ActionIntrin = 1356 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions); 1357 Builder.CreateCall(ActionIntrin, {}, "recover"); 1358 LPad->setCleanup(true); 1359 Builder.CreateUnreachable(); 1360 return StubBB; 1361 } 1362 1363 // Cycles through the blocks in an outlined handler function looking for an 1364 // invoke instruction and inserts an invoke of llvm.donothing with an empty 1365 // landing pad if none is found. The code that generates the .xdata tables for 1366 // the handler needs at least one landing pad to identify the parent function's 1367 // personality. 1368 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) { 1369 ReturnInst *Ret = nullptr; 1370 UnreachableInst *Unreached = nullptr; 1371 for (BasicBlock &BB : *Handler) { 1372 TerminatorInst *Terminator = BB.getTerminator(); 1373 // If we find an invoke, there is nothing to be done. 1374 auto *II = dyn_cast<InvokeInst>(Terminator); 1375 if (II) 1376 return; 1377 // If we've already recorded a return instruction, keep looking for invokes. 1378 if (!Ret) 1379 Ret = dyn_cast<ReturnInst>(Terminator); 1380 // If we haven't recorded an unreachable instruction, try this terminator. 1381 if (!Unreached) 1382 Unreached = dyn_cast<UnreachableInst>(Terminator); 1383 } 1384 1385 // If we got this far, the handler contains no invokes. We should have seen 1386 // at least one return or unreachable instruction. We'll insert an invoke of 1387 // llvm.donothing ahead of that instruction. 1388 assert(Ret || Unreached); 1389 TerminatorInst *Term; 1390 if (Ret) 1391 Term = Ret; 1392 else 1393 Term = Unreached; 1394 BasicBlock *OldRetBB = Term->getParent(); 1395 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT); 1396 // SplitBlock adds an unconditional branch instruction at the end of the 1397 // parent block. We want to replace that with an invoke call, so we can 1398 // erase it now. 1399 OldRetBB->getTerminator()->eraseFromParent(); 1400 BasicBlock *StubLandingPad = createStubLandingPad(Handler); 1401 Function *F = 1402 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing); 1403 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB); 1404 } 1405 1406 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering 1407 // usually doesn't build LLVM IR, so that's probably the wrong place. 1408 Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy, 1409 const Twine &Name, Module *M, 1410 Value *&ParentFP) { 1411 // x64 uses a two-argument prototype where the parent FP is the second 1412 // argument. x86 uses no arguments, just the incoming EBP value. 1413 LLVMContext &Context = M->getContext(); 1414 Type *Int8PtrType = Type::getInt8PtrTy(Context); 1415 FunctionType *FnType; 1416 if (TheTriple.getArch() == Triple::x86_64) { 1417 Type *ArgTys[2] = {Int8PtrType, Int8PtrType}; 1418 FnType = FunctionType::get(RetTy, ArgTys, false); 1419 } else { 1420 FnType = FunctionType::get(RetTy, None, false); 1421 } 1422 1423 Function *Handler = 1424 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M); 1425 BasicBlock *Entry = BasicBlock::Create(Context, "entry"); 1426 Handler->getBasicBlockList().push_front(Entry); 1427 if (TheTriple.getArch() == Triple::x86_64) { 1428 ParentFP = &(Handler->getArgumentList().back()); 1429 } else { 1430 assert(M); 1431 Function *FrameAddressFn = 1432 Intrinsic::getDeclaration(M, Intrinsic::frameaddress); 1433 Function *RecoverFPFn = 1434 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp); 1435 IRBuilder<> Builder(&Handler->getEntryBlock()); 1436 Value *EBP = 1437 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp"); 1438 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType); 1439 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP}); 1440 } 1441 return Handler; 1442 } 1443 1444 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn, 1445 LandingPadInst *LPad, BasicBlock *StartBB, 1446 FrameVarInfoMap &VarInfo) { 1447 Module *M = SrcFn->getParent(); 1448 LLVMContext &Context = M->getContext(); 1449 Type *Int8PtrType = Type::getInt8PtrTy(Context); 1450 1451 // Create a new function to receive the handler contents. 1452 Value *ParentFP; 1453 Function *Handler; 1454 if (Action->getType() == Catch) { 1455 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M, 1456 ParentFP); 1457 } else { 1458 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context), 1459 SrcFn->getName() + ".cleanup", M, ParentFP); 1460 } 1461 Handler->setPersonalityFn(SrcFn->getPersonalityFn()); 1462 HandlerToParentFP[Handler] = ParentFP; 1463 Handler->addFnAttr("wineh-parent", SrcFn->getName()); 1464 BasicBlock *Entry = &Handler->getEntryBlock(); 1465 1466 // Generate a standard prolog to setup the frame recovery structure. 1467 IRBuilder<> Builder(Context); 1468 Builder.SetInsertPoint(Entry); 1469 Builder.SetCurrentDebugLocation(LPad->getDebugLoc()); 1470 1471 std::unique_ptr<WinEHCloningDirectorBase> Director; 1472 1473 ValueToValueMapTy VMap; 1474 1475 LandingPadMap &LPadMap = LPadMaps[LPad]; 1476 if (!LPadMap.isInitialized()) 1477 LPadMap.mapLandingPad(LPad); 1478 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { 1479 Constant *Sel = CatchAction->getSelector(); 1480 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo, 1481 LPadMap, NestedLPtoOriginalLP, DT, 1482 EHBlocks)); 1483 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), 1484 ConstantInt::get(Type::getInt32Ty(Context), 1)); 1485 } else { 1486 Director.reset( 1487 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap)); 1488 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), 1489 UndefValue::get(Type::getInt32Ty(Context))); 1490 } 1491 1492 SmallVector<ReturnInst *, 8> Returns; 1493 ClonedCodeInfo OutlinedFunctionInfo; 1494 1495 // If the start block contains PHI nodes, we need to map them. 1496 BasicBlock::iterator II = StartBB->begin(); 1497 while (auto *PN = dyn_cast<PHINode>(II)) { 1498 bool Mapped = false; 1499 // Look for PHI values that we have already mapped (such as the selector). 1500 for (Value *Val : PN->incoming_values()) { 1501 if (VMap.count(Val)) { 1502 VMap[PN] = VMap[Val]; 1503 Mapped = true; 1504 } 1505 } 1506 // If we didn't find a match for this value, map it as an undef. 1507 if (!Mapped) { 1508 VMap[PN] = UndefValue::get(PN->getType()); 1509 } 1510 ++II; 1511 } 1512 1513 // The landing pad value may be used by PHI nodes. It will ultimately be 1514 // eliminated, but we need it in the map for intermediate handling. 1515 VMap[LPad] = UndefValue::get(LPad->getType()); 1516 1517 // Skip over PHIs and, if applicable, landingpad instructions. 1518 II = StartBB->getFirstInsertionPt(); 1519 1520 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap, 1521 /*ModuleLevelChanges=*/false, Returns, "", 1522 &OutlinedFunctionInfo, Director.get()); 1523 1524 // Move all the instructions in the cloned "entry" block into our entry block. 1525 // Depending on how the parent function was laid out, the block that will 1526 // correspond to the outlined entry block may not be the first block in the 1527 // list. We can recognize it, however, as the cloned block which has no 1528 // predecessors. Any other block wouldn't have been cloned if it didn't 1529 // have a predecessor which was also cloned. 1530 Function::iterator ClonedIt = std::next(Function::iterator(Entry)); 1531 while (!pred_empty(ClonedIt)) 1532 ++ClonedIt; 1533 BasicBlock *ClonedEntryBB = ClonedIt; 1534 assert(ClonedEntryBB); 1535 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList()); 1536 ClonedEntryBB->eraseFromParent(); 1537 1538 // Make sure we can identify the handler's personality later. 1539 addStubInvokeToHandlerIfNeeded(Handler); 1540 1541 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { 1542 WinEHCatchDirector *CatchDirector = 1543 reinterpret_cast<WinEHCatchDirector *>(Director.get()); 1544 CatchAction->setExceptionVar(CatchDirector->getExceptionVar()); 1545 CatchAction->setReturnTargets(CatchDirector->getReturnTargets()); 1546 1547 // Look for blocks that are not part of the landing pad that we just 1548 // outlined but terminate with a call to llvm.eh.endcatch and a 1549 // branch to a block that is in the handler we just outlined. 1550 // These blocks will be part of a nested landing pad that intends to 1551 // return to an address in this handler. This case is best handled 1552 // after both landing pads have been outlined, so for now we'll just 1553 // save the association of the blocks in LPadTargetBlocks. The 1554 // return instructions which are created from these branches will be 1555 // replaced after all landing pads have been outlined. 1556 for (const auto MapEntry : VMap) { 1557 // VMap maps all values and blocks that were just cloned, but dead 1558 // blocks which were pruned will map to nullptr. 1559 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr) 1560 continue; 1561 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first); 1562 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) { 1563 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator()); 1564 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1) 1565 continue; 1566 BasicBlock::iterator II = const_cast<BranchInst *>(Branch); 1567 --II; 1568 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) { 1569 // This would indicate that a nested landing pad wants to return 1570 // to a block that is outlined into two different handlers. 1571 assert(!LPadTargetBlocks.count(MappedBB)); 1572 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second); 1573 } 1574 } 1575 } 1576 } // End if (CatchAction) 1577 1578 Action->setHandlerBlockOrFunc(Handler); 1579 1580 return true; 1581 } 1582 1583 /// This BB must end in a selector dispatch. All we need to do is pass the 1584 /// handler block to llvm.eh.actions and list it as a possible indirectbr 1585 /// target. 1586 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction, 1587 BasicBlock *StartBB) { 1588 BasicBlock *HandlerBB; 1589 BasicBlock *NextBB; 1590 Constant *Selector; 1591 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB); 1592 if (Res) { 1593 // If this was EH dispatch, this must be a conditional branch to the handler 1594 // block. 1595 // FIXME: Handle instructions in the dispatch block. Currently we drop them, 1596 // leading to crashes if some optimization hoists stuff here. 1597 assert(CatchAction->getSelector() && HandlerBB && 1598 "expected catch EH dispatch"); 1599 } else { 1600 // This must be a catch-all. Split the block after the landingpad. 1601 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all"); 1602 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT); 1603 } 1604 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt()); 1605 Function *EHCodeFn = Intrinsic::getDeclaration( 1606 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode); 1607 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode"); 1608 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType()); 1609 Builder.CreateStore(Code, SEHExceptionCodeSlot); 1610 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB)); 1611 TinyPtrVector<BasicBlock *> Targets(HandlerBB); 1612 CatchAction->setReturnTargets(Targets); 1613 } 1614 1615 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) { 1616 // Each instance of this class should only ever be used to map a single 1617 // landing pad. 1618 assert(OriginLPad == nullptr || OriginLPad == LPad); 1619 1620 // If the landing pad has already been mapped, there's nothing more to do. 1621 if (OriginLPad == LPad) 1622 return; 1623 1624 OriginLPad = LPad; 1625 1626 // The landingpad instruction returns an aggregate value. Typically, its 1627 // value will be passed to a pair of extract value instructions and the 1628 // results of those extracts will have been promoted to reg values before 1629 // this routine is called. 1630 for (auto *U : LPad->users()) { 1631 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); 1632 if (!Extract) 1633 continue; 1634 assert(Extract->getNumIndices() == 1 && 1635 "Unexpected operation: extracting both landing pad values"); 1636 unsigned int Idx = *(Extract->idx_begin()); 1637 assert((Idx == 0 || Idx == 1) && 1638 "Unexpected operation: extracting an unknown landing pad element"); 1639 if (Idx == 0) { 1640 ExtractedEHPtrs.push_back(Extract); 1641 } else if (Idx == 1) { 1642 ExtractedSelectors.push_back(Extract); 1643 } 1644 } 1645 } 1646 1647 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const { 1648 return BB->getLandingPadInst() == OriginLPad; 1649 } 1650 1651 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const { 1652 if (Inst == OriginLPad) 1653 return true; 1654 for (auto *Extract : ExtractedEHPtrs) { 1655 if (Inst == Extract) 1656 return true; 1657 } 1658 for (auto *Extract : ExtractedSelectors) { 1659 if (Inst == Extract) 1660 return true; 1661 } 1662 return false; 1663 } 1664 1665 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, 1666 Value *SelectorValue) const { 1667 // Remap all landing pad extract instructions to the specified values. 1668 for (auto *Extract : ExtractedEHPtrs) 1669 VMap[Extract] = EHPtrValue; 1670 for (auto *Extract : ExtractedSelectors) 1671 VMap[Extract] = SelectorValue; 1672 } 1673 1674 static bool isLocalAddressCall(const Value *V) { 1675 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>()); 1676 } 1677 1678 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction( 1679 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1680 // If this is one of the boilerplate landing pad instructions, skip it. 1681 // The instruction will have already been remapped in VMap. 1682 if (LPadMap.isLandingPadSpecificInst(Inst)) 1683 return CloningDirector::SkipInstruction; 1684 1685 // Nested landing pads that have not already been outlined will be cloned as 1686 // stubs, with just the landingpad instruction and an unreachable instruction. 1687 // When all landingpads have been outlined, we'll replace this with the 1688 // llvm.eh.actions call and indirect branch created when the landing pad was 1689 // outlined. 1690 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) { 1691 return handleLandingPad(VMap, LPad, NewBB); 1692 } 1693 1694 // Nested landing pads that have already been outlined will be cloned in their 1695 // outlined form, but we need to intercept the ibr instruction to filter out 1696 // targets that do not return to the handler we are outlining. 1697 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) { 1698 return handleIndirectBr(VMap, IBr, NewBB); 1699 } 1700 1701 if (auto *Invoke = dyn_cast<InvokeInst>(Inst)) 1702 return handleInvoke(VMap, Invoke, NewBB); 1703 1704 if (auto *Resume = dyn_cast<ResumeInst>(Inst)) 1705 return handleResume(VMap, Resume, NewBB); 1706 1707 if (auto *Cmp = dyn_cast<CmpInst>(Inst)) 1708 return handleCompare(VMap, Cmp, NewBB); 1709 1710 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) 1711 return handleBeginCatch(VMap, Inst, NewBB); 1712 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) 1713 return handleEndCatch(VMap, Inst, NewBB); 1714 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) 1715 return handleTypeIdFor(VMap, Inst, NewBB); 1716 1717 // When outlining llvm.localaddress(), remap that to the second argument, 1718 // which is the FP of the parent. 1719 if (isLocalAddressCall(Inst)) { 1720 VMap[Inst] = ParentFP; 1721 return CloningDirector::SkipInstruction; 1722 } 1723 1724 // Continue with the default cloning behavior. 1725 return CloningDirector::CloneInstruction; 1726 } 1727 1728 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad( 1729 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { 1730 // If the instruction after the landing pad is a call to llvm.eh.actions 1731 // the landing pad has already been outlined. In this case, we should 1732 // clone it because it may return to a block in the handler we are 1733 // outlining now that would otherwise be unreachable. The landing pads 1734 // are sorted before outlining begins to enable this case to work 1735 // properly. 1736 const Instruction *NextI = LPad->getNextNode(); 1737 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>())) 1738 return CloningDirector::CloneInstruction; 1739 1740 // If the landing pad hasn't been outlined yet, the landing pad we are 1741 // outlining now does not dominate it and so it cannot return to a block 1742 // in this handler. In that case, we can just insert a stub landing 1743 // pad now and patch it up later. 1744 Instruction *NewInst = LPad->clone(); 1745 if (LPad->hasName()) 1746 NewInst->setName(LPad->getName()); 1747 // Save this correlation for later processing. 1748 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad; 1749 VMap[LPad] = NewInst; 1750 BasicBlock::InstListType &InstList = NewBB->getInstList(); 1751 InstList.push_back(NewInst); 1752 InstList.push_back(new UnreachableInst(NewBB->getContext())); 1753 return CloningDirector::StopCloningBB; 1754 } 1755 1756 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch( 1757 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1758 // The argument to the call is some form of the first element of the 1759 // landingpad aggregate value, but that doesn't matter. It isn't used 1760 // here. 1761 // The second argument is an outparameter where the exception object will be 1762 // stored. Typically the exception object is a scalar, but it can be an 1763 // aggregate when catching by value. 1764 // FIXME: Leave something behind to indicate where the exception object lives 1765 // for this handler. Should it be part of llvm.eh.actions? 1766 assert(ExceptionObjectVar == nullptr && "Multiple calls to " 1767 "llvm.eh.begincatch found while " 1768 "outlining catch handler."); 1769 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts(); 1770 if (isa<ConstantPointerNull>(ExceptionObjectVar)) 1771 return CloningDirector::SkipInstruction; 1772 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() && 1773 "catch parameter is not static alloca"); 1774 Materializer.escapeCatchObject(ExceptionObjectVar); 1775 return CloningDirector::SkipInstruction; 1776 } 1777 1778 CloningDirector::CloningAction 1779 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap, 1780 const Instruction *Inst, BasicBlock *NewBB) { 1781 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); 1782 // It might be interesting to track whether or not we are inside a catch 1783 // function, but that might make the algorithm more brittle than it needs 1784 // to be. 1785 1786 // The end catch call can occur in one of two places: either in a 1787 // landingpad block that is part of the catch handlers exception mechanism, 1788 // or at the end of the catch block. However, a catch-all handler may call 1789 // end catch from the original landing pad. If the call occurs in a nested 1790 // landing pad block, we must skip it and continue so that the landing pad 1791 // gets cloned. 1792 auto *ParentBB = IntrinCall->getParent(); 1793 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB)) 1794 return CloningDirector::SkipInstruction; 1795 1796 // If an end catch occurs anywhere else we want to terminate the handler 1797 // with a return to the code that follows the endcatch call. If the 1798 // next instruction is not an unconditional branch, we need to split the 1799 // block to provide a clear target for the return instruction. 1800 BasicBlock *ContinueBB; 1801 auto Next = std::next(BasicBlock::const_iterator(IntrinCall)); 1802 const BranchInst *Branch = dyn_cast<BranchInst>(Next); 1803 if (!Branch || !Branch->isUnconditional()) { 1804 // We're interrupting the cloning process at this location, so the 1805 // const_cast we're doing here will not cause a problem. 1806 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB), 1807 const_cast<Instruction *>(cast<Instruction>(Next))); 1808 } else { 1809 ContinueBB = Branch->getSuccessor(0); 1810 } 1811 1812 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB); 1813 ReturnTargets.push_back(ContinueBB); 1814 1815 // We just added a terminator to the cloned block. 1816 // Tell the caller to stop processing the current basic block so that 1817 // the branch instruction will be skipped. 1818 return CloningDirector::StopCloningBB; 1819 } 1820 1821 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor( 1822 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1823 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); 1824 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); 1825 // This causes a replacement that will collapse the landing pad CFG based 1826 // on the filter function we intend to match. 1827 if (Selector == CurrentSelector) 1828 VMap[Inst] = ConstantInt::get(SelectorIDType, 1); 1829 else 1830 VMap[Inst] = ConstantInt::get(SelectorIDType, 0); 1831 // Tell the caller not to clone this instruction. 1832 return CloningDirector::SkipInstruction; 1833 } 1834 1835 CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr( 1836 ValueToValueMapTy &VMap, 1837 const IndirectBrInst *IBr, 1838 BasicBlock *NewBB) { 1839 // If this indirect branch is not part of a landing pad block, just clone it. 1840 const BasicBlock *ParentBB = IBr->getParent(); 1841 if (!ParentBB->isLandingPad()) 1842 return CloningDirector::CloneInstruction; 1843 1844 // If it is part of a landing pad, we want to filter out target blocks 1845 // that are not part of the handler we are outlining. 1846 const LandingPadInst *LPad = ParentBB->getLandingPadInst(); 1847 1848 // Save this correlation for later processing. 1849 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad; 1850 1851 // We should only get here for landing pads that have already been outlined. 1852 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>())); 1853 1854 // Copy the indirectbr, but only include targets that were previously 1855 // identified as EH blocks and are dominated by the nested landing pad. 1856 SetVector<const BasicBlock *> ReturnTargets; 1857 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) { 1858 auto *TargetBB = IBr->getDestination(I); 1859 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) && 1860 DT->dominates(ParentBB, TargetBB)) { 1861 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n"); 1862 ReturnTargets.insert(TargetBB); 1863 } 1864 } 1865 IndirectBrInst *NewBranch = 1866 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()), 1867 ReturnTargets.size(), NewBB); 1868 for (auto *Target : ReturnTargets) 1869 NewBranch->addDestination(const_cast<BasicBlock*>(Target)); 1870 1871 // The operands and targets of the branch instruction are remapped later 1872 // because it is a terminator. Tell the cloning code to clone the 1873 // blocks we just added to the target list. 1874 return CloningDirector::CloneSuccessors; 1875 } 1876 1877 CloningDirector::CloningAction 1878 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap, 1879 const InvokeInst *Invoke, BasicBlock *NewBB) { 1880 return CloningDirector::CloneInstruction; 1881 } 1882 1883 CloningDirector::CloningAction 1884 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap, 1885 const ResumeInst *Resume, BasicBlock *NewBB) { 1886 // Resume instructions shouldn't be reachable from catch handlers. 1887 // We still need to handle it, but it will be pruned. 1888 BasicBlock::InstListType &InstList = NewBB->getInstList(); 1889 InstList.push_back(new UnreachableInst(NewBB->getContext())); 1890 return CloningDirector::StopCloningBB; 1891 } 1892 1893 CloningDirector::CloningAction 1894 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap, 1895 const CmpInst *Compare, BasicBlock *NewBB) { 1896 const IntrinsicInst *IntrinCall = nullptr; 1897 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) { 1898 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0)); 1899 } else if (match(Compare->getOperand(1), 1900 m_Intrinsic<Intrinsic::eh_typeid_for>())) { 1901 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1)); 1902 } 1903 if (IntrinCall) { 1904 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); 1905 // This causes a replacement that will collapse the landing pad CFG based 1906 // on the filter function we intend to match. 1907 if (Selector == CurrentSelector->stripPointerCasts()) { 1908 VMap[Compare] = ConstantInt::get(SelectorIDType, 1); 1909 } else { 1910 VMap[Compare] = ConstantInt::get(SelectorIDType, 0); 1911 } 1912 return CloningDirector::SkipInstruction; 1913 } 1914 return CloningDirector::CloneInstruction; 1915 } 1916 1917 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad( 1918 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { 1919 // The MS runtime will terminate the process if an exception occurs in a 1920 // cleanup handler, so we shouldn't encounter landing pads in the actual 1921 // cleanup code, but they may appear in catch blocks. Depending on where 1922 // we started cloning we may see one, but it will get dropped during dead 1923 // block pruning. 1924 Instruction *NewInst = new UnreachableInst(NewBB->getContext()); 1925 VMap[LPad] = NewInst; 1926 BasicBlock::InstListType &InstList = NewBB->getInstList(); 1927 InstList.push_back(NewInst); 1928 return CloningDirector::StopCloningBB; 1929 } 1930 1931 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch( 1932 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1933 // Cleanup code may flow into catch blocks or the catch block may be part 1934 // of a branch that will be optimized away. We'll insert a return 1935 // instruction now, but it may be pruned before the cloning process is 1936 // complete. 1937 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); 1938 return CloningDirector::StopCloningBB; 1939 } 1940 1941 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch( 1942 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1943 // Cleanup handlers nested within catch handlers may begin with a call to 1944 // eh.endcatch. We can just ignore that instruction. 1945 return CloningDirector::SkipInstruction; 1946 } 1947 1948 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor( 1949 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { 1950 // If we encounter a selector comparison while cloning a cleanup handler, 1951 // we want to stop cloning immediately. Anything after the dispatch 1952 // will be outlined into a different handler. 1953 BasicBlock *CatchHandler; 1954 Constant *Selector; 1955 BasicBlock *NextBB; 1956 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()), 1957 CatchHandler, Selector, NextBB)) { 1958 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); 1959 return CloningDirector::StopCloningBB; 1960 } 1961 // If eg.typeid.for is called for any other reason, it can be ignored. 1962 VMap[Inst] = ConstantInt::get(SelectorIDType, 0); 1963 return CloningDirector::SkipInstruction; 1964 } 1965 1966 CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr( 1967 ValueToValueMapTy &VMap, 1968 const IndirectBrInst *IBr, 1969 BasicBlock *NewBB) { 1970 // No special handling is required for cleanup cloning. 1971 return CloningDirector::CloneInstruction; 1972 } 1973 1974 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke( 1975 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) { 1976 // All invokes in cleanup handlers can be replaced with calls. 1977 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3); 1978 // Insert a normal call instruction... 1979 CallInst *NewCall = 1980 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs, 1981 Invoke->getName(), NewBB); 1982 NewCall->setCallingConv(Invoke->getCallingConv()); 1983 NewCall->setAttributes(Invoke->getAttributes()); 1984 NewCall->setDebugLoc(Invoke->getDebugLoc()); 1985 VMap[Invoke] = NewCall; 1986 1987 // Remap the operands. 1988 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer); 1989 1990 // Insert an unconditional branch to the normal destination. 1991 BranchInst::Create(Invoke->getNormalDest(), NewBB); 1992 1993 // The unwind destination won't be cloned into the new function, so 1994 // we don't need to clean up its phi nodes. 1995 1996 // We just added a terminator to the cloned block. 1997 // Tell the caller to stop processing the current basic block. 1998 return CloningDirector::CloneSuccessors; 1999 } 2000 2001 CloningDirector::CloningAction WinEHCleanupDirector::handleResume( 2002 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) { 2003 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); 2004 2005 // We just added a terminator to the cloned block. 2006 // Tell the caller to stop processing the current basic block so that 2007 // the branch instruction will be skipped. 2008 return CloningDirector::StopCloningBB; 2009 } 2010 2011 CloningDirector::CloningAction 2012 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap, 2013 const CmpInst *Compare, BasicBlock *NewBB) { 2014 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) || 2015 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) { 2016 VMap[Compare] = ConstantInt::get(SelectorIDType, 1); 2017 return CloningDirector::SkipInstruction; 2018 } 2019 return CloningDirector::CloneInstruction; 2020 } 2021 2022 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer( 2023 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo) 2024 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) { 2025 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock(); 2026 2027 // New allocas should be inserted in the entry block, but after the parent FP 2028 // is established if it is an instruction. 2029 Instruction *InsertPoint = EntryBB->getFirstInsertionPt(); 2030 if (auto *FPInst = dyn_cast<Instruction>(ParentFP)) 2031 InsertPoint = FPInst->getNextNode(); 2032 Builder.SetInsertPoint(EntryBB, InsertPoint); 2033 } 2034 2035 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) { 2036 // If we're asked to materialize a static alloca, we temporarily create an 2037 // alloca in the outlined function and add this to the FrameVarInfo map. When 2038 // all the outlining is complete, we'll replace these temporary allocas with 2039 // calls to llvm.localrecover. 2040 if (auto *AV = dyn_cast<AllocaInst>(V)) { 2041 assert(AV->isStaticAlloca() && 2042 "cannot materialize un-demoted dynamic alloca"); 2043 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone()); 2044 Builder.Insert(NewAlloca, AV->getName()); 2045 FrameVarInfo[AV].push_back(NewAlloca); 2046 return NewAlloca; 2047 } 2048 2049 if (isa<Instruction>(V) || isa<Argument>(V)) { 2050 Function *Parent = isa<Instruction>(V) 2051 ? cast<Instruction>(V)->getParent()->getParent() 2052 : cast<Argument>(V)->getParent(); 2053 errs() 2054 << "Failed to demote instruction used in exception handler of function " 2055 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n"; 2056 errs() << " " << *V << '\n'; 2057 report_fatal_error("WinEHPrepare failed to demote instruction"); 2058 } 2059 2060 // Don't materialize other values. 2061 return nullptr; 2062 } 2063 2064 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) { 2065 // Catch parameter objects have to live in the parent frame. When we see a use 2066 // of a catch parameter, add a sentinel to the multimap to indicate that it's 2067 // used from another handler. This will prevent us from trying to sink the 2068 // alloca into the handler and ensure that the catch parameter is present in 2069 // the call to llvm.localescape. 2070 FrameVarInfo[V].push_back(getCatchObjectSentinel()); 2071 } 2072 2073 // This function maps the catch and cleanup handlers that are reachable from the 2074 // specified landing pad. The landing pad sequence will have this basic shape: 2075 // 2076 // <cleanup handler> 2077 // <selector comparison> 2078 // <catch handler> 2079 // <cleanup handler> 2080 // <selector comparison> 2081 // <catch handler> 2082 // <cleanup handler> 2083 // ... 2084 // 2085 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by 2086 // any arbitrary control flow, but all paths through the cleanup code must 2087 // eventually reach the next selector comparison and no path can skip to a 2088 // different selector comparisons, though some paths may terminate abnormally. 2089 // Therefore, we will use a depth first search from the start of any given 2090 // cleanup block and stop searching when we find the next selector comparison. 2091 // 2092 // If the landingpad instruction does not have a catch clause, we will assume 2093 // that any instructions other than selector comparisons and catch handlers can 2094 // be ignored. In practice, these will only be the boilerplate instructions. 2095 // 2096 // The catch handlers may also have any control structure, but we are only 2097 // interested in the start of the catch handlers, so we don't need to actually 2098 // follow the flow of the catch handlers. The start of the catch handlers can 2099 // be located from the compare instructions, but they can be skipped in the 2100 // flow by following the contrary branch. 2101 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad, 2102 LandingPadActions &Actions) { 2103 unsigned int NumClauses = LPad->getNumClauses(); 2104 unsigned int HandlersFound = 0; 2105 BasicBlock *BB = LPad->getParent(); 2106 2107 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n"); 2108 2109 if (NumClauses == 0) { 2110 findCleanupHandlers(Actions, BB, nullptr); 2111 return; 2112 } 2113 2114 VisitedBlockSet VisitedBlocks; 2115 2116 while (HandlersFound != NumClauses) { 2117 BasicBlock *NextBB = nullptr; 2118 2119 // Skip over filter clauses. 2120 if (LPad->isFilter(HandlersFound)) { 2121 ++HandlersFound; 2122 continue; 2123 } 2124 2125 // See if the clause we're looking for is a catch-all. 2126 // If so, the catch begins immediately. 2127 Constant *ExpectedSelector = 2128 LPad->getClause(HandlersFound)->stripPointerCasts(); 2129 if (isa<ConstantPointerNull>(ExpectedSelector)) { 2130 // The catch all must occur last. 2131 assert(HandlersFound == NumClauses - 1); 2132 2133 // There can be additional selector dispatches in the call chain that we 2134 // need to ignore. 2135 BasicBlock *CatchBlock = nullptr; 2136 Constant *Selector; 2137 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { 2138 DEBUG(dbgs() << " Found extra catch dispatch in block " 2139 << CatchBlock->getName() << "\n"); 2140 BB = NextBB; 2141 } 2142 2143 // Add the catch handler to the action list. 2144 CatchHandler *Action = nullptr; 2145 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { 2146 // If the CatchHandlerMap already has an entry for this BB, re-use it. 2147 Action = CatchHandlerMap[BB]; 2148 assert(Action->getSelector() == ExpectedSelector); 2149 } else { 2150 // We don't expect a selector dispatch, but there may be a call to 2151 // llvm.eh.begincatch, which separates catch handling code from 2152 // cleanup code in the same control flow. This call looks for the 2153 // begincatch intrinsic. 2154 Action = findCatchHandler(BB, NextBB, VisitedBlocks); 2155 if (Action) { 2156 // For C++ EH, check if there is any interesting cleanup code before 2157 // we begin the catch. This is important because cleanups cannot 2158 // rethrow exceptions but code called from catches can. For SEH, it 2159 // isn't important if some finally code before a catch-all is executed 2160 // out of line or after recovering from the exception. 2161 if (Personality == EHPersonality::MSVC_CXX) 2162 findCleanupHandlers(Actions, BB, BB); 2163 } else { 2164 // If an action was not found, it means that the control flows 2165 // directly into the catch-all handler and there is no cleanup code. 2166 // That's an expected situation and we must create a catch action. 2167 // Since this is a catch-all handler, the selector won't actually 2168 // appear in the code anywhere. ExpectedSelector here is the constant 2169 // null ptr that we got from the landing pad instruction. 2170 Action = new CatchHandler(BB, ExpectedSelector, nullptr); 2171 CatchHandlerMap[BB] = Action; 2172 } 2173 } 2174 Actions.insertCatchHandler(Action); 2175 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n"); 2176 ++HandlersFound; 2177 2178 // Once we reach a catch-all, don't expect to hit a resume instruction. 2179 BB = nullptr; 2180 break; 2181 } 2182 2183 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks); 2184 assert(CatchAction); 2185 2186 // See if there is any interesting code executed before the dispatch. 2187 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock()); 2188 2189 // When the source program contains multiple nested try blocks the catch 2190 // handlers can get strung together in such a way that we can encounter 2191 // a dispatch for a selector that we've already had a handler for. 2192 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) { 2193 ++HandlersFound; 2194 2195 // Add the catch handler to the action list. 2196 DEBUG(dbgs() << " Found catch dispatch in block " 2197 << CatchAction->getStartBlock()->getName() << "\n"); 2198 Actions.insertCatchHandler(CatchAction); 2199 } else { 2200 // Under some circumstances optimized IR will flow unconditionally into a 2201 // handler block without checking the selector. This can only happen if 2202 // the landing pad has a catch-all handler and the handler for the 2203 // preceding catch clause is identical to the catch-call handler 2204 // (typically an empty catch). In this case, the handler must be shared 2205 // by all remaining clauses. 2206 if (isa<ConstantPointerNull>( 2207 CatchAction->getSelector()->stripPointerCasts())) { 2208 DEBUG(dbgs() << " Applying early catch-all handler in block " 2209 << CatchAction->getStartBlock()->getName() 2210 << " to all remaining clauses.\n"); 2211 Actions.insertCatchHandler(CatchAction); 2212 return; 2213 } 2214 2215 DEBUG(dbgs() << " Found extra catch dispatch in block " 2216 << CatchAction->getStartBlock()->getName() << "\n"); 2217 } 2218 2219 // Move on to the block after the catch handler. 2220 BB = NextBB; 2221 } 2222 2223 // If we didn't wind up in a catch-all, see if there is any interesting code 2224 // executed before the resume. 2225 findCleanupHandlers(Actions, BB, BB); 2226 2227 // It's possible that some optimization moved code into a landingpad that 2228 // wasn't 2229 // previously being used for cleanup. If that happens, we need to execute 2230 // that 2231 // extra code from a cleanup handler. 2232 if (Actions.includesCleanup() && !LPad->isCleanup()) 2233 LPad->setCleanup(true); 2234 } 2235 2236 // This function searches starting with the input block for the next 2237 // block that terminates with a branch whose condition is based on a selector 2238 // comparison. This may be the input block. See the mapLandingPadBlocks 2239 // comments for a discussion of control flow assumptions. 2240 // 2241 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB, 2242 BasicBlock *&NextBB, 2243 VisitedBlockSet &VisitedBlocks) { 2244 // See if we've already found a catch handler use it. 2245 // Call count() first to avoid creating a null entry for blocks 2246 // we haven't seen before. 2247 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { 2248 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]); 2249 NextBB = Action->getNextBB(); 2250 return Action; 2251 } 2252 2253 // VisitedBlocks applies only to the current search. We still 2254 // need to consider blocks that we've visited while mapping other 2255 // landing pads. 2256 VisitedBlocks.insert(BB); 2257 2258 BasicBlock *CatchBlock = nullptr; 2259 Constant *Selector = nullptr; 2260 2261 // If this is the first time we've visited this block from any landing pad 2262 // look to see if it is a selector dispatch block. 2263 if (!CatchHandlerMap.count(BB)) { 2264 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { 2265 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB); 2266 CatchHandlerMap[BB] = Action; 2267 return Action; 2268 } 2269 // If we encounter a block containing an llvm.eh.begincatch before we 2270 // find a selector dispatch block, the handler is assumed to be 2271 // reached unconditionally. This happens for catch-all blocks, but 2272 // it can also happen for other catch handlers that have been combined 2273 // with the catch-all handler during optimization. 2274 if (isCatchBlock(BB)) { 2275 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext()); 2276 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy); 2277 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr); 2278 CatchHandlerMap[BB] = Action; 2279 return Action; 2280 } 2281 } 2282 2283 // Visit each successor, looking for the dispatch. 2284 // FIXME: We expect to find the dispatch quickly, so this will probably 2285 // work better as a breadth first search. 2286 for (BasicBlock *Succ : successors(BB)) { 2287 if (VisitedBlocks.count(Succ)) 2288 continue; 2289 2290 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks); 2291 if (Action) 2292 return Action; 2293 } 2294 return nullptr; 2295 } 2296 2297 // These are helper functions to combine repeated code from findCleanupHandlers. 2298 static void createCleanupHandler(LandingPadActions &Actions, 2299 CleanupHandlerMapTy &CleanupHandlerMap, 2300 BasicBlock *BB) { 2301 CleanupHandler *Action = new CleanupHandler(BB); 2302 CleanupHandlerMap[BB] = Action; 2303 Actions.insertCleanupHandler(Action); 2304 DEBUG(dbgs() << " Found cleanup code in block " 2305 << Action->getStartBlock()->getName() << "\n"); 2306 } 2307 2308 static CallSite matchOutlinedFinallyCall(BasicBlock *BB, 2309 Instruction *MaybeCall) { 2310 // Look for finally blocks that Clang has already outlined for us. 2311 // %fp = call i8* @llvm.localaddress() 2312 // call void @"fin$parent"(iN 1, i8* %fp) 2313 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator()) 2314 MaybeCall = MaybeCall->getNextNode(); 2315 CallSite FinallyCall(MaybeCall); 2316 if (!FinallyCall || FinallyCall.arg_size() != 2) 2317 return CallSite(); 2318 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1))) 2319 return CallSite(); 2320 if (!isLocalAddressCall(FinallyCall.getArgument(1))) 2321 return CallSite(); 2322 return FinallyCall; 2323 } 2324 2325 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) { 2326 // Skip single ubr blocks. 2327 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) { 2328 auto *Br = dyn_cast<BranchInst>(BB->getTerminator()); 2329 if (Br && Br->isUnconditional()) 2330 BB = Br->getSuccessor(0); 2331 else 2332 return BB; 2333 } 2334 return BB; 2335 } 2336 2337 // This function searches starting with the input block for the next block that 2338 // contains code that is not part of a catch handler and would not be eliminated 2339 // during handler outlining. 2340 // 2341 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions, 2342 BasicBlock *StartBB, BasicBlock *EndBB) { 2343 // Here we will skip over the following: 2344 // 2345 // landing pad prolog: 2346 // 2347 // Unconditional branches 2348 // 2349 // Selector dispatch 2350 // 2351 // Resume pattern 2352 // 2353 // Anything else marks the start of an interesting block 2354 2355 BasicBlock *BB = StartBB; 2356 // Anything other than an unconditional branch will kick us out of this loop 2357 // one way or another. 2358 while (BB) { 2359 BB = followSingleUnconditionalBranches(BB); 2360 // If we've already scanned this block, don't scan it again. If it is 2361 // a cleanup block, there will be an action in the CleanupHandlerMap. 2362 // If we've scanned it and it is not a cleanup block, there will be a 2363 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will 2364 // be no entry in the CleanupHandlerMap. We must call count() first to 2365 // avoid creating a null entry for blocks we haven't scanned. 2366 if (CleanupHandlerMap.count(BB)) { 2367 if (auto *Action = CleanupHandlerMap[BB]) { 2368 Actions.insertCleanupHandler(Action); 2369 DEBUG(dbgs() << " Found cleanup code in block " 2370 << Action->getStartBlock()->getName() << "\n"); 2371 // FIXME: This cleanup might chain into another, and we need to discover 2372 // that. 2373 return; 2374 } else { 2375 // Here we handle the case where the cleanup handler map contains a 2376 // value for this block but the value is a nullptr. This means that 2377 // we have previously analyzed the block and determined that it did 2378 // not contain any cleanup code. Based on the earlier analysis, we 2379 // know the block must end in either an unconditional branch, a 2380 // resume or a conditional branch that is predicated on a comparison 2381 // with a selector. Either the resume or the selector dispatch 2382 // would terminate the search for cleanup code, so the unconditional 2383 // branch is the only case for which we might need to continue 2384 // searching. 2385 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB); 2386 if (SuccBB == BB || SuccBB == EndBB) 2387 return; 2388 BB = SuccBB; 2389 continue; 2390 } 2391 } 2392 2393 // Create an entry in the cleanup handler map for this block. Initially 2394 // we create an entry that says this isn't a cleanup block. If we find 2395 // cleanup code, the caller will replace this entry. 2396 CleanupHandlerMap[BB] = nullptr; 2397 2398 TerminatorInst *Terminator = BB->getTerminator(); 2399 2400 // Landing pad blocks have extra instructions we need to accept. 2401 LandingPadMap *LPadMap = nullptr; 2402 if (BB->isLandingPad()) { 2403 LandingPadInst *LPad = BB->getLandingPadInst(); 2404 LPadMap = &LPadMaps[LPad]; 2405 if (!LPadMap->isInitialized()) 2406 LPadMap->mapLandingPad(LPad); 2407 } 2408 2409 // Look for the bare resume pattern: 2410 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0 2411 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1 2412 // resume { i8*, i32 } %lpad.val2 2413 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) { 2414 InsertValueInst *Insert1 = nullptr; 2415 InsertValueInst *Insert2 = nullptr; 2416 Value *ResumeVal = Resume->getOperand(0); 2417 // If the resume value isn't a phi or landingpad value, it should be a 2418 // series of insertions. Identify them so we can avoid them when scanning 2419 // for cleanups. 2420 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) { 2421 Insert2 = dyn_cast<InsertValueInst>(ResumeVal); 2422 if (!Insert2) 2423 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2424 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand()); 2425 if (!Insert1) 2426 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2427 } 2428 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 2429 II != IE; ++II) { 2430 Instruction *Inst = II; 2431 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) 2432 continue; 2433 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume) 2434 continue; 2435 if (!Inst->hasOneUse() || 2436 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) { 2437 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2438 } 2439 } 2440 return; 2441 } 2442 2443 BranchInst *Branch = dyn_cast<BranchInst>(Terminator); 2444 if (Branch && Branch->isConditional()) { 2445 // Look for the selector dispatch. 2446 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*)) 2447 // %matches = icmp eq i32 %sel, %2 2448 // br i1 %matches, label %catch14, label %eh.resume 2449 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition()); 2450 if (!Compare || !Compare->isEquality()) 2451 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2452 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 2453 II != IE; ++II) { 2454 Instruction *Inst = II; 2455 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) 2456 continue; 2457 if (Inst == Compare || Inst == Branch) 2458 continue; 2459 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) 2460 continue; 2461 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2462 } 2463 // The selector dispatch block should always terminate our search. 2464 assert(BB == EndBB); 2465 return; 2466 } 2467 2468 if (isAsynchronousEHPersonality(Personality)) { 2469 // If this is a landingpad block, split the block at the first non-landing 2470 // pad instruction. 2471 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg(); 2472 if (LPadMap) { 2473 while (MaybeCall != BB->getTerminator() && 2474 LPadMap->isLandingPadSpecificInst(MaybeCall)) 2475 MaybeCall = MaybeCall->getNextNode(); 2476 } 2477 2478 // Look for outlined finally calls on x64, since those happen to match the 2479 // prototype provided by the runtime. 2480 if (TheTriple.getArch() == Triple::x86_64) { 2481 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) { 2482 Function *Fin = FinallyCall.getCalledFunction(); 2483 assert(Fin && "outlined finally call should be direct"); 2484 auto *Action = new CleanupHandler(BB); 2485 Action->setHandlerBlockOrFunc(Fin); 2486 Actions.insertCleanupHandler(Action); 2487 CleanupHandlerMap[BB] = Action; 2488 DEBUG(dbgs() << " Found frontend-outlined finally call to " 2489 << Fin->getName() << " in block " 2490 << Action->getStartBlock()->getName() << "\n"); 2491 2492 // Split the block if there were more interesting instructions and 2493 // look for finally calls in the normal successor block. 2494 BasicBlock *SuccBB = BB; 2495 if (FinallyCall.getInstruction() != BB->getTerminator() && 2496 FinallyCall.getInstruction()->getNextNode() != 2497 BB->getTerminator()) { 2498 SuccBB = 2499 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT); 2500 } else { 2501 if (FinallyCall.isInvoke()) { 2502 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction()) 2503 ->getNormalDest(); 2504 } else { 2505 SuccBB = BB->getUniqueSuccessor(); 2506 assert(SuccBB && 2507 "splitOutlinedFinallyCalls didn't insert a branch"); 2508 } 2509 } 2510 BB = SuccBB; 2511 if (BB == EndBB) 2512 return; 2513 continue; 2514 } 2515 } 2516 } 2517 2518 // Anything else is either a catch block or interesting cleanup code. 2519 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); 2520 II != IE; ++II) { 2521 Instruction *Inst = II; 2522 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) 2523 continue; 2524 // Unconditional branches fall through to this loop. 2525 if (Inst == Branch) 2526 continue; 2527 // If this is a catch block, there is no cleanup code to be found. 2528 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) 2529 return; 2530 // If this a nested landing pad, it may contain an endcatch call. 2531 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) 2532 return; 2533 // Anything else makes this interesting cleanup code. 2534 return createCleanupHandler(Actions, CleanupHandlerMap, BB); 2535 } 2536 2537 // Only unconditional branches in empty blocks should get this far. 2538 assert(Branch && Branch->isUnconditional()); 2539 if (BB == EndBB) 2540 return; 2541 BB = Branch->getSuccessor(0); 2542 } 2543 } 2544 2545 // This is a public function, declared in WinEHFuncInfo.h and is also 2546 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp. 2547 void llvm::parseEHActions( 2548 const IntrinsicInst *II, 2549 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) { 2550 assert(II->getIntrinsicID() == Intrinsic::eh_actions && 2551 "attempted to parse non eh.actions intrinsic"); 2552 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) { 2553 uint64_t ActionKind = 2554 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue(); 2555 if (ActionKind == /*catch=*/1) { 2556 auto *Selector = cast<Constant>(II->getArgOperand(I + 1)); 2557 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2)); 2558 int64_t EHObjIndexVal = EHObjIndex->getSExtValue(); 2559 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3)); 2560 I += 4; 2561 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector, 2562 /*NextBB=*/nullptr); 2563 CH->setHandlerBlockOrFunc(Handler); 2564 CH->setExceptionVarIndex(EHObjIndexVal); 2565 Actions.push_back(std::move(CH)); 2566 } else if (ActionKind == 0) { 2567 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1)); 2568 I += 2; 2569 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr); 2570 CH->setHandlerBlockOrFunc(Handler); 2571 Actions.push_back(std::move(CH)); 2572 } else { 2573 llvm_unreachable("Expected either a catch or cleanup handler!"); 2574 } 2575 } 2576 std::reverse(Actions.begin(), Actions.end()); 2577 } 2578 2579 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState, 2580 const Value *V) { 2581 WinEHUnwindMapEntry UME; 2582 UME.ToState = ToState; 2583 UME.Cleanup = V; 2584 FuncInfo.UnwindMap.push_back(UME); 2585 return FuncInfo.getLastStateNumber(); 2586 } 2587 2588 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow, 2589 int TryHigh, int CatchHigh, 2590 ArrayRef<const CatchPadInst *> Handlers) { 2591 WinEHTryBlockMapEntry TBME; 2592 TBME.TryLow = TryLow; 2593 TBME.TryHigh = TryHigh; 2594 TBME.CatchHigh = CatchHigh; 2595 assert(TBME.TryLow <= TBME.TryHigh); 2596 for (const CatchPadInst *CPI : Handlers) { 2597 WinEHHandlerType HT; 2598 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0)); 2599 if (TypeInfo->isNullValue()) 2600 HT.TypeDescriptor = nullptr; 2601 else 2602 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts()); 2603 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue(); 2604 HT.Handler = CPI->getNormalDest(); 2605 HT.CatchObjRecoverIdx = -2; 2606 if (isa<ConstantPointerNull>(CPI->getArgOperand(2))) 2607 HT.CatchObj.Alloca = nullptr; 2608 else 2609 HT.CatchObj.Alloca = cast<AllocaInst>(CPI->getArgOperand(2)); 2610 TBME.HandlerArray.push_back(HT); 2611 } 2612 FuncInfo.TryBlockMap.push_back(TBME); 2613 } 2614 2615 static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) { 2616 for (const BasicBlock *PredBlock : predecessors(BB)) 2617 if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI())) 2618 return CPI; 2619 return nullptr; 2620 } 2621 2622 /// Find all the catchpads that feed directly into the catchendpad. Frontends 2623 /// using this personality should ensure that each catchendpad and catchpad has 2624 /// one or zero catchpad predecessors. 2625 /// 2626 /// The following C++ generates the IR after it: 2627 /// try { 2628 /// } catch (A) { 2629 /// } catch (B) { 2630 /// } 2631 /// 2632 /// IR: 2633 /// %catchpad.A 2634 /// catchpad [i8* A typeinfo] 2635 /// to label %catch.A unwind label %catchpad.B 2636 /// %catchpad.B 2637 /// catchpad [i8* B typeinfo] 2638 /// to label %catch.B unwind label %endcatches 2639 /// %endcatches 2640 /// catchendblock unwind to caller 2641 void findCatchPadsForCatchEndPad( 2642 const BasicBlock *CatchEndBB, 2643 SmallVectorImpl<const CatchPadInst *> &Handlers) { 2644 const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB); 2645 while (CPI) { 2646 Handlers.push_back(CPI); 2647 CPI = getSingleCatchPadPredecessor(CPI->getParent()); 2648 } 2649 // We've pushed these back into reverse source order. Reverse them to get 2650 // the list back into source order. 2651 std::reverse(Handlers.begin(), Handlers.end()); 2652 } 2653 2654 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs 2655 // to. If the unwind edge came from an invoke, return null. 2656 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) { 2657 const TerminatorInst *TI = BB->getTerminator(); 2658 if (isa<InvokeInst>(TI)) 2659 return nullptr; 2660 if (TI->isEHPad()) 2661 return BB; 2662 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent(); 2663 } 2664 2665 static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo, 2666 const BasicBlock &BB, 2667 int ParentState) { 2668 assert(BB.isEHPad()); 2669 const Instruction *FirstNonPHI = BB.getFirstNonPHI(); 2670 // All catchpad instructions will be handled when we process their 2671 // respective catchendpad instruction. 2672 if (isa<CatchPadInst>(FirstNonPHI)) 2673 return; 2674 2675 if (isa<CatchEndPadInst>(FirstNonPHI)) { 2676 SmallVector<const CatchPadInst *, 2> Handlers; 2677 findCatchPadsForCatchEndPad(&BB, Handlers); 2678 const BasicBlock *FirstTryPad = Handlers.front()->getParent(); 2679 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr); 2680 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow; 2681 for (const BasicBlock *PredBlock : predecessors(FirstTryPad)) 2682 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2683 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow); 2684 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr); 2685 2686 // catchpads are separate funclets in C++ EH due to the way rethrow works. 2687 // In SEH, they aren't, so no invokes will unwind to the catchendpad. 2688 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow; 2689 int TryHigh = CatchLow - 1; 2690 for (const BasicBlock *PredBlock : predecessors(&BB)) 2691 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2692 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow); 2693 int CatchHigh = FuncInfo.getLastStateNumber(); 2694 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers); 2695 DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow 2696 << '\n'); 2697 DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh 2698 << '\n'); 2699 DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh 2700 << '\n'); 2701 } else if (isa<CleanupPadInst>(FirstNonPHI)) { 2702 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB); 2703 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState; 2704 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB " 2705 << BB.getName() << '\n'); 2706 for (const BasicBlock *PredBlock : predecessors(&BB)) 2707 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2708 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState); 2709 } else if (isa<TerminatePadInst>(FirstNonPHI)) { 2710 report_fatal_error("Not yet implemented!"); 2711 } else { 2712 llvm_unreachable("unexpected EH Pad!"); 2713 } 2714 } 2715 2716 static int addSEHHandler(WinEHFuncInfo &FuncInfo, int ParentState, 2717 const Function *Filter, const BasicBlock *Handler) { 2718 SEHUnwindMapEntry Entry; 2719 Entry.ToState = ParentState; 2720 Entry.Filter = Filter; 2721 Entry.Handler = Handler; 2722 FuncInfo.SEHUnwindMap.push_back(Entry); 2723 return FuncInfo.SEHUnwindMap.size() - 1; 2724 } 2725 2726 static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo, 2727 const BasicBlock &BB, 2728 int ParentState) { 2729 assert(BB.isEHPad()); 2730 const Instruction *FirstNonPHI = BB.getFirstNonPHI(); 2731 // All catchpad instructions will be handled when we process their 2732 // respective catchendpad instruction. 2733 if (isa<CatchPadInst>(FirstNonPHI)) 2734 return; 2735 2736 if (isa<CatchEndPadInst>(FirstNonPHI)) { 2737 // Extract the filter function and the __except basic block and create a 2738 // state for them. 2739 SmallVector<const CatchPadInst *, 1> Handlers; 2740 findCatchPadsForCatchEndPad(&BB, Handlers); 2741 assert(Handlers.size() == 1 && 2742 "SEH doesn't have multiple handlers per __try"); 2743 const CatchPadInst *CPI = Handlers.front(); 2744 const BasicBlock *CatchPadBB = CPI->getParent(); 2745 const Function *Filter = 2746 cast<Function>(CPI->getArgOperand(0)->stripPointerCasts()); 2747 int TryState = 2748 addSEHHandler(FuncInfo, ParentState, Filter, CPI->getNormalDest()); 2749 2750 // Everything in the __try block uses TryState as its parent state. 2751 FuncInfo.EHPadStateMap[CPI] = TryState; 2752 DEBUG(dbgs() << "Assigning state #" << TryState << " to BB " 2753 << CatchPadBB->getName() << '\n'); 2754 for (const BasicBlock *PredBlock : predecessors(CatchPadBB)) 2755 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2756 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState); 2757 2758 // Everything in the __except block unwinds to ParentState, just like code 2759 // outside the __try. 2760 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState; 2761 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB " 2762 << BB.getName() << '\n'); 2763 for (const BasicBlock *PredBlock : predecessors(&BB)) 2764 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2765 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState); 2766 } else if (isa<CleanupPadInst>(FirstNonPHI)) { 2767 int CleanupState = 2768 addSEHHandler(FuncInfo, ParentState, /*Filter=*/nullptr, &BB); 2769 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState; 2770 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB " 2771 << BB.getName() << '\n'); 2772 for (const BasicBlock *PredBlock : predecessors(&BB)) 2773 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2774 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState); 2775 } else if (isa<CleanupEndPadInst>(FirstNonPHI)) { 2776 // Anything unwinding through CleanupEndPadInst is in ParentState. 2777 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState; 2778 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB " 2779 << BB.getName() << '\n'); 2780 for (const BasicBlock *PredBlock : predecessors(&BB)) 2781 if ((PredBlock = getEHPadFromPredecessor(PredBlock))) 2782 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState); 2783 } else if (isa<TerminatePadInst>(FirstNonPHI)) { 2784 report_fatal_error("Not yet implemented!"); 2785 } else { 2786 llvm_unreachable("unexpected EH Pad!"); 2787 } 2788 } 2789 2790 /// Check if the EH Pad unwinds to caller. Cleanups are a little bit of a 2791 /// special case because we have to look at the cleanupret instruction that uses 2792 /// the cleanuppad. 2793 static bool doesEHPadUnwindToCaller(const Instruction *EHPad) { 2794 auto *CPI = dyn_cast<CleanupPadInst>(EHPad); 2795 if (!CPI) 2796 return EHPad->mayThrow(); 2797 2798 // This cleanup does not return or unwind, so we say it unwinds to caller. 2799 if (CPI->use_empty()) 2800 return true; 2801 2802 const Instruction *User = CPI->user_back(); 2803 if (auto *CRI = dyn_cast<CleanupReturnInst>(User)) 2804 return CRI->unwindsToCaller(); 2805 return cast<CleanupEndPadInst>(User)->unwindsToCaller(); 2806 } 2807 2808 void llvm::calculateSEHStateNumbers(const Function *Fn, 2809 WinEHFuncInfo &FuncInfo) { 2810 // Don't compute state numbers twice. 2811 if (!FuncInfo.SEHUnwindMap.empty()) 2812 return; 2813 2814 for (const BasicBlock &BB : *Fn) { 2815 if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI())) 2816 continue; 2817 calculateExplicitSEHStateNumbers(FuncInfo, BB, -1); 2818 } 2819 } 2820 2821 void llvm::calculateWinCXXEHStateNumbers(const Function *Fn, 2822 WinEHFuncInfo &FuncInfo) { 2823 // Return if it's already been done. 2824 if (!FuncInfo.EHPadStateMap.empty()) 2825 return; 2826 2827 for (const BasicBlock &BB : *Fn) { 2828 if (!BB.isEHPad()) 2829 continue; 2830 if (BB.isLandingPad()) 2831 report_fatal_error("MSVC C++ EH cannot use landingpads"); 2832 const Instruction *FirstNonPHI = BB.getFirstNonPHI(); 2833 // Skip cleanupendpads; they are exits, not entries. 2834 if (isa<CleanupEndPadInst>(FirstNonPHI)) 2835 continue; 2836 if (!doesEHPadUnwindToCaller(FirstNonPHI)) 2837 continue; 2838 calculateExplicitCXXStateNumbers(FuncInfo, BB, -1); 2839 } 2840 } 2841 2842 void WinEHPrepare::replaceTerminatePadWithCleanup(Function &F) { 2843 if (Personality != EHPersonality::MSVC_CXX) 2844 return; 2845 for (BasicBlock &BB : F) { 2846 Instruction *First = BB.getFirstNonPHI(); 2847 auto *TPI = dyn_cast<TerminatePadInst>(First); 2848 if (!TPI) 2849 continue; 2850 2851 if (TPI->getNumArgOperands() != 1) 2852 report_fatal_error( 2853 "Expected a unary terminatepad for MSVC C++ personalities!"); 2854 2855 auto *TerminateFn = dyn_cast<Function>(TPI->getArgOperand(0)); 2856 if (!TerminateFn) 2857 report_fatal_error("Function operand expected in terminatepad for MSVC " 2858 "C++ personalities!"); 2859 2860 // Insert the cleanuppad instruction. 2861 auto *CPI = CleanupPadInst::Create( 2862 BB.getContext(), {}, Twine("terminatepad.for.", BB.getName()), &BB); 2863 2864 // Insert the call to the terminate instruction. 2865 auto *CallTerminate = CallInst::Create(TerminateFn, {}, &BB); 2866 CallTerminate->setDoesNotThrow(); 2867 CallTerminate->setDoesNotReturn(); 2868 CallTerminate->setCallingConv(TerminateFn->getCallingConv()); 2869 2870 // Insert a new terminator for the cleanuppad using the same successor as 2871 // the terminatepad. 2872 CleanupReturnInst::Create(CPI, TPI->getUnwindDest(), &BB); 2873 2874 // Let's remove the terminatepad now that we've inserted the new 2875 // instructions. 2876 TPI->eraseFromParent(); 2877 } 2878 } 2879 2880 void WinEHPrepare::colorFunclets(Function &F, 2881 SmallVectorImpl<BasicBlock *> &EntryBlocks) { 2882 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist; 2883 BasicBlock *EntryBlock = &F.getEntryBlock(); 2884 2885 // Build up the color map, which maps each block to its set of 'colors'. 2886 // For any block B, the "colors" of B are the set of funclets F (possibly 2887 // including a root "funclet" representing the main function), such that 2888 // F will need to directly contain B or a copy of B (where the term "directly 2889 // contain" is used to distinguish from being "transitively contained" in 2890 // a nested funclet). 2891 // Use a CFG walk driven by a worklist of (block, color) pairs. The "color" 2892 // sets attached during this processing to a block which is the entry of some 2893 // funclet F is actually the set of F's parents -- i.e. the union of colors 2894 // of all predecessors of F's entry. For all other blocks, the color sets 2895 // are as defined above. A post-pass fixes up the block color map to reflect 2896 // the same sense of "color" for funclet entries as for other blocks. 2897 2898 Worklist.push_back({EntryBlock, EntryBlock}); 2899 2900 while (!Worklist.empty()) { 2901 BasicBlock *Visiting; 2902 BasicBlock *Color; 2903 std::tie(Visiting, Color) = Worklist.pop_back_val(); 2904 Instruction *VisitingHead = Visiting->getFirstNonPHI(); 2905 if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) && 2906 !isa<CleanupEndPadInst>(VisitingHead)) { 2907 // Mark this as a funclet head as a member of itself. 2908 FuncletBlocks[Visiting].insert(Visiting); 2909 // Queue exits with the parent color. 2910 for (User *Exit : VisitingHead->users()) { 2911 for (BasicBlock *Succ : 2912 successors(cast<Instruction>(Exit)->getParent())) { 2913 if (BlockColors[Succ].insert(Color).second) { 2914 Worklist.push_back({Succ, Color}); 2915 } 2916 } 2917 } 2918 // Handle CatchPad specially since its successors need different colors. 2919 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) { 2920 // Visit the normal successor with the color of the new EH pad, and 2921 // visit the unwind successor with the color of the parent. 2922 BasicBlock *NormalSucc = CatchPad->getNormalDest(); 2923 if (BlockColors[NormalSucc].insert(Visiting).second) { 2924 Worklist.push_back({NormalSucc, Visiting}); 2925 } 2926 BasicBlock *UnwindSucc = CatchPad->getUnwindDest(); 2927 if (BlockColors[UnwindSucc].insert(Color).second) { 2928 Worklist.push_back({UnwindSucc, Color}); 2929 } 2930 continue; 2931 } 2932 // Switch color to the current node, except for terminate pads which 2933 // have no bodies and only unwind successors and so need their successors 2934 // visited with the color of the parent. 2935 if (!isa<TerminatePadInst>(VisitingHead)) 2936 Color = Visiting; 2937 } else { 2938 // Note that this is a member of the given color. 2939 FuncletBlocks[Color].insert(Visiting); 2940 } 2941 2942 TerminatorInst *Terminator = Visiting->getTerminator(); 2943 if (isa<CleanupReturnInst>(Terminator) || 2944 isa<CatchReturnInst>(Terminator) || 2945 isa<CleanupEndPadInst>(Terminator)) { 2946 // These blocks' successors have already been queued with the parent 2947 // color. 2948 continue; 2949 } 2950 for (BasicBlock *Succ : successors(Visiting)) { 2951 if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) { 2952 // The catchendpad needs to be visited with the parent's color, not 2953 // the current color. This will happen in the code above that visits 2954 // any catchpad unwind successor with the parent color, so we can 2955 // safely skip this successor here. 2956 continue; 2957 } 2958 if (BlockColors[Succ].insert(Color).second) { 2959 Worklist.push_back({Succ, Color}); 2960 } 2961 } 2962 } 2963 2964 // The processing above actually accumulated the parent set for this 2965 // funclet into the color set for its entry; use the parent set to 2966 // populate the children map, and reset the color set to include just 2967 // the funclet itself (no instruction can target a funclet entry except on 2968 // that transitions to the child funclet). 2969 for (BasicBlock *FuncletEntry : EntryBlocks) { 2970 std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry]; 2971 for (BasicBlock *Parent : ColorMapItem) 2972 FuncletChildren[Parent].insert(FuncletEntry); 2973 ColorMapItem.clear(); 2974 ColorMapItem.insert(FuncletEntry); 2975 } 2976 } 2977 2978 void WinEHPrepare::demotePHIsOnFunclets(Function &F) { 2979 // Strip PHI nodes off of EH pads. 2980 SmallVector<PHINode *, 16> PHINodes; 2981 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 2982 BasicBlock *BB = FI++; 2983 if (!BB->isEHPad()) 2984 continue; 2985 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { 2986 Instruction *I = BI++; 2987 auto *PN = dyn_cast<PHINode>(I); 2988 // Stop at the first non-PHI. 2989 if (!PN) 2990 break; 2991 2992 AllocaInst *SpillSlot = insertPHILoads(PN, F); 2993 if (SpillSlot) 2994 insertPHIStores(PN, SpillSlot); 2995 2996 PHINodes.push_back(PN); 2997 } 2998 } 2999 3000 for (auto *PN : PHINodes) { 3001 // There may be lingering uses on other EH PHIs being removed 3002 PN->replaceAllUsesWith(UndefValue::get(PN->getType())); 3003 PN->eraseFromParent(); 3004 } 3005 } 3006 3007 void WinEHPrepare::demoteUsesBetweenFunclets(Function &F) { 3008 // Turn all inter-funclet uses of a Value into loads and stores. 3009 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 3010 BasicBlock *BB = FI++; 3011 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB]; 3012 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) { 3013 Instruction *I = BI++; 3014 // Funclets are permitted to use static allocas. 3015 if (auto *AI = dyn_cast<AllocaInst>(I)) 3016 if (AI->isStaticAlloca()) 3017 continue; 3018 3019 demoteNonlocalUses(I, ColorsForBB, F); 3020 } 3021 } 3022 } 3023 3024 void WinEHPrepare::demoteArgumentUses(Function &F) { 3025 // Also demote function parameters used in funclets. 3026 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()]; 3027 for (Argument &Arg : F.args()) 3028 demoteNonlocalUses(&Arg, ColorsForEntry, F); 3029 } 3030 3031 void WinEHPrepare::cloneCommonBlocks( 3032 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) { 3033 // We need to clone all blocks which belong to multiple funclets. Values are 3034 // remapped throughout the funclet to propogate both the new instructions 3035 // *and* the new basic blocks themselves. 3036 for (BasicBlock *FuncletPadBB : EntryBlocks) { 3037 std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB]; 3038 3039 std::map<BasicBlock *, BasicBlock *> Orig2Clone; 3040 ValueToValueMapTy VMap; 3041 for (BasicBlock *BB : BlocksInFunclet) { 3042 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB]; 3043 // We don't need to do anything if the block is monochromatic. 3044 size_t NumColorsForBB = ColorsForBB.size(); 3045 if (NumColorsForBB == 1) 3046 continue; 3047 3048 // Create a new basic block and copy instructions into it! 3049 BasicBlock *CBB = 3050 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName())); 3051 // Insert the clone immediately after the original to ensure determinism 3052 // and to keep the same relative ordering of any funclet's blocks. 3053 CBB->insertInto(&F, BB->getNextNode()); 3054 3055 // Add basic block mapping. 3056 VMap[BB] = CBB; 3057 3058 // Record delta operations that we need to perform to our color mappings. 3059 Orig2Clone[BB] = CBB; 3060 } 3061 3062 // Update our color mappings to reflect that one block has lost a color and 3063 // another has gained a color. 3064 for (auto &BBMapping : Orig2Clone) { 3065 BasicBlock *OldBlock = BBMapping.first; 3066 BasicBlock *NewBlock = BBMapping.second; 3067 3068 BlocksInFunclet.insert(NewBlock); 3069 BlockColors[NewBlock].insert(FuncletPadBB); 3070 3071 BlocksInFunclet.erase(OldBlock); 3072 BlockColors[OldBlock].erase(FuncletPadBB); 3073 } 3074 3075 // Loop over all of the instructions in the function, fixing up operand 3076 // references as we go. This uses VMap to do all the hard work. 3077 for (BasicBlock *BB : BlocksInFunclet) 3078 // Loop over all instructions, fixing each one as we find it... 3079 for (Instruction &I : *BB) 3080 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries); 3081 3082 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to 3083 // the PHI nodes for NewBB now. 3084 for (auto &BBMapping : Orig2Clone) { 3085 BasicBlock *OldBlock = BBMapping.first; 3086 BasicBlock *NewBlock = BBMapping.second; 3087 for (BasicBlock *SuccBB : successors(NewBlock)) { 3088 for (Instruction &SuccI : *SuccBB) { 3089 auto *SuccPN = dyn_cast<PHINode>(&SuccI); 3090 if (!SuccPN) 3091 break; 3092 3093 // Ok, we have a PHI node. Figure out what the incoming value was for 3094 // the OldBlock. 3095 int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock); 3096 if (OldBlockIdx == -1) 3097 break; 3098 Value *IV = SuccPN->getIncomingValue(OldBlockIdx); 3099 3100 // Remap the value if necessary. 3101 if (auto *Inst = dyn_cast<Instruction>(IV)) { 3102 ValueToValueMapTy::iterator I = VMap.find(Inst); 3103 if (I != VMap.end()) 3104 IV = I->second; 3105 } 3106 3107 SuccPN->addIncoming(IV, NewBlock); 3108 } 3109 } 3110 } 3111 3112 for (ValueToValueMapTy::value_type VT : VMap) { 3113 // If there were values defined in BB that are used outside the funclet, 3114 // then we now have to update all uses of the value to use either the 3115 // original value, the cloned value, or some PHI derived value. This can 3116 // require arbitrary PHI insertion, of which we are prepared to do, clean 3117 // these up now. 3118 SmallVector<Use *, 16> UsesToRename; 3119 3120 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first)); 3121 if (!OldI) 3122 continue; 3123 auto *NewI = cast<Instruction>(VT.second); 3124 // Scan all uses of this instruction to see if it is used outside of its 3125 // funclet, and if so, record them in UsesToRename. 3126 for (Use &U : OldI->uses()) { 3127 Instruction *UserI = cast<Instruction>(U.getUser()); 3128 BasicBlock *UserBB = UserI->getParent(); 3129 std::set<BasicBlock *> &ColorsForUserBB = BlockColors[UserBB]; 3130 assert(!ColorsForUserBB.empty()); 3131 if (ColorsForUserBB.size() > 1 || 3132 *ColorsForUserBB.begin() != FuncletPadBB) 3133 UsesToRename.push_back(&U); 3134 } 3135 3136 // If there are no uses outside the block, we're done with this 3137 // instruction. 3138 if (UsesToRename.empty()) 3139 continue; 3140 3141 // We found a use of OldI outside of the funclet. Rename all uses of OldI 3142 // that are outside its funclet to be uses of the appropriate PHI node 3143 // etc. 3144 SSAUpdater SSAUpdate; 3145 SSAUpdate.Initialize(OldI->getType(), OldI->getName()); 3146 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI); 3147 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI); 3148 3149 while (!UsesToRename.empty()) 3150 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val()); 3151 } 3152 } 3153 } 3154 3155 void WinEHPrepare::removeImplausibleTerminators(Function &F) { 3156 // Remove implausible terminators and replace them with UnreachableInst. 3157 for (auto &Funclet : FuncletBlocks) { 3158 BasicBlock *FuncletPadBB = Funclet.first; 3159 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second; 3160 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI(); 3161 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI); 3162 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI); 3163 3164 for (BasicBlock *BB : BlocksInFunclet) { 3165 TerminatorInst *TI = BB->getTerminator(); 3166 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst. 3167 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad); 3168 // The token consumed by a CatchReturnInst must match the funclet token. 3169 bool IsUnreachableCatchret = false; 3170 if (auto *CRI = dyn_cast<CatchReturnInst>(TI)) 3171 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad; 3172 // The token consumed by a CleanupReturnInst must match the funclet token. 3173 bool IsUnreachableCleanupret = false; 3174 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) 3175 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad; 3176 // The token consumed by a CleanupEndPadInst must match the funclet token. 3177 bool IsUnreachableCleanupendpad = false; 3178 if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI)) 3179 IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad; 3180 if (IsUnreachableRet || IsUnreachableCatchret || 3181 IsUnreachableCleanupret || IsUnreachableCleanupendpad) { 3182 // Loop through all of our successors and make sure they know that one 3183 // of their predecessors is going away. 3184 for (BasicBlock *SuccBB : TI->successors()) 3185 SuccBB->removePredecessor(BB); 3186 3187 new UnreachableInst(BB->getContext(), TI); 3188 TI->eraseFromParent(); 3189 } 3190 } 3191 } 3192 } 3193 3194 void WinEHPrepare::cleanupPreparedFunclets(Function &F) { 3195 // Clean-up some of the mess we made by removing useles PHI nodes, trivial 3196 // branches, etc. 3197 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) { 3198 BasicBlock *BB = FI++; 3199 SimplifyInstructionsInBlock(BB); 3200 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true); 3201 MergeBlockIntoPredecessor(BB); 3202 } 3203 3204 // We might have some unreachable blocks after cleaning up some impossible 3205 // control flow. 3206 removeUnreachableBlocks(F); 3207 } 3208 3209 void WinEHPrepare::verifyPreparedFunclets(Function &F) { 3210 // Recolor the CFG to verify that all is well. 3211 for (BasicBlock &BB : F) { 3212 size_t NumColors = BlockColors[&BB].size(); 3213 assert(NumColors == 1 && "Expected monochromatic BB!"); 3214 if (NumColors == 0) 3215 report_fatal_error("Uncolored BB!"); 3216 if (NumColors > 1) 3217 report_fatal_error("Multicolor BB!"); 3218 if (!DisableDemotion) { 3219 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin()); 3220 assert(!EHPadHasPHI && "EH Pad still has a PHI!"); 3221 if (EHPadHasPHI) 3222 report_fatal_error("EH Pad still has a PHI!"); 3223 } 3224 } 3225 } 3226 3227 bool WinEHPrepare::prepareExplicitEH( 3228 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) { 3229 // Remove unreachable blocks. It is not valuable to assign them a color and 3230 // their existence can trick us into thinking values are alive when they are 3231 // not. 3232 removeUnreachableBlocks(F); 3233 3234 replaceTerminatePadWithCleanup(F); 3235 3236 // Determine which blocks are reachable from which funclet entries. 3237 colorFunclets(F, EntryBlocks); 3238 3239 if (!DisableDemotion) { 3240 demotePHIsOnFunclets(F); 3241 3242 demoteUsesBetweenFunclets(F); 3243 3244 demoteArgumentUses(F); 3245 } 3246 3247 cloneCommonBlocks(F, EntryBlocks); 3248 3249 if (!DisableCleanups) { 3250 removeImplausibleTerminators(F); 3251 3252 cleanupPreparedFunclets(F); 3253 } 3254 3255 verifyPreparedFunclets(F); 3256 3257 BlockColors.clear(); 3258 FuncletBlocks.clear(); 3259 FuncletChildren.clear(); 3260 3261 return true; 3262 } 3263 3264 // TODO: Share loads when one use dominates another, or when a catchpad exit 3265 // dominates uses (needs dominators). 3266 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) { 3267 BasicBlock *PHIBlock = PN->getParent(); 3268 AllocaInst *SpillSlot = nullptr; 3269 3270 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) { 3271 // Insert a load in place of the PHI and replace all uses. 3272 SpillSlot = new AllocaInst(PN->getType(), nullptr, 3273 Twine(PN->getName(), ".wineh.spillslot"), 3274 F.getEntryBlock().begin()); 3275 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"), 3276 PHIBlock->getFirstInsertionPt()); 3277 PN->replaceAllUsesWith(V); 3278 return SpillSlot; 3279 } 3280 3281 DenseMap<BasicBlock *, Value *> Loads; 3282 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end(); 3283 UI != UE;) { 3284 Use &U = *UI++; 3285 auto *UsingInst = cast<Instruction>(U.getUser()); 3286 BasicBlock *UsingBB = UsingInst->getParent(); 3287 if (UsingBB->isEHPad()) { 3288 // Use is on an EH pad phi. Leave it alone; we'll insert loads and 3289 // stores for it separately. 3290 assert(isa<PHINode>(UsingInst)); 3291 continue; 3292 } 3293 replaceUseWithLoad(PN, U, SpillSlot, Loads, F); 3294 } 3295 return SpillSlot; 3296 } 3297 3298 // TODO: improve store placement. Inserting at def is probably good, but need 3299 // to be careful not to introduce interfering stores (needs liveness analysis). 3300 // TODO: identify related phi nodes that can share spill slots, and share them 3301 // (also needs liveness). 3302 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI, 3303 AllocaInst *SpillSlot) { 3304 // Use a worklist of (Block, Value) pairs -- the given Value needs to be 3305 // stored to the spill slot by the end of the given Block. 3306 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist; 3307 3308 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI}); 3309 3310 while (!Worklist.empty()) { 3311 BasicBlock *EHBlock; 3312 Value *InVal; 3313 std::tie(EHBlock, InVal) = Worklist.pop_back_val(); 3314 3315 PHINode *PN = dyn_cast<PHINode>(InVal); 3316 if (PN && PN->getParent() == EHBlock) { 3317 // The value is defined by another PHI we need to remove, with no room to 3318 // insert a store after the PHI, so each predecessor needs to store its 3319 // incoming value. 3320 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) { 3321 Value *PredVal = PN->getIncomingValue(i); 3322 3323 // Undef can safely be skipped. 3324 if (isa<UndefValue>(PredVal)) 3325 continue; 3326 3327 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist); 3328 } 3329 } else { 3330 // We need to store InVal, which dominates EHBlock, but can't put a store 3331 // in EHBlock, so need to put stores in each predecessor. 3332 for (BasicBlock *PredBlock : predecessors(EHBlock)) { 3333 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist); 3334 } 3335 } 3336 } 3337 } 3338 3339 void WinEHPrepare::insertPHIStore( 3340 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot, 3341 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) { 3342 3343 if (PredBlock->isEHPad() && 3344 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) { 3345 // Pred is unsplittable, so we need to queue it on the worklist. 3346 Worklist.push_back({PredBlock, PredVal}); 3347 return; 3348 } 3349 3350 // Otherwise, insert the store at the end of the basic block. 3351 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator()); 3352 } 3353 3354 // TODO: Share loads for same-funclet uses (requires dominators if funclets 3355 // aren't properly nested). 3356 void WinEHPrepare::demoteNonlocalUses(Value *V, 3357 std::set<BasicBlock *> &ColorsForBB, 3358 Function &F) { 3359 // Tokens can only be used non-locally due to control flow involving 3360 // unreachable edges. Don't try to demote the token usage, we'll simply 3361 // delete the cloned user later. 3362 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V)) 3363 return; 3364 3365 DenseMap<BasicBlock *, Value *> Loads; 3366 AllocaInst *SpillSlot = nullptr; 3367 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) { 3368 Use &U = *UI++; 3369 auto *UsingInst = cast<Instruction>(U.getUser()); 3370 BasicBlock *UsingBB = UsingInst->getParent(); 3371 3372 // Is the Use inside a block which is colored the same as the Def? 3373 // If so, we don't need to escape the Def because we will clone 3374 // ourselves our own private copy. 3375 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB]; 3376 if (ColorsForUsingBB == ColorsForBB) 3377 continue; 3378 3379 replaceUseWithLoad(V, U, SpillSlot, Loads, F); 3380 } 3381 if (SpillSlot) { 3382 // Insert stores of the computed value into the stack slot. 3383 // We have to be careful if I is an invoke instruction, 3384 // because we can't insert the store AFTER the terminator instruction. 3385 BasicBlock::iterator InsertPt; 3386 if (isa<Argument>(V)) { 3387 InsertPt = F.getEntryBlock().getTerminator(); 3388 } else if (isa<TerminatorInst>(V)) { 3389 auto *II = cast<InvokeInst>(V); 3390 // We cannot demote invoke instructions to the stack if their normal 3391 // edge is critical. Therefore, split the critical edge and create a 3392 // basic block into which the store can be inserted. 3393 if (!II->getNormalDest()->getSinglePredecessor()) { 3394 unsigned SuccNum = 3395 GetSuccessorNumber(II->getParent(), II->getNormalDest()); 3396 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!"); 3397 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum); 3398 assert(NewBlock && "Unable to split critical edge."); 3399 // Update the color mapping for the newly split edge. 3400 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()]; 3401 BlockColors[NewBlock] = ColorsForUsingBB; 3402 for (BasicBlock *FuncletPad : ColorsForUsingBB) 3403 FuncletBlocks[FuncletPad].insert(NewBlock); 3404 } 3405 InsertPt = II->getNormalDest()->getFirstInsertionPt(); 3406 } else { 3407 InsertPt = cast<Instruction>(V); 3408 ++InsertPt; 3409 // Don't insert before PHI nodes or EH pad instrs. 3410 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt) 3411 ; 3412 } 3413 new StoreInst(V, SpillSlot, InsertPt); 3414 } 3415 } 3416 3417 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot, 3418 DenseMap<BasicBlock *, Value *> &Loads, 3419 Function &F) { 3420 // Lazilly create the spill slot. 3421 if (!SpillSlot) 3422 SpillSlot = new AllocaInst(V->getType(), nullptr, 3423 Twine(V->getName(), ".wineh.spillslot"), 3424 F.getEntryBlock().begin()); 3425 3426 auto *UsingInst = cast<Instruction>(U.getUser()); 3427 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) { 3428 // If this is a PHI node, we can't insert a load of the value before 3429 // the use. Instead insert the load in the predecessor block 3430 // corresponding to the incoming value. 3431 // 3432 // Note that if there are multiple edges from a basic block to this 3433 // PHI node that we cannot have multiple loads. The problem is that 3434 // the resulting PHI node will have multiple values (from each load) 3435 // coming in from the same block, which is illegal SSA form. 3436 // For this reason, we keep track of and reuse loads we insert. 3437 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U); 3438 if (auto *CatchRet = 3439 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) { 3440 // Putting a load above a catchret and use on the phi would still leave 3441 // a cross-funclet def/use. We need to split the edge, change the 3442 // catchret to target the new block, and put the load there. 3443 BasicBlock *PHIBlock = UsingInst->getParent(); 3444 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock); 3445 // SplitEdge gives us: 3446 // IncomingBlock: 3447 // ... 3448 // br label %NewBlock 3449 // NewBlock: 3450 // catchret label %PHIBlock 3451 // But we need: 3452 // IncomingBlock: 3453 // ... 3454 // catchret label %NewBlock 3455 // NewBlock: 3456 // br label %PHIBlock 3457 // So move the terminators to each others' blocks and swap their 3458 // successors. 3459 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator()); 3460 Goto->removeFromParent(); 3461 CatchRet->removeFromParent(); 3462 IncomingBlock->getInstList().push_back(CatchRet); 3463 NewBlock->getInstList().push_back(Goto); 3464 Goto->setSuccessor(0, PHIBlock); 3465 CatchRet->setSuccessor(NewBlock); 3466 // Update the color mapping for the newly split edge. 3467 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock]; 3468 BlockColors[NewBlock] = ColorsForPHIBlock; 3469 for (BasicBlock *FuncletPad : ColorsForPHIBlock) 3470 FuncletBlocks[FuncletPad].insert(NewBlock); 3471 // Treat the new block as incoming for load insertion. 3472 IncomingBlock = NewBlock; 3473 } 3474 Value *&Load = Loads[IncomingBlock]; 3475 // Insert the load into the predecessor block 3476 if (!Load) 3477 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"), 3478 /*Volatile=*/false, IncomingBlock->getTerminator()); 3479 3480 U.set(Load); 3481 } else { 3482 // Reload right before the old use. 3483 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"), 3484 /*Volatile=*/false, UsingInst); 3485 U.set(Load); 3486 } 3487 } 3488