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