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