1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
17 //===----------------------------------------------------------------------===//
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"
47 using namespace llvm::PatternMatch;
49 #define DEBUG_TYPE "winehprepare"
53 // This map is used to model frame variable usage during outlining, to
54 // construct a structure type to hold the frame variables in a frame
55 // allocation block, and to remap the frame variable allocas (including
56 // spill locations as needed) to GEPs that get the variable from the
57 // frame allocation structure.
58 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
60 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
62 AllocaInst *getCatchObjectSentinel() {
63 return static_cast<AllocaInst *>(nullptr) + 1;
66 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
68 class LandingPadActions;
71 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
72 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
74 class WinEHPrepare : public FunctionPass {
76 static char ID; // Pass identification, replacement for typeid.
77 WinEHPrepare(const TargetMachine *TM = nullptr)
80 TheTriple = TM->getTargetTriple();
83 bool runOnFunction(Function &Fn) override;
85 bool doFinalization(Module &M) override;
87 void getAnalysisUsage(AnalysisUsage &AU) const override;
89 const char *getPassName() const override {
90 return "Windows exception handling preparation";
94 bool prepareExceptionHandlers(Function &F,
95 SmallVectorImpl<LandingPadInst *> &LPads);
96 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
97 void promoteLandingPadValues(LandingPadInst *LPad);
98 void demoteValuesLiveAcrossHandlers(Function &F,
99 SmallVectorImpl<LandingPadInst *> &LPads);
100 void findSEHEHReturnPoints(Function &F,
101 SetVector<BasicBlock *> &EHReturnBlocks);
102 void findCXXEHReturnPoints(Function &F,
103 SetVector<BasicBlock *> &EHReturnBlocks);
104 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
105 SetVector<BasicBlock*> &Targets);
106 void completeNestedLandingPad(Function *ParentFn,
107 LandingPadInst *OutlinedLPad,
108 const LandingPadInst *OriginalLPad,
109 FrameVarInfoMap &VarInfo);
110 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
111 const Twine &Name, Module *M, Value *&ParentFP);
112 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
113 LandingPadInst *LPad, BasicBlock *StartBB,
114 FrameVarInfoMap &VarInfo);
115 void addStubInvokeToHandlerIfNeeded(Function *Handler);
117 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
118 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
119 VisitedBlockSet &VisitedBlocks);
120 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
123 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
124 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
126 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
127 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
128 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
129 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
130 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
131 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
133 bool prepareExplicitEH(Function &F);
134 void numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB);
138 // All fields are reset by runOnFunction.
139 DominatorTree *DT = nullptr;
140 const TargetLibraryInfo *LibInfo = nullptr;
141 EHPersonality Personality = EHPersonality::Unknown;
142 CatchHandlerMapTy CatchHandlerMap;
143 CleanupHandlerMapTy CleanupHandlerMap;
144 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
145 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
146 SmallPtrSet<BasicBlock *, 4> EHBlocks;
147 SetVector<BasicBlock *> EHReturnBlocks;
149 // This maps landing pad instructions found in outlined handlers to
150 // the landing pad instruction in the parent function from which they
151 // were cloned. The cloned/nested landing pad is used as the key
152 // because the landing pad may be cloned into multiple handlers.
153 // This map will be used to add the llvm.eh.actions call to the nested
154 // landing pads after all handlers have been outlined.
155 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
157 // This maps blocks in the parent function which are destinations of
158 // catch handlers to cloned blocks in (other) outlined handlers. This
159 // handles the case where a nested landing pads has a catch handler that
160 // returns to a handler function rather than the parent function.
161 // The original block is used as the key here because there should only
162 // ever be one handler function from which the cloned block is not pruned.
163 // The original block will be pruned from the parent function after all
164 // handlers have been outlined. This map will be used to adjust the
165 // return instructions of handlers which return to the block that was
166 // outlined into a handler. This is done after all handlers have been
167 // outlined but before the outlined code is pruned from the parent function.
168 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
170 // Map from outlined handler to call to parent local address. Only used for
172 DenseMap<Function *, Value *> HandlerToParentFP;
174 AllocaInst *SEHExceptionCodeSlot = nullptr;
176 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
177 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
180 class WinEHFrameVariableMaterializer : public ValueMaterializer {
182 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
183 FrameVarInfoMap &FrameVarInfo);
184 ~WinEHFrameVariableMaterializer() override {}
186 Value *materializeValueFor(Value *V) override;
188 void escapeCatchObject(Value *V);
191 FrameVarInfoMap &FrameVarInfo;
195 class LandingPadMap {
197 LandingPadMap() : OriginLPad(nullptr) {}
198 void mapLandingPad(const LandingPadInst *LPad);
200 bool isInitialized() { return OriginLPad != nullptr; }
202 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
203 bool isLandingPadSpecificInst(const Instruction *Inst) const;
205 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
206 Value *SelectorValue) const;
209 const LandingPadInst *OriginLPad;
210 // We will normally only see one of each of these instructions, but
211 // if more than one occurs for some reason we can handle that.
212 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
213 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
216 class WinEHCloningDirectorBase : public CloningDirector {
218 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
219 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
220 : Materializer(HandlerFn, ParentFP, VarInfo),
221 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
222 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
223 LPadMap(LPadMap), ParentFP(ParentFP) {}
225 CloningAction handleInstruction(ValueToValueMapTy &VMap,
226 const Instruction *Inst,
227 BasicBlock *NewBB) override;
229 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
230 const Instruction *Inst,
231 BasicBlock *NewBB) = 0;
232 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
233 const Instruction *Inst,
234 BasicBlock *NewBB) = 0;
235 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
236 const Instruction *Inst,
237 BasicBlock *NewBB) = 0;
238 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
239 const IndirectBrInst *IBr,
240 BasicBlock *NewBB) = 0;
241 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
242 const InvokeInst *Invoke,
243 BasicBlock *NewBB) = 0;
244 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
245 const ResumeInst *Resume,
246 BasicBlock *NewBB) = 0;
247 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
248 const CmpInst *Compare,
249 BasicBlock *NewBB) = 0;
250 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
251 const LandingPadInst *LPad,
252 BasicBlock *NewBB) = 0;
254 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
257 WinEHFrameVariableMaterializer Materializer;
258 Type *SelectorIDType;
260 LandingPadMap &LPadMap;
262 /// The value representing the parent frame pointer.
266 class WinEHCatchDirector : public WinEHCloningDirectorBase {
269 Function *CatchFn, Value *ParentFP, Value *Selector,
270 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
271 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
272 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
273 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
274 CurrentSelector(Selector->stripPointerCasts()),
275 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
276 DT(DT), EHBlocks(EHBlocks) {}
278 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
279 const Instruction *Inst,
280 BasicBlock *NewBB) override;
281 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
282 BasicBlock *NewBB) override;
283 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
284 const Instruction *Inst,
285 BasicBlock *NewBB) override;
286 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
287 const IndirectBrInst *IBr,
288 BasicBlock *NewBB) override;
289 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
290 BasicBlock *NewBB) override;
291 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
292 BasicBlock *NewBB) override;
293 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
294 BasicBlock *NewBB) override;
295 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
296 const LandingPadInst *LPad,
297 BasicBlock *NewBB) override;
299 Value *getExceptionVar() { return ExceptionObjectVar; }
300 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
303 Value *CurrentSelector;
305 Value *ExceptionObjectVar;
306 TinyPtrVector<BasicBlock *> ReturnTargets;
308 // This will be a reference to the field of the same name in the WinEHPrepare
309 // object which instantiates this WinEHCatchDirector object.
310 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
312 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
315 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
317 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
318 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
319 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
322 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
323 const Instruction *Inst,
324 BasicBlock *NewBB) override;
325 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
326 BasicBlock *NewBB) override;
327 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
328 const Instruction *Inst,
329 BasicBlock *NewBB) override;
330 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
331 const IndirectBrInst *IBr,
332 BasicBlock *NewBB) override;
333 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
334 BasicBlock *NewBB) override;
335 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
336 BasicBlock *NewBB) override;
337 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
338 BasicBlock *NewBB) override;
339 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
340 const LandingPadInst *LPad,
341 BasicBlock *NewBB) override;
344 class LandingPadActions {
346 LandingPadActions() : HasCleanupHandlers(false) {}
348 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
349 void insertCleanupHandler(CleanupHandler *Action) {
350 Actions.push_back(Action);
351 HasCleanupHandlers = true;
354 bool includesCleanup() const { return HasCleanupHandlers; }
356 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
357 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
358 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
361 // Note that this class does not own the ActionHandler objects in this vector.
362 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
363 // in the WinEHPrepare class.
364 SmallVector<ActionHandler *, 4> Actions;
365 bool HasCleanupHandlers;
368 } // end anonymous namespace
370 char WinEHPrepare::ID = 0;
371 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
374 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
375 return new WinEHPrepare(TM);
378 bool WinEHPrepare::runOnFunction(Function &Fn) {
379 if (!Fn.hasPersonalityFn())
382 // No need to prepare outlined handlers.
383 if (Fn.hasFnAttribute("wineh-parent"))
386 // Classify the personality to see what kind of preparation we need.
387 Personality = classifyEHPersonality(Fn.getPersonalityFn());
389 // Do nothing if this is not an MSVC personality.
390 if (!isMSVCEHPersonality(Personality))
393 SmallVector<LandingPadInst *, 4> LPads;
394 SmallVector<ResumeInst *, 4> Resumes;
395 bool ForExplicitEH = false;
396 for (BasicBlock &BB : Fn) {
397 if (auto *LP = BB.getLandingPadInst()) {
399 } else if (BB.getFirstNonPHI()->isEHPad()) {
400 ForExplicitEH = true;
403 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
404 Resumes.push_back(Resume);
408 return prepareExplicitEH(Fn);
410 // No need to prepare functions that lack landing pads.
414 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
415 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
417 // If there were any landing pads, prepareExceptionHandlers will make changes.
418 prepareExceptionHandlers(Fn, LPads);
422 bool WinEHPrepare::doFinalization(Module &M) { return false; }
424 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
425 AU.addRequired<DominatorTreeWrapperPass>();
426 AU.addRequired<TargetLibraryInfoWrapperPass>();
429 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
430 Constant *&Selector, BasicBlock *&NextBB);
432 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
433 // edges or blocks listed in StopPoints.
434 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
435 SetVector<BasicBlock *> &Worklist,
436 const SetVector<BasicBlock *> *StopPoints) {
437 while (!Worklist.empty()) {
438 BasicBlock *BB = Worklist.pop_back_val();
440 // Don't cross blocks that we should stop at.
441 if (StopPoints && StopPoints->count(BB))
444 if (!ReachableBBs.insert(BB).second)
445 continue; // Already visited.
447 // Don't follow unwind edges of invokes.
448 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
449 Worklist.insert(II->getNormalDest());
453 // Otherwise, follow all successors.
454 Worklist.insert(succ_begin(BB), succ_end(BB));
458 // Attempt to find an instruction where a block can be split before
459 // a call to llvm.eh.begincatch and its operands. If the block
460 // begins with the begincatch call or one of its adjacent operands
461 // the block will not be split.
462 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
464 // If the begincatch call is already the first instruction in the block,
466 Instruction *FirstNonPHI = BB->getFirstNonPHI();
467 if (II == FirstNonPHI)
470 // If either operand is in the same basic block as the instruction and
471 // isn't used by another instruction before the begincatch call, include it
472 // in the split block.
473 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
474 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
476 Instruction *I = II->getPrevNode();
477 Instruction *LastI = II;
479 while (I == Op0 || I == Op1) {
480 // If the block begins with one of the operands and there are no other
481 // instructions between the operand and the begincatch call, don't split.
482 if (I == FirstNonPHI)
486 I = I->getPrevNode();
489 // If there is at least one instruction in the block before the begincatch
490 // call and its operands, split the block at either the begincatch or
495 /// Find all points where exceptional control rejoins normal control flow via
496 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
497 void WinEHPrepare::findCXXEHReturnPoints(
498 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
499 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
500 BasicBlock *BB = BBI;
501 for (Instruction &I : *BB) {
502 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
503 Instruction *SplitPt =
504 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
506 // Split the block before the llvm.eh.begincatch call to allow
507 // cleanup and catch code to be distinguished later.
508 // Do not update BBI because we still need to process the
509 // portion of the block that we are splitting off.
510 SplitBlock(BB, SplitPt, DT);
514 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
515 // Split the block after the call to llvm.eh.endcatch if there is
516 // anything other than an unconditional branch, or if the successor
517 // starts with a phi.
518 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
519 if (!Br || !Br->isUnconditional() ||
520 isa<PHINode>(Br->getSuccessor(0)->begin())) {
521 DEBUG(dbgs() << "splitting block " << BB->getName()
522 << " with llvm.eh.endcatch\n");
523 BBI = SplitBlock(BB, I.getNextNode(), DT);
525 // The next BB is normal control flow.
526 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
533 static bool isCatchAllLandingPad(const BasicBlock *BB) {
534 const LandingPadInst *LP = BB->getLandingPadInst();
537 unsigned N = LP->getNumClauses();
538 return (N > 0 && LP->isCatch(N - 1) &&
539 isa<ConstantPointerNull>(LP->getClause(N - 1)));
542 /// Find all points where exceptions control rejoins normal control flow via
543 /// selector dispatch.
544 void WinEHPrepare::findSEHEHReturnPoints(
545 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
546 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
547 BasicBlock *BB = BBI;
548 // If the landingpad is a catch-all, treat the whole lpad as if it is
549 // reachable from normal control flow.
550 // FIXME: This is imprecise. We need a better way of identifying where a
551 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
553 if (isCatchAllLandingPad(BB)) {
554 EHReturnBlocks.insert(BB);
558 BasicBlock *CatchHandler;
561 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
562 // Split the edge if there are multiple predecessors. This creates a place
563 // where we can insert EH recovery code.
564 if (!CatchHandler->getSinglePredecessor()) {
565 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
566 << " to " << CatchHandler->getName() << '\n');
567 BBI = CatchHandler = SplitCriticalEdge(
568 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
570 EHReturnBlocks.insert(CatchHandler);
575 void WinEHPrepare::identifyEHBlocks(Function &F,
576 SmallVectorImpl<LandingPadInst *> &LPads) {
577 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
578 << F.getName() << '\n');
580 // Build a set of all non-exceptional blocks and exceptional blocks.
581 // - Non-exceptional blocks are blocks reachable from the entry block while
582 // not following invoke unwind edges.
583 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
584 // not follow llvm.eh.endcatch blocks, which mark a transition from
585 // exceptional to normal control.
587 if (Personality == EHPersonality::MSVC_CXX)
588 findCXXEHReturnPoints(F, EHReturnBlocks);
590 findSEHEHReturnPoints(F, EHReturnBlocks);
593 dbgs() << "identified the following blocks as EH return points:\n";
594 for (BasicBlock *BB : EHReturnBlocks)
595 dbgs() << " " << BB->getName() << '\n';
598 // Join points should not have phis at this point, unless they are a
599 // landingpad, in which case we will demote their phis later.
601 for (BasicBlock *BB : EHReturnBlocks)
602 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
603 "non-lpad EH return block has phi");
606 // Normal blocks are the blocks reachable from the entry block and all EH
608 SetVector<BasicBlock *> Worklist;
609 Worklist = EHReturnBlocks;
610 Worklist.insert(&F.getEntryBlock());
611 findReachableBlocks(NormalBlocks, Worklist, nullptr);
613 dbgs() << "marked the following blocks as normal:\n";
614 for (BasicBlock *BB : NormalBlocks)
615 dbgs() << " " << BB->getName() << '\n';
618 // Exceptional blocks are the blocks reachable from landingpads that don't
619 // cross EH return points.
621 for (auto *LPI : LPads)
622 Worklist.insert(LPI->getParent());
623 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
625 dbgs() << "marked the following blocks as exceptional:\n";
626 for (BasicBlock *BB : EHBlocks)
627 dbgs() << " " << BB->getName() << '\n';
632 /// Ensure that all values live into and out of exception handlers are stored
634 /// FIXME: This falls down when values are defined in one handler and live into
635 /// another handler. For example, a cleanup defines a value used only by a
637 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
638 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
639 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
640 << F.getName() << '\n');
642 // identifyEHBlocks() should have been called before this function.
643 assert(!NormalBlocks.empty());
645 // Try to avoid demoting EH pointer and selector values. They get in the way
646 // of our pattern matching.
647 SmallPtrSet<Instruction *, 10> EHVals;
648 for (BasicBlock &BB : F) {
649 LandingPadInst *LP = BB.getLandingPadInst();
653 for (User *U : LP->users()) {
654 auto *EI = dyn_cast<ExtractValueInst>(U);
658 for (User *U2 : EI->users()) {
659 if (auto *PN = dyn_cast<PHINode>(U2))
665 SetVector<Argument *> ArgsToDemote;
666 SetVector<Instruction *> InstrsToDemote;
667 for (BasicBlock &BB : F) {
668 bool IsNormalBB = NormalBlocks.count(&BB);
669 bool IsEHBB = EHBlocks.count(&BB);
670 if (!IsNormalBB && !IsEHBB)
671 continue; // Blocks that are neither normal nor EH are unreachable.
672 for (Instruction &I : BB) {
673 for (Value *Op : I.operands()) {
674 // Don't demote static allocas, constants, and labels.
675 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
677 auto *AI = dyn_cast<AllocaInst>(Op);
678 if (AI && AI->isStaticAlloca())
681 if (auto *Arg = dyn_cast<Argument>(Op)) {
683 DEBUG(dbgs() << "Demoting argument " << *Arg
684 << " used by EH instr: " << I << "\n");
685 ArgsToDemote.insert(Arg);
690 // Don't demote EH values.
691 auto *OpI = cast<Instruction>(Op);
692 if (EHVals.count(OpI))
695 BasicBlock *OpBB = OpI->getParent();
696 // If a value is produced and consumed in the same BB, we don't need to
700 bool IsOpNormalBB = NormalBlocks.count(OpBB);
701 bool IsOpEHBB = EHBlocks.count(OpBB);
702 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
704 dbgs() << "Demoting instruction live in-out from EH:\n";
705 dbgs() << "Instr: " << *OpI << '\n';
706 dbgs() << "User: " << I << '\n';
708 InstrsToDemote.insert(OpI);
714 // Demote values live into and out of handlers.
715 // FIXME: This demotion is inefficient. We should insert spills at the point
716 // of definition, insert one reload in each handler that uses the value, and
717 // insert reloads in the BB used to rejoin normal control flow.
718 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
719 for (Instruction *I : InstrsToDemote)
720 DemoteRegToStack(*I, false, AllocaInsertPt);
722 // Demote arguments separately, and only for uses in EH blocks.
723 for (Argument *Arg : ArgsToDemote) {
724 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
725 Arg->getName() + ".reg2mem", AllocaInsertPt);
726 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
727 for (User *U : Users) {
728 auto *I = dyn_cast<Instruction>(U);
729 if (I && EHBlocks.count(I->getParent())) {
730 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
731 U->replaceUsesOfWith(Arg, Reload);
734 new StoreInst(Arg, Slot, AllocaInsertPt);
737 // Demote landingpad phis, as the landingpad will be removed from the machine
739 for (LandingPadInst *LPI : LPads) {
740 BasicBlock *BB = LPI->getParent();
741 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
742 DemotePHIToStack(Phi, AllocaInsertPt);
745 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
746 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
749 bool WinEHPrepare::prepareExceptionHandlers(
750 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
751 // Don't run on functions that are already prepared.
752 for (LandingPadInst *LPad : LPads) {
753 BasicBlock *LPadBB = LPad->getParent();
754 for (Instruction &Inst : *LPadBB)
755 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
759 identifyEHBlocks(F, LPads);
760 demoteValuesLiveAcrossHandlers(F, LPads);
762 // These containers are used to re-map frame variables that are used in
763 // outlined catch and cleanup handlers. They will be populated as the
764 // handlers are outlined.
765 FrameVarInfoMap FrameVarInfo;
767 bool HandlersOutlined = false;
769 Module *M = F.getParent();
770 LLVMContext &Context = M->getContext();
772 // Create a new function to receive the handler contents.
773 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
774 Type *Int32Type = Type::getInt32Ty(Context);
775 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
777 if (isAsynchronousEHPersonality(Personality)) {
778 // FIXME: Switch the ehptr type to i32 and then switch this.
779 SEHExceptionCodeSlot =
780 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
781 F.getEntryBlock().getFirstInsertionPt());
784 // In order to handle the case where one outlined catch handler returns
785 // to a block within another outlined catch handler that would otherwise
786 // be unreachable, we need to outline the nested landing pad before we
787 // outline the landing pad which encloses it.
788 if (!isAsynchronousEHPersonality(Personality))
789 std::sort(LPads.begin(), LPads.end(),
790 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
791 return DT->properlyDominates(R->getParent(), L->getParent());
794 // This container stores the llvm.eh.recover and IndirectBr instructions
795 // that make up the body of each landing pad after it has been outlined.
796 // We need to defer the population of the target list for the indirectbr
797 // until all landing pads have been outlined so that we can handle the
798 // case of blocks in the target that are reached only from nested
800 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
802 for (LandingPadInst *LPad : LPads) {
803 // Look for evidence that this landingpad has already been processed.
804 bool LPadHasActionList = false;
805 BasicBlock *LPadBB = LPad->getParent();
806 for (Instruction &Inst : *LPadBB) {
807 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
808 LPadHasActionList = true;
813 // If we've already outlined the handlers for this landingpad,
814 // there's nothing more to do here.
815 if (LPadHasActionList)
818 // If either of the values in the aggregate returned by the landing pad is
819 // extracted and stored to memory, promote the stored value to a register.
820 promoteLandingPadValues(LPad);
822 LandingPadActions Actions;
823 mapLandingPadBlocks(LPad, Actions);
825 HandlersOutlined |= !Actions.actions().empty();
826 for (ActionHandler *Action : Actions) {
827 if (Action->hasBeenProcessed())
829 BasicBlock *StartBB = Action->getStartBlock();
831 // SEH doesn't do any outlining for catches. Instead, pass the handler
832 // basic block addr to llvm.eh.actions and list the block as a return
834 if (isAsynchronousEHPersonality(Personality)) {
835 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
836 processSEHCatchHandler(CatchAction, StartBB);
841 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
844 // Split the block after the landingpad instruction so that it is just a
845 // call to llvm.eh.actions followed by indirectbr.
846 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
847 SplitBlock(LPadBB, LPad->getNextNode(), DT);
848 // Erase the branch inserted by the split so we can insert indirectbr.
849 LPadBB->getTerminator()->eraseFromParent();
851 // Replace all extracted values with undef and ultimately replace the
852 // landingpad with undef.
853 SmallVector<Instruction *, 4> SEHCodeUses;
854 SmallVector<Instruction *, 4> EHUndefs;
855 for (User *U : LPad->users()) {
856 auto *E = dyn_cast<ExtractValueInst>(U);
859 assert(E->getNumIndices() == 1 &&
860 "Unexpected operation: extracting both landing pad values");
861 unsigned Idx = *E->idx_begin();
862 assert((Idx == 0 || Idx == 1) && "unexpected index");
863 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
864 SEHCodeUses.push_back(E);
866 EHUndefs.push_back(E);
868 for (Instruction *E : EHUndefs) {
869 E->replaceAllUsesWith(UndefValue::get(E->getType()));
870 E->eraseFromParent();
872 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
874 // Rewrite uses of the exception pointer to loads of an alloca.
875 while (!SEHCodeUses.empty()) {
876 Instruction *E = SEHCodeUses.pop_back_val();
877 SmallVector<Use *, 4> Uses;
878 for (Use &U : E->uses())
880 for (Use *U : Uses) {
881 auto *I = cast<Instruction>(U->getUser());
882 if (isa<ResumeInst>(I))
884 if (auto *Phi = dyn_cast<PHINode>(I))
885 SEHCodeUses.push_back(Phi);
887 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
889 E->replaceAllUsesWith(UndefValue::get(E->getType()));
890 E->eraseFromParent();
893 // Add a call to describe the actions for this landing pad.
894 std::vector<Value *> ActionArgs;
895 for (ActionHandler *Action : Actions) {
896 // Action codes from docs are: 0 cleanup, 1 catch.
897 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
898 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
899 ActionArgs.push_back(CatchAction->getSelector());
900 // Find the frame escape index of the exception object alloca in the
902 int FrameEscapeIdx = -1;
903 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
904 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
905 auto I = FrameVarInfo.find(EHObj);
906 assert(I != FrameVarInfo.end() &&
907 "failed to map llvm.eh.begincatch var");
908 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
910 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
912 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
914 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
917 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
919 SetVector<BasicBlock *> ReturnTargets;
920 for (ActionHandler *Action : Actions) {
921 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
922 const auto &CatchTargets = CatchAction->getReturnTargets();
923 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
926 IndirectBrInst *Branch =
927 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
928 for (BasicBlock *Target : ReturnTargets)
929 Branch->addDestination(Target);
931 if (!isAsynchronousEHPersonality(Personality)) {
932 // C++ EH must repopulate the targets later to handle the case of
933 // targets that are reached indirectly through nested landing pads.
934 LPadImpls.push_back(std::make_pair(Recover, Branch));
937 } // End for each landingpad
939 // If nothing got outlined, there is no more processing to be done.
940 if (!HandlersOutlined)
943 // Replace any nested landing pad stubs with the correct action handler.
944 // This must be done before we remove unreachable blocks because it
945 // cleans up references to outlined blocks that will be deleted.
946 for (auto &LPadPair : NestedLPtoOriginalLP)
947 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
948 NestedLPtoOriginalLP.clear();
950 // Update the indirectbr instructions' target lists if necessary.
951 SetVector<BasicBlock*> CheckedTargets;
952 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
953 for (auto &LPadImplPair : LPadImpls) {
954 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
955 IndirectBrInst *Branch = LPadImplPair.second;
957 // Get a list of handlers called by
958 parseEHActions(Recover, ActionList);
960 // Add an indirect branch listing possible successors of the catch handlers.
961 SetVector<BasicBlock *> ReturnTargets;
962 for (const auto &Action : ActionList) {
963 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
964 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
965 getPossibleReturnTargets(&F, Handler, ReturnTargets);
969 // Clear any targets we already knew about.
970 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
971 BasicBlock *KnownTarget = Branch->getDestination(I);
972 if (ReturnTargets.count(KnownTarget))
973 ReturnTargets.remove(KnownTarget);
975 for (BasicBlock *Target : ReturnTargets) {
976 Branch->addDestination(Target);
977 // The target may be a block that we excepted to get pruned.
978 // If it is, it may contain a call to llvm.eh.endcatch.
979 if (CheckedTargets.insert(Target)) {
980 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
981 // will be followed by an unconditional branch.
982 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
983 if (Br && Br->isUnconditional() &&
984 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
985 Instruction *Prev = Br->getPrevNode();
986 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
987 Prev->eraseFromParent();
994 F.addFnAttr("wineh-parent", F.getName());
996 // Delete any blocks that were only used by handlers that were outlined above.
997 removeUnreachableBlocks(F);
999 BasicBlock *Entry = &F.getEntryBlock();
1000 IRBuilder<> Builder(F.getParent()->getContext());
1001 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
1003 Function *FrameEscapeFn =
1004 Intrinsic::getDeclaration(M, Intrinsic::localescape);
1005 Function *RecoverFrameFn =
1006 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
1007 SmallVector<Value *, 8> AllocasToEscape;
1009 // Scan the entry block for an existing call to llvm.localescape. We need to
1010 // keep escaping those objects.
1011 for (Instruction &I : F.front()) {
1012 auto *II = dyn_cast<IntrinsicInst>(&I);
1013 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1014 auto Args = II->arg_operands();
1015 AllocasToEscape.append(Args.begin(), Args.end());
1016 II->eraseFromParent();
1021 // Finally, replace all of the temporary allocas for frame variables used in
1022 // the outlined handlers with calls to llvm.localrecover.
1023 for (auto &VarInfoEntry : FrameVarInfo) {
1024 Value *ParentVal = VarInfoEntry.first;
1025 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
1026 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
1028 // FIXME: We should try to sink unescaped allocas from the parent frame into
1029 // the child frame. If the alloca is escaped, we have to use the lifetime
1030 // markers to ensure that the alloca is only live within the child frame.
1032 // Add this alloca to the list of things to escape.
1033 AllocasToEscape.push_back(ParentAlloca);
1035 // Next replace all outlined allocas that are mapped to it.
1036 for (AllocaInst *TempAlloca : Allocas) {
1037 if (TempAlloca == getCatchObjectSentinel())
1038 continue; // Skip catch parameter sentinels.
1039 Function *HandlerFn = TempAlloca->getParent()->getParent();
1040 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1043 // FIXME: Sink this localrecover into the blocks where it is used.
1044 Builder.SetInsertPoint(TempAlloca);
1045 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1046 Value *RecoverArgs[] = {
1047 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
1048 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
1049 Instruction *RecoveredAlloca =
1050 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1052 // Add a pointer bitcast if the alloca wasn't an i8.
1053 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1054 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
1055 RecoveredAlloca = cast<Instruction>(
1056 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
1058 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1059 TempAlloca->removeFromParent();
1060 RecoveredAlloca->takeName(TempAlloca);
1063 } // End for each FrameVarInfo entry.
1065 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
1067 Builder.SetInsertPoint(&F.getEntryBlock().back());
1068 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1070 if (SEHExceptionCodeSlot) {
1071 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1072 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1073 for (User *U : SEHExceptionCodeSlot->users()) {
1074 if (auto *Inst = dyn_cast<Instruction>(U))
1075 UserBlocks.insert(Inst->getParent());
1077 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
1078 // After the promotion, kill off dead instructions.
1079 for (BasicBlock *BB : UserBlocks)
1080 SimplifyInstructionsInBlock(BB, LibInfo);
1084 // Clean up the handler action maps we created for this function
1085 DeleteContainerSeconds(CatchHandlerMap);
1086 CatchHandlerMap.clear();
1087 DeleteContainerSeconds(CleanupHandlerMap);
1088 CleanupHandlerMap.clear();
1089 HandlerToParentFP.clear();
1092 SEHExceptionCodeSlot = nullptr;
1094 NormalBlocks.clear();
1095 EHReturnBlocks.clear();
1097 return HandlersOutlined;
1100 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1101 // If the return values of the landing pad instruction are extracted and
1102 // stored to memory, we want to promote the store locations to reg values.
1103 SmallVector<AllocaInst *, 2> EHAllocas;
1105 // The landingpad instruction returns an aggregate value. Typically, its
1106 // value will be passed to a pair of extract value instructions and the
1107 // results of those extracts are often passed to store instructions.
1108 // In unoptimized code the stored value will often be loaded and then stored
1110 for (auto *U : LPad->users()) {
1111 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1115 for (auto *EU : Extract->users()) {
1116 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1117 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1118 EHAllocas.push_back(AV);
1123 // We can't do this without a dominator tree.
1126 if (!EHAllocas.empty()) {
1127 PromoteMemToReg(EHAllocas, *DT);
1131 // After promotion, some extracts may be trivially dead. Remove them.
1132 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1133 for (auto *U : Users)
1134 RecursivelyDeleteTriviallyDeadInstructions(U);
1137 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1139 SetVector<BasicBlock*> &Targets) {
1140 for (BasicBlock &BB : *HandlerF) {
1141 // If the handler contains landing pads, check for any
1142 // handlers that may return directly to a block in the
1144 if (auto *LPI = BB.getLandingPadInst()) {
1145 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
1146 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1147 parseEHActions(Recover, ActionList);
1148 for (const auto &Action : ActionList) {
1149 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
1150 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1151 getPossibleReturnTargets(ParentF, NestedF, Targets);
1156 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1160 // Handler functions must always return a block address.
1161 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1163 // If this is the handler for a nested landing pad, the
1164 // return address may have been remapped to a block in the
1165 // parent handler. We're not interested in those.
1166 if (BA->getFunction() != ParentF)
1169 Targets.insert(BA->getBasicBlock());
1173 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1174 LandingPadInst *OutlinedLPad,
1175 const LandingPadInst *OriginalLPad,
1176 FrameVarInfoMap &FrameVarInfo) {
1177 // Get the nested block and erase the unreachable instruction that was
1178 // temporarily inserted as its terminator.
1179 LLVMContext &Context = ParentFn->getContext();
1180 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1181 // If the nested landing pad was outlined before the landing pad that enclosed
1182 // it, it will already be in outlined form. In that case, we just need to see
1183 // if the returns and the enclosing branch instruction need to be updated.
1184 IndirectBrInst *Branch =
1185 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1187 // If the landing pad wasn't in outlined form, it should be a stub with
1188 // an unreachable terminator.
1189 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1190 OutlinedBB->getTerminator()->eraseFromParent();
1191 // That should leave OutlinedLPad as the last instruction in its block.
1192 assert(&OutlinedBB->back() == OutlinedLPad);
1195 // The original landing pad will have already had its action intrinsic
1196 // built by the outlining loop. We need to clone that into the outlined
1197 // location. It may also be necessary to add references to the exception
1198 // variables to the outlined handler in which this landing pad is nested
1199 // and remap return instructions in the nested handlers that should return
1200 // to an address in the outlined handler.
1201 Function *OutlinedHandlerFn = OutlinedBB->getParent();
1202 BasicBlock::const_iterator II = OriginalLPad;
1204 // The instruction after the landing pad should now be a call to eh.actions.
1205 const Instruction *Recover = II;
1206 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
1208 // Remap the return target in the nested handler.
1209 SmallVector<BlockAddress *, 4> ActionTargets;
1210 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1211 parseEHActions(EHActions, ActionList);
1212 for (const auto &Action : ActionList) {
1213 auto *Catch = dyn_cast<CatchHandler>(Action.get());
1216 // The dyn_cast to function here selects C++ catch handlers and skips
1217 // SEH catch handlers.
1218 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1221 // Visit all the return instructions, looking for places that return
1222 // to a location within OutlinedHandlerFn.
1223 for (BasicBlock &NestedHandlerBB : *Handler) {
1224 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1228 // Handler functions must always return a block address.
1229 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1230 // The original target will have been in the main parent function,
1231 // but if it is the address of a block that has been outlined, it
1232 // should be a block that was outlined into OutlinedHandlerFn.
1233 assert(BA->getFunction() == ParentFn);
1235 // Ignore targets that aren't part of an outlined handler function.
1236 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1239 // If the return value is the address ofF a block that we
1240 // previously outlined into the parent handler function, replace
1241 // the return instruction and add the mapped target to the list
1242 // of possible return addresses.
1243 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1244 assert(MappedBB->getParent() == OutlinedHandlerFn);
1245 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1246 Ret->eraseFromParent();
1247 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1248 ActionTargets.push_back(NewBA);
1254 // If the landing pad was already in outlined form, just update its targets.
1255 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1256 Branch->removeDestination(I);
1257 // Add the previously collected action targets.
1258 for (auto *Target : ActionTargets)
1259 Branch->addDestination(Target->getBasicBlock());
1261 // If the landing pad was previously stubbed out, fill in its outlined form.
1262 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1263 OutlinedBB->getInstList().push_back(NewEHActions);
1265 // Insert an indirect branch into the outlined landing pad BB.
1266 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1267 // Add the previously collected action targets.
1268 for (auto *Target : ActionTargets)
1269 IBr->addDestination(Target->getBasicBlock());
1273 // This function examines a block to determine whether the block ends with a
1274 // conditional branch to a catch handler based on a selector comparison.
1275 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1276 // WinEHCleanupDirector::handleTypeIdFor().
1277 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1278 Constant *&Selector, BasicBlock *&NextBB) {
1279 ICmpInst::Predicate Pred;
1280 BasicBlock *TBB, *FBB;
1283 if (!match(BB->getTerminator(),
1284 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1288 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1289 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1292 if (Pred == CmpInst::ICMP_EQ) {
1298 if (Pred == CmpInst::ICMP_NE) {
1307 static bool isCatchBlock(BasicBlock *BB) {
1308 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1310 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1316 static BasicBlock *createStubLandingPad(Function *Handler) {
1317 // FIXME: Finish this!
1318 LLVMContext &Context = Handler->getContext();
1319 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1320 Handler->getBasicBlockList().push_back(StubBB);
1321 IRBuilder<> Builder(StubBB);
1322 LandingPadInst *LPad = Builder.CreateLandingPad(
1323 llvm::StructType::get(Type::getInt8PtrTy(Context),
1324 Type::getInt32Ty(Context), nullptr),
1326 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1327 Function *ActionIntrin =
1328 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1329 Builder.CreateCall(ActionIntrin, {}, "recover");
1330 LPad->setCleanup(true);
1331 Builder.CreateUnreachable();
1335 // Cycles through the blocks in an outlined handler function looking for an
1336 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1337 // landing pad if none is found. The code that generates the .xdata tables for
1338 // the handler needs at least one landing pad to identify the parent function's
1340 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
1341 ReturnInst *Ret = nullptr;
1342 UnreachableInst *Unreached = nullptr;
1343 for (BasicBlock &BB : *Handler) {
1344 TerminatorInst *Terminator = BB.getTerminator();
1345 // If we find an invoke, there is nothing to be done.
1346 auto *II = dyn_cast<InvokeInst>(Terminator);
1349 // If we've already recorded a return instruction, keep looking for invokes.
1351 Ret = dyn_cast<ReturnInst>(Terminator);
1352 // If we haven't recorded an unreachable instruction, try this terminator.
1354 Unreached = dyn_cast<UnreachableInst>(Terminator);
1357 // If we got this far, the handler contains no invokes. We should have seen
1358 // at least one return or unreachable instruction. We'll insert an invoke of
1359 // llvm.donothing ahead of that instruction.
1360 assert(Ret || Unreached);
1361 TerminatorInst *Term;
1366 BasicBlock *OldRetBB = Term->getParent();
1367 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1368 // SplitBlock adds an unconditional branch instruction at the end of the
1369 // parent block. We want to replace that with an invoke call, so we can
1371 OldRetBB->getTerminator()->eraseFromParent();
1372 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
1374 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1375 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1378 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1379 // usually doesn't build LLVM IR, so that's probably the wrong place.
1380 Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1381 const Twine &Name, Module *M,
1383 // x64 uses a two-argument prototype where the parent FP is the second
1384 // argument. x86 uses no arguments, just the incoming EBP value.
1385 LLVMContext &Context = M->getContext();
1386 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1387 FunctionType *FnType;
1388 if (TheTriple.getArch() == Triple::x86_64) {
1389 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1390 FnType = FunctionType::get(RetTy, ArgTys, false);
1392 FnType = FunctionType::get(RetTy, None, false);
1396 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1397 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1398 Handler->getBasicBlockList().push_front(Entry);
1399 if (TheTriple.getArch() == Triple::x86_64) {
1400 ParentFP = &(Handler->getArgumentList().back());
1403 Function *FrameAddressFn =
1404 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1405 Function *RecoverFPFn =
1406 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1407 IRBuilder<> Builder(&Handler->getEntryBlock());
1409 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1410 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1411 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
1416 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1417 LandingPadInst *LPad, BasicBlock *StartBB,
1418 FrameVarInfoMap &VarInfo) {
1419 Module *M = SrcFn->getParent();
1420 LLVMContext &Context = M->getContext();
1421 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1423 // Create a new function to receive the handler contents.
1426 if (Action->getType() == Catch) {
1427 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
1430 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
1431 SrcFn->getName() + ".cleanup", M, ParentFP);
1433 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
1434 HandlerToParentFP[Handler] = ParentFP;
1435 Handler->addFnAttr("wineh-parent", SrcFn->getName());
1436 BasicBlock *Entry = &Handler->getEntryBlock();
1438 // Generate a standard prolog to setup the frame recovery structure.
1439 IRBuilder<> Builder(Context);
1440 Builder.SetInsertPoint(Entry);
1441 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1443 std::unique_ptr<WinEHCloningDirectorBase> Director;
1445 ValueToValueMapTy VMap;
1447 LandingPadMap &LPadMap = LPadMaps[LPad];
1448 if (!LPadMap.isInitialized())
1449 LPadMap.mapLandingPad(LPad);
1450 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1451 Constant *Sel = CatchAction->getSelector();
1452 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1453 LPadMap, NestedLPtoOriginalLP, DT,
1455 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1456 ConstantInt::get(Type::getInt32Ty(Context), 1));
1459 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1460 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1461 UndefValue::get(Type::getInt32Ty(Context)));
1464 SmallVector<ReturnInst *, 8> Returns;
1465 ClonedCodeInfo OutlinedFunctionInfo;
1467 // If the start block contains PHI nodes, we need to map them.
1468 BasicBlock::iterator II = StartBB->begin();
1469 while (auto *PN = dyn_cast<PHINode>(II)) {
1470 bool Mapped = false;
1471 // Look for PHI values that we have already mapped (such as the selector).
1472 for (Value *Val : PN->incoming_values()) {
1473 if (VMap.count(Val)) {
1474 VMap[PN] = VMap[Val];
1478 // If we didn't find a match for this value, map it as an undef.
1480 VMap[PN] = UndefValue::get(PN->getType());
1485 // The landing pad value may be used by PHI nodes. It will ultimately be
1486 // eliminated, but we need it in the map for intermediate handling.
1487 VMap[LPad] = UndefValue::get(LPad->getType());
1489 // Skip over PHIs and, if applicable, landingpad instructions.
1490 II = StartBB->getFirstInsertionPt();
1492 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1493 /*ModuleLevelChanges=*/false, Returns, "",
1494 &OutlinedFunctionInfo, Director.get());
1496 // Move all the instructions in the cloned "entry" block into our entry block.
1497 // Depending on how the parent function was laid out, the block that will
1498 // correspond to the outlined entry block may not be the first block in the
1499 // list. We can recognize it, however, as the cloned block which has no
1500 // predecessors. Any other block wouldn't have been cloned if it didn't
1501 // have a predecessor which was also cloned.
1502 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1503 while (!pred_empty(ClonedIt))
1505 BasicBlock *ClonedEntryBB = ClonedIt;
1506 assert(ClonedEntryBB);
1507 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1508 ClonedEntryBB->eraseFromParent();
1510 // Make sure we can identify the handler's personality later.
1511 addStubInvokeToHandlerIfNeeded(Handler);
1513 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1514 WinEHCatchDirector *CatchDirector =
1515 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1516 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1517 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1519 // Look for blocks that are not part of the landing pad that we just
1520 // outlined but terminate with a call to llvm.eh.endcatch and a
1521 // branch to a block that is in the handler we just outlined.
1522 // These blocks will be part of a nested landing pad that intends to
1523 // return to an address in this handler. This case is best handled
1524 // after both landing pads have been outlined, so for now we'll just
1525 // save the association of the blocks in LPadTargetBlocks. The
1526 // return instructions which are created from these branches will be
1527 // replaced after all landing pads have been outlined.
1528 for (const auto MapEntry : VMap) {
1529 // VMap maps all values and blocks that were just cloned, but dead
1530 // blocks which were pruned will map to nullptr.
1531 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1533 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1534 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1535 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1536 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1538 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1540 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1541 // This would indicate that a nested landing pad wants to return
1542 // to a block that is outlined into two different handlers.
1543 assert(!LPadTargetBlocks.count(MappedBB));
1544 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1548 } // End if (CatchAction)
1550 Action->setHandlerBlockOrFunc(Handler);
1555 /// This BB must end in a selector dispatch. All we need to do is pass the
1556 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1558 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1559 BasicBlock *StartBB) {
1560 BasicBlock *HandlerBB;
1563 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1565 // If this was EH dispatch, this must be a conditional branch to the handler
1567 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1568 // leading to crashes if some optimization hoists stuff here.
1569 assert(CatchAction->getSelector() && HandlerBB &&
1570 "expected catch EH dispatch");
1572 // This must be a catch-all. Split the block after the landingpad.
1573 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1574 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1576 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1577 Function *EHCodeFn = Intrinsic::getDeclaration(
1578 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1579 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
1580 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1581 Builder.CreateStore(Code, SEHExceptionCodeSlot);
1582 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1583 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1584 CatchAction->setReturnTargets(Targets);
1587 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1588 // Each instance of this class should only ever be used to map a single
1590 assert(OriginLPad == nullptr || OriginLPad == LPad);
1592 // If the landing pad has already been mapped, there's nothing more to do.
1593 if (OriginLPad == LPad)
1598 // The landingpad instruction returns an aggregate value. Typically, its
1599 // value will be passed to a pair of extract value instructions and the
1600 // results of those extracts will have been promoted to reg values before
1601 // this routine is called.
1602 for (auto *U : LPad->users()) {
1603 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1606 assert(Extract->getNumIndices() == 1 &&
1607 "Unexpected operation: extracting both landing pad values");
1608 unsigned int Idx = *(Extract->idx_begin());
1609 assert((Idx == 0 || Idx == 1) &&
1610 "Unexpected operation: extracting an unknown landing pad element");
1612 ExtractedEHPtrs.push_back(Extract);
1613 } else if (Idx == 1) {
1614 ExtractedSelectors.push_back(Extract);
1619 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1620 return BB->getLandingPadInst() == OriginLPad;
1623 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1624 if (Inst == OriginLPad)
1626 for (auto *Extract : ExtractedEHPtrs) {
1627 if (Inst == Extract)
1630 for (auto *Extract : ExtractedSelectors) {
1631 if (Inst == Extract)
1637 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1638 Value *SelectorValue) const {
1639 // Remap all landing pad extract instructions to the specified values.
1640 for (auto *Extract : ExtractedEHPtrs)
1641 VMap[Extract] = EHPtrValue;
1642 for (auto *Extract : ExtractedSelectors)
1643 VMap[Extract] = SelectorValue;
1646 static bool isLocalAddressCall(const Value *V) {
1647 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
1650 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1651 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1652 // If this is one of the boilerplate landing pad instructions, skip it.
1653 // The instruction will have already been remapped in VMap.
1654 if (LPadMap.isLandingPadSpecificInst(Inst))
1655 return CloningDirector::SkipInstruction;
1657 // Nested landing pads that have not already been outlined will be cloned as
1658 // stubs, with just the landingpad instruction and an unreachable instruction.
1659 // When all landingpads have been outlined, we'll replace this with the
1660 // llvm.eh.actions call and indirect branch created when the landing pad was
1662 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1663 return handleLandingPad(VMap, LPad, NewBB);
1666 // Nested landing pads that have already been outlined will be cloned in their
1667 // outlined form, but we need to intercept the ibr instruction to filter out
1668 // targets that do not return to the handler we are outlining.
1669 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1670 return handleIndirectBr(VMap, IBr, NewBB);
1673 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1674 return handleInvoke(VMap, Invoke, NewBB);
1676 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1677 return handleResume(VMap, Resume, NewBB);
1679 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1680 return handleCompare(VMap, Cmp, NewBB);
1682 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1683 return handleBeginCatch(VMap, Inst, NewBB);
1684 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1685 return handleEndCatch(VMap, Inst, NewBB);
1686 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1687 return handleTypeIdFor(VMap, Inst, NewBB);
1689 // When outlining llvm.localaddress(), remap that to the second argument,
1690 // which is the FP of the parent.
1691 if (isLocalAddressCall(Inst)) {
1692 VMap[Inst] = ParentFP;
1693 return CloningDirector::SkipInstruction;
1696 // Continue with the default cloning behavior.
1697 return CloningDirector::CloneInstruction;
1700 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1701 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1702 // If the instruction after the landing pad is a call to llvm.eh.actions
1703 // the landing pad has already been outlined. In this case, we should
1704 // clone it because it may return to a block in the handler we are
1705 // outlining now that would otherwise be unreachable. The landing pads
1706 // are sorted before outlining begins to enable this case to work
1708 const Instruction *NextI = LPad->getNextNode();
1709 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1710 return CloningDirector::CloneInstruction;
1712 // If the landing pad hasn't been outlined yet, the landing pad we are
1713 // outlining now does not dominate it and so it cannot return to a block
1714 // in this handler. In that case, we can just insert a stub landing
1715 // pad now and patch it up later.
1716 Instruction *NewInst = LPad->clone();
1717 if (LPad->hasName())
1718 NewInst->setName(LPad->getName());
1719 // Save this correlation for later processing.
1720 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1721 VMap[LPad] = NewInst;
1722 BasicBlock::InstListType &InstList = NewBB->getInstList();
1723 InstList.push_back(NewInst);
1724 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1725 return CloningDirector::StopCloningBB;
1728 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1729 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1730 // The argument to the call is some form of the first element of the
1731 // landingpad aggregate value, but that doesn't matter. It isn't used
1733 // The second argument is an outparameter where the exception object will be
1734 // stored. Typically the exception object is a scalar, but it can be an
1735 // aggregate when catching by value.
1736 // FIXME: Leave something behind to indicate where the exception object lives
1737 // for this handler. Should it be part of llvm.eh.actions?
1738 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1739 "llvm.eh.begincatch found while "
1740 "outlining catch handler.");
1741 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1742 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1743 return CloningDirector::SkipInstruction;
1744 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1745 "catch parameter is not static alloca");
1746 Materializer.escapeCatchObject(ExceptionObjectVar);
1747 return CloningDirector::SkipInstruction;
1750 CloningDirector::CloningAction
1751 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1752 const Instruction *Inst, BasicBlock *NewBB) {
1753 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1754 // It might be interesting to track whether or not we are inside a catch
1755 // function, but that might make the algorithm more brittle than it needs
1758 // The end catch call can occur in one of two places: either in a
1759 // landingpad block that is part of the catch handlers exception mechanism,
1760 // or at the end of the catch block. However, a catch-all handler may call
1761 // end catch from the original landing pad. If the call occurs in a nested
1762 // landing pad block, we must skip it and continue so that the landing pad
1764 auto *ParentBB = IntrinCall->getParent();
1765 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1766 return CloningDirector::SkipInstruction;
1768 // If an end catch occurs anywhere else we want to terminate the handler
1769 // with a return to the code that follows the endcatch call. If the
1770 // next instruction is not an unconditional branch, we need to split the
1771 // block to provide a clear target for the return instruction.
1772 BasicBlock *ContinueBB;
1773 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1774 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1775 if (!Branch || !Branch->isUnconditional()) {
1776 // We're interrupting the cloning process at this location, so the
1777 // const_cast we're doing here will not cause a problem.
1778 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1779 const_cast<Instruction *>(cast<Instruction>(Next)));
1781 ContinueBB = Branch->getSuccessor(0);
1784 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1785 ReturnTargets.push_back(ContinueBB);
1787 // We just added a terminator to the cloned block.
1788 // Tell the caller to stop processing the current basic block so that
1789 // the branch instruction will be skipped.
1790 return CloningDirector::StopCloningBB;
1793 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1794 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1795 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1796 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1797 // This causes a replacement that will collapse the landing pad CFG based
1798 // on the filter function we intend to match.
1799 if (Selector == CurrentSelector)
1800 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1802 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1803 // Tell the caller not to clone this instruction.
1804 return CloningDirector::SkipInstruction;
1807 CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1808 ValueToValueMapTy &VMap,
1809 const IndirectBrInst *IBr,
1810 BasicBlock *NewBB) {
1811 // If this indirect branch is not part of a landing pad block, just clone it.
1812 const BasicBlock *ParentBB = IBr->getParent();
1813 if (!ParentBB->isLandingPad())
1814 return CloningDirector::CloneInstruction;
1816 // If it is part of a landing pad, we want to filter out target blocks
1817 // that are not part of the handler we are outlining.
1818 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1820 // Save this correlation for later processing.
1821 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1823 // We should only get here for landing pads that have already been outlined.
1824 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1826 // Copy the indirectbr, but only include targets that were previously
1827 // identified as EH blocks and are dominated by the nested landing pad.
1828 SetVector<const BasicBlock *> ReturnTargets;
1829 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1830 auto *TargetBB = IBr->getDestination(I);
1831 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1832 DT->dominates(ParentBB, TargetBB)) {
1833 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1834 ReturnTargets.insert(TargetBB);
1837 IndirectBrInst *NewBranch =
1838 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1839 ReturnTargets.size(), NewBB);
1840 for (auto *Target : ReturnTargets)
1841 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1843 // The operands and targets of the branch instruction are remapped later
1844 // because it is a terminator. Tell the cloning code to clone the
1845 // blocks we just added to the target list.
1846 return CloningDirector::CloneSuccessors;
1849 CloningDirector::CloningAction
1850 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1851 const InvokeInst *Invoke, BasicBlock *NewBB) {
1852 return CloningDirector::CloneInstruction;
1855 CloningDirector::CloningAction
1856 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1857 const ResumeInst *Resume, BasicBlock *NewBB) {
1858 // Resume instructions shouldn't be reachable from catch handlers.
1859 // We still need to handle it, but it will be pruned.
1860 BasicBlock::InstListType &InstList = NewBB->getInstList();
1861 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1862 return CloningDirector::StopCloningBB;
1865 CloningDirector::CloningAction
1866 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1867 const CmpInst *Compare, BasicBlock *NewBB) {
1868 const IntrinsicInst *IntrinCall = nullptr;
1869 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1870 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1871 } else if (match(Compare->getOperand(1),
1872 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1873 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1876 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1877 // This causes a replacement that will collapse the landing pad CFG based
1878 // on the filter function we intend to match.
1879 if (Selector == CurrentSelector->stripPointerCasts()) {
1880 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1882 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1884 return CloningDirector::SkipInstruction;
1886 return CloningDirector::CloneInstruction;
1889 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1890 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1891 // The MS runtime will terminate the process if an exception occurs in a
1892 // cleanup handler, so we shouldn't encounter landing pads in the actual
1893 // cleanup code, but they may appear in catch blocks. Depending on where
1894 // we started cloning we may see one, but it will get dropped during dead
1896 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1897 VMap[LPad] = NewInst;
1898 BasicBlock::InstListType &InstList = NewBB->getInstList();
1899 InstList.push_back(NewInst);
1900 return CloningDirector::StopCloningBB;
1903 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1904 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1905 // Cleanup code may flow into catch blocks or the catch block may be part
1906 // of a branch that will be optimized away. We'll insert a return
1907 // instruction now, but it may be pruned before the cloning process is
1909 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1910 return CloningDirector::StopCloningBB;
1913 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1914 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1915 // Cleanup handlers nested within catch handlers may begin with a call to
1916 // eh.endcatch. We can just ignore that instruction.
1917 return CloningDirector::SkipInstruction;
1920 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1921 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1922 // If we encounter a selector comparison while cloning a cleanup handler,
1923 // we want to stop cloning immediately. Anything after the dispatch
1924 // will be outlined into a different handler.
1925 BasicBlock *CatchHandler;
1928 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1929 CatchHandler, Selector, NextBB)) {
1930 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1931 return CloningDirector::StopCloningBB;
1933 // If eg.typeid.for is called for any other reason, it can be ignored.
1934 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1935 return CloningDirector::SkipInstruction;
1938 CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1939 ValueToValueMapTy &VMap,
1940 const IndirectBrInst *IBr,
1941 BasicBlock *NewBB) {
1942 // No special handling is required for cleanup cloning.
1943 return CloningDirector::CloneInstruction;
1946 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1947 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1948 // All invokes in cleanup handlers can be replaced with calls.
1949 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1950 // Insert a normal call instruction...
1952 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1953 Invoke->getName(), NewBB);
1954 NewCall->setCallingConv(Invoke->getCallingConv());
1955 NewCall->setAttributes(Invoke->getAttributes());
1956 NewCall->setDebugLoc(Invoke->getDebugLoc());
1957 VMap[Invoke] = NewCall;
1959 // Remap the operands.
1960 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1962 // Insert an unconditional branch to the normal destination.
1963 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1965 // The unwind destination won't be cloned into the new function, so
1966 // we don't need to clean up its phi nodes.
1968 // We just added a terminator to the cloned block.
1969 // Tell the caller to stop processing the current basic block.
1970 return CloningDirector::CloneSuccessors;
1973 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1974 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1975 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1977 // We just added a terminator to the cloned block.
1978 // Tell the caller to stop processing the current basic block so that
1979 // the branch instruction will be skipped.
1980 return CloningDirector::StopCloningBB;
1983 CloningDirector::CloningAction
1984 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1985 const CmpInst *Compare, BasicBlock *NewBB) {
1986 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1987 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1988 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1989 return CloningDirector::SkipInstruction;
1991 return CloningDirector::CloneInstruction;
1994 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1995 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
1996 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1997 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1999 // New allocas should be inserted in the entry block, but after the parent FP
2000 // is established if it is an instruction.
2001 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2002 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2003 InsertPoint = FPInst->getNextNode();
2004 Builder.SetInsertPoint(EntryBB, InsertPoint);
2007 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
2008 // If we're asked to materialize a static alloca, we temporarily create an
2009 // alloca in the outlined function and add this to the FrameVarInfo map. When
2010 // all the outlining is complete, we'll replace these temporary allocas with
2011 // calls to llvm.localrecover.
2012 if (auto *AV = dyn_cast<AllocaInst>(V)) {
2013 assert(AV->isStaticAlloca() &&
2014 "cannot materialize un-demoted dynamic alloca");
2015 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2016 Builder.Insert(NewAlloca, AV->getName());
2017 FrameVarInfo[AV].push_back(NewAlloca);
2021 if (isa<Instruction>(V) || isa<Argument>(V)) {
2022 Function *Parent = isa<Instruction>(V)
2023 ? cast<Instruction>(V)->getParent()->getParent()
2024 : cast<Argument>(V)->getParent();
2026 << "Failed to demote instruction used in exception handler of function "
2027 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
2028 errs() << " " << *V << '\n';
2029 report_fatal_error("WinEHPrepare failed to demote instruction");
2032 // Don't materialize other values.
2036 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2037 // Catch parameter objects have to live in the parent frame. When we see a use
2038 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2039 // used from another handler. This will prevent us from trying to sink the
2040 // alloca into the handler and ensure that the catch parameter is present in
2041 // the call to llvm.localescape.
2042 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2045 // This function maps the catch and cleanup handlers that are reachable from the
2046 // specified landing pad. The landing pad sequence will have this basic shape:
2048 // <cleanup handler>
2049 // <selector comparison>
2051 // <cleanup handler>
2052 // <selector comparison>
2054 // <cleanup handler>
2057 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2058 // any arbitrary control flow, but all paths through the cleanup code must
2059 // eventually reach the next selector comparison and no path can skip to a
2060 // different selector comparisons, though some paths may terminate abnormally.
2061 // Therefore, we will use a depth first search from the start of any given
2062 // cleanup block and stop searching when we find the next selector comparison.
2064 // If the landingpad instruction does not have a catch clause, we will assume
2065 // that any instructions other than selector comparisons and catch handlers can
2066 // be ignored. In practice, these will only be the boilerplate instructions.
2068 // The catch handlers may also have any control structure, but we are only
2069 // interested in the start of the catch handlers, so we don't need to actually
2070 // follow the flow of the catch handlers. The start of the catch handlers can
2071 // be located from the compare instructions, but they can be skipped in the
2072 // flow by following the contrary branch.
2073 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2074 LandingPadActions &Actions) {
2075 unsigned int NumClauses = LPad->getNumClauses();
2076 unsigned int HandlersFound = 0;
2077 BasicBlock *BB = LPad->getParent();
2079 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2081 if (NumClauses == 0) {
2082 findCleanupHandlers(Actions, BB, nullptr);
2086 VisitedBlockSet VisitedBlocks;
2088 while (HandlersFound != NumClauses) {
2089 BasicBlock *NextBB = nullptr;
2091 // Skip over filter clauses.
2092 if (LPad->isFilter(HandlersFound)) {
2097 // See if the clause we're looking for is a catch-all.
2098 // If so, the catch begins immediately.
2099 Constant *ExpectedSelector =
2100 LPad->getClause(HandlersFound)->stripPointerCasts();
2101 if (isa<ConstantPointerNull>(ExpectedSelector)) {
2102 // The catch all must occur last.
2103 assert(HandlersFound == NumClauses - 1);
2105 // There can be additional selector dispatches in the call chain that we
2107 BasicBlock *CatchBlock = nullptr;
2109 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2110 DEBUG(dbgs() << " Found extra catch dispatch in block "
2111 << CatchBlock->getName() << "\n");
2115 // Add the catch handler to the action list.
2116 CatchHandler *Action = nullptr;
2117 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2118 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2119 Action = CatchHandlerMap[BB];
2120 assert(Action->getSelector() == ExpectedSelector);
2122 // We don't expect a selector dispatch, but there may be a call to
2123 // llvm.eh.begincatch, which separates catch handling code from
2124 // cleanup code in the same control flow. This call looks for the
2125 // begincatch intrinsic.
2126 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2128 // For C++ EH, check if there is any interesting cleanup code before
2129 // we begin the catch. This is important because cleanups cannot
2130 // rethrow exceptions but code called from catches can. For SEH, it
2131 // isn't important if some finally code before a catch-all is executed
2132 // out of line or after recovering from the exception.
2133 if (Personality == EHPersonality::MSVC_CXX)
2134 findCleanupHandlers(Actions, BB, BB);
2136 // If an action was not found, it means that the control flows
2137 // directly into the catch-all handler and there is no cleanup code.
2138 // That's an expected situation and we must create a catch action.
2139 // Since this is a catch-all handler, the selector won't actually
2140 // appear in the code anywhere. ExpectedSelector here is the constant
2141 // null ptr that we got from the landing pad instruction.
2142 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2143 CatchHandlerMap[BB] = Action;
2146 Actions.insertCatchHandler(Action);
2147 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2150 // Once we reach a catch-all, don't expect to hit a resume instruction.
2155 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
2156 assert(CatchAction);
2158 // See if there is any interesting code executed before the dispatch.
2159 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
2161 // When the source program contains multiple nested try blocks the catch
2162 // handlers can get strung together in such a way that we can encounter
2163 // a dispatch for a selector that we've already had a handler for.
2164 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2167 // Add the catch handler to the action list.
2168 DEBUG(dbgs() << " Found catch dispatch in block "
2169 << CatchAction->getStartBlock()->getName() << "\n");
2170 Actions.insertCatchHandler(CatchAction);
2172 // Under some circumstances optimized IR will flow unconditionally into a
2173 // handler block without checking the selector. This can only happen if
2174 // the landing pad has a catch-all handler and the handler for the
2175 // preceding catch clause is identical to the catch-call handler
2176 // (typically an empty catch). In this case, the handler must be shared
2177 // by all remaining clauses.
2178 if (isa<ConstantPointerNull>(
2179 CatchAction->getSelector()->stripPointerCasts())) {
2180 DEBUG(dbgs() << " Applying early catch-all handler in block "
2181 << CatchAction->getStartBlock()->getName()
2182 << " to all remaining clauses.\n");
2183 Actions.insertCatchHandler(CatchAction);
2187 DEBUG(dbgs() << " Found extra catch dispatch in block "
2188 << CatchAction->getStartBlock()->getName() << "\n");
2191 // Move on to the block after the catch handler.
2195 // If we didn't wind up in a catch-all, see if there is any interesting code
2196 // executed before the resume.
2197 findCleanupHandlers(Actions, BB, BB);
2199 // It's possible that some optimization moved code into a landingpad that
2201 // previously being used for cleanup. If that happens, we need to execute
2203 // extra code from a cleanup handler.
2204 if (Actions.includesCleanup() && !LPad->isCleanup())
2205 LPad->setCleanup(true);
2208 // This function searches starting with the input block for the next
2209 // block that terminates with a branch whose condition is based on a selector
2210 // comparison. This may be the input block. See the mapLandingPadBlocks
2211 // comments for a discussion of control flow assumptions.
2213 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2214 BasicBlock *&NextBB,
2215 VisitedBlockSet &VisitedBlocks) {
2216 // See if we've already found a catch handler use it.
2217 // Call count() first to avoid creating a null entry for blocks
2218 // we haven't seen before.
2219 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2220 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2221 NextBB = Action->getNextBB();
2225 // VisitedBlocks applies only to the current search. We still
2226 // need to consider blocks that we've visited while mapping other
2228 VisitedBlocks.insert(BB);
2230 BasicBlock *CatchBlock = nullptr;
2231 Constant *Selector = nullptr;
2233 // If this is the first time we've visited this block from any landing pad
2234 // look to see if it is a selector dispatch block.
2235 if (!CatchHandlerMap.count(BB)) {
2236 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2237 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2238 CatchHandlerMap[BB] = Action;
2241 // If we encounter a block containing an llvm.eh.begincatch before we
2242 // find a selector dispatch block, the handler is assumed to be
2243 // reached unconditionally. This happens for catch-all blocks, but
2244 // it can also happen for other catch handlers that have been combined
2245 // with the catch-all handler during optimization.
2246 if (isCatchBlock(BB)) {
2247 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2248 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2249 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2250 CatchHandlerMap[BB] = Action;
2255 // Visit each successor, looking for the dispatch.
2256 // FIXME: We expect to find the dispatch quickly, so this will probably
2257 // work better as a breadth first search.
2258 for (BasicBlock *Succ : successors(BB)) {
2259 if (VisitedBlocks.count(Succ))
2262 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2269 // These are helper functions to combine repeated code from findCleanupHandlers.
2270 static void createCleanupHandler(LandingPadActions &Actions,
2271 CleanupHandlerMapTy &CleanupHandlerMap,
2273 CleanupHandler *Action = new CleanupHandler(BB);
2274 CleanupHandlerMap[BB] = Action;
2275 Actions.insertCleanupHandler(Action);
2276 DEBUG(dbgs() << " Found cleanup code in block "
2277 << Action->getStartBlock()->getName() << "\n");
2280 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2281 Instruction *MaybeCall) {
2282 // Look for finally blocks that Clang has already outlined for us.
2283 // %fp = call i8* @llvm.localaddress()
2284 // call void @"fin$parent"(iN 1, i8* %fp)
2285 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2286 MaybeCall = MaybeCall->getNextNode();
2287 CallSite FinallyCall(MaybeCall);
2288 if (!FinallyCall || FinallyCall.arg_size() != 2)
2290 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2292 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
2297 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2298 // Skip single ubr blocks.
2299 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2300 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2301 if (Br && Br->isUnconditional())
2302 BB = Br->getSuccessor(0);
2309 // This function searches starting with the input block for the next block that
2310 // contains code that is not part of a catch handler and would not be eliminated
2311 // during handler outlining.
2313 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2314 BasicBlock *StartBB, BasicBlock *EndBB) {
2315 // Here we will skip over the following:
2317 // landing pad prolog:
2319 // Unconditional branches
2321 // Selector dispatch
2325 // Anything else marks the start of an interesting block
2327 BasicBlock *BB = StartBB;
2328 // Anything other than an unconditional branch will kick us out of this loop
2329 // one way or another.
2331 BB = followSingleUnconditionalBranches(BB);
2332 // If we've already scanned this block, don't scan it again. If it is
2333 // a cleanup block, there will be an action in the CleanupHandlerMap.
2334 // If we've scanned it and it is not a cleanup block, there will be a
2335 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2336 // be no entry in the CleanupHandlerMap. We must call count() first to
2337 // avoid creating a null entry for blocks we haven't scanned.
2338 if (CleanupHandlerMap.count(BB)) {
2339 if (auto *Action = CleanupHandlerMap[BB]) {
2340 Actions.insertCleanupHandler(Action);
2341 DEBUG(dbgs() << " Found cleanup code in block "
2342 << Action->getStartBlock()->getName() << "\n");
2343 // FIXME: This cleanup might chain into another, and we need to discover
2347 // Here we handle the case where the cleanup handler map contains a
2348 // value for this block but the value is a nullptr. This means that
2349 // we have previously analyzed the block and determined that it did
2350 // not contain any cleanup code. Based on the earlier analysis, we
2351 // know the block must end in either an unconditional branch, a
2352 // resume or a conditional branch that is predicated on a comparison
2353 // with a selector. Either the resume or the selector dispatch
2354 // would terminate the search for cleanup code, so the unconditional
2355 // branch is the only case for which we might need to continue
2357 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2358 if (SuccBB == BB || SuccBB == EndBB)
2365 // Create an entry in the cleanup handler map for this block. Initially
2366 // we create an entry that says this isn't a cleanup block. If we find
2367 // cleanup code, the caller will replace this entry.
2368 CleanupHandlerMap[BB] = nullptr;
2370 TerminatorInst *Terminator = BB->getTerminator();
2372 // Landing pad blocks have extra instructions we need to accept.
2373 LandingPadMap *LPadMap = nullptr;
2374 if (BB->isLandingPad()) {
2375 LandingPadInst *LPad = BB->getLandingPadInst();
2376 LPadMap = &LPadMaps[LPad];
2377 if (!LPadMap->isInitialized())
2378 LPadMap->mapLandingPad(LPad);
2381 // Look for the bare resume pattern:
2382 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2383 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2384 // resume { i8*, i32 } %lpad.val2
2385 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2386 InsertValueInst *Insert1 = nullptr;
2387 InsertValueInst *Insert2 = nullptr;
2388 Value *ResumeVal = Resume->getOperand(0);
2389 // If the resume value isn't a phi or landingpad value, it should be a
2390 // series of insertions. Identify them so we can avoid them when scanning
2392 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2393 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2395 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2396 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2398 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2400 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2402 Instruction *Inst = II;
2403 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2405 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2407 if (!Inst->hasOneUse() ||
2408 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2409 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2415 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2416 if (Branch && Branch->isConditional()) {
2417 // Look for the selector dispatch.
2418 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2419 // %matches = icmp eq i32 %sel, %2
2420 // br i1 %matches, label %catch14, label %eh.resume
2421 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2422 if (!Compare || !Compare->isEquality())
2423 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2424 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2426 Instruction *Inst = II;
2427 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2429 if (Inst == Compare || Inst == Branch)
2431 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2433 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2435 // The selector dispatch block should always terminate our search.
2436 assert(BB == EndBB);
2440 if (isAsynchronousEHPersonality(Personality)) {
2441 // If this is a landingpad block, split the block at the first non-landing
2443 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2445 while (MaybeCall != BB->getTerminator() &&
2446 LPadMap->isLandingPadSpecificInst(MaybeCall))
2447 MaybeCall = MaybeCall->getNextNode();
2450 // Look for outlined finally calls on x64, since those happen to match the
2451 // prototype provided by the runtime.
2452 if (TheTriple.getArch() == Triple::x86_64) {
2453 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2454 Function *Fin = FinallyCall.getCalledFunction();
2455 assert(Fin && "outlined finally call should be direct");
2456 auto *Action = new CleanupHandler(BB);
2457 Action->setHandlerBlockOrFunc(Fin);
2458 Actions.insertCleanupHandler(Action);
2459 CleanupHandlerMap[BB] = Action;
2460 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2461 << Fin->getName() << " in block "
2462 << Action->getStartBlock()->getName() << "\n");
2464 // Split the block if there were more interesting instructions and
2465 // look for finally calls in the normal successor block.
2466 BasicBlock *SuccBB = BB;
2467 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2468 FinallyCall.getInstruction()->getNextNode() !=
2469 BB->getTerminator()) {
2471 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2473 if (FinallyCall.isInvoke()) {
2474 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2477 SuccBB = BB->getUniqueSuccessor();
2479 "splitOutlinedFinallyCalls didn't insert a branch");
2490 // Anything else is either a catch block or interesting cleanup code.
2491 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2493 Instruction *Inst = II;
2494 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2496 // Unconditional branches fall through to this loop.
2499 // If this is a catch block, there is no cleanup code to be found.
2500 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2502 // If this a nested landing pad, it may contain an endcatch call.
2503 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2505 // Anything else makes this interesting cleanup code.
2506 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2509 // Only unconditional branches in empty blocks should get this far.
2510 assert(Branch && Branch->isUnconditional());
2513 BB = Branch->getSuccessor(0);
2517 // This is a public function, declared in WinEHFuncInfo.h and is also
2518 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2519 void llvm::parseEHActions(
2520 const IntrinsicInst *II,
2521 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
2522 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2523 "attempted to parse non eh.actions intrinsic");
2524 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2525 uint64_t ActionKind =
2526 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2527 if (ActionKind == /*catch=*/1) {
2528 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2529 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2530 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2531 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2533 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2534 /*NextBB=*/nullptr);
2535 CH->setHandlerBlockOrFunc(Handler);
2536 CH->setExceptionVarIndex(EHObjIndexVal);
2537 Actions.push_back(std::move(CH));
2538 } else if (ActionKind == 0) {
2539 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2541 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
2542 CH->setHandlerBlockOrFunc(Handler);
2543 Actions.push_back(std::move(CH));
2545 llvm_unreachable("Expected either a catch or cleanup handler!");
2548 std::reverse(Actions.begin(), Actions.end());
2552 struct WinEHNumbering {
2553 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2554 CurrentBaseState(-1), NextState(0) {}
2556 WinEHFuncInfo &FuncInfo;
2557 int CurrentBaseState;
2560 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2561 SmallPtrSet<const Function *, 4> VisitedHandlers;
2563 int currentEHNumber() const {
2564 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2567 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2568 void createTryBlockMapEntry(int TryLow, int TryHigh,
2569 ArrayRef<CatchHandler *> Handlers);
2570 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2571 ImmutableCallSite CS);
2572 void popUnmatchedActions(int FirstMismatch);
2573 void calculateStateNumbers(const Function &F);
2574 void findActionRootLPads(const Function &F);
2578 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2579 WinEHUnwindMapEntry UME;
2580 UME.ToState = ToState;
2581 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2582 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
2584 UME.Cleanup = nullptr;
2585 FuncInfo.UnwindMap.push_back(UME);
2588 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2589 ArrayRef<CatchHandler *> Handlers) {
2590 // See if we already have an entry for this set of handlers.
2591 // This is using iterators rather than a range-based for loop because
2592 // if we find the entry we're looking for we'll need the iterator to erase it.
2593 int NumHandlers = Handlers.size();
2594 auto I = FuncInfo.TryBlockMap.begin();
2595 auto E = FuncInfo.TryBlockMap.end();
2596 for ( ; I != E; ++I) {
2598 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2601 for (N = 0; N < NumHandlers; ++N) {
2602 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2603 break; // breaks out of inner loop
2605 // If all the handlers match, this is what we were looking for.
2606 if (N == NumHandlers) {
2611 // If we found an existing entry for this set of handlers, extend the range
2612 // but move the entry to the end of the map vector. The order of entries
2613 // in the map is critical to the way that the runtime finds handlers.
2614 // FIXME: Depending on what has happened with block ordering, this may
2615 // incorrectly combine entries that should remain separate.
2617 // Copy the existing entry.
2618 WinEHTryBlockMapEntry Entry = *I;
2619 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2620 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2621 assert(Entry.TryLow <= Entry.TryHigh);
2622 // Erase the old entry and add this one to the back.
2623 FuncInfo.TryBlockMap.erase(I);
2624 FuncInfo.TryBlockMap.push_back(Entry);
2628 // If we didn't find an entry, create a new one.
2629 WinEHTryBlockMapEntry TBME;
2630 TBME.TryLow = TryLow;
2631 TBME.TryHigh = TryHigh;
2632 assert(TBME.TryLow <= TBME.TryHigh);
2633 for (CatchHandler *CH : Handlers) {
2634 WinEHHandlerType HT;
2635 if (CH->getSelector()->isNullValue()) {
2636 HT.Adjectives = 0x40;
2637 HT.TypeDescriptor = nullptr;
2639 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2640 // Selectors are always pointers to GlobalVariables with 'struct' type.
2641 // The struct has two fields, adjectives and a type descriptor.
2642 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2644 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2646 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2648 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2649 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2650 TBME.HandlerArray.push_back(HT);
2652 FuncInfo.TryBlockMap.push_back(TBME);
2655 static void print_name(const Value *V) {
2658 DEBUG(dbgs() << "null");
2662 if (const auto *F = dyn_cast<Function>(V))
2663 DEBUG(dbgs() << F->getName());
2669 void WinEHNumbering::processCallSite(
2670 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2671 ImmutableCallSite CS) {
2672 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2674 print_name(CS ? CS.getCalledValue() : nullptr);
2675 DEBUG(dbgs() << '\n');
2677 DEBUG(dbgs() << "HandlerStack: \n");
2678 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2679 DEBUG(dbgs() << " ");
2680 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2681 DEBUG(dbgs() << '\n');
2683 DEBUG(dbgs() << "Actions: \n");
2684 for (int I = 0, E = Actions.size(); I < E; ++I) {
2685 DEBUG(dbgs() << " ");
2686 print_name(Actions[I]->getHandlerBlockOrFunc());
2687 DEBUG(dbgs() << '\n');
2689 int FirstMismatch = 0;
2690 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2692 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2693 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2697 // Remove unmatched actions from the stack and process their EH states.
2698 popUnmatchedActions(FirstMismatch);
2700 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2701 print_name(CS ? CS.getCalledValue() : nullptr);
2702 DEBUG(dbgs() << '\n');
2704 bool LastActionWasCatch = false;
2705 const LandingPadInst *LastRootLPad = nullptr;
2706 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2707 // We can reuse eh states when pushing two catches for the same invoke.
2708 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2709 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2710 // Various conditions can lead to a handler being popped from the
2711 // stack and re-pushed later. That shouldn't create a new state.
2712 // FIXME: Can code optimization lead to re-used handlers?
2713 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2714 // If we already assigned the state enclosed by this handler re-use it.
2715 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2718 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2719 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2720 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2721 Actions[I]->setEHState(currentEHNumber());
2723 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2724 print_name(Actions[I]->getHandlerBlockOrFunc());
2725 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2726 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2727 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2728 Actions[I]->setEHState(NextState);
2731 HandlerStack.push_back(std::move(Actions[I]));
2732 LastActionWasCatch = CurrActionIsCatch;
2733 LastRootLPad = RootLPad;
2736 // This is used to defer numbering states for a handler until after the
2737 // last time it appears in an invoke action list.
2738 if (CS.isInvoke()) {
2739 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2740 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2741 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2743 FuncInfo.LastInvokeVisited[Handler] = true;
2744 DEBUG(dbgs() << "Last invoke of ");
2745 print_name(Handler);
2746 DEBUG(dbgs() << " has been visited.\n");
2750 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2751 print_name(CS ? CS.getCalledValue() : nullptr);
2752 DEBUG(dbgs() << '\n');
2755 void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2756 // Don't recurse while we are looping over the handler stack. Instead, defer
2757 // the numbering of the catch handlers until we are done popping.
2758 SmallVector<CatchHandler *, 4> PoppedCatches;
2759 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2760 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2761 if (isa<CatchHandler>(Handler.get()))
2762 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2765 int TryHigh = NextState - 1;
2766 int LastTryLowIdx = 0;
2767 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2768 CatchHandler *CH = PoppedCatches[I];
2769 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2770 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2771 int TryLow = CH->getEHState();
2773 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2774 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2775 for (size_t J = 0; J < Handlers.size(); ++J) {
2776 DEBUG(dbgs() << ", ");
2777 print_name(Handlers[J]->getHandlerBlockOrFunc());
2779 DEBUG(dbgs() << ")\n");
2780 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2781 LastTryLowIdx = I + 1;
2785 for (CatchHandler *CH : PoppedCatches) {
2786 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2787 if (FuncInfo.LastInvokeVisited[F]) {
2788 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2790 DEBUG(dbgs() << '\n');
2791 FuncInfo.HandlerBaseState[F] = NextState;
2792 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2794 createUnwindMapEntry(currentEHNumber(), nullptr);
2796 calculateStateNumbers(*F);
2799 DEBUG(dbgs() << "Deferring handling of ");
2801 DEBUG(dbgs() << " until last invoke visited.\n");
2808 void WinEHNumbering::calculateStateNumbers(const Function &F) {
2809 auto I = VisitedHandlers.insert(&F);
2811 return; // We've already visited this handler, don't renumber it.
2813 int OldBaseState = CurrentBaseState;
2814 if (FuncInfo.HandlerBaseState.count(&F)) {
2815 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2818 size_t SavedHandlerStackSize = HandlerStack.size();
2820 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2821 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2822 for (const BasicBlock &BB : F) {
2823 for (const Instruction &I : BB) {
2824 const auto *CI = dyn_cast<CallInst>(&I);
2825 if (!CI || CI->doesNotThrow())
2827 processCallSite(None, CI);
2829 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2832 const LandingPadInst *LPI = II->getLandingPadInst();
2833 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2836 parseEHActions(ActionsCall, ActionList);
2837 if (ActionList.empty())
2839 processCallSite(ActionList, II);
2841 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
2842 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2843 << " to landing pad at " << LPI->getParent()->getName()
2847 // Pop any actions that were pushed on the stack for this function.
2848 popUnmatchedActions(SavedHandlerStackSize);
2850 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2851 << " to " << F.getName() << '\n');
2852 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2854 CurrentBaseState = OldBaseState;
2857 // This function follows the same basic traversal as calculateStateNumbers
2858 // but it is necessary to identify the root landing pad associated
2859 // with each action before we start assigning state numbers.
2860 void WinEHNumbering::findActionRootLPads(const Function &F) {
2861 auto I = VisitedHandlers.insert(&F);
2863 return; // We've already visited this handler, don't revisit it.
2865 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2866 for (const BasicBlock &BB : F) {
2867 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2870 const LandingPadInst *LPI = II->getLandingPadInst();
2871 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2875 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2876 parseEHActions(ActionsCall, ActionList);
2877 if (ActionList.empty())
2879 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2881 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2882 FuncInfo.LastInvoke[Handler] = II;
2883 // Don't replace the root landing pad if we previously saw this
2884 // handler in a different function.
2885 if (FuncInfo.RootLPad.count(Handler) &&
2886 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2888 DEBUG(dbgs() << "Setting root lpad for ");
2889 print_name(Handler);
2890 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2891 FuncInfo.RootLPad[Handler] = LPI;
2894 // Walk the actions again and look for nested handlers. This has to
2895 // happen after all of the actions have been processed in the current
2897 for (int I = 0, E = ActionList.size(); I < E; ++I)
2899 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2900 findActionRootLPads(*Handler);
2905 void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
2906 WinEHFuncInfo &FuncInfo) {
2907 // Return if it's already been done.
2908 if (!FuncInfo.LandingPadStateMap.empty())
2911 WinEHNumbering Num(FuncInfo);
2912 Num.findActionRootLPads(*ParentFn);
2913 // The VisitedHandlers list is used by both findActionRootLPads and
2914 // calculateStateNumbers, but both functions need to visit all handlers.
2915 Num.VisitedHandlers.clear();
2916 Num.calculateStateNumbers(*ParentFn);
2917 // Pop everything on the handler stack.
2918 // It may be necessary to call this more than once because a handler can
2919 // be pushed on the stack as a result of clearing the stack.
2920 while (!Num.HandlerStack.empty())
2921 Num.processCallSite(None, ImmutableCallSite());
2924 void WinEHPrepare::numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB) {
2925 Instruction *FirstNonPHI = FuncletBB->getFirstNonPHI();
2926 bool IsCatch = isa<CatchPadInst>(FirstNonPHI);
2927 bool IsCleanup = isa<CleanupPadInst>(FirstNonPHI);
2929 // Initialize the worklist with the funclet's entry point.
2930 std::vector<BasicBlock *> Worklist;
2931 Worklist.push_back(InitialBB);
2933 while (!Worklist.empty()) {
2934 BasicBlock *BB = Worklist.back();
2935 Worklist.pop_back();
2937 // There can be only one "pad" basic block in the funclet: the initial one.
2938 if (BB != FuncletBB && BB->isEHPad())
2941 // Add 'FuncletBB' as a possible color for 'BB'.
2942 if (BlockColors[BB].insert(FuncletBB).second == false) {
2943 // Skip basic blocks which we have already visited.
2947 FuncletBlocks[FuncletBB].insert(BB);
2949 Instruction *Terminator = BB->getTerminator();
2950 // The catchret's successors cannot be part of the funclet.
2951 if (IsCatch && isa<CatchReturnInst>(Terminator))
2953 // The cleanupret's successors cannot be part of the funclet.
2954 if (IsCleanup && isa<CleanupReturnInst>(Terminator))
2957 Worklist.insert(Worklist.end(), succ_begin(BB), succ_end(BB));
2961 bool WinEHPrepare::prepareExplicitEH(Function &F) {
2962 // Remove unreachable blocks. It is not valuable to assign them a color and
2963 // their existence can trick us into thinking values are alive when they are
2965 removeUnreachableBlocks(F);
2967 BasicBlock *EntryBlock = &F.getEntryBlock();
2969 // Number everything starting from the entry block.
2970 numberFunclet(EntryBlock, EntryBlock);
2972 for (BasicBlock &BB : F) {
2973 // Remove single entry PHIs to simplify preparation.
2974 if (auto *PN = dyn_cast<PHINode>(BB.begin()))
2975 if (PN->getNumIncomingValues() == 1)
2976 FoldSingleEntryPHINodes(&BB);
2978 // EH pad instructions are always the first non-PHI nodes in a block if they
2979 // are at all present.
2980 Instruction *I = BB.getFirstNonPHI();
2982 numberFunclet(&BB, &BB);
2984 // It is possible for a normal basic block to only be reachable via an
2985 // exceptional basic block. The successor of a catchret is the only case
2986 // where this is possible.
2987 if (auto *CRI = dyn_cast<CatchReturnInst>(BB.getTerminator()))
2988 numberFunclet(CRI->getSuccessor(), EntryBlock);
2991 // Strip PHI nodes off of EH pads.
2992 SmallVector<PHINode *, 16> PHINodes;
2993 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
2994 BasicBlock *BB = FI++;
2997 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
2998 Instruction *I = BI++;
2999 auto *PN = dyn_cast<PHINode>(I);
3000 // Stop at the first non-PHI.
3004 AllocaInst *SpillSlot = insertPHILoads(PN, F);
3006 insertPHIStores(PN, SpillSlot);
3008 PHINodes.push_back(PN);
3012 for (auto *PN : PHINodes) {
3013 // There may be lingering uses on other EH PHIs being removed
3014 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3015 PN->eraseFromParent();
3018 // Turn all inter-funclet uses of a Value into loads and stores.
3019 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3020 BasicBlock *BB = FI++;
3021 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3022 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3023 Instruction *I = BI++;
3024 // Funclets are permitted to use static allocas.
3025 if (auto *AI = dyn_cast<AllocaInst>(I))
3026 if (AI->isStaticAlloca())
3029 demoteNonlocalUses(I, ColorsForBB, F);
3032 // Also demote function parameters used in funclets.
3033 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3034 for (Argument &Arg : F.args())
3035 demoteNonlocalUses(&Arg, ColorsForEntry, F);
3037 // We need to clone all blocks which belong to multiple funclets. Values are
3038 // remapped throughout the funclet to propogate both the new instructions
3039 // *and* the new basic blocks themselves.
3040 for (auto &Funclet : FuncletBlocks) {
3041 BasicBlock *FuncletPadBB = Funclet.first;
3042 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3044 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3045 ValueToValueMapTy VMap;
3046 for (BasicBlock *BB : BlocksInFunclet) {
3047 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3048 // We don't need to do anything if the block is monochromatic.
3049 size_t NumColorsForBB = ColorsForBB.size();
3050 if (NumColorsForBB == 1)
3053 assert(!isa<PHINode>(BB->front()) &&
3054 "Polychromatic PHI nodes should have been demoted!");
3056 // Create a new basic block and copy instructions into it!
3057 BasicBlock *CBB = CloneBasicBlock(
3058 BB, VMap, Twine(".for.", FuncletPadBB->getName()), &F);
3060 // Add basic block mapping.
3063 // Record delta operations that we need to perform to our color mappings.
3064 Orig2Clone[BB] = CBB;
3067 // Update our color mappings to reflect that one block has lost a color and
3068 // another has gained a color.
3069 for (auto &BBMapping : Orig2Clone) {
3070 BasicBlock *OldBlock = BBMapping.first;
3071 BasicBlock *NewBlock = BBMapping.second;
3073 BlocksInFunclet.insert(NewBlock);
3074 BlockColors[NewBlock].insert(FuncletPadBB);
3076 BlocksInFunclet.erase(OldBlock);
3077 BlockColors[OldBlock].erase(FuncletPadBB);
3080 // Loop over all of the instructions in the function, fixing up operand
3081 // references as we go. This uses VMap to do all the hard work.
3082 for (BasicBlock *BB : BlocksInFunclet)
3083 // Loop over all instructions, fixing each one as we find it...
3084 for (Instruction &I : *BB)
3085 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3088 // Remove implausible terminators and replace them with UnreachableInst.
3089 for (auto &Funclet : FuncletBlocks) {
3090 BasicBlock *FuncletPadBB = Funclet.first;
3091 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3092 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3093 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3094 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3096 for (BasicBlock *BB : BlocksInFunclet) {
3097 TerminatorInst *TI = BB->getTerminator();
3098 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3099 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3100 // The token consumed by a CatchReturnInst must match the funclet token.
3101 bool IsUnreachableCatchret = false;
3102 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
3103 IsUnreachableCatchret = CRI->getReturnValue() != CatchPad;
3104 // The token consumed by a CleanupPadInst must match the funclet token.
3105 bool IsUnreachableCleanupret = false;
3106 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
3107 IsUnreachableCleanupret = CRI->getReturnValue() != CleanupPad;
3108 if (IsUnreachableRet || IsUnreachableCatchret || IsUnreachableCleanupret) {
3109 new UnreachableInst(BB->getContext(), TI);
3110 TI->eraseFromParent();
3115 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3117 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3118 BasicBlock *BB = FI++;
3119 SimplifyInstructionsInBlock(BB);
3120 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3121 MergeBlockIntoPredecessor(BB);
3124 // We might have some unreachable blocks after cleaning up some impossible
3126 removeUnreachableBlocks(F);
3128 // Recolor the CFG to verify that all is well.
3129 for (BasicBlock &BB : F) {
3130 size_t NumColors = BlockColors[&BB].size();
3131 assert(NumColors == 1 && "Expected monochromatic BB!");
3133 report_fatal_error("Uncolored BB!");
3135 report_fatal_error("Multicolor BB!");
3136 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3137 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3139 report_fatal_error("EH Pad still has a PHI!");
3142 BlockColors.clear();
3143 FuncletBlocks.clear();
3147 // TODO: Share loads when one use dominates another, or when a catchpad exit
3148 // dominates uses (needs dominators).
3149 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3150 BasicBlock *PHIBlock = PN->getParent();
3151 AllocaInst *SpillSlot = nullptr;
3153 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3154 // Insert a load in place of the PHI and replace all uses.
3155 SpillSlot = new AllocaInst(PN->getType(), nullptr,
3156 Twine(PN->getName(), ".wineh.spillslot"),
3157 F.getEntryBlock().begin());
3158 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3159 PHIBlock->getFirstInsertionPt());
3160 PN->replaceAllUsesWith(V);
3164 DenseMap<BasicBlock *, Value *> Loads;
3165 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3168 auto *UsingInst = cast<Instruction>(U.getUser());
3169 BasicBlock *UsingBB = UsingInst->getParent();
3170 if (UsingBB->isEHPad()) {
3171 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
3172 // stores for it separately.
3173 assert(isa<PHINode>(UsingInst));
3176 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3181 // TODO: improve store placement. Inserting at def is probably good, but need
3182 // to be careful not to introduce interfering stores (needs liveness analysis).
3183 // TODO: identify related phi nodes that can share spill slots, and share them
3184 // (also needs liveness).
3185 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3186 AllocaInst *SpillSlot) {
3187 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3188 // stored to the spill slot by the end of the given Block.
3189 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3191 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3193 while (!Worklist.empty()) {
3194 BasicBlock *EHBlock;
3196 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3198 PHINode *PN = dyn_cast<PHINode>(InVal);
3199 if (PN && PN->getParent() == EHBlock) {
3200 // The value is defined by another PHI we need to remove, with no room to
3201 // insert a store after the PHI, so each predecessor needs to store its
3203 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3204 Value *PredVal = PN->getIncomingValue(i);
3206 // Undef can safely be skipped.
3207 if (isa<UndefValue>(PredVal))
3210 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3213 // We need to store InVal, which dominates EHBlock, but can't put a store
3214 // in EHBlock, so need to put stores in each predecessor.
3215 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3216 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3222 void WinEHPrepare::insertPHIStore(
3223 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3224 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3226 if (PredBlock->isEHPad() &&
3227 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3228 // Pred is unsplittable, so we need to queue it on the worklist.
3229 Worklist.push_back({PredBlock, PredVal});
3233 // Otherwise, insert the store at the end of the basic block.
3234 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3237 // TODO: Share loads for same-funclet uses (requires dominators if funclets
3238 // aren't properly nested).
3239 void WinEHPrepare::demoteNonlocalUses(Value *V,
3240 std::set<BasicBlock *> &ColorsForBB,
3242 // Tokens can only be used non-locally due to control flow involving
3243 // unreachable edges. Don't try to demote the token usage, we'll simply
3244 // delete the cloned user later.
3245 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3248 DenseMap<BasicBlock *, Value *> Loads;
3249 AllocaInst *SpillSlot = nullptr;
3250 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3252 auto *UsingInst = cast<Instruction>(U.getUser());
3253 BasicBlock *UsingBB = UsingInst->getParent();
3255 // Is the Use inside a block which is colored with a subset of the Def?
3256 // If so, we don't need to escape the Def because we will clone
3257 // ourselves our own private copy.
3258 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3259 if (std::includes(ColorsForBB.begin(), ColorsForBB.end(),
3260 ColorsForUsingBB.begin(), ColorsForUsingBB.end()))
3263 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3266 // Insert stores of the computed value into the stack slot.
3267 // We have to be careful if I is an invoke instruction,
3268 // because we can't insert the store AFTER the terminator instruction.
3269 BasicBlock::iterator InsertPt;
3270 if (isa<Argument>(V)) {
3271 InsertPt = F.getEntryBlock().getTerminator();
3272 } else if (isa<TerminatorInst>(V)) {
3273 auto *II = cast<InvokeInst>(V);
3274 // We cannot demote invoke instructions to the stack if their normal
3275 // edge is critical. Therefore, split the critical edge and create a
3276 // basic block into which the store can be inserted.
3277 if (!II->getNormalDest()->getSinglePredecessor()) {
3279 GetSuccessorNumber(II->getParent(), II->getNormalDest());
3280 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3281 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3282 assert(NewBlock && "Unable to split critical edge.");
3283 // Update the color mapping for the newly split edge.
3284 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3285 BlockColors[NewBlock] = ColorsForUsingBB;
3286 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3287 FuncletBlocks[FuncletPad].insert(NewBlock);
3289 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3291 InsertPt = cast<Instruction>(V);
3293 // Don't insert before PHI nodes or EH pad instrs.
3294 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3297 new StoreInst(V, SpillSlot, InsertPt);
3301 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3302 DenseMap<BasicBlock *, Value *> &Loads,
3304 // Lazilly create the spill slot.
3306 SpillSlot = new AllocaInst(V->getType(), nullptr,
3307 Twine(V->getName(), ".wineh.spillslot"),
3308 F.getEntryBlock().begin());
3310 auto *UsingInst = cast<Instruction>(U.getUser());
3311 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3312 // If this is a PHI node, we can't insert a load of the value before
3313 // the use. Instead insert the load in the predecessor block
3314 // corresponding to the incoming value.
3316 // Note that if there are multiple edges from a basic block to this
3317 // PHI node that we cannot have multiple loads. The problem is that
3318 // the resulting PHI node will have multiple values (from each load)
3319 // coming in from the same block, which is illegal SSA form.
3320 // For this reason, we keep track of and reuse loads we insert.
3321 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
3322 if (auto *CatchRet =
3323 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3324 // Putting a load above a catchret and use on the phi would still leave
3325 // a cross-funclet def/use. We need to split the edge, change the
3326 // catchret to target the new block, and put the load there.
3327 BasicBlock *PHIBlock = UsingInst->getParent();
3328 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3329 // SplitEdge gives us:
3332 // br label %NewBlock
3334 // catchret label %PHIBlock
3338 // catchret label %NewBlock
3340 // br label %PHIBlock
3341 // So move the terminators to each others' blocks and swap their
3343 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3344 Goto->removeFromParent();
3345 CatchRet->removeFromParent();
3346 IncomingBlock->getInstList().push_back(CatchRet);
3347 NewBlock->getInstList().push_back(Goto);
3348 Goto->setSuccessor(0, PHIBlock);
3349 CatchRet->setSuccessor(NewBlock);
3350 // Update the color mapping for the newly split edge.
3351 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3352 BlockColors[NewBlock] = ColorsForPHIBlock;
3353 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3354 FuncletBlocks[FuncletPad].insert(NewBlock);
3355 // Treat the new block as incoming for load insertion.
3356 IncomingBlock = NewBlock;
3358 Value *&Load = Loads[IncomingBlock];
3359 // Insert the load into the predecessor block
3361 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3362 /*Volatile=*/false, IncomingBlock->getTerminator());
3366 // Reload right before the old use.
3367 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3368 /*Volatile=*/false, UsingInst);