2cebb1d40cf9d0d1b48010f1d86d574e3a15d145
[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       delete Action;
886     }
887     ActionList.clear();
888     for (BasicBlock *Target : ReturnTargets) {
889       Branch->addDestination(Target);
890       // The target may be a block that we excepted to get pruned.
891       // If it is, it may contain a call to llvm.eh.endcatch.
892       if (CheckedTargets.insert(Target)) {
893         // Earlier preparations guarantee that all calls to llvm.eh.endcatch
894         // will be followed by an unconditional branch.
895         auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
896         if (Br && Br->isUnconditional() &&
897             Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
898           Instruction *Prev = Br->getPrevNode();
899           if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
900             Prev->eraseFromParent();
901         }
902       }
903     }
904   }
905   LPadImpls.clear();
906
907   F.addFnAttr("wineh-parent", F.getName());
908
909   // Delete any blocks that were only used by handlers that were outlined above.
910   removeUnreachableBlocks(F);
911
912   BasicBlock *Entry = &F.getEntryBlock();
913   IRBuilder<> Builder(F.getParent()->getContext());
914   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
915
916   Function *FrameEscapeFn =
917       Intrinsic::getDeclaration(M, Intrinsic::frameescape);
918   Function *RecoverFrameFn =
919       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
920   SmallVector<Value *, 8> AllocasToEscape;
921
922   // Scan the entry block for an existing call to llvm.frameescape. We need to
923   // keep escaping those objects.
924   for (Instruction &I : F.front()) {
925     auto *II = dyn_cast<IntrinsicInst>(&I);
926     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
927       auto Args = II->arg_operands();
928       AllocasToEscape.append(Args.begin(), Args.end());
929       II->eraseFromParent();
930       break;
931     }
932   }
933
934   // Finally, replace all of the temporary allocas for frame variables used in
935   // the outlined handlers with calls to llvm.framerecover.
936   for (auto &VarInfoEntry : FrameVarInfo) {
937     Value *ParentVal = VarInfoEntry.first;
938     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
939     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
940
941     // FIXME: We should try to sink unescaped allocas from the parent frame into
942     // the child frame. If the alloca is escaped, we have to use the lifetime
943     // markers to ensure that the alloca is only live within the child frame.
944
945     // Add this alloca to the list of things to escape.
946     AllocasToEscape.push_back(ParentAlloca);
947
948     // Next replace all outlined allocas that are mapped to it.
949     for (AllocaInst *TempAlloca : Allocas) {
950       if (TempAlloca == getCatchObjectSentinel())
951         continue; // Skip catch parameter sentinels.
952       Function *HandlerFn = TempAlloca->getParent()->getParent();
953       llvm::Value *FP = HandlerToParentFP[HandlerFn];
954       assert(FP);
955
956       // FIXME: Sink this framerecover into the blocks where it is used.
957       Builder.SetInsertPoint(TempAlloca);
958       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
959       Value *RecoverArgs[] = {
960           Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
961           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
962       Instruction *RecoveredAlloca =
963           Builder.CreateCall(RecoverFrameFn, RecoverArgs);
964
965       // Add a pointer bitcast if the alloca wasn't an i8.
966       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
967         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
968         RecoveredAlloca = cast<Instruction>(
969             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
970       }
971       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
972       TempAlloca->removeFromParent();
973       RecoveredAlloca->takeName(TempAlloca);
974       delete TempAlloca;
975     }
976   } // End for each FrameVarInfo entry.
977
978   // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
979   // block.
980   Builder.SetInsertPoint(&F.getEntryBlock().back());
981   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
982
983   if (SEHExceptionCodeSlot) {
984     if (SEHExceptionCodeSlot->hasNUses(0))
985       SEHExceptionCodeSlot->eraseFromParent();
986     else if (isAllocaPromotable(SEHExceptionCodeSlot))
987       PromoteMemToReg(SEHExceptionCodeSlot, *DT);
988   }
989
990   // Clean up the handler action maps we created for this function
991   DeleteContainerSeconds(CatchHandlerMap);
992   CatchHandlerMap.clear();
993   DeleteContainerSeconds(CleanupHandlerMap);
994   CleanupHandlerMap.clear();
995   HandlerToParentFP.clear();
996   DT = nullptr;
997   SEHExceptionCodeSlot = nullptr;
998
999   return HandlersOutlined;
1000 }
1001
1002 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1003   // If the return values of the landing pad instruction are extracted and
1004   // stored to memory, we want to promote the store locations to reg values.
1005   SmallVector<AllocaInst *, 2> EHAllocas;
1006
1007   // The landingpad instruction returns an aggregate value.  Typically, its
1008   // value will be passed to a pair of extract value instructions and the
1009   // results of those extracts are often passed to store instructions.
1010   // In unoptimized code the stored value will often be loaded and then stored
1011   // again.
1012   for (auto *U : LPad->users()) {
1013     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1014     if (!Extract)
1015       continue;
1016
1017     for (auto *EU : Extract->users()) {
1018       if (auto *Store = dyn_cast<StoreInst>(EU)) {
1019         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1020         EHAllocas.push_back(AV);
1021       }
1022     }
1023   }
1024
1025   // We can't do this without a dominator tree.
1026   assert(DT);
1027
1028   if (!EHAllocas.empty()) {
1029     PromoteMemToReg(EHAllocas, *DT);
1030     EHAllocas.clear();
1031   }
1032
1033   // After promotion, some extracts may be trivially dead. Remove them.
1034   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1035   for (auto *U : Users)
1036     RecursivelyDeleteTriviallyDeadInstructions(U);
1037 }
1038
1039 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1040                                             Function *HandlerF,
1041                                             SetVector<BasicBlock*> &Targets) {
1042   for (BasicBlock &BB : *HandlerF) {
1043     // If the handler contains landing pads, check for any
1044     // handlers that may return directly to a block in the
1045     // parent function.
1046     if (auto *LPI = BB.getLandingPadInst()) {
1047       IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
1048       SmallVector<ActionHandler *, 4> ActionList;
1049       parseEHActions(Recover, ActionList);
1050       for (auto *Action : ActionList) {
1051         if (auto *CH = dyn_cast<CatchHandler>(Action)) {
1052           Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1053           getPossibleReturnTargets(ParentF, NestedF, Targets);
1054         }
1055       }
1056     }
1057
1058     auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1059     if (!Ret)
1060       continue;
1061
1062     // Handler functions must always return a block address.
1063     BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1064
1065     // If this is the handler for a nested landing pad, the
1066     // return address may have been remapped to a block in the
1067     // parent handler.  We're not interested in those.
1068     if (BA->getFunction() != ParentF)
1069       continue;
1070
1071     Targets.insert(BA->getBasicBlock());
1072   }
1073 }
1074
1075 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1076                                             LandingPadInst *OutlinedLPad,
1077                                             const LandingPadInst *OriginalLPad,
1078                                             FrameVarInfoMap &FrameVarInfo) {
1079   // Get the nested block and erase the unreachable instruction that was
1080   // temporarily inserted as its terminator.
1081   LLVMContext &Context = ParentFn->getContext();
1082   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1083   assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1084   OutlinedBB->getTerminator()->eraseFromParent();
1085   // That should leave OutlinedLPad as the last instruction in its block.
1086   assert(&OutlinedBB->back() == OutlinedLPad);
1087
1088   // The original landing pad will have already had its action intrinsic
1089   // built by the outlining loop.  We need to clone that into the outlined
1090   // location.  It may also be necessary to add references to the exception
1091   // variables to the outlined handler in which this landing pad is nested
1092   // and remap return instructions in the nested handlers that should return
1093   // to an address in the outlined handler.
1094   Function *OutlinedHandlerFn = OutlinedBB->getParent();
1095   BasicBlock::const_iterator II = OriginalLPad;
1096   ++II;
1097   // The instruction after the landing pad should now be a call to eh.actions.
1098   const Instruction *Recover = II;
1099   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
1100   IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
1101
1102   // Remap the exception variables into the outlined function.
1103   SmallVector<BlockAddress *, 4> ActionTargets;
1104   SmallVector<ActionHandler *, 4> ActionList;
1105   parseEHActions(EHActions, ActionList);
1106   for (auto *Action : ActionList) {
1107     auto *Catch = dyn_cast<CatchHandler>(Action);
1108     if (!Catch)
1109       continue;
1110     // The dyn_cast to function here selects C++ catch handlers and skips
1111     // SEH catch handlers.
1112     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1113     if (!Handler)
1114       continue;
1115     // Visit all the return instructions, looking for places that return
1116     // to a location within OutlinedHandlerFn.
1117     for (BasicBlock &NestedHandlerBB : *Handler) {
1118       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1119       if (!Ret)
1120         continue;
1121
1122       // Handler functions must always return a block address.
1123       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1124       // The original target will have been in the main parent function,
1125       // but if it is the address of a block that has been outlined, it
1126       // should be a block that was outlined into OutlinedHandlerFn.
1127       assert(BA->getFunction() == ParentFn);
1128
1129       // Ignore targets that aren't part of OutlinedHandlerFn.
1130       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1131         continue;
1132
1133       // If the return value is the address ofF a block that we
1134       // previously outlined into the parent handler function, replace
1135       // the return instruction and add the mapped target to the list
1136       // of possible return addresses.
1137       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1138       assert(MappedBB->getParent() == OutlinedHandlerFn);
1139       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1140       Ret->eraseFromParent();
1141       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1142       ActionTargets.push_back(NewBA);
1143     }
1144   }
1145   DeleteContainerPointers(ActionList);
1146   ActionList.clear();
1147   OutlinedBB->getInstList().push_back(EHActions);
1148
1149   // Insert an indirect branch into the outlined landing pad BB.
1150   IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
1151   // Add the previously collected action targets.
1152   for (auto *Target : ActionTargets)
1153     IBr->addDestination(Target->getBasicBlock());
1154 }
1155
1156 // This function examines a block to determine whether the block ends with a
1157 // conditional branch to a catch handler based on a selector comparison.
1158 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1159 // WinEHCleanupDirector::handleTypeIdFor().
1160 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1161                                Constant *&Selector, BasicBlock *&NextBB) {
1162   ICmpInst::Predicate Pred;
1163   BasicBlock *TBB, *FBB;
1164   Value *LHS, *RHS;
1165
1166   if (!match(BB->getTerminator(),
1167              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1168     return false;
1169
1170   if (!match(LHS,
1171              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1172       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1173     return false;
1174
1175   if (Pred == CmpInst::ICMP_EQ) {
1176     CatchHandler = TBB;
1177     NextBB = FBB;
1178     return true;
1179   }
1180
1181   if (Pred == CmpInst::ICMP_NE) {
1182     CatchHandler = FBB;
1183     NextBB = TBB;
1184     return true;
1185   }
1186
1187   return false;
1188 }
1189
1190 static bool isCatchBlock(BasicBlock *BB) {
1191   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1192        II != IE; ++II) {
1193     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1194       return true;
1195   }
1196   return false;
1197 }
1198
1199 static BasicBlock *createStubLandingPad(Function *Handler,
1200                                         Value *PersonalityFn) {
1201   // FIXME: Finish this!
1202   LLVMContext &Context = Handler->getContext();
1203   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1204   Handler->getBasicBlockList().push_back(StubBB);
1205   IRBuilder<> Builder(StubBB);
1206   LandingPadInst *LPad = Builder.CreateLandingPad(
1207       llvm::StructType::get(Type::getInt8PtrTy(Context),
1208                             Type::getInt32Ty(Context), nullptr),
1209       PersonalityFn, 0);
1210   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1211   Function *ActionIntrin =
1212       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1213   Builder.CreateCall(ActionIntrin, "recover");
1214   LPad->setCleanup(true);
1215   Builder.CreateUnreachable();
1216   return StubBB;
1217 }
1218
1219 // Cycles through the blocks in an outlined handler function looking for an
1220 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1221 // landing pad if none is found.  The code that generates the .xdata tables for
1222 // the handler needs at least one landing pad to identify the parent function's
1223 // personality.
1224 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1225                                                   Value *PersonalityFn) {
1226   ReturnInst *Ret = nullptr;
1227   UnreachableInst *Unreached = nullptr;
1228   for (BasicBlock &BB : *Handler) {
1229     TerminatorInst *Terminator = BB.getTerminator();
1230     // If we find an invoke, there is nothing to be done.
1231     auto *II = dyn_cast<InvokeInst>(Terminator);
1232     if (II)
1233       return;
1234     // If we've already recorded a return instruction, keep looking for invokes.
1235     if (!Ret)
1236       Ret = dyn_cast<ReturnInst>(Terminator);
1237     // If we haven't recorded an unreachable instruction, try this terminator.
1238     if (!Unreached)
1239       Unreached = dyn_cast<UnreachableInst>(Terminator);
1240   }
1241
1242   // If we got this far, the handler contains no invokes.  We should have seen
1243   // at least one return or unreachable instruction.  We'll insert an invoke of
1244   // llvm.donothing ahead of that instruction.
1245   assert(Ret || Unreached);
1246   TerminatorInst *Term;
1247   if (Ret)
1248     Term = Ret;
1249   else
1250     Term = Unreached;
1251   BasicBlock *OldRetBB = Term->getParent();
1252   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1253   // SplitBlock adds an unconditional branch instruction at the end of the
1254   // parent block.  We want to replace that with an invoke call, so we can
1255   // erase it now.
1256   OldRetBB->getTerminator()->eraseFromParent();
1257   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1258   Function *F =
1259       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1260   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1261 }
1262
1263 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1264 // usually doesn't build LLVM IR, so that's probably the wrong place.
1265 Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name,
1266                                           Module *M, Value *&ParentFP) {
1267   // x64 uses a two-argument prototype where the parent FP is the second
1268   // argument. x86 uses no arguments, just the incoming EBP value.
1269   LLVMContext &Context = M->getContext();
1270   FunctionType *FnType;
1271   if (TheTriple.getArch() == Triple::x86_64) {
1272     Type *Int8PtrType = Type::getInt8PtrTy(Context);
1273     Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1274     FnType = FunctionType::get(RetTy, ArgTys, false);
1275   } else {
1276     FnType = FunctionType::get(RetTy, None, false);
1277   }
1278
1279   Function *Handler =
1280       Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1281   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1282   Handler->getBasicBlockList().push_front(Entry);
1283   if (TheTriple.getArch() == Triple::x86_64) {
1284     ParentFP = &(Handler->getArgumentList().back());
1285   } else {
1286     assert(M);
1287     Function *FrameAddressFn =
1288         Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1289     Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)};
1290     ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp",
1291                                 &Handler->getEntryBlock());
1292   }
1293   return Handler;
1294 }
1295
1296 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1297                                   LandingPadInst *LPad, BasicBlock *StartBB,
1298                                   FrameVarInfoMap &VarInfo) {
1299   Module *M = SrcFn->getParent();
1300   LLVMContext &Context = M->getContext();
1301   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1302
1303   // Create a new function to receive the handler contents.
1304   Value *ParentFP;
1305   Function *Handler;
1306   if (Action->getType() == Catch) {
1307     Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M,
1308                                 ParentFP);
1309   } else {
1310     Handler = createHandlerFunc(Type::getVoidTy(Context),
1311                                 SrcFn->getName() + ".cleanup", M, ParentFP);
1312   }
1313   HandlerToParentFP[Handler] = ParentFP;
1314   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1315   BasicBlock *Entry = &Handler->getEntryBlock();
1316
1317   // Generate a standard prolog to setup the frame recovery structure.
1318   IRBuilder<> Builder(Context);
1319   Builder.SetInsertPoint(Entry);
1320   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1321
1322   std::unique_ptr<WinEHCloningDirectorBase> Director;
1323
1324   ValueToValueMapTy VMap;
1325
1326   LandingPadMap &LPadMap = LPadMaps[LPad];
1327   if (!LPadMap.isInitialized())
1328     LPadMap.mapLandingPad(LPad);
1329   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1330     Constant *Sel = CatchAction->getSelector();
1331     Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
1332                                           VarInfo, LPadMap,
1333                                           NestedLPtoOriginalLP));
1334     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1335                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1336   } else {
1337     Director.reset(
1338         new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1339     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1340                           UndefValue::get(Type::getInt32Ty(Context)));
1341   }
1342
1343   SmallVector<ReturnInst *, 8> Returns;
1344   ClonedCodeInfo OutlinedFunctionInfo;
1345
1346   // If the start block contains PHI nodes, we need to map them.
1347   BasicBlock::iterator II = StartBB->begin();
1348   while (auto *PN = dyn_cast<PHINode>(II)) {
1349     bool Mapped = false;
1350     // Look for PHI values that we have already mapped (such as the selector).
1351     for (Value *Val : PN->incoming_values()) {
1352       if (VMap.count(Val)) {
1353         VMap[PN] = VMap[Val];
1354         Mapped = true;
1355       }
1356     }
1357     // If we didn't find a match for this value, map it as an undef.
1358     if (!Mapped) {
1359       VMap[PN] = UndefValue::get(PN->getType());
1360     }
1361     ++II;
1362   }
1363
1364   // The landing pad value may be used by PHI nodes.  It will ultimately be
1365   // eliminated, but we need it in the map for intermediate handling.
1366   VMap[LPad] = UndefValue::get(LPad->getType());
1367
1368   // Skip over PHIs and, if applicable, landingpad instructions.
1369   II = StartBB->getFirstInsertionPt();
1370
1371   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1372                             /*ModuleLevelChanges=*/false, Returns, "",
1373                             &OutlinedFunctionInfo, Director.get());
1374
1375   // Move all the instructions in the cloned "entry" block into our entry block.
1376   // Depending on how the parent function was laid out, the block that will
1377   // correspond to the outlined entry block may not be the first block in the
1378   // list.  We can recognize it, however, as the cloned block which has no
1379   // predecessors.  Any other block wouldn't have been cloned if it didn't
1380   // have a predecessor which was also cloned.
1381   Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1382   while (!pred_empty(ClonedIt))
1383     ++ClonedIt;
1384   BasicBlock *ClonedEntryBB = ClonedIt;
1385   assert(ClonedEntryBB);
1386   Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1387   ClonedEntryBB->eraseFromParent();
1388
1389   // Make sure we can identify the handler's personality later.
1390   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1391
1392   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1393     WinEHCatchDirector *CatchDirector =
1394         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1395     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1396     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1397
1398     // Look for blocks that are not part of the landing pad that we just
1399     // outlined but terminate with a call to llvm.eh.endcatch and a
1400     // branch to a block that is in the handler we just outlined.
1401     // These blocks will be part of a nested landing pad that intends to
1402     // return to an address in this handler.  This case is best handled
1403     // after both landing pads have been outlined, so for now we'll just
1404     // save the association of the blocks in LPadTargetBlocks.  The
1405     // return instructions which are created from these branches will be
1406     // replaced after all landing pads have been outlined.
1407     for (const auto MapEntry : VMap) {
1408       // VMap maps all values and blocks that were just cloned, but dead
1409       // blocks which were pruned will map to nullptr.
1410       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1411         continue;
1412       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1413       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1414         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1415         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1416           continue;
1417         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1418         --II;
1419         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1420           // This would indicate that a nested landing pad wants to return
1421           // to a block that is outlined into two different handlers.
1422           assert(!LPadTargetBlocks.count(MappedBB));
1423           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1424         }
1425       }
1426     }
1427   } // End if (CatchAction)
1428
1429   Action->setHandlerBlockOrFunc(Handler);
1430
1431   return true;
1432 }
1433
1434 /// This BB must end in a selector dispatch. All we need to do is pass the
1435 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1436 /// target.
1437 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1438                                           BasicBlock *StartBB) {
1439   BasicBlock *HandlerBB;
1440   BasicBlock *NextBB;
1441   Constant *Selector;
1442   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1443   if (Res) {
1444     // If this was EH dispatch, this must be a conditional branch to the handler
1445     // block.
1446     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1447     // leading to crashes if some optimization hoists stuff here.
1448     assert(CatchAction->getSelector() && HandlerBB &&
1449            "expected catch EH dispatch");
1450   } else {
1451     // This must be a catch-all. Split the block after the landingpad.
1452     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1453     HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1454   }
1455   IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1456   Function *EHCodeFn = Intrinsic::getDeclaration(
1457       StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1458   Value *Code = Builder.CreateCall(EHCodeFn, "sehcode");
1459   Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1460   Builder.CreateStore(Code, SEHExceptionCodeSlot);
1461   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1462   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1463   CatchAction->setReturnTargets(Targets);
1464 }
1465
1466 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1467   // Each instance of this class should only ever be used to map a single
1468   // landing pad.
1469   assert(OriginLPad == nullptr || OriginLPad == LPad);
1470
1471   // If the landing pad has already been mapped, there's nothing more to do.
1472   if (OriginLPad == LPad)
1473     return;
1474
1475   OriginLPad = LPad;
1476
1477   // The landingpad instruction returns an aggregate value.  Typically, its
1478   // value will be passed to a pair of extract value instructions and the
1479   // results of those extracts will have been promoted to reg values before
1480   // this routine is called.
1481   for (auto *U : LPad->users()) {
1482     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1483     if (!Extract)
1484       continue;
1485     assert(Extract->getNumIndices() == 1 &&
1486            "Unexpected operation: extracting both landing pad values");
1487     unsigned int Idx = *(Extract->idx_begin());
1488     assert((Idx == 0 || Idx == 1) &&
1489            "Unexpected operation: extracting an unknown landing pad element");
1490     if (Idx == 0) {
1491       ExtractedEHPtrs.push_back(Extract);
1492     } else if (Idx == 1) {
1493       ExtractedSelectors.push_back(Extract);
1494     }
1495   }
1496 }
1497
1498 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1499   return BB->getLandingPadInst() == OriginLPad;
1500 }
1501
1502 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1503   if (Inst == OriginLPad)
1504     return true;
1505   for (auto *Extract : ExtractedEHPtrs) {
1506     if (Inst == Extract)
1507       return true;
1508   }
1509   for (auto *Extract : ExtractedSelectors) {
1510     if (Inst == Extract)
1511       return true;
1512   }
1513   return false;
1514 }
1515
1516 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1517                                   Value *SelectorValue) const {
1518   // Remap all landing pad extract instructions to the specified values.
1519   for (auto *Extract : ExtractedEHPtrs)
1520     VMap[Extract] = EHPtrValue;
1521   for (auto *Extract : ExtractedSelectors)
1522     VMap[Extract] = SelectorValue;
1523 }
1524
1525 static bool isFrameAddressCall(const Value *V) {
1526   return match(const_cast<Value *>(V),
1527                m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1528 }
1529
1530 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1531     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1532   // If this is one of the boilerplate landing pad instructions, skip it.
1533   // The instruction will have already been remapped in VMap.
1534   if (LPadMap.isLandingPadSpecificInst(Inst))
1535     return CloningDirector::SkipInstruction;
1536
1537   // Nested landing pads will be cloned as stubs, with just the
1538   // landingpad instruction and an unreachable instruction. When
1539   // all landingpads have been outlined, we'll replace this with the
1540   // llvm.eh.actions call and indirect branch created when the
1541   // landing pad was outlined.
1542   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1543     return handleLandingPad(VMap, LPad, NewBB);
1544   }
1545
1546   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1547     return handleInvoke(VMap, Invoke, NewBB);
1548
1549   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1550     return handleResume(VMap, Resume, NewBB);
1551
1552   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1553     return handleCompare(VMap, Cmp, NewBB);
1554
1555   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1556     return handleBeginCatch(VMap, Inst, NewBB);
1557   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1558     return handleEndCatch(VMap, Inst, NewBB);
1559   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1560     return handleTypeIdFor(VMap, Inst, NewBB);
1561
1562   // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1563   // which is the FP of the parent.
1564   if (isFrameAddressCall(Inst)) {
1565     VMap[Inst] = ParentFP;
1566     return CloningDirector::SkipInstruction;
1567   }
1568
1569   // Continue with the default cloning behavior.
1570   return CloningDirector::CloneInstruction;
1571 }
1572
1573 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1574     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1575   Instruction *NewInst = LPad->clone();
1576   if (LPad->hasName())
1577     NewInst->setName(LPad->getName());
1578   // Save this correlation for later processing.
1579   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1580   VMap[LPad] = NewInst;
1581   BasicBlock::InstListType &InstList = NewBB->getInstList();
1582   InstList.push_back(NewInst);
1583   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1584   return CloningDirector::StopCloningBB;
1585 }
1586
1587 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1588     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1589   // The argument to the call is some form of the first element of the
1590   // landingpad aggregate value, but that doesn't matter.  It isn't used
1591   // here.
1592   // The second argument is an outparameter where the exception object will be
1593   // stored. Typically the exception object is a scalar, but it can be an
1594   // aggregate when catching by value.
1595   // FIXME: Leave something behind to indicate where the exception object lives
1596   // for this handler. Should it be part of llvm.eh.actions?
1597   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1598                                           "llvm.eh.begincatch found while "
1599                                           "outlining catch handler.");
1600   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1601   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1602     return CloningDirector::SkipInstruction;
1603   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1604          "catch parameter is not static alloca");
1605   Materializer.escapeCatchObject(ExceptionObjectVar);
1606   return CloningDirector::SkipInstruction;
1607 }
1608
1609 CloningDirector::CloningAction
1610 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1611                                    const Instruction *Inst, BasicBlock *NewBB) {
1612   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1613   // It might be interesting to track whether or not we are inside a catch
1614   // function, but that might make the algorithm more brittle than it needs
1615   // to be.
1616
1617   // The end catch call can occur in one of two places: either in a
1618   // landingpad block that is part of the catch handlers exception mechanism,
1619   // or at the end of the catch block.  However, a catch-all handler may call
1620   // end catch from the original landing pad.  If the call occurs in a nested
1621   // landing pad block, we must skip it and continue so that the landing pad
1622   // gets cloned.
1623   auto *ParentBB = IntrinCall->getParent();
1624   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1625     return CloningDirector::SkipInstruction;
1626
1627   // If an end catch occurs anywhere else we want to terminate the handler
1628   // with a return to the code that follows the endcatch call.  If the
1629   // next instruction is not an unconditional branch, we need to split the
1630   // block to provide a clear target for the return instruction.
1631   BasicBlock *ContinueBB;
1632   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1633   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1634   if (!Branch || !Branch->isUnconditional()) {
1635     // We're interrupting the cloning process at this location, so the
1636     // const_cast we're doing here will not cause a problem.
1637     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1638                             const_cast<Instruction *>(cast<Instruction>(Next)));
1639   } else {
1640     ContinueBB = Branch->getSuccessor(0);
1641   }
1642
1643   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1644   ReturnTargets.push_back(ContinueBB);
1645
1646   // We just added a terminator to the cloned block.
1647   // Tell the caller to stop processing the current basic block so that
1648   // the branch instruction will be skipped.
1649   return CloningDirector::StopCloningBB;
1650 }
1651
1652 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1653     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1654   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1655   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1656   // This causes a replacement that will collapse the landing pad CFG based
1657   // on the filter function we intend to match.
1658   if (Selector == CurrentSelector)
1659     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1660   else
1661     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1662   // Tell the caller not to clone this instruction.
1663   return CloningDirector::SkipInstruction;
1664 }
1665
1666 CloningDirector::CloningAction
1667 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1668                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1669   return CloningDirector::CloneInstruction;
1670 }
1671
1672 CloningDirector::CloningAction
1673 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1674                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1675   // Resume instructions shouldn't be reachable from catch handlers.
1676   // We still need to handle it, but it will be pruned.
1677   BasicBlock::InstListType &InstList = NewBB->getInstList();
1678   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1679   return CloningDirector::StopCloningBB;
1680 }
1681
1682 CloningDirector::CloningAction
1683 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1684                                   const CmpInst *Compare, BasicBlock *NewBB) {
1685   const IntrinsicInst *IntrinCall = nullptr;
1686   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1687     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1688   } else if (match(Compare->getOperand(1),
1689                    m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1690     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1691   }
1692   if (IntrinCall) {
1693     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1694     // This causes a replacement that will collapse the landing pad CFG based
1695     // on the filter function we intend to match.
1696     if (Selector == CurrentSelector->stripPointerCasts()) {
1697       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1698     } else {
1699       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1700     }
1701     return CloningDirector::SkipInstruction;
1702   }
1703   return CloningDirector::CloneInstruction;
1704 }
1705
1706 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1707     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1708   // The MS runtime will terminate the process if an exception occurs in a
1709   // cleanup handler, so we shouldn't encounter landing pads in the actual
1710   // cleanup code, but they may appear in catch blocks.  Depending on where
1711   // we started cloning we may see one, but it will get dropped during dead
1712   // block pruning.
1713   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1714   VMap[LPad] = NewInst;
1715   BasicBlock::InstListType &InstList = NewBB->getInstList();
1716   InstList.push_back(NewInst);
1717   return CloningDirector::StopCloningBB;
1718 }
1719
1720 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1721     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1722   // Cleanup code may flow into catch blocks or the catch block may be part
1723   // of a branch that will be optimized away.  We'll insert a return
1724   // instruction now, but it may be pruned before the cloning process is
1725   // complete.
1726   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1727   return CloningDirector::StopCloningBB;
1728 }
1729
1730 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1731     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1732   // Cleanup handlers nested within catch handlers may begin with a call to
1733   // eh.endcatch.  We can just ignore that instruction.
1734   return CloningDirector::SkipInstruction;
1735 }
1736
1737 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1738     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1739   // If we encounter a selector comparison while cloning a cleanup handler,
1740   // we want to stop cloning immediately.  Anything after the dispatch
1741   // will be outlined into a different handler.
1742   BasicBlock *CatchHandler;
1743   Constant *Selector;
1744   BasicBlock *NextBB;
1745   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1746                          CatchHandler, Selector, NextBB)) {
1747     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1748     return CloningDirector::StopCloningBB;
1749   }
1750   // If eg.typeid.for is called for any other reason, it can be ignored.
1751   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1752   return CloningDirector::SkipInstruction;
1753 }
1754
1755 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1756     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1757   // All invokes in cleanup handlers can be replaced with calls.
1758   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1759   // Insert a normal call instruction...
1760   CallInst *NewCall =
1761       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1762                        Invoke->getName(), NewBB);
1763   NewCall->setCallingConv(Invoke->getCallingConv());
1764   NewCall->setAttributes(Invoke->getAttributes());
1765   NewCall->setDebugLoc(Invoke->getDebugLoc());
1766   VMap[Invoke] = NewCall;
1767
1768   // Remap the operands.
1769   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1770
1771   // Insert an unconditional branch to the normal destination.
1772   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1773
1774   // The unwind destination won't be cloned into the new function, so
1775   // we don't need to clean up its phi nodes.
1776
1777   // We just added a terminator to the cloned block.
1778   // Tell the caller to stop processing the current basic block.
1779   return CloningDirector::CloneSuccessors;
1780 }
1781
1782 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1783     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1784   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1785
1786   // We just added a terminator to the cloned block.
1787   // Tell the caller to stop processing the current basic block so that
1788   // the branch instruction will be skipped.
1789   return CloningDirector::StopCloningBB;
1790 }
1791
1792 CloningDirector::CloningAction
1793 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1794                                     const CmpInst *Compare, BasicBlock *NewBB) {
1795   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1796       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1797     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1798     return CloningDirector::SkipInstruction;
1799   }
1800   return CloningDirector::CloneInstruction;
1801 }
1802
1803 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1804     Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
1805     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1806   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1807
1808   // New allocas should be inserted in the entry block, but after the parent FP
1809   // is established if it is an instruction.
1810   Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1811   if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1812     InsertPoint = FPInst->getNextNode();
1813   Builder.SetInsertPoint(EntryBB, InsertPoint);
1814 }
1815
1816 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1817   // If we're asked to materialize a static alloca, we temporarily create an
1818   // alloca in the outlined function and add this to the FrameVarInfo map.  When
1819   // all the outlining is complete, we'll replace these temporary allocas with
1820   // calls to llvm.framerecover.
1821   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1822     assert(AV->isStaticAlloca() &&
1823            "cannot materialize un-demoted dynamic alloca");
1824     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1825     Builder.Insert(NewAlloca, AV->getName());
1826     FrameVarInfo[AV].push_back(NewAlloca);
1827     return NewAlloca;
1828   }
1829
1830   if (isa<Instruction>(V) || isa<Argument>(V)) {
1831     Function *Parent = isa<Instruction>(V)
1832                            ? cast<Instruction>(V)->getParent()->getParent()
1833                            : cast<Argument>(V)->getParent();
1834     errs()
1835         << "Failed to demote instruction used in exception handler of function "
1836         << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
1837     errs() << "  " << *V << '\n';
1838     report_fatal_error("WinEHPrepare failed to demote instruction");
1839   }
1840
1841   // Don't materialize other values.
1842   return nullptr;
1843 }
1844
1845 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1846   // Catch parameter objects have to live in the parent frame. When we see a use
1847   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1848   // used from another handler. This will prevent us from trying to sink the
1849   // alloca into the handler and ensure that the catch parameter is present in
1850   // the call to llvm.frameescape.
1851   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1852 }
1853
1854 // This function maps the catch and cleanup handlers that are reachable from the
1855 // specified landing pad. The landing pad sequence will have this basic shape:
1856 //
1857 //  <cleanup handler>
1858 //  <selector comparison>
1859 //  <catch handler>
1860 //  <cleanup handler>
1861 //  <selector comparison>
1862 //  <catch handler>
1863 //  <cleanup handler>
1864 //  ...
1865 //
1866 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1867 // any arbitrary control flow, but all paths through the cleanup code must
1868 // eventually reach the next selector comparison and no path can skip to a
1869 // different selector comparisons, though some paths may terminate abnormally.
1870 // Therefore, we will use a depth first search from the start of any given
1871 // cleanup block and stop searching when we find the next selector comparison.
1872 //
1873 // If the landingpad instruction does not have a catch clause, we will assume
1874 // that any instructions other than selector comparisons and catch handlers can
1875 // be ignored.  In practice, these will only be the boilerplate instructions.
1876 //
1877 // The catch handlers may also have any control structure, but we are only
1878 // interested in the start of the catch handlers, so we don't need to actually
1879 // follow the flow of the catch handlers.  The start of the catch handlers can
1880 // be located from the compare instructions, but they can be skipped in the
1881 // flow by following the contrary branch.
1882 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1883                                        LandingPadActions &Actions) {
1884   unsigned int NumClauses = LPad->getNumClauses();
1885   unsigned int HandlersFound = 0;
1886   BasicBlock *BB = LPad->getParent();
1887
1888   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1889
1890   if (NumClauses == 0) {
1891     findCleanupHandlers(Actions, BB, nullptr);
1892     return;
1893   }
1894
1895   VisitedBlockSet VisitedBlocks;
1896
1897   while (HandlersFound != NumClauses) {
1898     BasicBlock *NextBB = nullptr;
1899
1900     // Skip over filter clauses.
1901     if (LPad->isFilter(HandlersFound)) {
1902       ++HandlersFound;
1903       continue;
1904     }
1905
1906     // See if the clause we're looking for is a catch-all.
1907     // If so, the catch begins immediately.
1908     Constant *ExpectedSelector =
1909         LPad->getClause(HandlersFound)->stripPointerCasts();
1910     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1911       // The catch all must occur last.
1912       assert(HandlersFound == NumClauses - 1);
1913
1914       // There can be additional selector dispatches in the call chain that we
1915       // need to ignore.
1916       BasicBlock *CatchBlock = nullptr;
1917       Constant *Selector;
1918       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1919         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1920                      << CatchBlock->getName() << "\n");
1921         BB = NextBB;
1922       }
1923
1924       // Add the catch handler to the action list.
1925       CatchHandler *Action = nullptr;
1926       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1927         // If the CatchHandlerMap already has an entry for this BB, re-use it.
1928         Action = CatchHandlerMap[BB];
1929         assert(Action->getSelector() == ExpectedSelector);
1930       } else {
1931         // We don't expect a selector dispatch, but there may be a call to
1932         // llvm.eh.begincatch, which separates catch handling code from
1933         // cleanup code in the same control flow.  This call looks for the
1934         // begincatch intrinsic.
1935         Action = findCatchHandler(BB, NextBB, VisitedBlocks);
1936         if (Action) {
1937           // For C++ EH, check if there is any interesting cleanup code before
1938           // we begin the catch. This is important because cleanups cannot
1939           // rethrow exceptions but code called from catches can. For SEH, it
1940           // isn't important if some finally code before a catch-all is executed
1941           // out of line or after recovering from the exception.
1942           if (Personality == EHPersonality::MSVC_CXX)
1943             findCleanupHandlers(Actions, BB, BB);
1944         } else {
1945           // If an action was not found, it means that the control flows
1946           // directly into the catch-all handler and there is no cleanup code.
1947           // That's an expected situation and we must create a catch action.
1948           // Since this is a catch-all handler, the selector won't actually
1949           // appear in the code anywhere.  ExpectedSelector here is the constant
1950           // null ptr that we got from the landing pad instruction.
1951           Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1952           CatchHandlerMap[BB] = Action;
1953         }
1954       }
1955       Actions.insertCatchHandler(Action);
1956       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1957       ++HandlersFound;
1958
1959       // Once we reach a catch-all, don't expect to hit a resume instruction.
1960       BB = nullptr;
1961       break;
1962     }
1963
1964     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1965     assert(CatchAction);
1966
1967     // See if there is any interesting code executed before the dispatch.
1968     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1969
1970     // When the source program contains multiple nested try blocks the catch
1971     // handlers can get strung together in such a way that we can encounter
1972     // a dispatch for a selector that we've already had a handler for.
1973     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1974       ++HandlersFound;
1975
1976       // Add the catch handler to the action list.
1977       DEBUG(dbgs() << "  Found catch dispatch in block "
1978                    << CatchAction->getStartBlock()->getName() << "\n");
1979       Actions.insertCatchHandler(CatchAction);
1980     } else {
1981       // Under some circumstances optimized IR will flow unconditionally into a
1982       // handler block without checking the selector.  This can only happen if
1983       // the landing pad has a catch-all handler and the handler for the
1984       // preceeding catch clause is identical to the catch-call handler
1985       // (typically an empty catch).  In this case, the handler must be shared
1986       // by all remaining clauses.
1987       if (isa<ConstantPointerNull>(
1988               CatchAction->getSelector()->stripPointerCasts())) {
1989         DEBUG(dbgs() << "  Applying early catch-all handler in block "
1990                      << CatchAction->getStartBlock()->getName()
1991                      << "  to all remaining clauses.\n");
1992         Actions.insertCatchHandler(CatchAction);
1993         return;
1994       }
1995
1996       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1997                    << CatchAction->getStartBlock()->getName() << "\n");
1998     }
1999
2000     // Move on to the block after the catch handler.
2001     BB = NextBB;
2002   }
2003
2004   // If we didn't wind up in a catch-all, see if there is any interesting code
2005   // executed before the resume.
2006   findCleanupHandlers(Actions, BB, BB);
2007
2008   // It's possible that some optimization moved code into a landingpad that
2009   // wasn't
2010   // previously being used for cleanup.  If that happens, we need to execute
2011   // that
2012   // extra code from a cleanup handler.
2013   if (Actions.includesCleanup() && !LPad->isCleanup())
2014     LPad->setCleanup(true);
2015 }
2016
2017 // This function searches starting with the input block for the next
2018 // block that terminates with a branch whose condition is based on a selector
2019 // comparison.  This may be the input block.  See the mapLandingPadBlocks
2020 // comments for a discussion of control flow assumptions.
2021 //
2022 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2023                                              BasicBlock *&NextBB,
2024                                              VisitedBlockSet &VisitedBlocks) {
2025   // See if we've already found a catch handler use it.
2026   // Call count() first to avoid creating a null entry for blocks
2027   // we haven't seen before.
2028   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2029     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2030     NextBB = Action->getNextBB();
2031     return Action;
2032   }
2033
2034   // VisitedBlocks applies only to the current search.  We still
2035   // need to consider blocks that we've visited while mapping other
2036   // landing pads.
2037   VisitedBlocks.insert(BB);
2038
2039   BasicBlock *CatchBlock = nullptr;
2040   Constant *Selector = nullptr;
2041
2042   // If this is the first time we've visited this block from any landing pad
2043   // look to see if it is a selector dispatch block.
2044   if (!CatchHandlerMap.count(BB)) {
2045     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2046       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2047       CatchHandlerMap[BB] = Action;
2048       return Action;
2049     }
2050     // If we encounter a block containing an llvm.eh.begincatch before we
2051     // find a selector dispatch block, the handler is assumed to be
2052     // reached unconditionally.  This happens for catch-all blocks, but
2053     // it can also happen for other catch handlers that have been combined
2054     // with the catch-all handler during optimization.
2055     if (isCatchBlock(BB)) {
2056       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2057       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2058       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2059       CatchHandlerMap[BB] = Action;
2060       return Action;
2061     }
2062   }
2063
2064   // Visit each successor, looking for the dispatch.
2065   // FIXME: We expect to find the dispatch quickly, so this will probably
2066   //        work better as a breadth first search.
2067   for (BasicBlock *Succ : successors(BB)) {
2068     if (VisitedBlocks.count(Succ))
2069       continue;
2070
2071     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2072     if (Action)
2073       return Action;
2074   }
2075   return nullptr;
2076 }
2077
2078 // These are helper functions to combine repeated code from findCleanupHandlers.
2079 static void createCleanupHandler(LandingPadActions &Actions,
2080                                  CleanupHandlerMapTy &CleanupHandlerMap,
2081                                  BasicBlock *BB) {
2082   CleanupHandler *Action = new CleanupHandler(BB);
2083   CleanupHandlerMap[BB] = Action;
2084   Actions.insertCleanupHandler(Action);
2085   DEBUG(dbgs() << "  Found cleanup code in block "
2086                << Action->getStartBlock()->getName() << "\n");
2087 }
2088
2089 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2090                                          Instruction *MaybeCall) {
2091   // Look for finally blocks that Clang has already outlined for us.
2092   //   %fp = call i8* @llvm.frameaddress(i32 0)
2093   //   call void @"fin$parent"(iN 1, i8* %fp)
2094   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2095     MaybeCall = MaybeCall->getNextNode();
2096   CallSite FinallyCall(MaybeCall);
2097   if (!FinallyCall || FinallyCall.arg_size() != 2)
2098     return CallSite();
2099   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2100     return CallSite();
2101   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
2102     return CallSite();
2103   return FinallyCall;
2104 }
2105
2106 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2107   // Skip single ubr blocks.
2108   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2109     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2110     if (Br && Br->isUnconditional())
2111       BB = Br->getSuccessor(0);
2112     else
2113       return BB;
2114   }
2115   return BB;
2116 }
2117
2118 // This function searches starting with the input block for the next block that
2119 // contains code that is not part of a catch handler and would not be eliminated
2120 // during handler outlining.
2121 //
2122 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2123                                        BasicBlock *StartBB, BasicBlock *EndBB) {
2124   // Here we will skip over the following:
2125   //
2126   // landing pad prolog:
2127   //
2128   // Unconditional branches
2129   //
2130   // Selector dispatch
2131   //
2132   // Resume pattern
2133   //
2134   // Anything else marks the start of an interesting block
2135
2136   BasicBlock *BB = StartBB;
2137   // Anything other than an unconditional branch will kick us out of this loop
2138   // one way or another.
2139   while (BB) {
2140     BB = followSingleUnconditionalBranches(BB);
2141     // If we've already scanned this block, don't scan it again.  If it is
2142     // a cleanup block, there will be an action in the CleanupHandlerMap.
2143     // If we've scanned it and it is not a cleanup block, there will be a
2144     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
2145     // be no entry in the CleanupHandlerMap.  We must call count() first to
2146     // avoid creating a null entry for blocks we haven't scanned.
2147     if (CleanupHandlerMap.count(BB)) {
2148       if (auto *Action = CleanupHandlerMap[BB]) {
2149         Actions.insertCleanupHandler(Action);
2150         DEBUG(dbgs() << "  Found cleanup code in block "
2151                      << Action->getStartBlock()->getName() << "\n");
2152         // FIXME: This cleanup might chain into another, and we need to discover
2153         // that.
2154         return;
2155       } else {
2156         // Here we handle the case where the cleanup handler map contains a
2157         // value for this block but the value is a nullptr.  This means that
2158         // we have previously analyzed the block and determined that it did
2159         // not contain any cleanup code.  Based on the earlier analysis, we
2160         // know the the block must end in either an unconditional branch, a
2161         // resume or a conditional branch that is predicated on a comparison
2162         // with a selector.  Either the resume or the selector dispatch
2163         // would terminate the search for cleanup code, so the unconditional
2164         // branch is the only case for which we might need to continue
2165         // searching.
2166         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2167         if (SuccBB == BB || SuccBB == EndBB)
2168           return;
2169         BB = SuccBB;
2170         continue;
2171       }
2172     }
2173
2174     // Create an entry in the cleanup handler map for this block.  Initially
2175     // we create an entry that says this isn't a cleanup block.  If we find
2176     // cleanup code, the caller will replace this entry.
2177     CleanupHandlerMap[BB] = nullptr;
2178
2179     TerminatorInst *Terminator = BB->getTerminator();
2180
2181     // Landing pad blocks have extra instructions we need to accept.
2182     LandingPadMap *LPadMap = nullptr;
2183     if (BB->isLandingPad()) {
2184       LandingPadInst *LPad = BB->getLandingPadInst();
2185       LPadMap = &LPadMaps[LPad];
2186       if (!LPadMap->isInitialized())
2187         LPadMap->mapLandingPad(LPad);
2188     }
2189
2190     // Look for the bare resume pattern:
2191     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2192     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2193     //   resume { i8*, i32 } %lpad.val2
2194     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2195       InsertValueInst *Insert1 = nullptr;
2196       InsertValueInst *Insert2 = nullptr;
2197       Value *ResumeVal = Resume->getOperand(0);
2198       // If the resume value isn't a phi or landingpad value, it should be a
2199       // series of insertions. Identify them so we can avoid them when scanning
2200       // for cleanups.
2201       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2202         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2203         if (!Insert2)
2204           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2205         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2206         if (!Insert1)
2207           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2208       }
2209       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2210            II != IE; ++II) {
2211         Instruction *Inst = II;
2212         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2213           continue;
2214         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2215           continue;
2216         if (!Inst->hasOneUse() ||
2217             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2218           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2219         }
2220       }
2221       return;
2222     }
2223
2224     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2225     if (Branch && Branch->isConditional()) {
2226       // Look for the selector dispatch.
2227       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2228       //   %matches = icmp eq i32 %sel, %2
2229       //   br i1 %matches, label %catch14, label %eh.resume
2230       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2231       if (!Compare || !Compare->isEquality())
2232         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2233       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2234            II != IE; ++II) {
2235         Instruction *Inst = II;
2236         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2237           continue;
2238         if (Inst == Compare || Inst == Branch)
2239           continue;
2240         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2241           continue;
2242         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2243       }
2244       // The selector dispatch block should always terminate our search.
2245       assert(BB == EndBB);
2246       return;
2247     }
2248
2249     if (isAsynchronousEHPersonality(Personality)) {
2250       // If this is a landingpad block, split the block at the first non-landing
2251       // pad instruction.
2252       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2253       if (LPadMap) {
2254         while (MaybeCall != BB->getTerminator() &&
2255                LPadMap->isLandingPadSpecificInst(MaybeCall))
2256           MaybeCall = MaybeCall->getNextNode();
2257       }
2258
2259       // Look for outlined finally calls.
2260       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2261         Function *Fin = FinallyCall.getCalledFunction();
2262         assert(Fin && "outlined finally call should be direct");
2263         auto *Action = new CleanupHandler(BB);
2264         Action->setHandlerBlockOrFunc(Fin);
2265         Actions.insertCleanupHandler(Action);
2266         CleanupHandlerMap[BB] = Action;
2267         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2268                      << Fin->getName() << " in block "
2269                      << Action->getStartBlock()->getName() << "\n");
2270
2271         // Split the block if there were more interesting instructions and look
2272         // for finally calls in the normal successor block.
2273         BasicBlock *SuccBB = BB;
2274         if (FinallyCall.getInstruction() != BB->getTerminator() &&
2275             FinallyCall.getInstruction()->getNextNode() !=
2276                 BB->getTerminator()) {
2277           SuccBB =
2278               SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2279         } else {
2280           if (FinallyCall.isInvoke()) {
2281             SuccBB =
2282                 cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2283           } else {
2284             SuccBB = BB->getUniqueSuccessor();
2285             assert(SuccBB &&
2286                    "splitOutlinedFinallyCalls didn't insert a branch");
2287           }
2288         }
2289         BB = SuccBB;
2290         if (BB == EndBB)
2291           return;
2292         continue;
2293       }
2294     }
2295
2296     // Anything else is either a catch block or interesting cleanup code.
2297     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2298          II != IE; ++II) {
2299       Instruction *Inst = II;
2300       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2301         continue;
2302       // Unconditional branches fall through to this loop.
2303       if (Inst == Branch)
2304         continue;
2305       // If this is a catch block, there is no cleanup code to be found.
2306       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2307         return;
2308       // If this a nested landing pad, it may contain an endcatch call.
2309       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2310         return;
2311       // Anything else makes this interesting cleanup code.
2312       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2313     }
2314
2315     // Only unconditional branches in empty blocks should get this far.
2316     assert(Branch && Branch->isUnconditional());
2317     if (BB == EndBB)
2318       return;
2319     BB = Branch->getSuccessor(0);
2320   }
2321 }
2322
2323 // This is a public function, declared in WinEHFuncInfo.h and is also
2324 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2325 void llvm::parseEHActions(const IntrinsicInst *II,
2326                           SmallVectorImpl<ActionHandler *> &Actions) {
2327   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2328     uint64_t ActionKind =
2329         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2330     if (ActionKind == /*catch=*/1) {
2331       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2332       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2333       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2334       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2335       I += 4;
2336       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2337       CH->setHandlerBlockOrFunc(Handler);
2338       CH->setExceptionVarIndex(EHObjIndexVal);
2339       Actions.push_back(CH);
2340     } else if (ActionKind == 0) {
2341       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2342       I += 2;
2343       auto *CH = new CleanupHandler(/*BB=*/nullptr);
2344       CH->setHandlerBlockOrFunc(Handler);
2345       Actions.push_back(CH);
2346     } else {
2347       llvm_unreachable("Expected either a catch or cleanup handler!");
2348     }
2349   }
2350   std::reverse(Actions.begin(), Actions.end());
2351 }