[WinEH] Improve fatal error message about failed demotion
[oota-llvm.git] / lib / CodeGen / WinEHPrepare.cpp
1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers LLVM IR exception handling into something closer to what the
11 // backend wants for functions using a personality function from a runtime
12 // provided by MSVC. Functions with other personality functions are left alone
13 // and may be prepared by other passes. In particular, all supported MSVC
14 // personality functions require cleanup code to be outlined, and the C++
15 // personality requires catch handler code to be outlined.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/TinyPtrVector.h"
26 #include "llvm/Analysis/LibCallSemantics.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/IRBuilder.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/PatternMatch.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
40 #include "llvm/Transforms/Utils/Local.h"
41 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
42 #include <memory>
43
44 using namespace llvm;
45 using namespace llvm::PatternMatch;
46
47 #define DEBUG_TYPE "winehprepare"
48
49 namespace {
50
51 // This map is used to model frame variable usage during outlining, to
52 // construct a structure type to hold the frame variables in a frame
53 // allocation block, and to remap the frame variable allocas (including
54 // spill locations as needed) to GEPs that get the variable from the
55 // frame allocation structure.
56 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
57
58 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
59 // quite null.
60 AllocaInst *getCatchObjectSentinel() {
61   return static_cast<AllocaInst *>(nullptr) + 1;
62 }
63
64 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
65
66 class LandingPadActions;
67 class LandingPadMap;
68
69 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
70 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
71
72 class WinEHPrepare : public FunctionPass {
73 public:
74   static char ID; // Pass identification, replacement for typeid.
75   WinEHPrepare(const TargetMachine *TM = nullptr)
76       : FunctionPass(ID) {
77     if (TM)
78       TheTriple = Triple(TM->getTargetTriple());
79   }
80
81   bool runOnFunction(Function &Fn) override;
82
83   bool doFinalization(Module &M) override;
84
85   void getAnalysisUsage(AnalysisUsage &AU) const override;
86
87   const char *getPassName() const override {
88     return "Windows exception handling preparation";
89   }
90
91 private:
92   bool prepareExceptionHandlers(Function &F,
93                                 SmallVectorImpl<LandingPadInst *> &LPads);
94   void promoteLandingPadValues(LandingPadInst *LPad);
95   void demoteValuesLiveAcrossHandlers(Function &F,
96                                       SmallVectorImpl<LandingPadInst *> &LPads);
97   void findSEHEHReturnPoints(Function &F,
98                              SetVector<BasicBlock *> &EHReturnBlocks);
99   void findCXXEHReturnPoints(Function &F,
100                              SetVector<BasicBlock *> &EHReturnBlocks);
101   void completeNestedLandingPad(Function *ParentFn,
102                                 LandingPadInst *OutlinedLPad,
103                                 const LandingPadInst *OriginalLPad,
104                                 FrameVarInfoMap &VarInfo);
105   Function *createHandlerFunc(Type *RetTy, const Twine &Name, Module *M,
106                               Value *&ParentFP);
107   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
108                       LandingPadInst *LPad, BasicBlock *StartBB,
109                       FrameVarInfoMap &VarInfo);
110   void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
111
112   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
113   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
114                                  VisitedBlockSet &VisitedBlocks);
115   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
116                            BasicBlock *EndBB);
117
118   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
119
120   Triple TheTriple;
121
122   // All fields are reset by runOnFunction.
123   DominatorTree *DT = nullptr;
124   EHPersonality Personality = EHPersonality::Unknown;
125   CatchHandlerMapTy CatchHandlerMap;
126   CleanupHandlerMapTy CleanupHandlerMap;
127   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
128
129   // This maps landing pad instructions found in outlined handlers to
130   // the landing pad instruction in the parent function from which they
131   // were cloned.  The cloned/nested landing pad is used as the key
132   // because the landing pad may be cloned into multiple handlers.
133   // This map will be used to add the llvm.eh.actions call to the nested
134   // landing pads after all handlers have been outlined.
135   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
136
137   // This maps blocks in the parent function which are destinations of
138   // catch handlers to cloned blocks in (other) outlined handlers. This
139   // handles the case where a nested landing pads has a catch handler that
140   // returns to a handler function rather than the parent function.
141   // The original block is used as the key here because there should only
142   // ever be one handler function from which the cloned block is not pruned.
143   // The original block will be pruned from the parent function after all
144   // handlers have been outlined.  This map will be used to adjust the
145   // return instructions of handlers which return to the block that was
146   // outlined into a handler.  This is done after all handlers have been
147   // outlined but before the outlined code is pruned from the parent function.
148   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
149
150   // Map from outlined handler to call to llvm.frameaddress(1). Only used for
151   // 32-bit EH.
152   DenseMap<Function *, Value *> HandlerToParentFP;
153
154   AllocaInst *SEHExceptionCodeSlot = nullptr;
155 };
156
157 class WinEHFrameVariableMaterializer : public ValueMaterializer {
158 public:
159   WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
160                                  FrameVarInfoMap &FrameVarInfo);
161   ~WinEHFrameVariableMaterializer() override {}
162
163   Value *materializeValueFor(Value *V) override;
164
165   void escapeCatchObject(Value *V);
166
167 private:
168   FrameVarInfoMap &FrameVarInfo;
169   IRBuilder<> Builder;
170 };
171
172 class LandingPadMap {
173 public:
174   LandingPadMap() : OriginLPad(nullptr) {}
175   void mapLandingPad(const LandingPadInst *LPad);
176
177   bool isInitialized() { return OriginLPad != nullptr; }
178
179   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
180   bool isLandingPadSpecificInst(const Instruction *Inst) const;
181
182   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
183                      Value *SelectorValue) const;
184
185 private:
186   const LandingPadInst *OriginLPad;
187   // We will normally only see one of each of these instructions, but
188   // if more than one occurs for some reason we can handle that.
189   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
190   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
191 };
192
193 class WinEHCloningDirectorBase : public CloningDirector {
194 public:
195   WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
196                            FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
197       : Materializer(HandlerFn, ParentFP, VarInfo),
198         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
199         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
200         LPadMap(LPadMap), ParentFP(ParentFP) {}
201
202   CloningAction handleInstruction(ValueToValueMapTy &VMap,
203                                   const Instruction *Inst,
204                                   BasicBlock *NewBB) override;
205
206   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
207                                          const Instruction *Inst,
208                                          BasicBlock *NewBB) = 0;
209   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
210                                        const Instruction *Inst,
211                                        BasicBlock *NewBB) = 0;
212   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
213                                         const Instruction *Inst,
214                                         BasicBlock *NewBB) = 0;
215   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
216                                      const InvokeInst *Invoke,
217                                      BasicBlock *NewBB) = 0;
218   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
219                                      const ResumeInst *Resume,
220                                      BasicBlock *NewBB) = 0;
221   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
222                                       const CmpInst *Compare,
223                                       BasicBlock *NewBB) = 0;
224   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
225                                          const LandingPadInst *LPad,
226                                          BasicBlock *NewBB) = 0;
227
228   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
229
230 protected:
231   WinEHFrameVariableMaterializer Materializer;
232   Type *SelectorIDType;
233   Type *Int8PtrType;
234   LandingPadMap &LPadMap;
235
236   /// The value representing the parent frame pointer.
237   Value *ParentFP;
238 };
239
240 class WinEHCatchDirector : public WinEHCloningDirectorBase {
241 public:
242   WinEHCatchDirector(
243       Function *CatchFn, Value *ParentFP, Value *Selector,
244       FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
245       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
246       : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
247         CurrentSelector(Selector->stripPointerCasts()),
248         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
249
250   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
251                                  const Instruction *Inst,
252                                  BasicBlock *NewBB) override;
253   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
254                                BasicBlock *NewBB) override;
255   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
256                                 const Instruction *Inst,
257                                 BasicBlock *NewBB) override;
258   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
259                              BasicBlock *NewBB) override;
260   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
261                              BasicBlock *NewBB) override;
262   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
263                               BasicBlock *NewBB) override;
264   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
265                                  const LandingPadInst *LPad,
266                                  BasicBlock *NewBB) override;
267
268   Value *getExceptionVar() { return ExceptionObjectVar; }
269   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
270
271 private:
272   Value *CurrentSelector;
273
274   Value *ExceptionObjectVar;
275   TinyPtrVector<BasicBlock *> ReturnTargets;
276
277   // This will be a reference to the field of the same name in the WinEHPrepare
278   // object which instantiates this WinEHCatchDirector object.
279   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
280 };
281
282 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
283 public:
284   WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
285                        FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
286       : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
287                                  LPadMap) {}
288
289   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
290                                  const Instruction *Inst,
291                                  BasicBlock *NewBB) override;
292   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
293                                BasicBlock *NewBB) override;
294   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
295                                 const Instruction *Inst,
296                                 BasicBlock *NewBB) override;
297   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
298                              BasicBlock *NewBB) override;
299   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
300                              BasicBlock *NewBB) override;
301   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
302                               BasicBlock *NewBB) override;
303   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
304                                  const LandingPadInst *LPad,
305                                  BasicBlock *NewBB) override;
306 };
307
308 class LandingPadActions {
309 public:
310   LandingPadActions() : HasCleanupHandlers(false) {}
311
312   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
313   void insertCleanupHandler(CleanupHandler *Action) {
314     Actions.push_back(Action);
315     HasCleanupHandlers = true;
316   }
317
318   bool includesCleanup() const { return HasCleanupHandlers; }
319
320   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
321   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
322   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
323
324 private:
325   // Note that this class does not own the ActionHandler objects in this vector.
326   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
327   // in the WinEHPrepare class.
328   SmallVector<ActionHandler *, 4> Actions;
329   bool HasCleanupHandlers;
330 };
331
332 } // end anonymous namespace
333
334 char WinEHPrepare::ID = 0;
335 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
336                    false, false)
337
338 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
339   return new WinEHPrepare(TM);
340 }
341
342 bool WinEHPrepare::runOnFunction(Function &Fn) {
343   // No need to prepare outlined handlers.
344   if (Fn.hasFnAttribute("wineh-parent"))
345     return false;
346
347   SmallVector<LandingPadInst *, 4> LPads;
348   SmallVector<ResumeInst *, 4> Resumes;
349   for (BasicBlock &BB : Fn) {
350     if (auto *LP = BB.getLandingPadInst())
351       LPads.push_back(LP);
352     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
353       Resumes.push_back(Resume);
354   }
355
356   // No need to prepare functions that lack landing pads.
357   if (LPads.empty())
358     return false;
359
360   // Classify the personality to see what kind of preparation we need.
361   Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
362
363   // Do nothing if this is not an MSVC personality.
364   if (!isMSVCEHPersonality(Personality))
365     return false;
366
367   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
368
369   // If there were any landing pads, prepareExceptionHandlers will make changes.
370   prepareExceptionHandlers(Fn, LPads);
371   return true;
372 }
373
374 bool WinEHPrepare::doFinalization(Module &M) { return false; }
375
376 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
377   AU.addRequired<DominatorTreeWrapperPass>();
378 }
379
380 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
381                                Constant *&Selector, BasicBlock *&NextBB);
382
383 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
384 // edges or blocks listed in StopPoints.
385 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
386                                 SetVector<BasicBlock *> &Worklist,
387                                 const SetVector<BasicBlock *> *StopPoints) {
388   while (!Worklist.empty()) {
389     BasicBlock *BB = Worklist.pop_back_val();
390
391     // Don't cross blocks that we should stop at.
392     if (StopPoints && StopPoints->count(BB))
393       continue;
394
395     if (!ReachableBBs.insert(BB).second)
396       continue; // Already visited.
397
398     // Don't follow unwind edges of invokes.
399     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
400       Worklist.insert(II->getNormalDest());
401       continue;
402     }
403
404     // Otherwise, follow all successors.
405     Worklist.insert(succ_begin(BB), succ_end(BB));
406   }
407 }
408
409 // Attempt to find an instruction where a block can be split before
410 // a call to llvm.eh.begincatch and its operands.  If the block
411 // begins with the begincatch call or one of its adjacent operands
412 // the block will not be split.
413 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
414                                              IntrinsicInst *II) {
415   // If the begincatch call is already the first instruction in the block,
416   // don't split.
417   Instruction *FirstNonPHI = BB->getFirstNonPHI();
418   if (II == FirstNonPHI)
419     return nullptr;
420
421   // If either operand is in the same basic block as the instruction and
422   // isn't used by another instruction before the begincatch call, include it
423   // in the split block.
424   auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
425   auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
426
427   Instruction *I = II->getPrevNode();
428   Instruction *LastI = II;
429
430   while (I == Op0 || I == Op1) {
431     // If the block begins with one of the operands and there are no other
432     // instructions between the operand and the begincatch call, don't split.
433     if (I == FirstNonPHI)
434       return nullptr;
435
436     LastI = I;
437     I = I->getPrevNode();
438   }
439
440   // If there is at least one instruction in the block before the begincatch
441   // call and its operands, split the block at either the begincatch or
442   // its operand.
443   return LastI;
444 }
445
446 /// Find all points where exceptional control rejoins normal control flow via
447 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
448 void WinEHPrepare::findCXXEHReturnPoints(
449     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
450   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
451     BasicBlock *BB = BBI;
452     for (Instruction &I : *BB) {
453       if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
454         Instruction *SplitPt =
455             findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
456         if (SplitPt) {
457           // Split the block before the llvm.eh.begincatch call to allow
458           // cleanup and catch code to be distinguished later.
459           // Do not update BBI because we still need to process the
460           // portion of the block that we are splitting off.
461           SplitBlock(BB, SplitPt, DT);
462           break;
463         }
464       }
465       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
466         // Split the block after the call to llvm.eh.endcatch if there is
467         // anything other than an unconditional branch, or if the successor
468         // starts with a phi.
469         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
470         if (!Br || !Br->isUnconditional() ||
471             isa<PHINode>(Br->getSuccessor(0)->begin())) {
472           DEBUG(dbgs() << "splitting block " << BB->getName()
473                        << " with llvm.eh.endcatch\n");
474           BBI = SplitBlock(BB, I.getNextNode(), DT);
475         }
476         // The next BB is normal control flow.
477         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
478         break;
479       }
480     }
481   }
482 }
483
484 static bool isCatchAllLandingPad(const BasicBlock *BB) {
485   const LandingPadInst *LP = BB->getLandingPadInst();
486   if (!LP)
487     return false;
488   unsigned N = LP->getNumClauses();
489   return (N > 0 && LP->isCatch(N - 1) &&
490           isa<ConstantPointerNull>(LP->getClause(N - 1)));
491 }
492
493 /// Find all points where exceptions control rejoins normal control flow via
494 /// selector dispatch.
495 void WinEHPrepare::findSEHEHReturnPoints(
496     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
497   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
498     BasicBlock *BB = BBI;
499     // If the landingpad is a catch-all, treat the whole lpad as if it is
500     // reachable from normal control flow.
501     // FIXME: This is imprecise. We need a better way of identifying where a
502     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
503     // is no difference.
504     if (isCatchAllLandingPad(BB)) {
505       EHReturnBlocks.insert(BB);
506       continue;
507     }
508
509     BasicBlock *CatchHandler;
510     BasicBlock *NextBB;
511     Constant *Selector;
512     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
513       // Split the edge if there is a phi node. Returning from EH to a phi node
514       // is just as impossible as having a phi after an indirectbr.
515       if (isa<PHINode>(CatchHandler->begin())) {
516         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
517                      << " to " << CatchHandler->getName() << '\n');
518         BBI = CatchHandler = SplitCriticalEdge(
519             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
520       }
521       EHReturnBlocks.insert(CatchHandler);
522     }
523   }
524 }
525
526 /// Ensure that all values live into and out of exception handlers are stored
527 /// in memory.
528 /// FIXME: This falls down when values are defined in one handler and live into
529 /// another handler. For example, a cleanup defines a value used only by a
530 /// catch handler.
531 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
532     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
533   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
534                << F.getName() << '\n');
535
536   // Build a set of all non-exceptional blocks and exceptional blocks.
537   // - Non-exceptional blocks are blocks reachable from the entry block while
538   //   not following invoke unwind edges.
539   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
540   //   not follow llvm.eh.endcatch blocks, which mark a transition from
541   //   exceptional to normal control.
542   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
543   SmallPtrSet<BasicBlock *, 4> EHBlocks;
544   SetVector<BasicBlock *> EHReturnBlocks;
545   SetVector<BasicBlock *> Worklist;
546
547   if (Personality == EHPersonality::MSVC_CXX)
548     findCXXEHReturnPoints(F, EHReturnBlocks);
549   else
550     findSEHEHReturnPoints(F, EHReturnBlocks);
551
552   DEBUG({
553     dbgs() << "identified the following blocks as EH return points:\n";
554     for (BasicBlock *BB : EHReturnBlocks)
555       dbgs() << "  " << BB->getName() << '\n';
556   });
557
558 // Join points should not have phis at this point, unless they are a
559 // landingpad, in which case we will demote their phis later.
560 #ifndef NDEBUG
561   for (BasicBlock *BB : EHReturnBlocks)
562     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
563            "non-lpad EH return block has phi");
564 #endif
565
566   // Normal blocks are the blocks reachable from the entry block and all EH
567   // return points.
568   Worklist = EHReturnBlocks;
569   Worklist.insert(&F.getEntryBlock());
570   findReachableBlocks(NormalBlocks, Worklist, nullptr);
571   DEBUG({
572     dbgs() << "marked the following blocks as normal:\n";
573     for (BasicBlock *BB : NormalBlocks)
574       dbgs() << "  " << BB->getName() << '\n';
575   });
576
577   // Exceptional blocks are the blocks reachable from landingpads that don't
578   // cross EH return points.
579   Worklist.clear();
580   for (auto *LPI : LPads)
581     Worklist.insert(LPI->getParent());
582   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
583   DEBUG({
584     dbgs() << "marked the following blocks as exceptional:\n";
585     for (BasicBlock *BB : EHBlocks)
586       dbgs() << "  " << BB->getName() << '\n';
587   });
588
589   SetVector<Argument *> ArgsToDemote;
590   SetVector<Instruction *> InstrsToDemote;
591   for (BasicBlock &BB : F) {
592     bool IsNormalBB = NormalBlocks.count(&BB);
593     bool IsEHBB = EHBlocks.count(&BB);
594     if (!IsNormalBB && !IsEHBB)
595       continue; // Blocks that are neither normal nor EH are unreachable.
596     for (Instruction &I : BB) {
597       for (Value *Op : I.operands()) {
598         // Don't demote static allocas, constants, and labels.
599         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
600           continue;
601         auto *AI = dyn_cast<AllocaInst>(Op);
602         if (AI && AI->isStaticAlloca())
603           continue;
604
605         if (auto *Arg = dyn_cast<Argument>(Op)) {
606           if (IsEHBB) {
607             DEBUG(dbgs() << "Demoting argument " << *Arg
608                          << " used by EH instr: " << I << "\n");
609             ArgsToDemote.insert(Arg);
610           }
611           continue;
612         }
613
614         auto *OpI = cast<Instruction>(Op);
615         BasicBlock *OpBB = OpI->getParent();
616         // If a value is produced and consumed in the same BB, we don't need to
617         // demote it.
618         if (OpBB == &BB)
619           continue;
620         bool IsOpNormalBB = NormalBlocks.count(OpBB);
621         bool IsOpEHBB = EHBlocks.count(OpBB);
622         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
623           DEBUG({
624             dbgs() << "Demoting instruction live in-out from EH:\n";
625             dbgs() << "Instr: " << *OpI << '\n';
626             dbgs() << "User: " << I << '\n';
627           });
628           InstrsToDemote.insert(OpI);
629         }
630       }
631     }
632   }
633
634   // Demote values live into and out of handlers.
635   // FIXME: This demotion is inefficient. We should insert spills at the point
636   // of definition, insert one reload in each handler that uses the value, and
637   // insert reloads in the BB used to rejoin normal control flow.
638   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
639   for (Instruction *I : InstrsToDemote)
640     DemoteRegToStack(*I, false, AllocaInsertPt);
641
642   // Demote arguments separately, and only for uses in EH blocks.
643   for (Argument *Arg : ArgsToDemote) {
644     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
645                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
646     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
647     for (User *U : Users) {
648       auto *I = dyn_cast<Instruction>(U);
649       if (I && EHBlocks.count(I->getParent())) {
650         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
651         U->replaceUsesOfWith(Arg, Reload);
652       }
653     }
654     new StoreInst(Arg, Slot, AllocaInsertPt);
655   }
656
657   // Demote landingpad phis, as the landingpad will be removed from the machine
658   // CFG.
659   for (LandingPadInst *LPI : LPads) {
660     BasicBlock *BB = LPI->getParent();
661     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
662       DemotePHIToStack(Phi, AllocaInsertPt);
663   }
664
665   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
666                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
667 }
668
669 bool WinEHPrepare::prepareExceptionHandlers(
670     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
671   // Don't run on functions that are already prepared.
672   for (LandingPadInst *LPad : LPads) {
673     BasicBlock *LPadBB = LPad->getParent();
674     for (Instruction &Inst : *LPadBB)
675       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
676         return false;
677   }
678
679   demoteValuesLiveAcrossHandlers(F, LPads);
680
681   // These containers are used to re-map frame variables that are used in
682   // outlined catch and cleanup handlers.  They will be populated as the
683   // handlers are outlined.
684   FrameVarInfoMap FrameVarInfo;
685
686   bool HandlersOutlined = false;
687
688   Module *M = F.getParent();
689   LLVMContext &Context = M->getContext();
690
691   // Create a new function to receive the handler contents.
692   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
693   Type *Int32Type = Type::getInt32Ty(Context);
694   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
695
696   if (isAsynchronousEHPersonality(Personality)) {
697     // FIXME: Switch the ehptr type to i32 and then switch this.
698     SEHExceptionCodeSlot =
699         new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
700                        F.getEntryBlock().getFirstInsertionPt());
701   }
702
703   for (LandingPadInst *LPad : LPads) {
704     // Look for evidence that this landingpad has already been processed.
705     bool LPadHasActionList = false;
706     BasicBlock *LPadBB = LPad->getParent();
707     for (Instruction &Inst : *LPadBB) {
708       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
709         LPadHasActionList = true;
710         break;
711       }
712     }
713
714     // If we've already outlined the handlers for this landingpad,
715     // there's nothing more to do here.
716     if (LPadHasActionList)
717       continue;
718
719     // If either of the values in the aggregate returned by the landing pad is
720     // extracted and stored to memory, promote the stored value to a register.
721     promoteLandingPadValues(LPad);
722
723     LandingPadActions Actions;
724     mapLandingPadBlocks(LPad, Actions);
725
726     HandlersOutlined |= !Actions.actions().empty();
727     for (ActionHandler *Action : Actions) {
728       if (Action->hasBeenProcessed())
729         continue;
730       BasicBlock *StartBB = Action->getStartBlock();
731
732       // SEH doesn't do any outlining for catches. Instead, pass the handler
733       // basic block addr to llvm.eh.actions and list the block as a return
734       // target.
735       if (isAsynchronousEHPersonality(Personality)) {
736         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
737           processSEHCatchHandler(CatchAction, StartBB);
738           continue;
739         }
740       }
741
742       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
743     }
744
745     // Split the block after the landingpad instruction so that it is just a
746     // call to llvm.eh.actions followed by indirectbr.
747     assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
748     SplitBlock(LPadBB, LPad->getNextNode(), DT);
749     // Erase the branch inserted by the split so we can insert indirectbr.
750     LPadBB->getTerminator()->eraseFromParent();
751
752     // Replace all extracted values with undef and ultimately replace the
753     // landingpad with undef.
754     SmallVector<Instruction *, 4> SEHCodeUses;
755     SmallVector<Instruction *, 4> EHUndefs;
756     for (User *U : LPad->users()) {
757       auto *E = dyn_cast<ExtractValueInst>(U);
758       if (!E)
759         continue;
760       assert(E->getNumIndices() == 1 &&
761              "Unexpected operation: extracting both landing pad values");
762       unsigned Idx = *E->idx_begin();
763       assert((Idx == 0 || Idx == 1) && "unexpected index");
764       if (Idx == 0 && isAsynchronousEHPersonality(Personality))
765         SEHCodeUses.push_back(E);
766       else
767         EHUndefs.push_back(E);
768     }
769     for (Instruction *E : EHUndefs) {
770       E->replaceAllUsesWith(UndefValue::get(E->getType()));
771       E->eraseFromParent();
772     }
773     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
774
775     // Rewrite uses of the exception pointer to loads of an alloca.
776     for (Instruction *E : SEHCodeUses) {
777       SmallVector<Use *, 4> Uses;
778       for (Use &U : E->uses())
779         Uses.push_back(&U);
780       for (Use *U : Uses) {
781         auto *I = cast<Instruction>(U->getUser());
782         if (isa<ResumeInst>(I))
783           continue;
784         LoadInst *LI;
785         if (auto *Phi = dyn_cast<PHINode>(I))
786           LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false,
787                             Phi->getIncomingBlock(*U));
788         else
789           LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I);
790         U->set(LI);
791       }
792       E->replaceAllUsesWith(UndefValue::get(E->getType()));
793       E->eraseFromParent();
794     }
795
796     // Add a call to describe the actions for this landing pad.
797     std::vector<Value *> ActionArgs;
798     for (ActionHandler *Action : Actions) {
799       // Action codes from docs are: 0 cleanup, 1 catch.
800       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
801         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
802         ActionArgs.push_back(CatchAction->getSelector());
803         // Find the frame escape index of the exception object alloca in the
804         // parent.
805         int FrameEscapeIdx = -1;
806         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
807         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
808           auto I = FrameVarInfo.find(EHObj);
809           assert(I != FrameVarInfo.end() &&
810                  "failed to map llvm.eh.begincatch var");
811           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
812         }
813         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
814       } else {
815         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
816       }
817       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
818     }
819     CallInst *Recover =
820         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
821
822     // Add an indirect branch listing possible successors of the catch handlers.
823     SetVector<BasicBlock *> ReturnTargets;
824     for (ActionHandler *Action : Actions) {
825       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
826         const auto &CatchTargets = CatchAction->getReturnTargets();
827         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
828       }
829     }
830     IndirectBrInst *Branch =
831         IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
832     for (BasicBlock *Target : ReturnTargets)
833       Branch->addDestination(Target);
834   } // End for each landingpad
835
836   // If nothing got outlined, there is no more processing to be done.
837   if (!HandlersOutlined)
838     return false;
839
840   // Replace any nested landing pad stubs with the correct action handler.
841   // This must be done before we remove unreachable blocks because it
842   // cleans up references to outlined blocks that will be deleted.
843   for (auto &LPadPair : NestedLPtoOriginalLP)
844     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
845   NestedLPtoOriginalLP.clear();
846
847   F.addFnAttr("wineh-parent", F.getName());
848
849   // Delete any blocks that were only used by handlers that were outlined above.
850   removeUnreachableBlocks(F);
851
852   BasicBlock *Entry = &F.getEntryBlock();
853   IRBuilder<> Builder(F.getParent()->getContext());
854   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
855
856   Function *FrameEscapeFn =
857       Intrinsic::getDeclaration(M, Intrinsic::frameescape);
858   Function *RecoverFrameFn =
859       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
860   SmallVector<Value *, 8> AllocasToEscape;
861
862   // Scan the entry block for an existing call to llvm.frameescape. We need to
863   // keep escaping those objects.
864   for (Instruction &I : F.front()) {
865     auto *II = dyn_cast<IntrinsicInst>(&I);
866     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
867       auto Args = II->arg_operands();
868       AllocasToEscape.append(Args.begin(), Args.end());
869       II->eraseFromParent();
870       break;
871     }
872   }
873
874   // Finally, replace all of the temporary allocas for frame variables used in
875   // the outlined handlers with calls to llvm.framerecover.
876   for (auto &VarInfoEntry : FrameVarInfo) {
877     Value *ParentVal = VarInfoEntry.first;
878     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
879     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
880
881     // FIXME: We should try to sink unescaped allocas from the parent frame into
882     // the child frame. If the alloca is escaped, we have to use the lifetime
883     // markers to ensure that the alloca is only live within the child frame.
884
885     // Add this alloca to the list of things to escape.
886     AllocasToEscape.push_back(ParentAlloca);
887
888     // Next replace all outlined allocas that are mapped to it.
889     for (AllocaInst *TempAlloca : Allocas) {
890       if (TempAlloca == getCatchObjectSentinel())
891         continue; // Skip catch parameter sentinels.
892       Function *HandlerFn = TempAlloca->getParent()->getParent();
893       llvm::Value *FP = HandlerToParentFP[HandlerFn];
894       assert(FP);
895
896       // FIXME: Sink this framerecover into the blocks where it is used.
897       Builder.SetInsertPoint(TempAlloca);
898       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
899       Value *RecoverArgs[] = {
900           Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
901           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
902       Instruction *RecoveredAlloca =
903           Builder.CreateCall(RecoverFrameFn, RecoverArgs);
904
905       // Add a pointer bitcast if the alloca wasn't an i8.
906       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
907         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
908         RecoveredAlloca = cast<Instruction>(
909             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
910       }
911       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
912       TempAlloca->removeFromParent();
913       RecoveredAlloca->takeName(TempAlloca);
914       delete TempAlloca;
915     }
916   } // End for each FrameVarInfo entry.
917
918   // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
919   // block.
920   Builder.SetInsertPoint(&F.getEntryBlock().back());
921   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
922
923   if (SEHExceptionCodeSlot) {
924     if (SEHExceptionCodeSlot->hasNUses(0))
925       SEHExceptionCodeSlot->eraseFromParent();
926     else if (isAllocaPromotable(SEHExceptionCodeSlot))
927       PromoteMemToReg(SEHExceptionCodeSlot, *DT);
928   }
929
930   // Clean up the handler action maps we created for this function
931   DeleteContainerSeconds(CatchHandlerMap);
932   CatchHandlerMap.clear();
933   DeleteContainerSeconds(CleanupHandlerMap);
934   CleanupHandlerMap.clear();
935   HandlerToParentFP.clear();
936   DT = nullptr;
937   SEHExceptionCodeSlot = nullptr;
938
939   return HandlersOutlined;
940 }
941
942 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
943   // If the return values of the landing pad instruction are extracted and
944   // stored to memory, we want to promote the store locations to reg values.
945   SmallVector<AllocaInst *, 2> EHAllocas;
946
947   // The landingpad instruction returns an aggregate value.  Typically, its
948   // value will be passed to a pair of extract value instructions and the
949   // results of those extracts are often passed to store instructions.
950   // In unoptimized code the stored value will often be loaded and then stored
951   // again.
952   for (auto *U : LPad->users()) {
953     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
954     if (!Extract)
955       continue;
956
957     for (auto *EU : Extract->users()) {
958       if (auto *Store = dyn_cast<StoreInst>(EU)) {
959         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
960         EHAllocas.push_back(AV);
961       }
962     }
963   }
964
965   // We can't do this without a dominator tree.
966   assert(DT);
967
968   if (!EHAllocas.empty()) {
969     PromoteMemToReg(EHAllocas, *DT);
970     EHAllocas.clear();
971   }
972
973   // After promotion, some extracts may be trivially dead. Remove them.
974   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
975   for (auto *U : Users)
976     RecursivelyDeleteTriviallyDeadInstructions(U);
977 }
978
979 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
980                                             LandingPadInst *OutlinedLPad,
981                                             const LandingPadInst *OriginalLPad,
982                                             FrameVarInfoMap &FrameVarInfo) {
983   // Get the nested block and erase the unreachable instruction that was
984   // temporarily inserted as its terminator.
985   LLVMContext &Context = ParentFn->getContext();
986   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
987   assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
988   OutlinedBB->getTerminator()->eraseFromParent();
989   // That should leave OutlinedLPad as the last instruction in its block.
990   assert(&OutlinedBB->back() == OutlinedLPad);
991
992   // The original landing pad will have already had its action intrinsic
993   // built by the outlining loop.  We need to clone that into the outlined
994   // location.  It may also be necessary to add references to the exception
995   // variables to the outlined handler in which this landing pad is nested
996   // and remap return instructions in the nested handlers that should return
997   // to an address in the outlined handler.
998   Function *OutlinedHandlerFn = OutlinedBB->getParent();
999   BasicBlock::const_iterator II = OriginalLPad;
1000   ++II;
1001   // The instruction after the landing pad should now be a call to eh.actions.
1002   const Instruction *Recover = II;
1003   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
1004   IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
1005
1006   // Remap the exception variables into the outlined function.
1007   SmallVector<BlockAddress *, 4> ActionTargets;
1008   SmallVector<ActionHandler *, 4> ActionList;
1009   parseEHActions(EHActions, ActionList);
1010   for (auto *Action : ActionList) {
1011     auto *Catch = dyn_cast<CatchHandler>(Action);
1012     if (!Catch)
1013       continue;
1014     // The dyn_cast to function here selects C++ catch handlers and skips
1015     // SEH catch handlers.
1016     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1017     if (!Handler)
1018       continue;
1019     // Visit all the return instructions, looking for places that return
1020     // to a location within OutlinedHandlerFn.
1021     for (BasicBlock &NestedHandlerBB : *Handler) {
1022       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1023       if (!Ret)
1024         continue;
1025
1026       // Handler functions must always return a block address.
1027       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1028       // The original target will have been in the main parent function,
1029       // but if it is the address of a block that has been outlined, it
1030       // should be a block that was outlined into OutlinedHandlerFn.
1031       assert(BA->getFunction() == ParentFn);
1032
1033       // Ignore targets that aren't part of OutlinedHandlerFn.
1034       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1035         continue;
1036
1037       // If the return value is the address ofF a block that we
1038       // previously outlined into the parent handler function, replace
1039       // the return instruction and add the mapped target to the list
1040       // of possible return addresses.
1041       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1042       assert(MappedBB->getParent() == OutlinedHandlerFn);
1043       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1044       Ret->eraseFromParent();
1045       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1046       ActionTargets.push_back(NewBA);
1047     }
1048   }
1049   DeleteContainerPointers(ActionList);
1050   ActionList.clear();
1051   OutlinedBB->getInstList().push_back(EHActions);
1052
1053   // Insert an indirect branch into the outlined landing pad BB.
1054   IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
1055   // Add the previously collected action targets.
1056   for (auto *Target : ActionTargets)
1057     IBr->addDestination(Target->getBasicBlock());
1058 }
1059
1060 // This function examines a block to determine whether the block ends with a
1061 // conditional branch to a catch handler based on a selector comparison.
1062 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1063 // WinEHCleanupDirector::handleTypeIdFor().
1064 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1065                                Constant *&Selector, BasicBlock *&NextBB) {
1066   ICmpInst::Predicate Pred;
1067   BasicBlock *TBB, *FBB;
1068   Value *LHS, *RHS;
1069
1070   if (!match(BB->getTerminator(),
1071              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1072     return false;
1073
1074   if (!match(LHS,
1075              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1076       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1077     return false;
1078
1079   if (Pred == CmpInst::ICMP_EQ) {
1080     CatchHandler = TBB;
1081     NextBB = FBB;
1082     return true;
1083   }
1084
1085   if (Pred == CmpInst::ICMP_NE) {
1086     CatchHandler = FBB;
1087     NextBB = TBB;
1088     return true;
1089   }
1090
1091   return false;
1092 }
1093
1094 static bool isCatchBlock(BasicBlock *BB) {
1095   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1096        II != IE; ++II) {
1097     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1098       return true;
1099   }
1100   return false;
1101 }
1102
1103 static BasicBlock *createStubLandingPad(Function *Handler,
1104                                         Value *PersonalityFn) {
1105   // FIXME: Finish this!
1106   LLVMContext &Context = Handler->getContext();
1107   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1108   Handler->getBasicBlockList().push_back(StubBB);
1109   IRBuilder<> Builder(StubBB);
1110   LandingPadInst *LPad = Builder.CreateLandingPad(
1111       llvm::StructType::get(Type::getInt8PtrTy(Context),
1112                             Type::getInt32Ty(Context), nullptr),
1113       PersonalityFn, 0);
1114   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1115   Function *ActionIntrin =
1116       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1117   Builder.CreateCall(ActionIntrin, "recover");
1118   LPad->setCleanup(true);
1119   Builder.CreateUnreachable();
1120   return StubBB;
1121 }
1122
1123 // Cycles through the blocks in an outlined handler function looking for an
1124 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1125 // landing pad if none is found.  The code that generates the .xdata tables for
1126 // the handler needs at least one landing pad to identify the parent function's
1127 // personality.
1128 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1129                                                   Value *PersonalityFn) {
1130   ReturnInst *Ret = nullptr;
1131   UnreachableInst *Unreached = nullptr;
1132   for (BasicBlock &BB : *Handler) {
1133     TerminatorInst *Terminator = BB.getTerminator();
1134     // If we find an invoke, there is nothing to be done.
1135     auto *II = dyn_cast<InvokeInst>(Terminator);
1136     if (II)
1137       return;
1138     // If we've already recorded a return instruction, keep looking for invokes.
1139     if (!Ret)
1140       Ret = dyn_cast<ReturnInst>(Terminator);
1141     // If we haven't recorded an unreachable instruction, try this terminator.
1142     if (!Unreached)
1143       Unreached = dyn_cast<UnreachableInst>(Terminator);
1144   }
1145
1146   // If we got this far, the handler contains no invokes.  We should have seen
1147   // at least one return or unreachable instruction.  We'll insert an invoke of
1148   // llvm.donothing ahead of that instruction.
1149   assert(Ret || Unreached);
1150   TerminatorInst *Term;
1151   if (Ret)
1152     Term = Ret;
1153   else
1154     Term = Unreached;
1155   BasicBlock *OldRetBB = Term->getParent();
1156   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1157   // SplitBlock adds an unconditional branch instruction at the end of the
1158   // parent block.  We want to replace that with an invoke call, so we can
1159   // erase it now.
1160   OldRetBB->getTerminator()->eraseFromParent();
1161   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1162   Function *F =
1163       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1164   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1165 }
1166
1167 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1168 // usually doesn't build LLVM IR, so that's probably the wrong place.
1169 Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name,
1170                                           Module *M, Value *&ParentFP) {
1171   // x64 uses a two-argument prototype where the parent FP is the second
1172   // argument. x86 uses no arguments, just the incoming EBP value.
1173   LLVMContext &Context = M->getContext();
1174   FunctionType *FnType;
1175   if (TheTriple.getArch() == Triple::x86_64) {
1176     Type *Int8PtrType = Type::getInt8PtrTy(Context);
1177     Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1178     FnType = FunctionType::get(RetTy, ArgTys, false);
1179   } else {
1180     FnType = FunctionType::get(RetTy, None, false);
1181   }
1182
1183   Function *Handler =
1184       Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1185   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1186   Handler->getBasicBlockList().push_front(Entry);
1187   if (TheTriple.getArch() == Triple::x86_64) {
1188     ParentFP = &(Handler->getArgumentList().back());
1189   } else {
1190     assert(M);
1191     Function *FrameAddressFn =
1192         Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1193     Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)};
1194     ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp",
1195                                 &Handler->getEntryBlock());
1196   }
1197   return Handler;
1198 }
1199
1200 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1201                                   LandingPadInst *LPad, BasicBlock *StartBB,
1202                                   FrameVarInfoMap &VarInfo) {
1203   Module *M = SrcFn->getParent();
1204   LLVMContext &Context = M->getContext();
1205   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1206
1207   // Create a new function to receive the handler contents.
1208   Value *ParentFP;
1209   Function *Handler;
1210   if (Action->getType() == Catch) {
1211     Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M,
1212                                 ParentFP);
1213   } else {
1214     Handler = createHandlerFunc(Type::getVoidTy(Context),
1215                                 SrcFn->getName() + ".cleanup", M, ParentFP);
1216   }
1217   HandlerToParentFP[Handler] = ParentFP;
1218   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1219   BasicBlock *Entry = &Handler->getEntryBlock();
1220
1221   // Generate a standard prolog to setup the frame recovery structure.
1222   IRBuilder<> Builder(Context);
1223   Builder.SetInsertPoint(Entry);
1224   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1225
1226   std::unique_ptr<WinEHCloningDirectorBase> Director;
1227
1228   ValueToValueMapTy VMap;
1229
1230   LandingPadMap &LPadMap = LPadMaps[LPad];
1231   if (!LPadMap.isInitialized())
1232     LPadMap.mapLandingPad(LPad);
1233   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1234     Constant *Sel = CatchAction->getSelector();
1235     Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
1236                                           VarInfo, LPadMap,
1237                                           NestedLPtoOriginalLP));
1238     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1239                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1240   } else {
1241     Director.reset(
1242         new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1243     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1244                           UndefValue::get(Type::getInt32Ty(Context)));
1245   }
1246
1247   SmallVector<ReturnInst *, 8> Returns;
1248   ClonedCodeInfo OutlinedFunctionInfo;
1249
1250   // If the start block contains PHI nodes, we need to map them.
1251   BasicBlock::iterator II = StartBB->begin();
1252   while (auto *PN = dyn_cast<PHINode>(II)) {
1253     bool Mapped = false;
1254     // Look for PHI values that we have already mapped (such as the selector).
1255     for (Value *Val : PN->incoming_values()) {
1256       if (VMap.count(Val)) {
1257         VMap[PN] = VMap[Val];
1258         Mapped = true;
1259       }
1260     }
1261     // If we didn't find a match for this value, map it as an undef.
1262     if (!Mapped) {
1263       VMap[PN] = UndefValue::get(PN->getType());
1264     }
1265     ++II;
1266   }
1267
1268   // The landing pad value may be used by PHI nodes.  It will ultimately be
1269   // eliminated, but we need it in the map for intermediate handling.
1270   VMap[LPad] = UndefValue::get(LPad->getType());
1271
1272   // Skip over PHIs and, if applicable, landingpad instructions.
1273   II = StartBB->getFirstInsertionPt();
1274
1275   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1276                             /*ModuleLevelChanges=*/false, Returns, "",
1277                             &OutlinedFunctionInfo, Director.get());
1278
1279   // Move all the instructions in the cloned "entry" block into our entry block.
1280   // Depending on how the parent function was laid out, the block that will
1281   // correspond to the outlined entry block may not be the first block in the
1282   // list.  We can recognize it, however, as the cloned block which has no
1283   // predecessors.  Any other block wouldn't have been cloned if it didn't
1284   // have a predecessor which was also cloned.
1285   Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1286   while (!pred_empty(ClonedIt))
1287     ++ClonedIt;
1288   BasicBlock *ClonedEntryBB = ClonedIt;
1289   assert(ClonedEntryBB);
1290   Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1291   ClonedEntryBB->eraseFromParent();
1292
1293   // Make sure we can identify the handler's personality later.
1294   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1295
1296   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1297     WinEHCatchDirector *CatchDirector =
1298         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1299     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1300     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1301
1302     // Look for blocks that are not part of the landing pad that we just
1303     // outlined but terminate with a call to llvm.eh.endcatch and a
1304     // branch to a block that is in the handler we just outlined.
1305     // These blocks will be part of a nested landing pad that intends to
1306     // return to an address in this handler.  This case is best handled
1307     // after both landing pads have been outlined, so for now we'll just
1308     // save the association of the blocks in LPadTargetBlocks.  The
1309     // return instructions which are created from these branches will be
1310     // replaced after all landing pads have been outlined.
1311     for (const auto MapEntry : VMap) {
1312       // VMap maps all values and blocks that were just cloned, but dead
1313       // blocks which were pruned will map to nullptr.
1314       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1315         continue;
1316       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1317       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1318         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1319         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1320           continue;
1321         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1322         --II;
1323         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1324           // This would indicate that a nested landing pad wants to return
1325           // to a block that is outlined into two different handlers.
1326           assert(!LPadTargetBlocks.count(MappedBB));
1327           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1328         }
1329       }
1330     }
1331   } // End if (CatchAction)
1332
1333   Action->setHandlerBlockOrFunc(Handler);
1334
1335   return true;
1336 }
1337
1338 /// This BB must end in a selector dispatch. All we need to do is pass the
1339 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1340 /// target.
1341 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1342                                           BasicBlock *StartBB) {
1343   BasicBlock *HandlerBB;
1344   BasicBlock *NextBB;
1345   Constant *Selector;
1346   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1347   if (Res) {
1348     // If this was EH dispatch, this must be a conditional branch to the handler
1349     // block.
1350     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1351     // leading to crashes if some optimization hoists stuff here.
1352     assert(CatchAction->getSelector() && HandlerBB &&
1353            "expected catch EH dispatch");
1354   } else {
1355     // This must be a catch-all. Split the block after the landingpad.
1356     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1357     HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1358   }
1359   IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1360   Function *EHCodeFn = Intrinsic::getDeclaration(
1361       StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1362   Value *Code = Builder.CreateCall(EHCodeFn, "sehcode");
1363   Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1364   Builder.CreateStore(Code, SEHExceptionCodeSlot);
1365   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1366   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1367   CatchAction->setReturnTargets(Targets);
1368 }
1369
1370 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1371   // Each instance of this class should only ever be used to map a single
1372   // landing pad.
1373   assert(OriginLPad == nullptr || OriginLPad == LPad);
1374
1375   // If the landing pad has already been mapped, there's nothing more to do.
1376   if (OriginLPad == LPad)
1377     return;
1378
1379   OriginLPad = LPad;
1380
1381   // The landingpad instruction returns an aggregate value.  Typically, its
1382   // value will be passed to a pair of extract value instructions and the
1383   // results of those extracts will have been promoted to reg values before
1384   // this routine is called.
1385   for (auto *U : LPad->users()) {
1386     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1387     if (!Extract)
1388       continue;
1389     assert(Extract->getNumIndices() == 1 &&
1390            "Unexpected operation: extracting both landing pad values");
1391     unsigned int Idx = *(Extract->idx_begin());
1392     assert((Idx == 0 || Idx == 1) &&
1393            "Unexpected operation: extracting an unknown landing pad element");
1394     if (Idx == 0) {
1395       ExtractedEHPtrs.push_back(Extract);
1396     } else if (Idx == 1) {
1397       ExtractedSelectors.push_back(Extract);
1398     }
1399   }
1400 }
1401
1402 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1403   return BB->getLandingPadInst() == OriginLPad;
1404 }
1405
1406 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1407   if (Inst == OriginLPad)
1408     return true;
1409   for (auto *Extract : ExtractedEHPtrs) {
1410     if (Inst == Extract)
1411       return true;
1412   }
1413   for (auto *Extract : ExtractedSelectors) {
1414     if (Inst == Extract)
1415       return true;
1416   }
1417   return false;
1418 }
1419
1420 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1421                                   Value *SelectorValue) const {
1422   // Remap all landing pad extract instructions to the specified values.
1423   for (auto *Extract : ExtractedEHPtrs)
1424     VMap[Extract] = EHPtrValue;
1425   for (auto *Extract : ExtractedSelectors)
1426     VMap[Extract] = SelectorValue;
1427 }
1428
1429 static bool isFrameAddressCall(const Value *V) {
1430   return match(const_cast<Value *>(V),
1431                m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1432 }
1433
1434 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1435     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1436   // If this is one of the boilerplate landing pad instructions, skip it.
1437   // The instruction will have already been remapped in VMap.
1438   if (LPadMap.isLandingPadSpecificInst(Inst))
1439     return CloningDirector::SkipInstruction;
1440
1441   // Nested landing pads will be cloned as stubs, with just the
1442   // landingpad instruction and an unreachable instruction. When
1443   // all landingpads have been outlined, we'll replace this with the
1444   // llvm.eh.actions call and indirect branch created when the
1445   // landing pad was outlined.
1446   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1447     return handleLandingPad(VMap, LPad, NewBB);
1448   }
1449
1450   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1451     return handleInvoke(VMap, Invoke, NewBB);
1452
1453   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1454     return handleResume(VMap, Resume, NewBB);
1455
1456   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1457     return handleCompare(VMap, Cmp, NewBB);
1458
1459   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1460     return handleBeginCatch(VMap, Inst, NewBB);
1461   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1462     return handleEndCatch(VMap, Inst, NewBB);
1463   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1464     return handleTypeIdFor(VMap, Inst, NewBB);
1465
1466   // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1467   // which is the FP of the parent.
1468   if (isFrameAddressCall(Inst)) {
1469     VMap[Inst] = ParentFP;
1470     return CloningDirector::SkipInstruction;
1471   }
1472
1473   // Continue with the default cloning behavior.
1474   return CloningDirector::CloneInstruction;
1475 }
1476
1477 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1478     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1479   Instruction *NewInst = LPad->clone();
1480   if (LPad->hasName())
1481     NewInst->setName(LPad->getName());
1482   // Save this correlation for later processing.
1483   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1484   VMap[LPad] = NewInst;
1485   BasicBlock::InstListType &InstList = NewBB->getInstList();
1486   InstList.push_back(NewInst);
1487   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1488   return CloningDirector::StopCloningBB;
1489 }
1490
1491 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1492     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1493   // The argument to the call is some form of the first element of the
1494   // landingpad aggregate value, but that doesn't matter.  It isn't used
1495   // here.
1496   // The second argument is an outparameter where the exception object will be
1497   // stored. Typically the exception object is a scalar, but it can be an
1498   // aggregate when catching by value.
1499   // FIXME: Leave something behind to indicate where the exception object lives
1500   // for this handler. Should it be part of llvm.eh.actions?
1501   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1502                                           "llvm.eh.begincatch found while "
1503                                           "outlining catch handler.");
1504   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1505   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1506     return CloningDirector::SkipInstruction;
1507   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1508          "catch parameter is not static alloca");
1509   Materializer.escapeCatchObject(ExceptionObjectVar);
1510   return CloningDirector::SkipInstruction;
1511 }
1512
1513 CloningDirector::CloningAction
1514 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1515                                    const Instruction *Inst, BasicBlock *NewBB) {
1516   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1517   // It might be interesting to track whether or not we are inside a catch
1518   // function, but that might make the algorithm more brittle than it needs
1519   // to be.
1520
1521   // The end catch call can occur in one of two places: either in a
1522   // landingpad block that is part of the catch handlers exception mechanism,
1523   // or at the end of the catch block.  However, a catch-all handler may call
1524   // end catch from the original landing pad.  If the call occurs in a nested
1525   // landing pad block, we must skip it and continue so that the landing pad
1526   // gets cloned.
1527   auto *ParentBB = IntrinCall->getParent();
1528   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1529     return CloningDirector::SkipInstruction;
1530
1531   // If an end catch occurs anywhere else we want to terminate the handler
1532   // with a return to the code that follows the endcatch call.  If the
1533   // next instruction is not an unconditional branch, we need to split the
1534   // block to provide a clear target for the return instruction.
1535   BasicBlock *ContinueBB;
1536   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1537   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1538   if (!Branch || !Branch->isUnconditional()) {
1539     // We're interrupting the cloning process at this location, so the
1540     // const_cast we're doing here will not cause a problem.
1541     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1542                             const_cast<Instruction *>(cast<Instruction>(Next)));
1543   } else {
1544     ContinueBB = Branch->getSuccessor(0);
1545   }
1546
1547   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1548   ReturnTargets.push_back(ContinueBB);
1549
1550   // We just added a terminator to the cloned block.
1551   // Tell the caller to stop processing the current basic block so that
1552   // the branch instruction will be skipped.
1553   return CloningDirector::StopCloningBB;
1554 }
1555
1556 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1557     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1558   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1559   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1560   // This causes a replacement that will collapse the landing pad CFG based
1561   // on the filter function we intend to match.
1562   if (Selector == CurrentSelector)
1563     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1564   else
1565     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1566   // Tell the caller not to clone this instruction.
1567   return CloningDirector::SkipInstruction;
1568 }
1569
1570 CloningDirector::CloningAction
1571 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1572                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1573   return CloningDirector::CloneInstruction;
1574 }
1575
1576 CloningDirector::CloningAction
1577 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1578                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1579   // Resume instructions shouldn't be reachable from catch handlers.
1580   // We still need to handle it, but it will be pruned.
1581   BasicBlock::InstListType &InstList = NewBB->getInstList();
1582   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1583   return CloningDirector::StopCloningBB;
1584 }
1585
1586 CloningDirector::CloningAction
1587 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1588                                   const CmpInst *Compare, BasicBlock *NewBB) {
1589   const IntrinsicInst *IntrinCall = nullptr;
1590   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1591     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1592   } else if (match(Compare->getOperand(1),
1593                    m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1594     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1595   }
1596   if (IntrinCall) {
1597     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1598     // This causes a replacement that will collapse the landing pad CFG based
1599     // on the filter function we intend to match.
1600     if (Selector == CurrentSelector->stripPointerCasts()) {
1601       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1602     } else {
1603       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1604     }
1605     return CloningDirector::SkipInstruction;
1606   }
1607   return CloningDirector::CloneInstruction;
1608 }
1609
1610 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1611     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1612   // The MS runtime will terminate the process if an exception occurs in a
1613   // cleanup handler, so we shouldn't encounter landing pads in the actual
1614   // cleanup code, but they may appear in catch blocks.  Depending on where
1615   // we started cloning we may see one, but it will get dropped during dead
1616   // block pruning.
1617   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1618   VMap[LPad] = NewInst;
1619   BasicBlock::InstListType &InstList = NewBB->getInstList();
1620   InstList.push_back(NewInst);
1621   return CloningDirector::StopCloningBB;
1622 }
1623
1624 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1625     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1626   // Cleanup code may flow into catch blocks or the catch block may be part
1627   // of a branch that will be optimized away.  We'll insert a return
1628   // instruction now, but it may be pruned before the cloning process is
1629   // complete.
1630   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1631   return CloningDirector::StopCloningBB;
1632 }
1633
1634 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1635     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1636   // Cleanup handlers nested within catch handlers may begin with a call to
1637   // eh.endcatch.  We can just ignore that instruction.
1638   return CloningDirector::SkipInstruction;
1639 }
1640
1641 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1642     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1643   // If we encounter a selector comparison while cloning a cleanup handler,
1644   // we want to stop cloning immediately.  Anything after the dispatch
1645   // will be outlined into a different handler.
1646   BasicBlock *CatchHandler;
1647   Constant *Selector;
1648   BasicBlock *NextBB;
1649   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1650                          CatchHandler, Selector, NextBB)) {
1651     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1652     return CloningDirector::StopCloningBB;
1653   }
1654   // If eg.typeid.for is called for any other reason, it can be ignored.
1655   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1656   return CloningDirector::SkipInstruction;
1657 }
1658
1659 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1660     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1661   // All invokes in cleanup handlers can be replaced with calls.
1662   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1663   // Insert a normal call instruction...
1664   CallInst *NewCall =
1665       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1666                        Invoke->getName(), NewBB);
1667   NewCall->setCallingConv(Invoke->getCallingConv());
1668   NewCall->setAttributes(Invoke->getAttributes());
1669   NewCall->setDebugLoc(Invoke->getDebugLoc());
1670   VMap[Invoke] = NewCall;
1671
1672   // Remap the operands.
1673   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1674
1675   // Insert an unconditional branch to the normal destination.
1676   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1677
1678   // The unwind destination won't be cloned into the new function, so
1679   // we don't need to clean up its phi nodes.
1680
1681   // We just added a terminator to the cloned block.
1682   // Tell the caller to stop processing the current basic block.
1683   return CloningDirector::CloneSuccessors;
1684 }
1685
1686 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1687     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1688   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1689
1690   // We just added a terminator to the cloned block.
1691   // Tell the caller to stop processing the current basic block so that
1692   // the branch instruction will be skipped.
1693   return CloningDirector::StopCloningBB;
1694 }
1695
1696 CloningDirector::CloningAction
1697 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1698                                     const CmpInst *Compare, BasicBlock *NewBB) {
1699   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1700       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1701     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1702     return CloningDirector::SkipInstruction;
1703   }
1704   return CloningDirector::CloneInstruction;
1705 }
1706
1707 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1708     Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
1709     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1710   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1711
1712   // New allocas should be inserted in the entry block, but after the parent FP
1713   // is established if it is an instruction.
1714   Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1715   if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1716     InsertPoint = FPInst->getNextNode();
1717   Builder.SetInsertPoint(EntryBB, InsertPoint);
1718 }
1719
1720 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1721   // If we're asked to materialize a static alloca, we temporarily create an
1722   // alloca in the outlined function and add this to the FrameVarInfo map.  When
1723   // all the outlining is complete, we'll replace these temporary allocas with
1724   // calls to llvm.framerecover.
1725   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1726     assert(AV->isStaticAlloca() &&
1727            "cannot materialize un-demoted dynamic alloca");
1728     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1729     Builder.Insert(NewAlloca, AV->getName());
1730     FrameVarInfo[AV].push_back(NewAlloca);
1731     return NewAlloca;
1732   }
1733
1734   if (isa<Instruction>(V) || isa<Argument>(V)) {
1735     Function *Parent = isa<Instruction>(V)
1736                            ? cast<Instruction>(V)->getParent()->getParent()
1737                            : cast<Argument>(V)->getParent();
1738     errs()
1739         << "Failed to demote instruction used in exception handler of function "
1740         << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
1741     errs() << "  " << *V << '\n';
1742     report_fatal_error("WinEHPrepare failed to demote instruction");
1743   }
1744
1745   // Don't materialize other values.
1746   return nullptr;
1747 }
1748
1749 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1750   // Catch parameter objects have to live in the parent frame. When we see a use
1751   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1752   // used from another handler. This will prevent us from trying to sink the
1753   // alloca into the handler and ensure that the catch parameter is present in
1754   // the call to llvm.frameescape.
1755   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1756 }
1757
1758 // This function maps the catch and cleanup handlers that are reachable from the
1759 // specified landing pad. The landing pad sequence will have this basic shape:
1760 //
1761 //  <cleanup handler>
1762 //  <selector comparison>
1763 //  <catch handler>
1764 //  <cleanup handler>
1765 //  <selector comparison>
1766 //  <catch handler>
1767 //  <cleanup handler>
1768 //  ...
1769 //
1770 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1771 // any arbitrary control flow, but all paths through the cleanup code must
1772 // eventually reach the next selector comparison and no path can skip to a
1773 // different selector comparisons, though some paths may terminate abnormally.
1774 // Therefore, we will use a depth first search from the start of any given
1775 // cleanup block and stop searching when we find the next selector comparison.
1776 //
1777 // If the landingpad instruction does not have a catch clause, we will assume
1778 // that any instructions other than selector comparisons and catch handlers can
1779 // be ignored.  In practice, these will only be the boilerplate instructions.
1780 //
1781 // The catch handlers may also have any control structure, but we are only
1782 // interested in the start of the catch handlers, so we don't need to actually
1783 // follow the flow of the catch handlers.  The start of the catch handlers can
1784 // be located from the compare instructions, but they can be skipped in the
1785 // flow by following the contrary branch.
1786 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1787                                        LandingPadActions &Actions) {
1788   unsigned int NumClauses = LPad->getNumClauses();
1789   unsigned int HandlersFound = 0;
1790   BasicBlock *BB = LPad->getParent();
1791
1792   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1793
1794   if (NumClauses == 0) {
1795     findCleanupHandlers(Actions, BB, nullptr);
1796     return;
1797   }
1798
1799   VisitedBlockSet VisitedBlocks;
1800
1801   while (HandlersFound != NumClauses) {
1802     BasicBlock *NextBB = nullptr;
1803
1804     // Skip over filter clauses.
1805     if (LPad->isFilter(HandlersFound)) {
1806       ++HandlersFound;
1807       continue;
1808     }
1809
1810     // See if the clause we're looking for is a catch-all.
1811     // If so, the catch begins immediately.
1812     Constant *ExpectedSelector =
1813         LPad->getClause(HandlersFound)->stripPointerCasts();
1814     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1815       // The catch all must occur last.
1816       assert(HandlersFound == NumClauses - 1);
1817
1818       // There can be additional selector dispatches in the call chain that we
1819       // need to ignore.
1820       BasicBlock *CatchBlock = nullptr;
1821       Constant *Selector;
1822       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1823         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1824                      << CatchBlock->getName() << "\n");
1825         BB = NextBB;
1826       }
1827
1828       // Add the catch handler to the action list.
1829       CatchHandler *Action = nullptr;
1830       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1831         // If the CatchHandlerMap already has an entry for this BB, re-use it.
1832         Action = CatchHandlerMap[BB];
1833         assert(Action->getSelector() == ExpectedSelector);
1834       } else {
1835         // We don't expect a selector dispatch, but there may be a call to
1836         // llvm.eh.begincatch, which separates catch handling code from
1837         // cleanup code in the same control flow.  This call looks for the
1838         // begincatch intrinsic.
1839         Action = findCatchHandler(BB, NextBB, VisitedBlocks);
1840         if (Action) {
1841           // For C++ EH, check if there is any interesting cleanup code before
1842           // we begin the catch. This is important because cleanups cannot
1843           // rethrow exceptions but code called from catches can. For SEH, it
1844           // isn't important if some finally code before a catch-all is executed
1845           // out of line or after recovering from the exception.
1846           if (Personality == EHPersonality::MSVC_CXX)
1847             findCleanupHandlers(Actions, BB, BB);
1848         } else {
1849           // If an action was not found, it means that the control flows
1850           // directly into the catch-all handler and there is no cleanup code.
1851           // That's an expected situation and we must create a catch action.
1852           // Since this is a catch-all handler, the selector won't actually
1853           // appear in the code anywhere.  ExpectedSelector here is the constant
1854           // null ptr that we got from the landing pad instruction.
1855           Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1856           CatchHandlerMap[BB] = Action;
1857         }
1858       }
1859       Actions.insertCatchHandler(Action);
1860       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1861       ++HandlersFound;
1862
1863       // Once we reach a catch-all, don't expect to hit a resume instruction.
1864       BB = nullptr;
1865       break;
1866     }
1867
1868     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1869     assert(CatchAction);
1870
1871     // See if there is any interesting code executed before the dispatch.
1872     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1873
1874     // When the source program contains multiple nested try blocks the catch
1875     // handlers can get strung together in such a way that we can encounter
1876     // a dispatch for a selector that we've already had a handler for.
1877     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1878       ++HandlersFound;
1879
1880       // Add the catch handler to the action list.
1881       DEBUG(dbgs() << "  Found catch dispatch in block "
1882                    << CatchAction->getStartBlock()->getName() << "\n");
1883       Actions.insertCatchHandler(CatchAction);
1884     } else {
1885       // Under some circumstances optimized IR will flow unconditionally into a
1886       // handler block without checking the selector.  This can only happen if
1887       // the landing pad has a catch-all handler and the handler for the
1888       // preceeding catch clause is identical to the catch-call handler
1889       // (typically an empty catch).  In this case, the handler must be shared
1890       // by all remaining clauses.
1891       if (isa<ConstantPointerNull>(
1892               CatchAction->getSelector()->stripPointerCasts())) {
1893         DEBUG(dbgs() << "  Applying early catch-all handler in block "
1894                      << CatchAction->getStartBlock()->getName()
1895                      << "  to all remaining clauses.\n");
1896         Actions.insertCatchHandler(CatchAction);
1897         return;
1898       }
1899
1900       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1901                    << CatchAction->getStartBlock()->getName() << "\n");
1902     }
1903
1904     // Move on to the block after the catch handler.
1905     BB = NextBB;
1906   }
1907
1908   // If we didn't wind up in a catch-all, see if there is any interesting code
1909   // executed before the resume.
1910   findCleanupHandlers(Actions, BB, BB);
1911
1912   // It's possible that some optimization moved code into a landingpad that
1913   // wasn't
1914   // previously being used for cleanup.  If that happens, we need to execute
1915   // that
1916   // extra code from a cleanup handler.
1917   if (Actions.includesCleanup() && !LPad->isCleanup())
1918     LPad->setCleanup(true);
1919 }
1920
1921 // This function searches starting with the input block for the next
1922 // block that terminates with a branch whose condition is based on a selector
1923 // comparison.  This may be the input block.  See the mapLandingPadBlocks
1924 // comments for a discussion of control flow assumptions.
1925 //
1926 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1927                                              BasicBlock *&NextBB,
1928                                              VisitedBlockSet &VisitedBlocks) {
1929   // See if we've already found a catch handler use it.
1930   // Call count() first to avoid creating a null entry for blocks
1931   // we haven't seen before.
1932   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1933     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1934     NextBB = Action->getNextBB();
1935     return Action;
1936   }
1937
1938   // VisitedBlocks applies only to the current search.  We still
1939   // need to consider blocks that we've visited while mapping other
1940   // landing pads.
1941   VisitedBlocks.insert(BB);
1942
1943   BasicBlock *CatchBlock = nullptr;
1944   Constant *Selector = nullptr;
1945
1946   // If this is the first time we've visited this block from any landing pad
1947   // look to see if it is a selector dispatch block.
1948   if (!CatchHandlerMap.count(BB)) {
1949     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1950       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1951       CatchHandlerMap[BB] = Action;
1952       return Action;
1953     }
1954     // If we encounter a block containing an llvm.eh.begincatch before we
1955     // find a selector dispatch block, the handler is assumed to be
1956     // reached unconditionally.  This happens for catch-all blocks, but
1957     // it can also happen for other catch handlers that have been combined
1958     // with the catch-all handler during optimization.
1959     if (isCatchBlock(BB)) {
1960       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1961       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1962       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1963       CatchHandlerMap[BB] = Action;
1964       return Action;
1965     }
1966   }
1967
1968   // Visit each successor, looking for the dispatch.
1969   // FIXME: We expect to find the dispatch quickly, so this will probably
1970   //        work better as a breadth first search.
1971   for (BasicBlock *Succ : successors(BB)) {
1972     if (VisitedBlocks.count(Succ))
1973       continue;
1974
1975     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1976     if (Action)
1977       return Action;
1978   }
1979   return nullptr;
1980 }
1981
1982 // These are helper functions to combine repeated code from findCleanupHandlers.
1983 static void createCleanupHandler(LandingPadActions &Actions,
1984                                  CleanupHandlerMapTy &CleanupHandlerMap,
1985                                  BasicBlock *BB) {
1986   CleanupHandler *Action = new CleanupHandler(BB);
1987   CleanupHandlerMap[BB] = Action;
1988   Actions.insertCleanupHandler(Action);
1989   DEBUG(dbgs() << "  Found cleanup code in block "
1990                << Action->getStartBlock()->getName() << "\n");
1991 }
1992
1993 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1994                                          Instruction *MaybeCall) {
1995   // Look for finally blocks that Clang has already outlined for us.
1996   //   %fp = call i8* @llvm.frameaddress(i32 0)
1997   //   call void @"fin$parent"(iN 1, i8* %fp)
1998   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1999     MaybeCall = MaybeCall->getNextNode();
2000   CallSite FinallyCall(MaybeCall);
2001   if (!FinallyCall || FinallyCall.arg_size() != 2)
2002     return CallSite();
2003   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2004     return CallSite();
2005   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
2006     return CallSite();
2007   return FinallyCall;
2008 }
2009
2010 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2011   // Skip single ubr blocks.
2012   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2013     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2014     if (Br && Br->isUnconditional())
2015       BB = Br->getSuccessor(0);
2016     else
2017       return BB;
2018   }
2019   return BB;
2020 }
2021
2022 // This function searches starting with the input block for the next block that
2023 // contains code that is not part of a catch handler and would not be eliminated
2024 // during handler outlining.
2025 //
2026 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2027                                        BasicBlock *StartBB, BasicBlock *EndBB) {
2028   // Here we will skip over the following:
2029   //
2030   // landing pad prolog:
2031   //
2032   // Unconditional branches
2033   //
2034   // Selector dispatch
2035   //
2036   // Resume pattern
2037   //
2038   // Anything else marks the start of an interesting block
2039
2040   BasicBlock *BB = StartBB;
2041   // Anything other than an unconditional branch will kick us out of this loop
2042   // one way or another.
2043   while (BB) {
2044     BB = followSingleUnconditionalBranches(BB);
2045     // If we've already scanned this block, don't scan it again.  If it is
2046     // a cleanup block, there will be an action in the CleanupHandlerMap.
2047     // If we've scanned it and it is not a cleanup block, there will be a
2048     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
2049     // be no entry in the CleanupHandlerMap.  We must call count() first to
2050     // avoid creating a null entry for blocks we haven't scanned.
2051     if (CleanupHandlerMap.count(BB)) {
2052       if (auto *Action = CleanupHandlerMap[BB]) {
2053         Actions.insertCleanupHandler(Action);
2054         DEBUG(dbgs() << "  Found cleanup code in block "
2055                      << Action->getStartBlock()->getName() << "\n");
2056         // FIXME: This cleanup might chain into another, and we need to discover
2057         // that.
2058         return;
2059       } else {
2060         // Here we handle the case where the cleanup handler map contains a
2061         // value for this block but the value is a nullptr.  This means that
2062         // we have previously analyzed the block and determined that it did
2063         // not contain any cleanup code.  Based on the earlier analysis, we
2064         // know the the block must end in either an unconditional branch, a
2065         // resume or a conditional branch that is predicated on a comparison
2066         // with a selector.  Either the resume or the selector dispatch
2067         // would terminate the search for cleanup code, so the unconditional
2068         // branch is the only case for which we might need to continue
2069         // searching.
2070         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2071         if (SuccBB == BB || SuccBB == EndBB)
2072           return;
2073         BB = SuccBB;
2074         continue;
2075       }
2076     }
2077
2078     // Create an entry in the cleanup handler map for this block.  Initially
2079     // we create an entry that says this isn't a cleanup block.  If we find
2080     // cleanup code, the caller will replace this entry.
2081     CleanupHandlerMap[BB] = nullptr;
2082
2083     TerminatorInst *Terminator = BB->getTerminator();
2084
2085     // Landing pad blocks have extra instructions we need to accept.
2086     LandingPadMap *LPadMap = nullptr;
2087     if (BB->isLandingPad()) {
2088       LandingPadInst *LPad = BB->getLandingPadInst();
2089       LPadMap = &LPadMaps[LPad];
2090       if (!LPadMap->isInitialized())
2091         LPadMap->mapLandingPad(LPad);
2092     }
2093
2094     // Look for the bare resume pattern:
2095     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2096     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2097     //   resume { i8*, i32 } %lpad.val2
2098     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2099       InsertValueInst *Insert1 = nullptr;
2100       InsertValueInst *Insert2 = nullptr;
2101       Value *ResumeVal = Resume->getOperand(0);
2102       // If the resume value isn't a phi or landingpad value, it should be a
2103       // series of insertions. Identify them so we can avoid them when scanning
2104       // for cleanups.
2105       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2106         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2107         if (!Insert2)
2108           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2109         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2110         if (!Insert1)
2111           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2112       }
2113       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2114            II != IE; ++II) {
2115         Instruction *Inst = II;
2116         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2117           continue;
2118         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2119           continue;
2120         if (!Inst->hasOneUse() ||
2121             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2122           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2123         }
2124       }
2125       return;
2126     }
2127
2128     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2129     if (Branch && Branch->isConditional()) {
2130       // Look for the selector dispatch.
2131       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2132       //   %matches = icmp eq i32 %sel, %2
2133       //   br i1 %matches, label %catch14, label %eh.resume
2134       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2135       if (!Compare || !Compare->isEquality())
2136         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2137       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2138            II != IE; ++II) {
2139         Instruction *Inst = II;
2140         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2141           continue;
2142         if (Inst == Compare || Inst == Branch)
2143           continue;
2144         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2145           continue;
2146         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2147       }
2148       // The selector dispatch block should always terminate our search.
2149       assert(BB == EndBB);
2150       return;
2151     }
2152
2153     if (isAsynchronousEHPersonality(Personality)) {
2154       // If this is a landingpad block, split the block at the first non-landing
2155       // pad instruction.
2156       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2157       if (LPadMap) {
2158         while (MaybeCall != BB->getTerminator() &&
2159                LPadMap->isLandingPadSpecificInst(MaybeCall))
2160           MaybeCall = MaybeCall->getNextNode();
2161       }
2162
2163       // Look for outlined finally calls.
2164       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2165         Function *Fin = FinallyCall.getCalledFunction();
2166         assert(Fin && "outlined finally call should be direct");
2167         auto *Action = new CleanupHandler(BB);
2168         Action->setHandlerBlockOrFunc(Fin);
2169         Actions.insertCleanupHandler(Action);
2170         CleanupHandlerMap[BB] = Action;
2171         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2172                      << Fin->getName() << " in block "
2173                      << Action->getStartBlock()->getName() << "\n");
2174
2175         // Split the block if there were more interesting instructions and look
2176         // for finally calls in the normal successor block.
2177         BasicBlock *SuccBB = BB;
2178         if (FinallyCall.getInstruction() != BB->getTerminator() &&
2179             FinallyCall.getInstruction()->getNextNode() !=
2180                 BB->getTerminator()) {
2181           SuccBB =
2182               SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2183         } else {
2184           if (FinallyCall.isInvoke()) {
2185             SuccBB =
2186                 cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2187           } else {
2188             SuccBB = BB->getUniqueSuccessor();
2189             assert(SuccBB &&
2190                    "splitOutlinedFinallyCalls didn't insert a branch");
2191           }
2192         }
2193         BB = SuccBB;
2194         if (BB == EndBB)
2195           return;
2196         continue;
2197       }
2198     }
2199
2200     // Anything else is either a catch block or interesting cleanup code.
2201     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2202          II != IE; ++II) {
2203       Instruction *Inst = II;
2204       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2205         continue;
2206       // Unconditional branches fall through to this loop.
2207       if (Inst == Branch)
2208         continue;
2209       // If this is a catch block, there is no cleanup code to be found.
2210       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2211         return;
2212       // If this a nested landing pad, it may contain an endcatch call.
2213       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2214         return;
2215       // Anything else makes this interesting cleanup code.
2216       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2217     }
2218
2219     // Only unconditional branches in empty blocks should get this far.
2220     assert(Branch && Branch->isUnconditional());
2221     if (BB == EndBB)
2222       return;
2223     BB = Branch->getSuccessor(0);
2224   }
2225 }
2226
2227 // This is a public function, declared in WinEHFuncInfo.h and is also
2228 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2229 void llvm::parseEHActions(const IntrinsicInst *II,
2230                           SmallVectorImpl<ActionHandler *> &Actions) {
2231   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2232     uint64_t ActionKind =
2233         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2234     if (ActionKind == /*catch=*/1) {
2235       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2236       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2237       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2238       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2239       I += 4;
2240       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2241       CH->setHandlerBlockOrFunc(Handler);
2242       CH->setExceptionVarIndex(EHObjIndexVal);
2243       Actions.push_back(CH);
2244     } else if (ActionKind == 0) {
2245       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2246       I += 2;
2247       auto *CH = new CleanupHandler(/*BB=*/nullptr);
2248       CH->setHandlerBlockOrFunc(Handler);
2249       Actions.push_back(CH);
2250     } else {
2251       llvm_unreachable("Expected either a catch or cleanup handler!");
2252     }
2253   }
2254   std::reverse(Actions.begin(), Actions.end());
2255 }