fefb444cea9dca744b9fcf24b38caefefff24d63
[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/CFG.h"
27 #include "llvm/Analysis/LibCallSemantics.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/CodeGen/WinEHFuncInfo.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
44 #include "llvm/Transforms/Utils/SSAUpdater.h"
45 #include <memory>
46
47 using namespace llvm;
48 using namespace llvm::PatternMatch;
49
50 #define DEBUG_TYPE "winehprepare"
51
52 static cl::opt<bool> DisableDemotion(
53     "disable-demotion", cl::Hidden,
54     cl::desc(
55         "Clone multicolor basic blocks but do not demote cross funclet values"),
56     cl::init(false));
57
58 static cl::opt<bool> DisableCleanups(
59     "disable-cleanups", cl::Hidden,
60     cl::desc("Do not remove implausible terminators or other similar cleanups"),
61     cl::init(false));
62
63 namespace {
64
65 // This map is used to model frame variable usage during outlining, to
66 // construct a structure type to hold the frame variables in a frame
67 // allocation block, and to remap the frame variable allocas (including
68 // spill locations as needed) to GEPs that get the variable from the
69 // frame allocation structure.
70 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
71
72 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
73 // quite null.
74 AllocaInst *getCatchObjectSentinel() {
75   return static_cast<AllocaInst *>(nullptr) + 1;
76 }
77
78 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
79
80 class LandingPadActions;
81 class LandingPadMap;
82
83 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
84 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
85
86 class WinEHPrepare : public FunctionPass {
87 public:
88   static char ID; // Pass identification, replacement for typeid.
89   WinEHPrepare(const TargetMachine *TM = nullptr)
90       : FunctionPass(ID) {
91     if (TM)
92       TheTriple = TM->getTargetTriple();
93   }
94
95   bool runOnFunction(Function &Fn) override;
96
97   bool doFinalization(Module &M) override;
98
99   void getAnalysisUsage(AnalysisUsage &AU) const override;
100
101   const char *getPassName() const override {
102     return "Windows exception handling preparation";
103   }
104
105 private:
106   bool prepareExceptionHandlers(Function &F,
107                                 SmallVectorImpl<LandingPadInst *> &LPads);
108   void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
109   void promoteLandingPadValues(LandingPadInst *LPad);
110   void demoteValuesLiveAcrossHandlers(Function &F,
111                                       SmallVectorImpl<LandingPadInst *> &LPads);
112   void findSEHEHReturnPoints(Function &F,
113                              SetVector<BasicBlock *> &EHReturnBlocks);
114   void findCXXEHReturnPoints(Function &F,
115                              SetVector<BasicBlock *> &EHReturnBlocks);
116   void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
117                                 SetVector<BasicBlock*> &Targets);
118   void completeNestedLandingPad(Function *ParentFn,
119                                 LandingPadInst *OutlinedLPad,
120                                 const LandingPadInst *OriginalLPad,
121                                 FrameVarInfoMap &VarInfo);
122   Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
123                               const Twine &Name, Module *M, Value *&ParentFP);
124   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
125                       LandingPadInst *LPad, BasicBlock *StartBB,
126                       FrameVarInfoMap &VarInfo);
127   void addStubInvokeToHandlerIfNeeded(Function *Handler);
128
129   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
130   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
131                                  VisitedBlockSet &VisitedBlocks);
132   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
133                            BasicBlock *EndBB);
134
135   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
136   void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
137   void
138   insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
139                  SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
140   AllocaInst *insertPHILoads(PHINode *PN, Function &F);
141   void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
142                           DenseMap<BasicBlock *, Value *> &Loads, Function &F);
143   void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
144                           Function &F);
145   bool prepareExplicitEH(Function &F,
146                          SmallVectorImpl<BasicBlock *> &EntryBlocks);
147   void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
148   void demotePHIsOnFunclets(Function &F);
149   void demoteUsesBetweenFunclets(Function &F);
150   void demoteArgumentUses(Function &F);
151   void cloneCommonBlocks(Function &F,
152                          SmallVectorImpl<BasicBlock *> &EntryBlocks);
153   void removeImplausibleTerminators(Function &F);
154   void cleanupPreparedFunclets(Function &F);
155   void verifyPreparedFunclets(Function &F);
156
157   Triple TheTriple;
158
159   // All fields are reset by runOnFunction.
160   DominatorTree *DT = nullptr;
161   const TargetLibraryInfo *LibInfo = nullptr;
162   EHPersonality Personality = EHPersonality::Unknown;
163   CatchHandlerMapTy CatchHandlerMap;
164   CleanupHandlerMapTy CleanupHandlerMap;
165   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
166   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
167   SmallPtrSet<BasicBlock *, 4> EHBlocks;
168   SetVector<BasicBlock *> EHReturnBlocks;
169
170   // This maps landing pad instructions found in outlined handlers to
171   // the landing pad instruction in the parent function from which they
172   // were cloned.  The cloned/nested landing pad is used as the key
173   // because the landing pad may be cloned into multiple handlers.
174   // This map will be used to add the llvm.eh.actions call to the nested
175   // landing pads after all handlers have been outlined.
176   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
177
178   // This maps blocks in the parent function which are destinations of
179   // catch handlers to cloned blocks in (other) outlined handlers. This
180   // handles the case where a nested landing pads has a catch handler that
181   // returns to a handler function rather than the parent function.
182   // The original block is used as the key here because there should only
183   // ever be one handler function from which the cloned block is not pruned.
184   // The original block will be pruned from the parent function after all
185   // handlers have been outlined.  This map will be used to adjust the
186   // return instructions of handlers which return to the block that was
187   // outlined into a handler.  This is done after all handlers have been
188   // outlined but before the outlined code is pruned from the parent function.
189   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
190
191   // Map from outlined handler to call to parent local address. Only used for
192   // 32-bit EH.
193   DenseMap<Function *, Value *> HandlerToParentFP;
194
195   AllocaInst *SEHExceptionCodeSlot = nullptr;
196
197   std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
198   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
199   std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
200 };
201
202 class WinEHFrameVariableMaterializer : public ValueMaterializer {
203 public:
204   WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
205                                  FrameVarInfoMap &FrameVarInfo);
206   ~WinEHFrameVariableMaterializer() override {}
207
208   Value *materializeValueFor(Value *V) override;
209
210   void escapeCatchObject(Value *V);
211
212 private:
213   FrameVarInfoMap &FrameVarInfo;
214   IRBuilder<> Builder;
215 };
216
217 class LandingPadMap {
218 public:
219   LandingPadMap() : OriginLPad(nullptr) {}
220   void mapLandingPad(const LandingPadInst *LPad);
221
222   bool isInitialized() { return OriginLPad != nullptr; }
223
224   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
225   bool isLandingPadSpecificInst(const Instruction *Inst) const;
226
227   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
228                      Value *SelectorValue) const;
229
230 private:
231   const LandingPadInst *OriginLPad;
232   // We will normally only see one of each of these instructions, but
233   // if more than one occurs for some reason we can handle that.
234   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
235   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
236 };
237
238 class WinEHCloningDirectorBase : public CloningDirector {
239 public:
240   WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
241                            FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
242       : Materializer(HandlerFn, ParentFP, VarInfo),
243         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
244         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
245         LPadMap(LPadMap), ParentFP(ParentFP) {}
246
247   CloningAction handleInstruction(ValueToValueMapTy &VMap,
248                                   const Instruction *Inst,
249                                   BasicBlock *NewBB) override;
250
251   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
252                                          const Instruction *Inst,
253                                          BasicBlock *NewBB) = 0;
254   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
255                                        const Instruction *Inst,
256                                        BasicBlock *NewBB) = 0;
257   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
258                                         const Instruction *Inst,
259                                         BasicBlock *NewBB) = 0;
260   virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
261                                          const IndirectBrInst *IBr,
262                                          BasicBlock *NewBB) = 0;
263   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
264                                      const InvokeInst *Invoke,
265                                      BasicBlock *NewBB) = 0;
266   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
267                                      const ResumeInst *Resume,
268                                      BasicBlock *NewBB) = 0;
269   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
270                                       const CmpInst *Compare,
271                                       BasicBlock *NewBB) = 0;
272   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
273                                          const LandingPadInst *LPad,
274                                          BasicBlock *NewBB) = 0;
275
276   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
277
278 protected:
279   WinEHFrameVariableMaterializer Materializer;
280   Type *SelectorIDType;
281   Type *Int8PtrType;
282   LandingPadMap &LPadMap;
283
284   /// The value representing the parent frame pointer.
285   Value *ParentFP;
286 };
287
288 class WinEHCatchDirector : public WinEHCloningDirectorBase {
289 public:
290   WinEHCatchDirector(
291       Function *CatchFn, Value *ParentFP, Value *Selector,
292       FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
293       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
294       DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
295       : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
296         CurrentSelector(Selector->stripPointerCasts()),
297         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
298         DT(DT), EHBlocks(EHBlocks) {}
299
300   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
301                                  const Instruction *Inst,
302                                  BasicBlock *NewBB) override;
303   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
304                                BasicBlock *NewBB) override;
305   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
306                                 const Instruction *Inst,
307                                 BasicBlock *NewBB) override;
308   CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
309                                  const IndirectBrInst *IBr,
310                                  BasicBlock *NewBB) override;
311   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
312                              BasicBlock *NewBB) override;
313   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
314                              BasicBlock *NewBB) override;
315   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
316                               BasicBlock *NewBB) override;
317   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
318                                  const LandingPadInst *LPad,
319                                  BasicBlock *NewBB) override;
320
321   Value *getExceptionVar() { return ExceptionObjectVar; }
322   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
323
324 private:
325   Value *CurrentSelector;
326
327   Value *ExceptionObjectVar;
328   TinyPtrVector<BasicBlock *> ReturnTargets;
329
330   // This will be a reference to the field of the same name in the WinEHPrepare
331   // object which instantiates this WinEHCatchDirector object.
332   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
333   DominatorTree *DT;
334   SmallPtrSetImpl<BasicBlock *> &EHBlocks;
335 };
336
337 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
338 public:
339   WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
340                        FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
341       : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
342                                  LPadMap) {}
343
344   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
345                                  const Instruction *Inst,
346                                  BasicBlock *NewBB) override;
347   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
348                                BasicBlock *NewBB) override;
349   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
350                                 const Instruction *Inst,
351                                 BasicBlock *NewBB) override;
352   CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
353                                  const IndirectBrInst *IBr,
354                                  BasicBlock *NewBB) override;
355   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
356                              BasicBlock *NewBB) override;
357   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
358                              BasicBlock *NewBB) override;
359   CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
360                               BasicBlock *NewBB) override;
361   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
362                                  const LandingPadInst *LPad,
363                                  BasicBlock *NewBB) override;
364 };
365
366 class LandingPadActions {
367 public:
368   LandingPadActions() : HasCleanupHandlers(false) {}
369
370   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
371   void insertCleanupHandler(CleanupHandler *Action) {
372     Actions.push_back(Action);
373     HasCleanupHandlers = true;
374   }
375
376   bool includesCleanup() const { return HasCleanupHandlers; }
377
378   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
379   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
380   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
381
382 private:
383   // Note that this class does not own the ActionHandler objects in this vector.
384   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
385   // in the WinEHPrepare class.
386   SmallVector<ActionHandler *, 4> Actions;
387   bool HasCleanupHandlers;
388 };
389
390 } // end anonymous namespace
391
392 char WinEHPrepare::ID = 0;
393 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
394                    false, false)
395
396 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
397   return new WinEHPrepare(TM);
398 }
399
400 bool WinEHPrepare::runOnFunction(Function &Fn) {
401   if (!Fn.hasPersonalityFn())
402     return false;
403
404   // No need to prepare outlined handlers.
405   if (Fn.hasFnAttribute("wineh-parent"))
406     return false;
407
408   // Classify the personality to see what kind of preparation we need.
409   Personality = classifyEHPersonality(Fn.getPersonalityFn());
410
411   // Do nothing if this is not an MSVC personality.
412   if (!isMSVCEHPersonality(Personality))
413     return false;
414
415   SmallVector<LandingPadInst *, 4> LPads;
416   SmallVector<ResumeInst *, 4> Resumes;
417   SmallVector<BasicBlock *, 4> EntryBlocks;
418   bool ForExplicitEH = false;
419   for (BasicBlock &BB : Fn) {
420     Instruction *First = BB.getFirstNonPHI();
421     if (auto *LP = dyn_cast<LandingPadInst>(First)) {
422       LPads.push_back(LP);
423     } else if (First->isEHPad()) {
424       if (!ForExplicitEH)
425         EntryBlocks.push_back(&Fn.getEntryBlock());
426       if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
427         EntryBlocks.push_back(&BB);
428       ForExplicitEH = true;
429     }
430     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
431       Resumes.push_back(Resume);
432   }
433
434   if (ForExplicitEH)
435     return prepareExplicitEH(Fn, EntryBlocks);
436
437   // No need to prepare functions that lack landing pads.
438   if (LPads.empty())
439     return false;
440
441   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
442   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
443
444   // If there were any landing pads, prepareExceptionHandlers will make changes.
445   prepareExceptionHandlers(Fn, LPads);
446   return true;
447 }
448
449 bool WinEHPrepare::doFinalization(Module &M) { return false; }
450
451 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
452   AU.addRequired<DominatorTreeWrapperPass>();
453   AU.addRequired<TargetLibraryInfoWrapperPass>();
454 }
455
456 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
457                                Constant *&Selector, BasicBlock *&NextBB);
458
459 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
460 // edges or blocks listed in StopPoints.
461 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
462                                 SetVector<BasicBlock *> &Worklist,
463                                 const SetVector<BasicBlock *> *StopPoints) {
464   while (!Worklist.empty()) {
465     BasicBlock *BB = Worklist.pop_back_val();
466
467     // Don't cross blocks that we should stop at.
468     if (StopPoints && StopPoints->count(BB))
469       continue;
470
471     if (!ReachableBBs.insert(BB).second)
472       continue; // Already visited.
473
474     // Don't follow unwind edges of invokes.
475     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
476       Worklist.insert(II->getNormalDest());
477       continue;
478     }
479
480     // Otherwise, follow all successors.
481     Worklist.insert(succ_begin(BB), succ_end(BB));
482   }
483 }
484
485 // Attempt to find an instruction where a block can be split before
486 // a call to llvm.eh.begincatch and its operands.  If the block
487 // begins with the begincatch call or one of its adjacent operands
488 // the block will not be split.
489 static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
490                                              IntrinsicInst *II) {
491   // If the begincatch call is already the first instruction in the block,
492   // don't split.
493   Instruction *FirstNonPHI = BB->getFirstNonPHI();
494   if (II == FirstNonPHI)
495     return nullptr;
496
497   // If either operand is in the same basic block as the instruction and
498   // isn't used by another instruction before the begincatch call, include it
499   // in the split block.
500   auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
501   auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
502
503   Instruction *I = II->getPrevNode();
504   Instruction *LastI = II;
505
506   while (I == Op0 || I == Op1) {
507     // If the block begins with one of the operands and there are no other
508     // instructions between the operand and the begincatch call, don't split.
509     if (I == FirstNonPHI)
510       return nullptr;
511
512     LastI = I;
513     I = I->getPrevNode();
514   }
515
516   // If there is at least one instruction in the block before the begincatch
517   // call and its operands, split the block at either the begincatch or
518   // its operand.
519   return LastI;
520 }
521
522 /// Find all points where exceptional control rejoins normal control flow via
523 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
524 void WinEHPrepare::findCXXEHReturnPoints(
525     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
526   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
527     BasicBlock *BB = BBI;
528     for (Instruction &I : *BB) {
529       if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
530         Instruction *SplitPt =
531             findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
532         if (SplitPt) {
533           // Split the block before the llvm.eh.begincatch call to allow
534           // cleanup and catch code to be distinguished later.
535           // Do not update BBI because we still need to process the
536           // portion of the block that we are splitting off.
537           SplitBlock(BB, SplitPt, DT);
538           break;
539         }
540       }
541       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
542         // Split the block after the call to llvm.eh.endcatch if there is
543         // anything other than an unconditional branch, or if the successor
544         // starts with a phi.
545         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
546         if (!Br || !Br->isUnconditional() ||
547             isa<PHINode>(Br->getSuccessor(0)->begin())) {
548           DEBUG(dbgs() << "splitting block " << BB->getName()
549                        << " with llvm.eh.endcatch\n");
550           BBI = SplitBlock(BB, I.getNextNode(), DT);
551         }
552         // The next BB is normal control flow.
553         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
554         break;
555       }
556     }
557   }
558 }
559
560 static bool isCatchAllLandingPad(const BasicBlock *BB) {
561   const LandingPadInst *LP = BB->getLandingPadInst();
562   if (!LP)
563     return false;
564   unsigned N = LP->getNumClauses();
565   return (N > 0 && LP->isCatch(N - 1) &&
566           isa<ConstantPointerNull>(LP->getClause(N - 1)));
567 }
568
569 /// Find all points where exceptions control rejoins normal control flow via
570 /// selector dispatch.
571 void WinEHPrepare::findSEHEHReturnPoints(
572     Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
573   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
574     BasicBlock *BB = BBI;
575     // If the landingpad is a catch-all, treat the whole lpad as if it is
576     // reachable from normal control flow.
577     // FIXME: This is imprecise. We need a better way of identifying where a
578     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
579     // is no difference.
580     if (isCatchAllLandingPad(BB)) {
581       EHReturnBlocks.insert(BB);
582       continue;
583     }
584
585     BasicBlock *CatchHandler;
586     BasicBlock *NextBB;
587     Constant *Selector;
588     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
589       // Split the edge if there are multiple predecessors. This creates a place
590       // where we can insert EH recovery code.
591       if (!CatchHandler->getSinglePredecessor()) {
592         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
593                      << " to " << CatchHandler->getName() << '\n');
594         BBI = CatchHandler = SplitCriticalEdge(
595             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
596       }
597       EHReturnBlocks.insert(CatchHandler);
598     }
599   }
600 }
601
602 void WinEHPrepare::identifyEHBlocks(Function &F, 
603                                     SmallVectorImpl<LandingPadInst *> &LPads) {
604   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
605                << F.getName() << '\n');
606
607   // Build a set of all non-exceptional blocks and exceptional blocks.
608   // - Non-exceptional blocks are blocks reachable from the entry block while
609   //   not following invoke unwind edges.
610   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
611   //   not follow llvm.eh.endcatch blocks, which mark a transition from
612   //   exceptional to normal control.
613
614   if (Personality == EHPersonality::MSVC_CXX)
615     findCXXEHReturnPoints(F, EHReturnBlocks);
616   else
617     findSEHEHReturnPoints(F, EHReturnBlocks);
618
619   DEBUG({
620     dbgs() << "identified the following blocks as EH return points:\n";
621     for (BasicBlock *BB : EHReturnBlocks)
622       dbgs() << "  " << BB->getName() << '\n';
623   });
624
625 // Join points should not have phis at this point, unless they are a
626 // landingpad, in which case we will demote their phis later.
627 #ifndef NDEBUG
628   for (BasicBlock *BB : EHReturnBlocks)
629     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
630            "non-lpad EH return block has phi");
631 #endif
632
633   // Normal blocks are the blocks reachable from the entry block and all EH
634   // return points.
635   SetVector<BasicBlock *> Worklist;
636   Worklist = EHReturnBlocks;
637   Worklist.insert(&F.getEntryBlock());
638   findReachableBlocks(NormalBlocks, Worklist, nullptr);
639   DEBUG({
640     dbgs() << "marked the following blocks as normal:\n";
641     for (BasicBlock *BB : NormalBlocks)
642       dbgs() << "  " << BB->getName() << '\n';
643   });
644
645   // Exceptional blocks are the blocks reachable from landingpads that don't
646   // cross EH return points.
647   Worklist.clear();
648   for (auto *LPI : LPads)
649     Worklist.insert(LPI->getParent());
650   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
651   DEBUG({
652     dbgs() << "marked the following blocks as exceptional:\n";
653     for (BasicBlock *BB : EHBlocks)
654       dbgs() << "  " << BB->getName() << '\n';
655   });
656
657 }
658
659 /// Ensure that all values live into and out of exception handlers are stored
660 /// in memory.
661 /// FIXME: This falls down when values are defined in one handler and live into
662 /// another handler. For example, a cleanup defines a value used only by a
663 /// catch handler.
664 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
665     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
666   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
667                << F.getName() << '\n');
668
669   // identifyEHBlocks() should have been called before this function.
670   assert(!NormalBlocks.empty());
671
672   // Try to avoid demoting EH pointer and selector values. They get in the way
673   // of our pattern matching.
674   SmallPtrSet<Instruction *, 10> EHVals;
675   for (BasicBlock &BB : F) {
676     LandingPadInst *LP = BB.getLandingPadInst();
677     if (!LP)
678       continue;
679     EHVals.insert(LP);
680     for (User *U : LP->users()) {
681       auto *EI = dyn_cast<ExtractValueInst>(U);
682       if (!EI)
683         continue;
684       EHVals.insert(EI);
685       for (User *U2 : EI->users()) {
686         if (auto *PN = dyn_cast<PHINode>(U2))
687           EHVals.insert(PN);
688       }
689     }
690   }
691
692   SetVector<Argument *> ArgsToDemote;
693   SetVector<Instruction *> InstrsToDemote;
694   for (BasicBlock &BB : F) {
695     bool IsNormalBB = NormalBlocks.count(&BB);
696     bool IsEHBB = EHBlocks.count(&BB);
697     if (!IsNormalBB && !IsEHBB)
698       continue; // Blocks that are neither normal nor EH are unreachable.
699     for (Instruction &I : BB) {
700       for (Value *Op : I.operands()) {
701         // Don't demote static allocas, constants, and labels.
702         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
703           continue;
704         auto *AI = dyn_cast<AllocaInst>(Op);
705         if (AI && AI->isStaticAlloca())
706           continue;
707
708         if (auto *Arg = dyn_cast<Argument>(Op)) {
709           if (IsEHBB) {
710             DEBUG(dbgs() << "Demoting argument " << *Arg
711                          << " used by EH instr: " << I << "\n");
712             ArgsToDemote.insert(Arg);
713           }
714           continue;
715         }
716
717         // Don't demote EH values.
718         auto *OpI = cast<Instruction>(Op);
719         if (EHVals.count(OpI))
720           continue;
721
722         BasicBlock *OpBB = OpI->getParent();
723         // If a value is produced and consumed in the same BB, we don't need to
724         // demote it.
725         if (OpBB == &BB)
726           continue;
727         bool IsOpNormalBB = NormalBlocks.count(OpBB);
728         bool IsOpEHBB = EHBlocks.count(OpBB);
729         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
730           DEBUG({
731             dbgs() << "Demoting instruction live in-out from EH:\n";
732             dbgs() << "Instr: " << *OpI << '\n';
733             dbgs() << "User: " << I << '\n';
734           });
735           InstrsToDemote.insert(OpI);
736         }
737       }
738     }
739   }
740
741   // Demote values live into and out of handlers.
742   // FIXME: This demotion is inefficient. We should insert spills at the point
743   // of definition, insert one reload in each handler that uses the value, and
744   // insert reloads in the BB used to rejoin normal control flow.
745   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
746   for (Instruction *I : InstrsToDemote)
747     DemoteRegToStack(*I, false, AllocaInsertPt);
748
749   // Demote arguments separately, and only for uses in EH blocks.
750   for (Argument *Arg : ArgsToDemote) {
751     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
752                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
753     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
754     for (User *U : Users) {
755       auto *I = dyn_cast<Instruction>(U);
756       if (I && EHBlocks.count(I->getParent())) {
757         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
758         U->replaceUsesOfWith(Arg, Reload);
759       }
760     }
761     new StoreInst(Arg, Slot, AllocaInsertPt);
762   }
763
764   // Demote landingpad phis, as the landingpad will be removed from the machine
765   // CFG.
766   for (LandingPadInst *LPI : LPads) {
767     BasicBlock *BB = LPI->getParent();
768     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
769       DemotePHIToStack(Phi, AllocaInsertPt);
770   }
771
772   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
773                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
774 }
775
776 bool WinEHPrepare::prepareExceptionHandlers(
777     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
778   // Don't run on functions that are already prepared.
779   for (LandingPadInst *LPad : LPads) {
780     BasicBlock *LPadBB = LPad->getParent();
781     for (Instruction &Inst : *LPadBB)
782       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
783         return false;
784   }
785
786   identifyEHBlocks(F, LPads);
787   demoteValuesLiveAcrossHandlers(F, LPads);
788
789   // These containers are used to re-map frame variables that are used in
790   // outlined catch and cleanup handlers.  They will be populated as the
791   // handlers are outlined.
792   FrameVarInfoMap FrameVarInfo;
793
794   bool HandlersOutlined = false;
795
796   Module *M = F.getParent();
797   LLVMContext &Context = M->getContext();
798
799   // Create a new function to receive the handler contents.
800   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
801   Type *Int32Type = Type::getInt32Ty(Context);
802   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
803
804   if (isAsynchronousEHPersonality(Personality)) {
805     // FIXME: Switch the ehptr type to i32 and then switch this.
806     SEHExceptionCodeSlot =
807         new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
808                        F.getEntryBlock().getFirstInsertionPt());
809   }
810
811   // In order to handle the case where one outlined catch handler returns
812   // to a block within another outlined catch handler that would otherwise
813   // be unreachable, we need to outline the nested landing pad before we
814   // outline the landing pad which encloses it.
815   if (!isAsynchronousEHPersonality(Personality))
816     std::sort(LPads.begin(), LPads.end(),
817               [this](LandingPadInst *const &L, LandingPadInst *const &R) {
818                 return DT->properlyDominates(R->getParent(), L->getParent());
819               });
820
821   // This container stores the llvm.eh.recover and IndirectBr instructions
822   // that make up the body of each landing pad after it has been outlined.
823   // We need to defer the population of the target list for the indirectbr
824   // until all landing pads have been outlined so that we can handle the
825   // case of blocks in the target that are reached only from nested
826   // landing pads.
827   SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
828
829   for (LandingPadInst *LPad : LPads) {
830     // Look for evidence that this landingpad has already been processed.
831     bool LPadHasActionList = false;
832     BasicBlock *LPadBB = LPad->getParent();
833     for (Instruction &Inst : *LPadBB) {
834       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
835         LPadHasActionList = true;
836         break;
837       }
838     }
839
840     // If we've already outlined the handlers for this landingpad,
841     // there's nothing more to do here.
842     if (LPadHasActionList)
843       continue;
844
845     // If either of the values in the aggregate returned by the landing pad is
846     // extracted and stored to memory, promote the stored value to a register.
847     promoteLandingPadValues(LPad);
848
849     LandingPadActions Actions;
850     mapLandingPadBlocks(LPad, Actions);
851
852     HandlersOutlined |= !Actions.actions().empty();
853     for (ActionHandler *Action : Actions) {
854       if (Action->hasBeenProcessed())
855         continue;
856       BasicBlock *StartBB = Action->getStartBlock();
857
858       // SEH doesn't do any outlining for catches. Instead, pass the handler
859       // basic block addr to llvm.eh.actions and list the block as a return
860       // target.
861       if (isAsynchronousEHPersonality(Personality)) {
862         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
863           processSEHCatchHandler(CatchAction, StartBB);
864           continue;
865         }
866       }
867
868       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
869     }
870
871     // Split the block after the landingpad instruction so that it is just a
872     // call to llvm.eh.actions followed by indirectbr.
873     assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
874     SplitBlock(LPadBB, LPad->getNextNode(), DT);
875     // Erase the branch inserted by the split so we can insert indirectbr.
876     LPadBB->getTerminator()->eraseFromParent();
877
878     // Replace all extracted values with undef and ultimately replace the
879     // landingpad with undef.
880     SmallVector<Instruction *, 4> SEHCodeUses;
881     SmallVector<Instruction *, 4> EHUndefs;
882     for (User *U : LPad->users()) {
883       auto *E = dyn_cast<ExtractValueInst>(U);
884       if (!E)
885         continue;
886       assert(E->getNumIndices() == 1 &&
887              "Unexpected operation: extracting both landing pad values");
888       unsigned Idx = *E->idx_begin();
889       assert((Idx == 0 || Idx == 1) && "unexpected index");
890       if (Idx == 0 && isAsynchronousEHPersonality(Personality))
891         SEHCodeUses.push_back(E);
892       else
893         EHUndefs.push_back(E);
894     }
895     for (Instruction *E : EHUndefs) {
896       E->replaceAllUsesWith(UndefValue::get(E->getType()));
897       E->eraseFromParent();
898     }
899     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
900
901     // Rewrite uses of the exception pointer to loads of an alloca.
902     while (!SEHCodeUses.empty()) {
903       Instruction *E = SEHCodeUses.pop_back_val();
904       SmallVector<Use *, 4> Uses;
905       for (Use &U : E->uses())
906         Uses.push_back(&U);
907       for (Use *U : Uses) {
908         auto *I = cast<Instruction>(U->getUser());
909         if (isa<ResumeInst>(I))
910           continue;
911         if (auto *Phi = dyn_cast<PHINode>(I))
912           SEHCodeUses.push_back(Phi);
913         else
914           U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
915       }
916       E->replaceAllUsesWith(UndefValue::get(E->getType()));
917       E->eraseFromParent();
918     }
919
920     // Add a call to describe the actions for this landing pad.
921     std::vector<Value *> ActionArgs;
922     for (ActionHandler *Action : Actions) {
923       // Action codes from docs are: 0 cleanup, 1 catch.
924       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
925         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
926         ActionArgs.push_back(CatchAction->getSelector());
927         // Find the frame escape index of the exception object alloca in the
928         // parent.
929         int FrameEscapeIdx = -1;
930         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
931         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
932           auto I = FrameVarInfo.find(EHObj);
933           assert(I != FrameVarInfo.end() &&
934                  "failed to map llvm.eh.begincatch var");
935           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
936         }
937         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
938       } else {
939         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
940       }
941       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
942     }
943     CallInst *Recover =
944         CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
945
946     SetVector<BasicBlock *> ReturnTargets;
947     for (ActionHandler *Action : Actions) {
948       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
949         const auto &CatchTargets = CatchAction->getReturnTargets();
950         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
951       }
952     }
953     IndirectBrInst *Branch =
954         IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
955     for (BasicBlock *Target : ReturnTargets)
956       Branch->addDestination(Target);
957
958     if (!isAsynchronousEHPersonality(Personality)) {
959       // C++ EH must repopulate the targets later to handle the case of
960       // targets that are reached indirectly through nested landing pads.
961       LPadImpls.push_back(std::make_pair(Recover, Branch));
962     }
963
964   } // End for each landingpad
965
966   // If nothing got outlined, there is no more processing to be done.
967   if (!HandlersOutlined)
968     return false;
969
970   // Replace any nested landing pad stubs with the correct action handler.
971   // This must be done before we remove unreachable blocks because it
972   // cleans up references to outlined blocks that will be deleted.
973   for (auto &LPadPair : NestedLPtoOriginalLP)
974     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
975   NestedLPtoOriginalLP.clear();
976
977   // Update the indirectbr instructions' target lists if necessary.
978   SetVector<BasicBlock*> CheckedTargets;
979   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
980   for (auto &LPadImplPair : LPadImpls) {
981     IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
982     IndirectBrInst *Branch = LPadImplPair.second;
983
984     // Get a list of handlers called by 
985     parseEHActions(Recover, ActionList);
986
987     // Add an indirect branch listing possible successors of the catch handlers.
988     SetVector<BasicBlock *> ReturnTargets;
989     for (const auto &Action : ActionList) {
990       if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
991         Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
992         getPossibleReturnTargets(&F, Handler, ReturnTargets);
993       }
994     }
995     ActionList.clear();
996     // Clear any targets we already knew about.
997     for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
998       BasicBlock *KnownTarget = Branch->getDestination(I);
999       if (ReturnTargets.count(KnownTarget))
1000         ReturnTargets.remove(KnownTarget);
1001     }
1002     for (BasicBlock *Target : ReturnTargets) {
1003       Branch->addDestination(Target);
1004       // The target may be a block that we excepted to get pruned.
1005       // If it is, it may contain a call to llvm.eh.endcatch.
1006       if (CheckedTargets.insert(Target)) {
1007         // Earlier preparations guarantee that all calls to llvm.eh.endcatch
1008         // will be followed by an unconditional branch.
1009         auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
1010         if (Br && Br->isUnconditional() &&
1011             Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
1012           Instruction *Prev = Br->getPrevNode();
1013           if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
1014             Prev->eraseFromParent();
1015         }
1016       }
1017     }
1018   }
1019   LPadImpls.clear();
1020
1021   F.addFnAttr("wineh-parent", F.getName());
1022
1023   // Delete any blocks that were only used by handlers that were outlined above.
1024   removeUnreachableBlocks(F);
1025
1026   BasicBlock *Entry = &F.getEntryBlock();
1027   IRBuilder<> Builder(F.getParent()->getContext());
1028   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
1029
1030   Function *FrameEscapeFn =
1031       Intrinsic::getDeclaration(M, Intrinsic::localescape);
1032   Function *RecoverFrameFn =
1033       Intrinsic::getDeclaration(M, Intrinsic::localrecover);
1034   SmallVector<Value *, 8> AllocasToEscape;
1035
1036   // Scan the entry block for an existing call to llvm.localescape. We need to
1037   // keep escaping those objects.
1038   for (Instruction &I : F.front()) {
1039     auto *II = dyn_cast<IntrinsicInst>(&I);
1040     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1041       auto Args = II->arg_operands();
1042       AllocasToEscape.append(Args.begin(), Args.end());
1043       II->eraseFromParent();
1044       break;
1045     }
1046   }
1047
1048   // Finally, replace all of the temporary allocas for frame variables used in
1049   // the outlined handlers with calls to llvm.localrecover.
1050   for (auto &VarInfoEntry : FrameVarInfo) {
1051     Value *ParentVal = VarInfoEntry.first;
1052     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
1053     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
1054
1055     // FIXME: We should try to sink unescaped allocas from the parent frame into
1056     // the child frame. If the alloca is escaped, we have to use the lifetime
1057     // markers to ensure that the alloca is only live within the child frame.
1058
1059     // Add this alloca to the list of things to escape.
1060     AllocasToEscape.push_back(ParentAlloca);
1061
1062     // Next replace all outlined allocas that are mapped to it.
1063     for (AllocaInst *TempAlloca : Allocas) {
1064       if (TempAlloca == getCatchObjectSentinel())
1065         continue; // Skip catch parameter sentinels.
1066       Function *HandlerFn = TempAlloca->getParent()->getParent();
1067       llvm::Value *FP = HandlerToParentFP[HandlerFn];
1068       assert(FP);
1069
1070       // FIXME: Sink this localrecover into the blocks where it is used.
1071       Builder.SetInsertPoint(TempAlloca);
1072       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1073       Value *RecoverArgs[] = {
1074           Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
1075           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
1076       Instruction *RecoveredAlloca =
1077           Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1078
1079       // Add a pointer bitcast if the alloca wasn't an i8.
1080       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1081         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
1082         RecoveredAlloca = cast<Instruction>(
1083             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
1084       }
1085       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1086       TempAlloca->removeFromParent();
1087       RecoveredAlloca->takeName(TempAlloca);
1088       delete TempAlloca;
1089     }
1090   } // End for each FrameVarInfo entry.
1091
1092   // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
1093   // block.
1094   Builder.SetInsertPoint(&F.getEntryBlock().back());
1095   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1096
1097   if (SEHExceptionCodeSlot) {
1098     if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1099       SmallPtrSet<BasicBlock *, 4> UserBlocks;
1100       for (User *U : SEHExceptionCodeSlot->users()) {
1101         if (auto *Inst = dyn_cast<Instruction>(U))
1102           UserBlocks.insert(Inst->getParent());
1103       }
1104       PromoteMemToReg(SEHExceptionCodeSlot, *DT);
1105       // After the promotion, kill off dead instructions.
1106       for (BasicBlock *BB : UserBlocks)
1107         SimplifyInstructionsInBlock(BB, LibInfo);
1108     }
1109   }
1110
1111   // Clean up the handler action maps we created for this function
1112   DeleteContainerSeconds(CatchHandlerMap);
1113   CatchHandlerMap.clear();
1114   DeleteContainerSeconds(CleanupHandlerMap);
1115   CleanupHandlerMap.clear();
1116   HandlerToParentFP.clear();
1117   DT = nullptr;
1118   LibInfo = nullptr;
1119   SEHExceptionCodeSlot = nullptr;
1120   EHBlocks.clear();
1121   NormalBlocks.clear();
1122   EHReturnBlocks.clear();
1123
1124   return HandlersOutlined;
1125 }
1126
1127 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1128   // If the return values of the landing pad instruction are extracted and
1129   // stored to memory, we want to promote the store locations to reg values.
1130   SmallVector<AllocaInst *, 2> EHAllocas;
1131
1132   // The landingpad instruction returns an aggregate value.  Typically, its
1133   // value will be passed to a pair of extract value instructions and the
1134   // results of those extracts are often passed to store instructions.
1135   // In unoptimized code the stored value will often be loaded and then stored
1136   // again.
1137   for (auto *U : LPad->users()) {
1138     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1139     if (!Extract)
1140       continue;
1141
1142     for (auto *EU : Extract->users()) {
1143       if (auto *Store = dyn_cast<StoreInst>(EU)) {
1144         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1145         EHAllocas.push_back(AV);
1146       }
1147     }
1148   }
1149
1150   // We can't do this without a dominator tree.
1151   assert(DT);
1152
1153   if (!EHAllocas.empty()) {
1154     PromoteMemToReg(EHAllocas, *DT);
1155     EHAllocas.clear();
1156   }
1157
1158   // After promotion, some extracts may be trivially dead. Remove them.
1159   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1160   for (auto *U : Users)
1161     RecursivelyDeleteTriviallyDeadInstructions(U);
1162 }
1163
1164 void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1165                                             Function *HandlerF,
1166                                             SetVector<BasicBlock*> &Targets) {
1167   for (BasicBlock &BB : *HandlerF) {
1168     // If the handler contains landing pads, check for any
1169     // handlers that may return directly to a block in the
1170     // parent function.
1171     if (auto *LPI = BB.getLandingPadInst()) {
1172       IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
1173       SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1174       parseEHActions(Recover, ActionList);
1175       for (const auto &Action : ActionList) {
1176         if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
1177           Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1178           getPossibleReturnTargets(ParentF, NestedF, Targets);
1179         }
1180       }
1181     }
1182
1183     auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1184     if (!Ret)
1185       continue;
1186
1187     // Handler functions must always return a block address.
1188     BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1189
1190     // If this is the handler for a nested landing pad, the
1191     // return address may have been remapped to a block in the
1192     // parent handler.  We're not interested in those.
1193     if (BA->getFunction() != ParentF)
1194       continue;
1195
1196     Targets.insert(BA->getBasicBlock());
1197   }
1198 }
1199
1200 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1201                                             LandingPadInst *OutlinedLPad,
1202                                             const LandingPadInst *OriginalLPad,
1203                                             FrameVarInfoMap &FrameVarInfo) {
1204   // Get the nested block and erase the unreachable instruction that was
1205   // temporarily inserted as its terminator.
1206   LLVMContext &Context = ParentFn->getContext();
1207   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1208   // If the nested landing pad was outlined before the landing pad that enclosed
1209   // it, it will already be in outlined form.  In that case, we just need to see
1210   // if the returns and the enclosing branch instruction need to be updated.
1211   IndirectBrInst *Branch =
1212       dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1213   if (!Branch) {
1214     // If the landing pad wasn't in outlined form, it should be a stub with
1215     // an unreachable terminator.
1216     assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1217     OutlinedBB->getTerminator()->eraseFromParent();
1218     // That should leave OutlinedLPad as the last instruction in its block.
1219     assert(&OutlinedBB->back() == OutlinedLPad);
1220   }
1221
1222   // The original landing pad will have already had its action intrinsic
1223   // built by the outlining loop.  We need to clone that into the outlined
1224   // location.  It may also be necessary to add references to the exception
1225   // variables to the outlined handler in which this landing pad is nested
1226   // and remap return instructions in the nested handlers that should return
1227   // to an address in the outlined handler.
1228   Function *OutlinedHandlerFn = OutlinedBB->getParent();
1229   BasicBlock::const_iterator II = OriginalLPad;
1230   ++II;
1231   // The instruction after the landing pad should now be a call to eh.actions.
1232   const Instruction *Recover = II;
1233   const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
1234
1235   // Remap the return target in the nested handler.
1236   SmallVector<BlockAddress *, 4> ActionTargets;
1237   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
1238   parseEHActions(EHActions, ActionList);
1239   for (const auto &Action : ActionList) {
1240     auto *Catch = dyn_cast<CatchHandler>(Action.get());
1241     if (!Catch)
1242       continue;
1243     // The dyn_cast to function here selects C++ catch handlers and skips
1244     // SEH catch handlers.
1245     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1246     if (!Handler)
1247       continue;
1248     // Visit all the return instructions, looking for places that return
1249     // to a location within OutlinedHandlerFn.
1250     for (BasicBlock &NestedHandlerBB : *Handler) {
1251       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1252       if (!Ret)
1253         continue;
1254
1255       // Handler functions must always return a block address.
1256       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1257       // The original target will have been in the main parent function,
1258       // but if it is the address of a block that has been outlined, it
1259       // should be a block that was outlined into OutlinedHandlerFn.
1260       assert(BA->getFunction() == ParentFn);
1261
1262       // Ignore targets that aren't part of an outlined handler function.
1263       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1264         continue;
1265
1266       // If the return value is the address ofF a block that we
1267       // previously outlined into the parent handler function, replace
1268       // the return instruction and add the mapped target to the list
1269       // of possible return addresses.
1270       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1271       assert(MappedBB->getParent() == OutlinedHandlerFn);
1272       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1273       Ret->eraseFromParent();
1274       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1275       ActionTargets.push_back(NewBA);
1276     }
1277   }
1278   ActionList.clear();
1279
1280   if (Branch) {
1281     // If the landing pad was already in outlined form, just update its targets.
1282     for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1283       Branch->removeDestination(I);
1284     // Add the previously collected action targets.
1285     for (auto *Target : ActionTargets)
1286       Branch->addDestination(Target->getBasicBlock());
1287   } else {
1288     // If the landing pad was previously stubbed out, fill in its outlined form.
1289     IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1290     OutlinedBB->getInstList().push_back(NewEHActions);
1291
1292     // Insert an indirect branch into the outlined landing pad BB.
1293     IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1294     // Add the previously collected action targets.
1295     for (auto *Target : ActionTargets)
1296       IBr->addDestination(Target->getBasicBlock());
1297   }
1298 }
1299
1300 // This function examines a block to determine whether the block ends with a
1301 // conditional branch to a catch handler based on a selector comparison.
1302 // This function is used both by the WinEHPrepare::findSelectorComparison() and
1303 // WinEHCleanupDirector::handleTypeIdFor().
1304 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1305                                Constant *&Selector, BasicBlock *&NextBB) {
1306   ICmpInst::Predicate Pred;
1307   BasicBlock *TBB, *FBB;
1308   Value *LHS, *RHS;
1309
1310   if (!match(BB->getTerminator(),
1311              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1312     return false;
1313
1314   if (!match(LHS,
1315              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1316       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1317     return false;
1318
1319   if (Pred == CmpInst::ICMP_EQ) {
1320     CatchHandler = TBB;
1321     NextBB = FBB;
1322     return true;
1323   }
1324
1325   if (Pred == CmpInst::ICMP_NE) {
1326     CatchHandler = FBB;
1327     NextBB = TBB;
1328     return true;
1329   }
1330
1331   return false;
1332 }
1333
1334 static bool isCatchBlock(BasicBlock *BB) {
1335   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1336        II != IE; ++II) {
1337     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1338       return true;
1339   }
1340   return false;
1341 }
1342
1343 static BasicBlock *createStubLandingPad(Function *Handler) {
1344   // FIXME: Finish this!
1345   LLVMContext &Context = Handler->getContext();
1346   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1347   Handler->getBasicBlockList().push_back(StubBB);
1348   IRBuilder<> Builder(StubBB);
1349   LandingPadInst *LPad = Builder.CreateLandingPad(
1350       llvm::StructType::get(Type::getInt8PtrTy(Context),
1351                             Type::getInt32Ty(Context), nullptr),
1352       0);
1353   // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1354   Function *ActionIntrin =
1355       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
1356   Builder.CreateCall(ActionIntrin, {}, "recover");
1357   LPad->setCleanup(true);
1358   Builder.CreateUnreachable();
1359   return StubBB;
1360 }
1361
1362 // Cycles through the blocks in an outlined handler function looking for an
1363 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1364 // landing pad if none is found.  The code that generates the .xdata tables for
1365 // the handler needs at least one landing pad to identify the parent function's
1366 // personality.
1367 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
1368   ReturnInst *Ret = nullptr;
1369   UnreachableInst *Unreached = nullptr;
1370   for (BasicBlock &BB : *Handler) {
1371     TerminatorInst *Terminator = BB.getTerminator();
1372     // If we find an invoke, there is nothing to be done.
1373     auto *II = dyn_cast<InvokeInst>(Terminator);
1374     if (II)
1375       return;
1376     // If we've already recorded a return instruction, keep looking for invokes.
1377     if (!Ret)
1378       Ret = dyn_cast<ReturnInst>(Terminator);
1379     // If we haven't recorded an unreachable instruction, try this terminator.
1380     if (!Unreached)
1381       Unreached = dyn_cast<UnreachableInst>(Terminator);
1382   }
1383
1384   // If we got this far, the handler contains no invokes.  We should have seen
1385   // at least one return or unreachable instruction.  We'll insert an invoke of
1386   // llvm.donothing ahead of that instruction.
1387   assert(Ret || Unreached);
1388   TerminatorInst *Term;
1389   if (Ret)
1390     Term = Ret;
1391   else
1392     Term = Unreached;
1393   BasicBlock *OldRetBB = Term->getParent();
1394   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
1395   // SplitBlock adds an unconditional branch instruction at the end of the
1396   // parent block.  We want to replace that with an invoke call, so we can
1397   // erase it now.
1398   OldRetBB->getTerminator()->eraseFromParent();
1399   BasicBlock *StubLandingPad = createStubLandingPad(Handler);
1400   Function *F =
1401       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1402   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1403 }
1404
1405 // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1406 // usually doesn't build LLVM IR, so that's probably the wrong place.
1407 Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1408                                           const Twine &Name, Module *M,
1409                                           Value *&ParentFP) {
1410   // x64 uses a two-argument prototype where the parent FP is the second
1411   // argument. x86 uses no arguments, just the incoming EBP value.
1412   LLVMContext &Context = M->getContext();
1413   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1414   FunctionType *FnType;
1415   if (TheTriple.getArch() == Triple::x86_64) {
1416     Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1417     FnType = FunctionType::get(RetTy, ArgTys, false);
1418   } else {
1419     FnType = FunctionType::get(RetTy, None, false);
1420   }
1421
1422   Function *Handler =
1423       Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1424   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1425   Handler->getBasicBlockList().push_front(Entry);
1426   if (TheTriple.getArch() == Triple::x86_64) {
1427     ParentFP = &(Handler->getArgumentList().back());
1428   } else {
1429     assert(M);
1430     Function *FrameAddressFn =
1431         Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1432     Function *RecoverFPFn =
1433         Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1434     IRBuilder<> Builder(&Handler->getEntryBlock());
1435     Value *EBP =
1436         Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1437     Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1438     ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
1439   }
1440   return Handler;
1441 }
1442
1443 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1444                                   LandingPadInst *LPad, BasicBlock *StartBB,
1445                                   FrameVarInfoMap &VarInfo) {
1446   Module *M = SrcFn->getParent();
1447   LLVMContext &Context = M->getContext();
1448   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1449
1450   // Create a new function to receive the handler contents.
1451   Value *ParentFP;
1452   Function *Handler;
1453   if (Action->getType() == Catch) {
1454     Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
1455                                 ParentFP);
1456   } else {
1457     Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
1458                                 SrcFn->getName() + ".cleanup", M, ParentFP);
1459   }
1460   Handler->setPersonalityFn(SrcFn->getPersonalityFn());
1461   HandlerToParentFP[Handler] = ParentFP;
1462   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1463   BasicBlock *Entry = &Handler->getEntryBlock();
1464
1465   // Generate a standard prolog to setup the frame recovery structure.
1466   IRBuilder<> Builder(Context);
1467   Builder.SetInsertPoint(Entry);
1468   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1469
1470   std::unique_ptr<WinEHCloningDirectorBase> Director;
1471
1472   ValueToValueMapTy VMap;
1473
1474   LandingPadMap &LPadMap = LPadMaps[LPad];
1475   if (!LPadMap.isInitialized())
1476     LPadMap.mapLandingPad(LPad);
1477   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1478     Constant *Sel = CatchAction->getSelector();
1479     Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1480                                           LPadMap, NestedLPtoOriginalLP, DT,
1481                                           EHBlocks));
1482     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1483                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1484   } else {
1485     Director.reset(
1486         new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
1487     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1488                           UndefValue::get(Type::getInt32Ty(Context)));
1489   }
1490
1491   SmallVector<ReturnInst *, 8> Returns;
1492   ClonedCodeInfo OutlinedFunctionInfo;
1493
1494   // If the start block contains PHI nodes, we need to map them.
1495   BasicBlock::iterator II = StartBB->begin();
1496   while (auto *PN = dyn_cast<PHINode>(II)) {
1497     bool Mapped = false;
1498     // Look for PHI values that we have already mapped (such as the selector).
1499     for (Value *Val : PN->incoming_values()) {
1500       if (VMap.count(Val)) {
1501         VMap[PN] = VMap[Val];
1502         Mapped = true;
1503       }
1504     }
1505     // If we didn't find a match for this value, map it as an undef.
1506     if (!Mapped) {
1507       VMap[PN] = UndefValue::get(PN->getType());
1508     }
1509     ++II;
1510   }
1511
1512   // The landing pad value may be used by PHI nodes.  It will ultimately be
1513   // eliminated, but we need it in the map for intermediate handling.
1514   VMap[LPad] = UndefValue::get(LPad->getType());
1515
1516   // Skip over PHIs and, if applicable, landingpad instructions.
1517   II = StartBB->getFirstInsertionPt();
1518
1519   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1520                             /*ModuleLevelChanges=*/false, Returns, "",
1521                             &OutlinedFunctionInfo, Director.get());
1522
1523   // Move all the instructions in the cloned "entry" block into our entry block.
1524   // Depending on how the parent function was laid out, the block that will
1525   // correspond to the outlined entry block may not be the first block in the
1526   // list.  We can recognize it, however, as the cloned block which has no
1527   // predecessors.  Any other block wouldn't have been cloned if it didn't
1528   // have a predecessor which was also cloned.
1529   Function::iterator ClonedIt = std::next(Function::iterator(Entry));
1530   while (!pred_empty(ClonedIt))
1531     ++ClonedIt;
1532   BasicBlock *ClonedEntryBB = ClonedIt;
1533   assert(ClonedEntryBB);
1534   Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1535   ClonedEntryBB->eraseFromParent();
1536
1537   // Make sure we can identify the handler's personality later.
1538   addStubInvokeToHandlerIfNeeded(Handler);
1539
1540   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1541     WinEHCatchDirector *CatchDirector =
1542         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1543     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1544     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1545
1546     // Look for blocks that are not part of the landing pad that we just
1547     // outlined but terminate with a call to llvm.eh.endcatch and a
1548     // branch to a block that is in the handler we just outlined.
1549     // These blocks will be part of a nested landing pad that intends to
1550     // return to an address in this handler.  This case is best handled
1551     // after both landing pads have been outlined, so for now we'll just
1552     // save the association of the blocks in LPadTargetBlocks.  The
1553     // return instructions which are created from these branches will be
1554     // replaced after all landing pads have been outlined.
1555     for (const auto MapEntry : VMap) {
1556       // VMap maps all values and blocks that were just cloned, but dead
1557       // blocks which were pruned will map to nullptr.
1558       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1559         continue;
1560       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1561       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1562         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1563         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1564           continue;
1565         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1566         --II;
1567         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1568           // This would indicate that a nested landing pad wants to return
1569           // to a block that is outlined into two different handlers.
1570           assert(!LPadTargetBlocks.count(MappedBB));
1571           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1572         }
1573       }
1574     }
1575   } // End if (CatchAction)
1576
1577   Action->setHandlerBlockOrFunc(Handler);
1578
1579   return true;
1580 }
1581
1582 /// This BB must end in a selector dispatch. All we need to do is pass the
1583 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1584 /// target.
1585 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1586                                           BasicBlock *StartBB) {
1587   BasicBlock *HandlerBB;
1588   BasicBlock *NextBB;
1589   Constant *Selector;
1590   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1591   if (Res) {
1592     // If this was EH dispatch, this must be a conditional branch to the handler
1593     // block.
1594     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1595     // leading to crashes if some optimization hoists stuff here.
1596     assert(CatchAction->getSelector() && HandlerBB &&
1597            "expected catch EH dispatch");
1598   } else {
1599     // This must be a catch-all. Split the block after the landingpad.
1600     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1601     HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
1602   }
1603   IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1604   Function *EHCodeFn = Intrinsic::getDeclaration(
1605       StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
1606   Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
1607   Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1608   Builder.CreateStore(Code, SEHExceptionCodeSlot);
1609   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1610   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1611   CatchAction->setReturnTargets(Targets);
1612 }
1613
1614 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1615   // Each instance of this class should only ever be used to map a single
1616   // landing pad.
1617   assert(OriginLPad == nullptr || OriginLPad == LPad);
1618
1619   // If the landing pad has already been mapped, there's nothing more to do.
1620   if (OriginLPad == LPad)
1621     return;
1622
1623   OriginLPad = LPad;
1624
1625   // The landingpad instruction returns an aggregate value.  Typically, its
1626   // value will be passed to a pair of extract value instructions and the
1627   // results of those extracts will have been promoted to reg values before
1628   // this routine is called.
1629   for (auto *U : LPad->users()) {
1630     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1631     if (!Extract)
1632       continue;
1633     assert(Extract->getNumIndices() == 1 &&
1634            "Unexpected operation: extracting both landing pad values");
1635     unsigned int Idx = *(Extract->idx_begin());
1636     assert((Idx == 0 || Idx == 1) &&
1637            "Unexpected operation: extracting an unknown landing pad element");
1638     if (Idx == 0) {
1639       ExtractedEHPtrs.push_back(Extract);
1640     } else if (Idx == 1) {
1641       ExtractedSelectors.push_back(Extract);
1642     }
1643   }
1644 }
1645
1646 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1647   return BB->getLandingPadInst() == OriginLPad;
1648 }
1649
1650 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1651   if (Inst == OriginLPad)
1652     return true;
1653   for (auto *Extract : ExtractedEHPtrs) {
1654     if (Inst == Extract)
1655       return true;
1656   }
1657   for (auto *Extract : ExtractedSelectors) {
1658     if (Inst == Extract)
1659       return true;
1660   }
1661   return false;
1662 }
1663
1664 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1665                                   Value *SelectorValue) const {
1666   // Remap all landing pad extract instructions to the specified values.
1667   for (auto *Extract : ExtractedEHPtrs)
1668     VMap[Extract] = EHPtrValue;
1669   for (auto *Extract : ExtractedSelectors)
1670     VMap[Extract] = SelectorValue;
1671 }
1672
1673 static bool isLocalAddressCall(const Value *V) {
1674   return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
1675 }
1676
1677 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1678     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1679   // If this is one of the boilerplate landing pad instructions, skip it.
1680   // The instruction will have already been remapped in VMap.
1681   if (LPadMap.isLandingPadSpecificInst(Inst))
1682     return CloningDirector::SkipInstruction;
1683
1684   // Nested landing pads that have not already been outlined will be cloned as
1685   // stubs, with just the landingpad instruction and an unreachable instruction.
1686   // When all landingpads have been outlined, we'll replace this with the
1687   // llvm.eh.actions call and indirect branch created when the landing pad was
1688   // outlined.
1689   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1690     return handleLandingPad(VMap, LPad, NewBB);
1691   }
1692
1693   // Nested landing pads that have already been outlined will be cloned in their
1694   // outlined form, but we need to intercept the ibr instruction to filter out
1695   // targets that do not return to the handler we are outlining.
1696   if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1697     return handleIndirectBr(VMap, IBr, NewBB);
1698   }
1699
1700   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1701     return handleInvoke(VMap, Invoke, NewBB);
1702
1703   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1704     return handleResume(VMap, Resume, NewBB);
1705
1706   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1707     return handleCompare(VMap, Cmp, NewBB);
1708
1709   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1710     return handleBeginCatch(VMap, Inst, NewBB);
1711   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1712     return handleEndCatch(VMap, Inst, NewBB);
1713   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1714     return handleTypeIdFor(VMap, Inst, NewBB);
1715
1716   // When outlining llvm.localaddress(), remap that to the second argument,
1717   // which is the FP of the parent.
1718   if (isLocalAddressCall(Inst)) {
1719     VMap[Inst] = ParentFP;
1720     return CloningDirector::SkipInstruction;
1721   }
1722
1723   // Continue with the default cloning behavior.
1724   return CloningDirector::CloneInstruction;
1725 }
1726
1727 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1728     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1729   // If the instruction after the landing pad is a call to llvm.eh.actions
1730   // the landing pad has already been outlined.  In this case, we should
1731   // clone it because it may return to a block in the handler we are
1732   // outlining now that would otherwise be unreachable.  The landing pads
1733   // are sorted before outlining begins to enable this case to work
1734   // properly.
1735   const Instruction *NextI = LPad->getNextNode();
1736   if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1737     return CloningDirector::CloneInstruction;
1738
1739   // If the landing pad hasn't been outlined yet, the landing pad we are
1740   // outlining now does not dominate it and so it cannot return to a block
1741   // in this handler.  In that case, we can just insert a stub landing
1742   // pad now and patch it up later.
1743   Instruction *NewInst = LPad->clone();
1744   if (LPad->hasName())
1745     NewInst->setName(LPad->getName());
1746   // Save this correlation for later processing.
1747   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1748   VMap[LPad] = NewInst;
1749   BasicBlock::InstListType &InstList = NewBB->getInstList();
1750   InstList.push_back(NewInst);
1751   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1752   return CloningDirector::StopCloningBB;
1753 }
1754
1755 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1756     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1757   // The argument to the call is some form of the first element of the
1758   // landingpad aggregate value, but that doesn't matter.  It isn't used
1759   // here.
1760   // The second argument is an outparameter where the exception object will be
1761   // stored. Typically the exception object is a scalar, but it can be an
1762   // aggregate when catching by value.
1763   // FIXME: Leave something behind to indicate where the exception object lives
1764   // for this handler. Should it be part of llvm.eh.actions?
1765   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1766                                           "llvm.eh.begincatch found while "
1767                                           "outlining catch handler.");
1768   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1769   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1770     return CloningDirector::SkipInstruction;
1771   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1772          "catch parameter is not static alloca");
1773   Materializer.escapeCatchObject(ExceptionObjectVar);
1774   return CloningDirector::SkipInstruction;
1775 }
1776
1777 CloningDirector::CloningAction
1778 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1779                                    const Instruction *Inst, BasicBlock *NewBB) {
1780   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1781   // It might be interesting to track whether or not we are inside a catch
1782   // function, but that might make the algorithm more brittle than it needs
1783   // to be.
1784
1785   // The end catch call can occur in one of two places: either in a
1786   // landingpad block that is part of the catch handlers exception mechanism,
1787   // or at the end of the catch block.  However, a catch-all handler may call
1788   // end catch from the original landing pad.  If the call occurs in a nested
1789   // landing pad block, we must skip it and continue so that the landing pad
1790   // gets cloned.
1791   auto *ParentBB = IntrinCall->getParent();
1792   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1793     return CloningDirector::SkipInstruction;
1794
1795   // If an end catch occurs anywhere else we want to terminate the handler
1796   // with a return to the code that follows the endcatch call.  If the
1797   // next instruction is not an unconditional branch, we need to split the
1798   // block to provide a clear target for the return instruction.
1799   BasicBlock *ContinueBB;
1800   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1801   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1802   if (!Branch || !Branch->isUnconditional()) {
1803     // We're interrupting the cloning process at this location, so the
1804     // const_cast we're doing here will not cause a problem.
1805     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1806                             const_cast<Instruction *>(cast<Instruction>(Next)));
1807   } else {
1808     ContinueBB = Branch->getSuccessor(0);
1809   }
1810
1811   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1812   ReturnTargets.push_back(ContinueBB);
1813
1814   // We just added a terminator to the cloned block.
1815   // Tell the caller to stop processing the current basic block so that
1816   // the branch instruction will be skipped.
1817   return CloningDirector::StopCloningBB;
1818 }
1819
1820 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1821     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1822   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1823   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1824   // This causes a replacement that will collapse the landing pad CFG based
1825   // on the filter function we intend to match.
1826   if (Selector == CurrentSelector)
1827     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1828   else
1829     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1830   // Tell the caller not to clone this instruction.
1831   return CloningDirector::SkipInstruction;
1832 }
1833
1834 CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1835     ValueToValueMapTy &VMap,
1836     const IndirectBrInst *IBr,
1837     BasicBlock *NewBB) {
1838   // If this indirect branch is not part of a landing pad block, just clone it.
1839   const BasicBlock *ParentBB = IBr->getParent();
1840   if (!ParentBB->isLandingPad())
1841     return CloningDirector::CloneInstruction;
1842
1843   // If it is part of a landing pad, we want to filter out target blocks
1844   // that are not part of the handler we are outlining.
1845   const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1846
1847   // Save this correlation for later processing.
1848   NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1849
1850   // We should only get here for landing pads that have already been outlined.
1851   assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1852
1853   // Copy the indirectbr, but only include targets that were previously
1854   // identified as EH blocks and are dominated by the nested landing pad.
1855   SetVector<const BasicBlock *> ReturnTargets;
1856   for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1857     auto *TargetBB = IBr->getDestination(I);
1858     if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1859         DT->dominates(ParentBB, TargetBB)) {
1860       DEBUG(dbgs() << "  Adding destination " << TargetBB->getName() << "\n");
1861       ReturnTargets.insert(TargetBB);
1862     }
1863   }
1864   IndirectBrInst *NewBranch = 
1865         IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1866                                ReturnTargets.size(), NewBB);
1867   for (auto *Target : ReturnTargets)
1868     NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1869
1870   // The operands and targets of the branch instruction are remapped later
1871   // because it is a terminator.  Tell the cloning code to clone the
1872   // blocks we just added to the target list.
1873   return CloningDirector::CloneSuccessors;
1874 }
1875
1876 CloningDirector::CloningAction
1877 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1878                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1879   return CloningDirector::CloneInstruction;
1880 }
1881
1882 CloningDirector::CloningAction
1883 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1884                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1885   // Resume instructions shouldn't be reachable from catch handlers.
1886   // We still need to handle it, but it will be pruned.
1887   BasicBlock::InstListType &InstList = NewBB->getInstList();
1888   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1889   return CloningDirector::StopCloningBB;
1890 }
1891
1892 CloningDirector::CloningAction
1893 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1894                                   const CmpInst *Compare, BasicBlock *NewBB) {
1895   const IntrinsicInst *IntrinCall = nullptr;
1896   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1897     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1898   } else if (match(Compare->getOperand(1),
1899                    m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1900     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1901   }
1902   if (IntrinCall) {
1903     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1904     // This causes a replacement that will collapse the landing pad CFG based
1905     // on the filter function we intend to match.
1906     if (Selector == CurrentSelector->stripPointerCasts()) {
1907       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1908     } else {
1909       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1910     }
1911     return CloningDirector::SkipInstruction;
1912   }
1913   return CloningDirector::CloneInstruction;
1914 }
1915
1916 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1917     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1918   // The MS runtime will terminate the process if an exception occurs in a
1919   // cleanup handler, so we shouldn't encounter landing pads in the actual
1920   // cleanup code, but they may appear in catch blocks.  Depending on where
1921   // we started cloning we may see one, but it will get dropped during dead
1922   // block pruning.
1923   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1924   VMap[LPad] = NewInst;
1925   BasicBlock::InstListType &InstList = NewBB->getInstList();
1926   InstList.push_back(NewInst);
1927   return CloningDirector::StopCloningBB;
1928 }
1929
1930 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1931     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1932   // Cleanup code may flow into catch blocks or the catch block may be part
1933   // of a branch that will be optimized away.  We'll insert a return
1934   // instruction now, but it may be pruned before the cloning process is
1935   // complete.
1936   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1937   return CloningDirector::StopCloningBB;
1938 }
1939
1940 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1941     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1942   // Cleanup handlers nested within catch handlers may begin with a call to
1943   // eh.endcatch.  We can just ignore that instruction.
1944   return CloningDirector::SkipInstruction;
1945 }
1946
1947 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1948     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1949   // If we encounter a selector comparison while cloning a cleanup handler,
1950   // we want to stop cloning immediately.  Anything after the dispatch
1951   // will be outlined into a different handler.
1952   BasicBlock *CatchHandler;
1953   Constant *Selector;
1954   BasicBlock *NextBB;
1955   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1956                          CatchHandler, Selector, NextBB)) {
1957     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1958     return CloningDirector::StopCloningBB;
1959   }
1960   // If eg.typeid.for is called for any other reason, it can be ignored.
1961   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1962   return CloningDirector::SkipInstruction;
1963 }
1964
1965 CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1966     ValueToValueMapTy &VMap,
1967     const IndirectBrInst *IBr,
1968     BasicBlock *NewBB) {
1969   // No special handling is required for cleanup cloning.
1970   return CloningDirector::CloneInstruction;
1971 }
1972
1973 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1974     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1975   // All invokes in cleanup handlers can be replaced with calls.
1976   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1977   // Insert a normal call instruction...
1978   CallInst *NewCall =
1979       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1980                        Invoke->getName(), NewBB);
1981   NewCall->setCallingConv(Invoke->getCallingConv());
1982   NewCall->setAttributes(Invoke->getAttributes());
1983   NewCall->setDebugLoc(Invoke->getDebugLoc());
1984   VMap[Invoke] = NewCall;
1985
1986   // Remap the operands.
1987   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1988
1989   // Insert an unconditional branch to the normal destination.
1990   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1991
1992   // The unwind destination won't be cloned into the new function, so
1993   // we don't need to clean up its phi nodes.
1994
1995   // We just added a terminator to the cloned block.
1996   // Tell the caller to stop processing the current basic block.
1997   return CloningDirector::CloneSuccessors;
1998 }
1999
2000 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
2001     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
2002   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
2003
2004   // We just added a terminator to the cloned block.
2005   // Tell the caller to stop processing the current basic block so that
2006   // the branch instruction will be skipped.
2007   return CloningDirector::StopCloningBB;
2008 }
2009
2010 CloningDirector::CloningAction
2011 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
2012                                     const CmpInst *Compare, BasicBlock *NewBB) {
2013   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
2014       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
2015     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
2016     return CloningDirector::SkipInstruction;
2017   }
2018   return CloningDirector::CloneInstruction;
2019 }
2020
2021 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
2022     Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
2023     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
2024   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
2025
2026   // New allocas should be inserted in the entry block, but after the parent FP
2027   // is established if it is an instruction.
2028   Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2029   if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2030     InsertPoint = FPInst->getNextNode();
2031   Builder.SetInsertPoint(EntryBB, InsertPoint);
2032 }
2033
2034 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
2035   // If we're asked to materialize a static alloca, we temporarily create an
2036   // alloca in the outlined function and add this to the FrameVarInfo map.  When
2037   // all the outlining is complete, we'll replace these temporary allocas with
2038   // calls to llvm.localrecover.
2039   if (auto *AV = dyn_cast<AllocaInst>(V)) {
2040     assert(AV->isStaticAlloca() &&
2041            "cannot materialize un-demoted dynamic alloca");
2042     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2043     Builder.Insert(NewAlloca, AV->getName());
2044     FrameVarInfo[AV].push_back(NewAlloca);
2045     return NewAlloca;
2046   }
2047
2048   if (isa<Instruction>(V) || isa<Argument>(V)) {
2049     Function *Parent = isa<Instruction>(V)
2050                            ? cast<Instruction>(V)->getParent()->getParent()
2051                            : cast<Argument>(V)->getParent();
2052     errs()
2053         << "Failed to demote instruction used in exception handler of function "
2054         << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
2055     errs() << "  " << *V << '\n';
2056     report_fatal_error("WinEHPrepare failed to demote instruction");
2057   }
2058
2059   // Don't materialize other values.
2060   return nullptr;
2061 }
2062
2063 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2064   // Catch parameter objects have to live in the parent frame. When we see a use
2065   // of a catch parameter, add a sentinel to the multimap to indicate that it's
2066   // used from another handler. This will prevent us from trying to sink the
2067   // alloca into the handler and ensure that the catch parameter is present in
2068   // the call to llvm.localescape.
2069   FrameVarInfo[V].push_back(getCatchObjectSentinel());
2070 }
2071
2072 // This function maps the catch and cleanup handlers that are reachable from the
2073 // specified landing pad. The landing pad sequence will have this basic shape:
2074 //
2075 //  <cleanup handler>
2076 //  <selector comparison>
2077 //  <catch handler>
2078 //  <cleanup handler>
2079 //  <selector comparison>
2080 //  <catch handler>
2081 //  <cleanup handler>
2082 //  ...
2083 //
2084 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
2085 // any arbitrary control flow, but all paths through the cleanup code must
2086 // eventually reach the next selector comparison and no path can skip to a
2087 // different selector comparisons, though some paths may terminate abnormally.
2088 // Therefore, we will use a depth first search from the start of any given
2089 // cleanup block and stop searching when we find the next selector comparison.
2090 //
2091 // If the landingpad instruction does not have a catch clause, we will assume
2092 // that any instructions other than selector comparisons and catch handlers can
2093 // be ignored.  In practice, these will only be the boilerplate instructions.
2094 //
2095 // The catch handlers may also have any control structure, but we are only
2096 // interested in the start of the catch handlers, so we don't need to actually
2097 // follow the flow of the catch handlers.  The start of the catch handlers can
2098 // be located from the compare instructions, but they can be skipped in the
2099 // flow by following the contrary branch.
2100 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2101                                        LandingPadActions &Actions) {
2102   unsigned int NumClauses = LPad->getNumClauses();
2103   unsigned int HandlersFound = 0;
2104   BasicBlock *BB = LPad->getParent();
2105
2106   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2107
2108   if (NumClauses == 0) {
2109     findCleanupHandlers(Actions, BB, nullptr);
2110     return;
2111   }
2112
2113   VisitedBlockSet VisitedBlocks;
2114
2115   while (HandlersFound != NumClauses) {
2116     BasicBlock *NextBB = nullptr;
2117
2118     // Skip over filter clauses.
2119     if (LPad->isFilter(HandlersFound)) {
2120       ++HandlersFound;
2121       continue;
2122     }
2123
2124     // See if the clause we're looking for is a catch-all.
2125     // If so, the catch begins immediately.
2126     Constant *ExpectedSelector =
2127         LPad->getClause(HandlersFound)->stripPointerCasts();
2128     if (isa<ConstantPointerNull>(ExpectedSelector)) {
2129       // The catch all must occur last.
2130       assert(HandlersFound == NumClauses - 1);
2131
2132       // There can be additional selector dispatches in the call chain that we
2133       // need to ignore.
2134       BasicBlock *CatchBlock = nullptr;
2135       Constant *Selector;
2136       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2137         DEBUG(dbgs() << "  Found extra catch dispatch in block "
2138                      << CatchBlock->getName() << "\n");
2139         BB = NextBB;
2140       }
2141
2142       // Add the catch handler to the action list.
2143       CatchHandler *Action = nullptr;
2144       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2145         // If the CatchHandlerMap already has an entry for this BB, re-use it.
2146         Action = CatchHandlerMap[BB];
2147         assert(Action->getSelector() == ExpectedSelector);
2148       } else {
2149         // We don't expect a selector dispatch, but there may be a call to
2150         // llvm.eh.begincatch, which separates catch handling code from
2151         // cleanup code in the same control flow.  This call looks for the
2152         // begincatch intrinsic.
2153         Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2154         if (Action) {
2155           // For C++ EH, check if there is any interesting cleanup code before
2156           // we begin the catch. This is important because cleanups cannot
2157           // rethrow exceptions but code called from catches can. For SEH, it
2158           // isn't important if some finally code before a catch-all is executed
2159           // out of line or after recovering from the exception.
2160           if (Personality == EHPersonality::MSVC_CXX)
2161             findCleanupHandlers(Actions, BB, BB);
2162         } else {
2163           // If an action was not found, it means that the control flows
2164           // directly into the catch-all handler and there is no cleanup code.
2165           // That's an expected situation and we must create a catch action.
2166           // Since this is a catch-all handler, the selector won't actually
2167           // appear in the code anywhere.  ExpectedSelector here is the constant
2168           // null ptr that we got from the landing pad instruction.
2169           Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2170           CatchHandlerMap[BB] = Action;
2171         }
2172       }
2173       Actions.insertCatchHandler(Action);
2174       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
2175       ++HandlersFound;
2176
2177       // Once we reach a catch-all, don't expect to hit a resume instruction.
2178       BB = nullptr;
2179       break;
2180     }
2181
2182     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
2183     assert(CatchAction);
2184
2185     // See if there is any interesting code executed before the dispatch.
2186     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
2187
2188     // When the source program contains multiple nested try blocks the catch
2189     // handlers can get strung together in such a way that we can encounter
2190     // a dispatch for a selector that we've already had a handler for.
2191     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2192       ++HandlersFound;
2193
2194       // Add the catch handler to the action list.
2195       DEBUG(dbgs() << "  Found catch dispatch in block "
2196                    << CatchAction->getStartBlock()->getName() << "\n");
2197       Actions.insertCatchHandler(CatchAction);
2198     } else {
2199       // Under some circumstances optimized IR will flow unconditionally into a
2200       // handler block without checking the selector.  This can only happen if
2201       // the landing pad has a catch-all handler and the handler for the
2202       // preceding catch clause is identical to the catch-call handler
2203       // (typically an empty catch).  In this case, the handler must be shared
2204       // by all remaining clauses.
2205       if (isa<ConstantPointerNull>(
2206               CatchAction->getSelector()->stripPointerCasts())) {
2207         DEBUG(dbgs() << "  Applying early catch-all handler in block "
2208                      << CatchAction->getStartBlock()->getName()
2209                      << "  to all remaining clauses.\n");
2210         Actions.insertCatchHandler(CatchAction);
2211         return;
2212       }
2213
2214       DEBUG(dbgs() << "  Found extra catch dispatch in block "
2215                    << CatchAction->getStartBlock()->getName() << "\n");
2216     }
2217
2218     // Move on to the block after the catch handler.
2219     BB = NextBB;
2220   }
2221
2222   // If we didn't wind up in a catch-all, see if there is any interesting code
2223   // executed before the resume.
2224   findCleanupHandlers(Actions, BB, BB);
2225
2226   // It's possible that some optimization moved code into a landingpad that
2227   // wasn't
2228   // previously being used for cleanup.  If that happens, we need to execute
2229   // that
2230   // extra code from a cleanup handler.
2231   if (Actions.includesCleanup() && !LPad->isCleanup())
2232     LPad->setCleanup(true);
2233 }
2234
2235 // This function searches starting with the input block for the next
2236 // block that terminates with a branch whose condition is based on a selector
2237 // comparison.  This may be the input block.  See the mapLandingPadBlocks
2238 // comments for a discussion of control flow assumptions.
2239 //
2240 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2241                                              BasicBlock *&NextBB,
2242                                              VisitedBlockSet &VisitedBlocks) {
2243   // See if we've already found a catch handler use it.
2244   // Call count() first to avoid creating a null entry for blocks
2245   // we haven't seen before.
2246   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2247     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2248     NextBB = Action->getNextBB();
2249     return Action;
2250   }
2251
2252   // VisitedBlocks applies only to the current search.  We still
2253   // need to consider blocks that we've visited while mapping other
2254   // landing pads.
2255   VisitedBlocks.insert(BB);
2256
2257   BasicBlock *CatchBlock = nullptr;
2258   Constant *Selector = nullptr;
2259
2260   // If this is the first time we've visited this block from any landing pad
2261   // look to see if it is a selector dispatch block.
2262   if (!CatchHandlerMap.count(BB)) {
2263     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2264       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2265       CatchHandlerMap[BB] = Action;
2266       return Action;
2267     }
2268     // If we encounter a block containing an llvm.eh.begincatch before we
2269     // find a selector dispatch block, the handler is assumed to be
2270     // reached unconditionally.  This happens for catch-all blocks, but
2271     // it can also happen for other catch handlers that have been combined
2272     // with the catch-all handler during optimization.
2273     if (isCatchBlock(BB)) {
2274       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2275       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2276       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2277       CatchHandlerMap[BB] = Action;
2278       return Action;
2279     }
2280   }
2281
2282   // Visit each successor, looking for the dispatch.
2283   // FIXME: We expect to find the dispatch quickly, so this will probably
2284   //        work better as a breadth first search.
2285   for (BasicBlock *Succ : successors(BB)) {
2286     if (VisitedBlocks.count(Succ))
2287       continue;
2288
2289     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2290     if (Action)
2291       return Action;
2292   }
2293   return nullptr;
2294 }
2295
2296 // These are helper functions to combine repeated code from findCleanupHandlers.
2297 static void createCleanupHandler(LandingPadActions &Actions,
2298                                  CleanupHandlerMapTy &CleanupHandlerMap,
2299                                  BasicBlock *BB) {
2300   CleanupHandler *Action = new CleanupHandler(BB);
2301   CleanupHandlerMap[BB] = Action;
2302   Actions.insertCleanupHandler(Action);
2303   DEBUG(dbgs() << "  Found cleanup code in block "
2304                << Action->getStartBlock()->getName() << "\n");
2305 }
2306
2307 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2308                                          Instruction *MaybeCall) {
2309   // Look for finally blocks that Clang has already outlined for us.
2310   //   %fp = call i8* @llvm.localaddress()
2311   //   call void @"fin$parent"(iN 1, i8* %fp)
2312   if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2313     MaybeCall = MaybeCall->getNextNode();
2314   CallSite FinallyCall(MaybeCall);
2315   if (!FinallyCall || FinallyCall.arg_size() != 2)
2316     return CallSite();
2317   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2318     return CallSite();
2319   if (!isLocalAddressCall(FinallyCall.getArgument(1)))
2320     return CallSite();
2321   return FinallyCall;
2322 }
2323
2324 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2325   // Skip single ubr blocks.
2326   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2327     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2328     if (Br && Br->isUnconditional())
2329       BB = Br->getSuccessor(0);
2330     else
2331       return BB;
2332   }
2333   return BB;
2334 }
2335
2336 // This function searches starting with the input block for the next block that
2337 // contains code that is not part of a catch handler and would not be eliminated
2338 // during handler outlining.
2339 //
2340 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2341                                        BasicBlock *StartBB, BasicBlock *EndBB) {
2342   // Here we will skip over the following:
2343   //
2344   // landing pad prolog:
2345   //
2346   // Unconditional branches
2347   //
2348   // Selector dispatch
2349   //
2350   // Resume pattern
2351   //
2352   // Anything else marks the start of an interesting block
2353
2354   BasicBlock *BB = StartBB;
2355   // Anything other than an unconditional branch will kick us out of this loop
2356   // one way or another.
2357   while (BB) {
2358     BB = followSingleUnconditionalBranches(BB);
2359     // If we've already scanned this block, don't scan it again.  If it is
2360     // a cleanup block, there will be an action in the CleanupHandlerMap.
2361     // If we've scanned it and it is not a cleanup block, there will be a
2362     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
2363     // be no entry in the CleanupHandlerMap.  We must call count() first to
2364     // avoid creating a null entry for blocks we haven't scanned.
2365     if (CleanupHandlerMap.count(BB)) {
2366       if (auto *Action = CleanupHandlerMap[BB]) {
2367         Actions.insertCleanupHandler(Action);
2368         DEBUG(dbgs() << "  Found cleanup code in block "
2369                      << Action->getStartBlock()->getName() << "\n");
2370         // FIXME: This cleanup might chain into another, and we need to discover
2371         // that.
2372         return;
2373       } else {
2374         // Here we handle the case where the cleanup handler map contains a
2375         // value for this block but the value is a nullptr.  This means that
2376         // we have previously analyzed the block and determined that it did
2377         // not contain any cleanup code.  Based on the earlier analysis, we
2378         // know the block must end in either an unconditional branch, a
2379         // resume or a conditional branch that is predicated on a comparison
2380         // with a selector.  Either the resume or the selector dispatch
2381         // would terminate the search for cleanup code, so the unconditional
2382         // branch is the only case for which we might need to continue
2383         // searching.
2384         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2385         if (SuccBB == BB || SuccBB == EndBB)
2386           return;
2387         BB = SuccBB;
2388         continue;
2389       }
2390     }
2391
2392     // Create an entry in the cleanup handler map for this block.  Initially
2393     // we create an entry that says this isn't a cleanup block.  If we find
2394     // cleanup code, the caller will replace this entry.
2395     CleanupHandlerMap[BB] = nullptr;
2396
2397     TerminatorInst *Terminator = BB->getTerminator();
2398
2399     // Landing pad blocks have extra instructions we need to accept.
2400     LandingPadMap *LPadMap = nullptr;
2401     if (BB->isLandingPad()) {
2402       LandingPadInst *LPad = BB->getLandingPadInst();
2403       LPadMap = &LPadMaps[LPad];
2404       if (!LPadMap->isInitialized())
2405         LPadMap->mapLandingPad(LPad);
2406     }
2407
2408     // Look for the bare resume pattern:
2409     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2410     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
2411     //   resume { i8*, i32 } %lpad.val2
2412     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2413       InsertValueInst *Insert1 = nullptr;
2414       InsertValueInst *Insert2 = nullptr;
2415       Value *ResumeVal = Resume->getOperand(0);
2416       // If the resume value isn't a phi or landingpad value, it should be a
2417       // series of insertions. Identify them so we can avoid them when scanning
2418       // for cleanups.
2419       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
2420         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
2421         if (!Insert2)
2422           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2423         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2424         if (!Insert1)
2425           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2426       }
2427       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2428            II != IE; ++II) {
2429         Instruction *Inst = II;
2430         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2431           continue;
2432         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2433           continue;
2434         if (!Inst->hasOneUse() ||
2435             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
2436           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2437         }
2438       }
2439       return;
2440     }
2441
2442     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
2443     if (Branch && Branch->isConditional()) {
2444       // Look for the selector dispatch.
2445       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2446       //   %matches = icmp eq i32 %sel, %2
2447       //   br i1 %matches, label %catch14, label %eh.resume
2448       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2449       if (!Compare || !Compare->isEquality())
2450         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2451       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2452            II != IE; ++II) {
2453         Instruction *Inst = II;
2454         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2455           continue;
2456         if (Inst == Compare || Inst == Branch)
2457           continue;
2458         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2459           continue;
2460         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2461       }
2462       // The selector dispatch block should always terminate our search.
2463       assert(BB == EndBB);
2464       return;
2465     }
2466
2467     if (isAsynchronousEHPersonality(Personality)) {
2468       // If this is a landingpad block, split the block at the first non-landing
2469       // pad instruction.
2470       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2471       if (LPadMap) {
2472         while (MaybeCall != BB->getTerminator() &&
2473                LPadMap->isLandingPadSpecificInst(MaybeCall))
2474           MaybeCall = MaybeCall->getNextNode();
2475       }
2476
2477       // Look for outlined finally calls on x64, since those happen to match the
2478       // prototype provided by the runtime.
2479       if (TheTriple.getArch() == Triple::x86_64) {
2480         if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2481           Function *Fin = FinallyCall.getCalledFunction();
2482           assert(Fin && "outlined finally call should be direct");
2483           auto *Action = new CleanupHandler(BB);
2484           Action->setHandlerBlockOrFunc(Fin);
2485           Actions.insertCleanupHandler(Action);
2486           CleanupHandlerMap[BB] = Action;
2487           DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2488                        << Fin->getName() << " in block "
2489                        << Action->getStartBlock()->getName() << "\n");
2490
2491           // Split the block if there were more interesting instructions and
2492           // look for finally calls in the normal successor block.
2493           BasicBlock *SuccBB = BB;
2494           if (FinallyCall.getInstruction() != BB->getTerminator() &&
2495               FinallyCall.getInstruction()->getNextNode() !=
2496                   BB->getTerminator()) {
2497             SuccBB =
2498                 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
2499           } else {
2500             if (FinallyCall.isInvoke()) {
2501               SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2502                            ->getNormalDest();
2503             } else {
2504               SuccBB = BB->getUniqueSuccessor();
2505               assert(SuccBB &&
2506                      "splitOutlinedFinallyCalls didn't insert a branch");
2507             }
2508           }
2509           BB = SuccBB;
2510           if (BB == EndBB)
2511             return;
2512           continue;
2513         }
2514       }
2515     }
2516
2517     // Anything else is either a catch block or interesting cleanup code.
2518     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2519          II != IE; ++II) {
2520       Instruction *Inst = II;
2521       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2522         continue;
2523       // Unconditional branches fall through to this loop.
2524       if (Inst == Branch)
2525         continue;
2526       // If this is a catch block, there is no cleanup code to be found.
2527       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2528         return;
2529       // If this a nested landing pad, it may contain an endcatch call.
2530       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2531         return;
2532       // Anything else makes this interesting cleanup code.
2533       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2534     }
2535
2536     // Only unconditional branches in empty blocks should get this far.
2537     assert(Branch && Branch->isUnconditional());
2538     if (BB == EndBB)
2539       return;
2540     BB = Branch->getSuccessor(0);
2541   }
2542 }
2543
2544 // This is a public function, declared in WinEHFuncInfo.h and is also
2545 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2546 void llvm::parseEHActions(
2547     const IntrinsicInst *II,
2548     SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
2549   assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2550          "attempted to parse non eh.actions intrinsic");
2551   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2552     uint64_t ActionKind =
2553         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2554     if (ActionKind == /*catch=*/1) {
2555       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2556       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2557       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2558       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2559       I += 4;
2560       auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2561                                           /*NextBB=*/nullptr);
2562       CH->setHandlerBlockOrFunc(Handler);
2563       CH->setExceptionVarIndex(EHObjIndexVal);
2564       Actions.push_back(std::move(CH));
2565     } else if (ActionKind == 0) {
2566       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2567       I += 2;
2568       auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
2569       CH->setHandlerBlockOrFunc(Handler);
2570       Actions.push_back(std::move(CH));
2571     } else {
2572       llvm_unreachable("Expected either a catch or cleanup handler!");
2573     }
2574   }
2575   std::reverse(Actions.begin(), Actions.end());
2576 }
2577
2578 namespace {
2579 struct WinEHNumbering {
2580   WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2581       CurrentBaseState(-1), NextState(0) {}
2582
2583   WinEHFuncInfo &FuncInfo;
2584   int CurrentBaseState;
2585   int NextState;
2586
2587   SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2588   SmallPtrSet<const Function *, 4> VisitedHandlers;
2589
2590   int currentEHNumber() const {
2591     return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2592   }
2593
2594   void createUnwindMapEntry(int ToState, ActionHandler *AH);
2595   void createTryBlockMapEntry(int TryLow, int TryHigh,
2596                               ArrayRef<CatchHandler *> Handlers);
2597   void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2598                        ImmutableCallSite CS);
2599   void popUnmatchedActions(int FirstMismatch);
2600   void calculateStateNumbers(const Function &F);
2601   void findActionRootLPads(const Function &F);
2602 };
2603 }
2604
2605 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2606                              const Value *V) {
2607   WinEHUnwindMapEntry UME;
2608   UME.ToState = ToState;
2609   UME.Cleanup = V;
2610   FuncInfo.UnwindMap.push_back(UME);
2611   return FuncInfo.getLastStateNumber();
2612 }
2613
2614 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2615                                 int TryHigh, int CatchHigh,
2616                                 ArrayRef<const CatchPadInst *> Handlers) {
2617   WinEHTryBlockMapEntry TBME;
2618   TBME.TryLow = TryLow;
2619   TBME.TryHigh = TryHigh;
2620   TBME.CatchHigh = CatchHigh;
2621   assert(TBME.TryLow <= TBME.TryHigh);
2622   for (const CatchPadInst *CPI : Handlers) {
2623     WinEHHandlerType HT;
2624     Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
2625     if (TypeInfo->isNullValue())
2626       HT.TypeDescriptor = nullptr;
2627     else
2628       HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2629     HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
2630     HT.Handler = CPI->getNormalDest();
2631     HT.CatchObjRecoverIdx = -2;
2632     if (isa<ConstantPointerNull>(CPI->getArgOperand(2)))
2633       HT.CatchObj.Alloca = nullptr;
2634     else
2635       HT.CatchObj.Alloca = cast<AllocaInst>(CPI->getArgOperand(2));
2636     TBME.HandlerArray.push_back(HT);
2637   }
2638   FuncInfo.TryBlockMap.push_back(TBME);
2639 }
2640
2641 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2642   Value *V = nullptr;
2643   if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2644     V = cast<Function>(CH->getHandlerBlockOrFunc());
2645   addUnwindMapEntry(FuncInfo, ToState, V);
2646 }
2647
2648 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2649                                             ArrayRef<CatchHandler *> Handlers) {
2650   // See if we already have an entry for this set of handlers.
2651   // This is using iterators rather than a range-based for loop because
2652   // if we find the entry we're looking for we'll need the iterator to erase it.
2653   int NumHandlers = Handlers.size();
2654   auto I = FuncInfo.TryBlockMap.begin();
2655   auto E = FuncInfo.TryBlockMap.end();
2656   for ( ; I != E; ++I) {
2657     auto &Entry = *I;
2658     if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2659       continue;
2660     int N;
2661     for (N = 0; N < NumHandlers; ++N) {
2662       if (Entry.HandlerArray[N].Handler.get<const Value *>() !=
2663           Handlers[N]->getHandlerBlockOrFunc())
2664         break; // breaks out of inner loop
2665     }
2666     // If all the handlers match, this is what we were looking for.
2667     if (N == NumHandlers) {
2668       break;
2669     }
2670   }
2671
2672   // If we found an existing entry for this set of handlers, extend the range
2673   // but move the entry to the end of the map vector.  The order of entries
2674   // in the map is critical to the way that the runtime finds handlers.
2675   // FIXME: Depending on what has happened with block ordering, this may
2676   //        incorrectly combine entries that should remain separate.
2677   if (I != E) {
2678     // Copy the existing entry.
2679     WinEHTryBlockMapEntry Entry = *I;
2680     Entry.TryLow = std::min(TryLow, Entry.TryLow);
2681     Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2682     assert(Entry.TryLow <= Entry.TryHigh);
2683     // Erase the old entry and add this one to the back.
2684     FuncInfo.TryBlockMap.erase(I);
2685     FuncInfo.TryBlockMap.push_back(Entry);
2686     return;
2687   }
2688
2689   // If we didn't find an entry, create a new one.
2690   WinEHTryBlockMapEntry TBME;
2691   TBME.TryLow = TryLow;
2692   TBME.TryHigh = TryHigh;
2693   assert(TBME.TryLow <= TBME.TryHigh);
2694   for (CatchHandler *CH : Handlers) {
2695     WinEHHandlerType HT;
2696     if (CH->getSelector()->isNullValue()) {
2697       HT.Adjectives = 0x40;
2698       HT.TypeDescriptor = nullptr;
2699     } else {
2700       auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2701       // Selectors are always pointers to GlobalVariables with 'struct' type.
2702       // The struct has two fields, adjectives and a type descriptor.
2703       auto *CS = cast<ConstantStruct>(GV->getInitializer());
2704       HT.Adjectives =
2705           cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2706       HT.TypeDescriptor =
2707           cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2708     }
2709     HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2710     HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2711     HT.CatchObj.Alloca = nullptr;
2712     TBME.HandlerArray.push_back(HT);
2713   }
2714   FuncInfo.TryBlockMap.push_back(TBME);
2715 }
2716
2717 static void print_name(const Value *V) {
2718 #ifndef NDEBUG
2719   if (!V) {
2720     DEBUG(dbgs() << "null");
2721     return;
2722   }
2723
2724   if (const auto *F = dyn_cast<Function>(V))
2725     DEBUG(dbgs() << F->getName());
2726   else
2727     DEBUG(V->dump());
2728 #endif
2729 }
2730
2731 void WinEHNumbering::processCallSite(
2732     MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2733     ImmutableCallSite CS) {
2734   DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2735                << ") for: ");
2736   print_name(CS ? CS.getCalledValue() : nullptr);
2737   DEBUG(dbgs() << '\n');
2738
2739   DEBUG(dbgs() << "HandlerStack: \n");
2740   for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2741     DEBUG(dbgs() << "  ");
2742     print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2743     DEBUG(dbgs() << '\n');
2744   }
2745   DEBUG(dbgs() << "Actions: \n");
2746   for (int I = 0, E = Actions.size(); I < E; ++I) {
2747     DEBUG(dbgs() << "  ");
2748     print_name(Actions[I]->getHandlerBlockOrFunc());
2749     DEBUG(dbgs() << '\n');
2750   }
2751   int FirstMismatch = 0;
2752   for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2753        ++FirstMismatch) {
2754     if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2755         Actions[FirstMismatch]->getHandlerBlockOrFunc())
2756       break;
2757   }
2758
2759   // Remove unmatched actions from the stack and process their EH states.
2760   popUnmatchedActions(FirstMismatch);
2761
2762   DEBUG(dbgs() << "Pushing actions for CallSite: ");
2763   print_name(CS ? CS.getCalledValue() : nullptr);
2764   DEBUG(dbgs() << '\n');
2765
2766   bool LastActionWasCatch = false;
2767   const LandingPadInst *LastRootLPad = nullptr;
2768   for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2769     // We can reuse eh states when pushing two catches for the same invoke.
2770     bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2771     auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2772     // Various conditions can lead to a handler being popped from the
2773     // stack and re-pushed later.  That shouldn't create a new state.
2774     // FIXME: Can code optimization lead to re-used handlers?
2775     if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2776       // If we already assigned the state enclosed by this handler re-use it.
2777       Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2778       continue;
2779     }
2780     const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2781     if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2782       DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2783       Actions[I]->setEHState(currentEHNumber());
2784     } else {
2785       DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2786       print_name(Actions[I]->getHandlerBlockOrFunc());
2787       DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2788       createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2789       DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2790       Actions[I]->setEHState(NextState);
2791       NextState++;
2792     }
2793     HandlerStack.push_back(std::move(Actions[I]));
2794     LastActionWasCatch = CurrActionIsCatch;
2795     LastRootLPad = RootLPad;
2796   }
2797
2798   // This is used to defer numbering states for a handler until after the
2799   // last time it appears in an invoke action list.
2800   if (CS.isInvoke()) {
2801     for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2802       auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2803       if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2804         continue;
2805       FuncInfo.LastInvokeVisited[Handler] = true;
2806       DEBUG(dbgs() << "Last invoke of ");
2807       print_name(Handler);
2808       DEBUG(dbgs() << " has been visited.\n");
2809     }
2810   }
2811
2812   DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2813   print_name(CS ? CS.getCalledValue() : nullptr);
2814   DEBUG(dbgs() << '\n');
2815 }
2816
2817 void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2818   // Don't recurse while we are looping over the handler stack.  Instead, defer
2819   // the numbering of the catch handlers until we are done popping.
2820   SmallVector<CatchHandler *, 4> PoppedCatches;
2821   for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2822     std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2823     if (isa<CatchHandler>(Handler.get()))
2824       PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2825   }
2826
2827   int TryHigh = NextState - 1;
2828   int LastTryLowIdx = 0;
2829   for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2830     CatchHandler *CH = PoppedCatches[I];
2831     DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2832     if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2833       int TryLow = CH->getEHState();
2834       auto Handlers =
2835           makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2836       DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2837       for (size_t J = 0; J < Handlers.size(); ++J) {
2838         DEBUG(dbgs() << ", ");
2839         print_name(Handlers[J]->getHandlerBlockOrFunc());
2840       }
2841       DEBUG(dbgs() << ")\n");
2842       createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2843       LastTryLowIdx = I + 1;
2844     }
2845   }
2846
2847   for (CatchHandler *CH : PoppedCatches) {
2848     if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2849       if (FuncInfo.LastInvokeVisited[F]) {
2850         DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2851         print_name(F);
2852         DEBUG(dbgs() << '\n');
2853         FuncInfo.HandlerBaseState[F] = NextState;
2854         DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2855                      << ", null)\n");
2856         createUnwindMapEntry(currentEHNumber(), nullptr);
2857         ++NextState;
2858         calculateStateNumbers(*F);
2859       }
2860       else {
2861         DEBUG(dbgs() << "Deferring handling of ");
2862         print_name(F);
2863         DEBUG(dbgs() << " until last invoke visited.\n");
2864       }
2865     }
2866     delete CH;
2867   }
2868 }
2869
2870 void WinEHNumbering::calculateStateNumbers(const Function &F) {
2871   auto I = VisitedHandlers.insert(&F);
2872   if (!I.second)
2873     return; // We've already visited this handler, don't renumber it.
2874
2875   int OldBaseState = CurrentBaseState;
2876   if (FuncInfo.HandlerBaseState.count(&F)) {
2877     CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2878   }
2879
2880   size_t SavedHandlerStackSize = HandlerStack.size();
2881
2882   DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2883   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2884   for (const BasicBlock &BB : F) {
2885     for (const Instruction &I : BB) {
2886       const auto *CI = dyn_cast<CallInst>(&I);
2887       if (!CI || CI->doesNotThrow())
2888         continue;
2889       processCallSite(None, CI);
2890     }
2891     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2892     if (!II)
2893       continue;
2894     const LandingPadInst *LPI = II->getLandingPadInst();
2895     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2896     if (!ActionsCall)
2897       continue;
2898     parseEHActions(ActionsCall, ActionList);
2899     if (ActionList.empty())
2900       continue;
2901     processCallSite(ActionList, II);
2902     ActionList.clear();
2903     FuncInfo.EHPadStateMap[LPI] = currentEHNumber();
2904     DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2905                   << " to landing pad at " << LPI->getParent()->getName()
2906                   << '\n');
2907   }
2908
2909   // Pop any actions that were pushed on the stack for this function.
2910   popUnmatchedActions(SavedHandlerStackSize);
2911
2912   DEBUG(dbgs() << "Assigning max state " << NextState - 1
2913                << " to " << F.getName() << '\n');
2914   FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2915
2916   CurrentBaseState = OldBaseState;
2917 }
2918
2919 // This function follows the same basic traversal as calculateStateNumbers
2920 // but it is necessary to identify the root landing pad associated
2921 // with each action before we start assigning state numbers.
2922 void WinEHNumbering::findActionRootLPads(const Function &F) {
2923   auto I = VisitedHandlers.insert(&F);
2924   if (!I.second)
2925     return; // We've already visited this handler, don't revisit it.
2926
2927   SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2928   for (const BasicBlock &BB : F) {
2929     const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2930     if (!II)
2931       continue;
2932     const LandingPadInst *LPI = II->getLandingPadInst();
2933     auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2934     if (!ActionsCall)
2935       continue;
2936
2937     assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2938     parseEHActions(ActionsCall, ActionList);
2939     if (ActionList.empty())
2940       continue;
2941     for (int I = 0, E = ActionList.size(); I < E; ++I) {
2942       if (auto *Handler
2943               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2944         FuncInfo.LastInvoke[Handler] = II;
2945         // Don't replace the root landing pad if we previously saw this
2946         // handler in a different function.
2947         if (FuncInfo.RootLPad.count(Handler) &&
2948             FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2949           continue;
2950         DEBUG(dbgs() << "Setting root lpad for ");
2951         print_name(Handler);
2952         DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2953         FuncInfo.RootLPad[Handler] = LPI;
2954       }
2955     }
2956     // Walk the actions again and look for nested handlers.  This has to
2957     // happen after all of the actions have been processed in the current
2958     // function.
2959     for (int I = 0, E = ActionList.size(); I < E; ++I)
2960       if (auto *Handler
2961               = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2962         findActionRootLPads(*Handler);
2963     ActionList.clear();
2964   }
2965 }
2966
2967 static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
2968   for (const BasicBlock *PredBlock : predecessors(BB))
2969     if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
2970       return CPI;
2971   return nullptr;
2972 }
2973
2974 /// Find all the catchpads that feed directly into the catchendpad. Frontends
2975 /// using this personality should ensure that each catchendpad and catchpad has
2976 /// one or zero catchpad predecessors.
2977 ///
2978 /// The following C++ generates the IR after it:
2979 ///   try {
2980 ///   } catch (A) {
2981 ///   } catch (B) {
2982 ///   }
2983 ///
2984 /// IR:
2985 ///   %catchpad.A
2986 ///     catchpad [i8* A typeinfo]
2987 ///         to label %catch.A unwind label %catchpad.B
2988 ///   %catchpad.B
2989 ///     catchpad [i8* B typeinfo]
2990 ///         to label %catch.B unwind label %endcatches
2991 ///   %endcatches
2992 ///     catchendblock unwind to caller
2993 void findCatchPadsForCatchEndPad(
2994     const BasicBlock *CatchEndBB,
2995     SmallVectorImpl<const CatchPadInst *> &Handlers) {
2996   const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
2997   while (CPI) {
2998     Handlers.push_back(CPI);
2999     CPI = getSingleCatchPadPredecessor(CPI->getParent());
3000   }
3001   // We've pushed these back into reverse source order.  Reverse them to get
3002   // the list back into source order.
3003   std::reverse(Handlers.begin(), Handlers.end());
3004 }
3005
3006 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
3007 // to. If the unwind edge came from an invoke, return null.
3008 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
3009   const TerminatorInst *TI = BB->getTerminator();
3010   if (isa<InvokeInst>(TI))
3011     return nullptr;
3012   if (TI->isEHPad())
3013     return BB;
3014   return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
3015 }
3016
3017 static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
3018                                              const BasicBlock &BB,
3019                                              int ParentState) {
3020   assert(BB.isEHPad());
3021   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3022   // All catchpad instructions will be handled when we process their
3023   // respective catchendpad instruction.
3024   if (isa<CatchPadInst>(FirstNonPHI))
3025     return;
3026
3027   if (isa<CatchEndPadInst>(FirstNonPHI)) {
3028     SmallVector<const CatchPadInst *, 2> Handlers;
3029     findCatchPadsForCatchEndPad(&BB, Handlers);
3030     const BasicBlock *FirstTryPad = Handlers.front()->getParent();
3031     int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3032     FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
3033     for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
3034       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3035         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
3036     int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3037
3038     // catchpads are separate funclets in C++ EH due to the way rethrow works.
3039     // In SEH, they aren't, so no invokes will unwind to the catchendpad.
3040     FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
3041     int TryHigh = CatchLow - 1;
3042     for (const BasicBlock *PredBlock : predecessors(&BB))
3043       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3044         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
3045     int CatchHigh = FuncInfo.getLastStateNumber();
3046     addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
3047     DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
3048                  << '\n');
3049     DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
3050                  << '\n');
3051     DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
3052                  << '\n');
3053   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3054     int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
3055     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3056     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3057                  << BB.getName() << '\n');
3058     for (const BasicBlock *PredBlock : predecessors(&BB))
3059       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3060         calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
3061   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3062     report_fatal_error("Not yet implemented!");
3063   } else {
3064     llvm_unreachable("unexpected EH Pad!");
3065   }
3066 }
3067
3068 static int addSEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
3069                          const Function *Filter, const BasicBlock *Handler) {
3070   SEHUnwindMapEntry Entry;
3071   Entry.ToState = ParentState;
3072   Entry.Filter = Filter;
3073   Entry.Handler = Handler;
3074   FuncInfo.SEHUnwindMap.push_back(Entry);
3075   return FuncInfo.SEHUnwindMap.size() - 1;
3076 }
3077
3078 static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
3079                                              const BasicBlock &BB,
3080                                              int ParentState) {
3081   assert(BB.isEHPad());
3082   const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3083   // All catchpad instructions will be handled when we process their
3084   // respective catchendpad instruction.
3085   if (isa<CatchPadInst>(FirstNonPHI))
3086     return;
3087
3088   if (isa<CatchEndPadInst>(FirstNonPHI)) {
3089     // Extract the filter function and the __except basic block and create a
3090     // state for them.
3091     SmallVector<const CatchPadInst *, 1> Handlers;
3092     findCatchPadsForCatchEndPad(&BB, Handlers);
3093     assert(Handlers.size() == 1 &&
3094            "SEH doesn't have multiple handlers per __try");
3095     const CatchPadInst *CPI = Handlers.front();
3096     const BasicBlock *CatchPadBB = CPI->getParent();
3097     const Function *Filter =
3098         cast<Function>(CPI->getArgOperand(0)->stripPointerCasts());
3099     int TryState =
3100         addSEHHandler(FuncInfo, ParentState, Filter, CPI->getNormalDest());
3101
3102     // Everything in the __try block uses TryState as its parent state.
3103     FuncInfo.EHPadStateMap[CPI] = TryState;
3104     DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
3105                  << CatchPadBB->getName() << '\n');
3106     for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
3107       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3108         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
3109
3110     // Everything in the __except block unwinds to ParentState, just like code
3111     // outside the __try.
3112     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
3113     DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
3114                  << BB.getName() << '\n');
3115     for (const BasicBlock *PredBlock : predecessors(&BB))
3116       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3117         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
3118   } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3119     int CleanupState =
3120         addSEHHandler(FuncInfo, ParentState, /*Filter=*/nullptr, &BB);
3121     FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3122     DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3123                  << BB.getName() << '\n');
3124     for (const BasicBlock *PredBlock : predecessors(&BB))
3125       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3126         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
3127   } else if (isa<CleanupEndPadInst>(FirstNonPHI)) {
3128     // Anything unwinding through CleanupEndPadInst is in ParentState.
3129     FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
3130     DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
3131                  << BB.getName() << '\n');
3132     for (const BasicBlock *PredBlock : predecessors(&BB))
3133       if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3134         calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
3135   } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3136     report_fatal_error("Not yet implemented!");
3137   } else {
3138     llvm_unreachable("unexpected EH Pad!");
3139   }
3140 }
3141
3142 /// Check if the EH Pad unwinds to caller.  Cleanups are a little bit of a
3143 /// special case because we have to look at the cleanupret instruction that uses
3144 /// the cleanuppad.
3145 static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
3146   auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
3147   if (!CPI)
3148     return EHPad->mayThrow();
3149
3150   // This cleanup does not return or unwind, so we say it unwinds to caller.
3151   if (CPI->use_empty())
3152     return true;
3153
3154   const Instruction *User = CPI->user_back();
3155   if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
3156     return CRI->unwindsToCaller();
3157   return cast<CleanupEndPadInst>(User)->unwindsToCaller();
3158 }
3159
3160 void llvm::calculateSEHStateNumbers(const Function *ParentFn,
3161                                     WinEHFuncInfo &FuncInfo) {
3162   // Don't compute state numbers twice.
3163   if (!FuncInfo.SEHUnwindMap.empty())
3164     return;
3165
3166   for (const BasicBlock &BB : *ParentFn) {
3167     if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
3168       continue;
3169     calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
3170   }
3171 }
3172
3173 void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
3174                                          WinEHFuncInfo &FuncInfo) {
3175   // Return if it's already been done.
3176   if (!FuncInfo.EHPadStateMap.empty())
3177     return;
3178
3179   bool IsExplicit = false;
3180   for (const BasicBlock &BB : *ParentFn) {
3181     if (!BB.isEHPad())
3182       continue;
3183     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3184     // Skip cleanupendpads; they are exits, not entries.
3185     if (isa<CleanupEndPadInst>(FirstNonPHI))
3186       continue;
3187     if (!doesEHPadUnwindToCaller(FirstNonPHI))
3188       continue;
3189     calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
3190     IsExplicit = true;
3191   }
3192
3193   if (IsExplicit)
3194     return;
3195
3196   WinEHNumbering Num(FuncInfo);
3197   Num.findActionRootLPads(*ParentFn);
3198   // The VisitedHandlers list is used by both findActionRootLPads and
3199   // calculateStateNumbers, but both functions need to visit all handlers.
3200   Num.VisitedHandlers.clear();
3201   Num.calculateStateNumbers(*ParentFn);
3202   // Pop everything on the handler stack.
3203   // It may be necessary to call this more than once because a handler can
3204   // be pushed on the stack as a result of clearing the stack.
3205   while (!Num.HandlerStack.empty())
3206     Num.processCallSite(None, ImmutableCallSite());
3207 }
3208
3209 void WinEHPrepare::colorFunclets(Function &F,
3210                                  SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3211   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
3212   BasicBlock *EntryBlock = &F.getEntryBlock();
3213
3214   // Build up the color map, which maps each block to its set of 'colors'.
3215   // For any block B, the "colors" of B are the set of funclets F (possibly
3216   // including a root "funclet" representing the main function), such that
3217   // F will need to directly contain B or a copy of B (where the term "directly
3218   // contain" is used to distinguish from being "transitively contained" in
3219   // a nested funclet).
3220   // Use a CFG walk driven by a worklist of (block, color) pairs.  The "color"
3221   // sets attached during this processing to a block which is the entry of some
3222   // funclet F is actually the set of F's parents -- i.e. the union of colors
3223   // of all predecessors of F's entry.  For all other blocks, the color sets
3224   // are as defined above.  A post-pass fixes up the block color map to reflect
3225   // the same sense of "color" for funclet entries as for other blocks.
3226
3227   Worklist.push_back({EntryBlock, EntryBlock});
3228
3229   while (!Worklist.empty()) {
3230     BasicBlock *Visiting;
3231     BasicBlock *Color;
3232     std::tie(Visiting, Color) = Worklist.pop_back_val();
3233     Instruction *VisitingHead = Visiting->getFirstNonPHI();
3234     if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
3235         !isa<CleanupEndPadInst>(VisitingHead)) {
3236       // Mark this as a funclet head as a member of itself.
3237       FuncletBlocks[Visiting].insert(Visiting);
3238       // Queue exits with the parent color.
3239       for (User *Exit : VisitingHead->users()) {
3240         for (BasicBlock *Succ :
3241              successors(cast<Instruction>(Exit)->getParent())) {
3242           if (BlockColors[Succ].insert(Color).second) {
3243             Worklist.push_back({Succ, Color});
3244           }
3245         }
3246       }
3247       // Handle CatchPad specially since its successors need different colors.
3248       if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
3249         // Visit the normal successor with the color of the new EH pad, and
3250         // visit the unwind successor with the color of the parent.
3251         BasicBlock *NormalSucc = CatchPad->getNormalDest();
3252         if (BlockColors[NormalSucc].insert(Visiting).second) {
3253           Worklist.push_back({NormalSucc, Visiting});
3254         }
3255         BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
3256         if (BlockColors[UnwindSucc].insert(Color).second) {
3257           Worklist.push_back({UnwindSucc, Color});
3258         }
3259         continue;
3260       }
3261       // Switch color to the current node, except for terminate pads which
3262       // have no bodies and only unwind successors and so need their successors
3263       // visited with the color of the parent.
3264       if (!isa<TerminatePadInst>(VisitingHead))
3265         Color = Visiting;
3266     } else {
3267       // Note that this is a member of the given color.
3268       FuncletBlocks[Color].insert(Visiting);
3269     }
3270
3271     TerminatorInst *Terminator = Visiting->getTerminator();
3272     if (isa<CleanupReturnInst>(Terminator) ||
3273         isa<CatchReturnInst>(Terminator) ||
3274         isa<CleanupEndPadInst>(Terminator)) {
3275       // These blocks' successors have already been queued with the parent
3276       // color.
3277       continue;
3278     }
3279     for (BasicBlock *Succ : successors(Visiting)) {
3280       if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
3281         // The catchendpad needs to be visited with the parent's color, not
3282         // the current color.  This will happen in the code above that visits
3283         // any catchpad unwind successor with the parent color, so we can
3284         // safely skip this successor here.
3285         continue;
3286       }
3287       if (BlockColors[Succ].insert(Color).second) {
3288         Worklist.push_back({Succ, Color});
3289       }
3290     }
3291   }
3292
3293   // The processing above actually accumulated the parent set for this
3294   // funclet into the color set for its entry; use the parent set to
3295   // populate the children map, and reset the color set to include just
3296   // the funclet itself (no instruction can target a funclet entry except on
3297   // that transitions to the child funclet).
3298   for (BasicBlock *FuncletEntry : EntryBlocks) {
3299     std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
3300     for (BasicBlock *Parent : ColorMapItem)
3301       FuncletChildren[Parent].insert(FuncletEntry);
3302     ColorMapItem.clear();
3303     ColorMapItem.insert(FuncletEntry);
3304   }
3305 }
3306
3307 void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
3308   // Strip PHI nodes off of EH pads.
3309   SmallVector<PHINode *, 16> PHINodes;
3310   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3311     BasicBlock *BB = FI++;
3312     if (!BB->isEHPad())
3313       continue;
3314     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3315       Instruction *I = BI++;
3316       auto *PN = dyn_cast<PHINode>(I);
3317       // Stop at the first non-PHI.
3318       if (!PN)
3319         break;
3320
3321       AllocaInst *SpillSlot = insertPHILoads(PN, F);
3322       if (SpillSlot)
3323         insertPHIStores(PN, SpillSlot);
3324
3325       PHINodes.push_back(PN);
3326     }
3327   }
3328
3329   for (auto *PN : PHINodes) {
3330     // There may be lingering uses on other EH PHIs being removed
3331     PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3332     PN->eraseFromParent();
3333   }
3334 }
3335
3336 void WinEHPrepare::demoteUsesBetweenFunclets(Function &F) {
3337   // Turn all inter-funclet uses of a Value into loads and stores.
3338   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3339     BasicBlock *BB = FI++;
3340     std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3341     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3342       Instruction *I = BI++;
3343       // Funclets are permitted to use static allocas.
3344       if (auto *AI = dyn_cast<AllocaInst>(I))
3345         if (AI->isStaticAlloca())
3346           continue;
3347
3348       demoteNonlocalUses(I, ColorsForBB, F);
3349     }
3350   }
3351 }
3352
3353 void WinEHPrepare::demoteArgumentUses(Function &F) {
3354   // Also demote function parameters used in funclets.
3355   std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3356   for (Argument &Arg : F.args())
3357     demoteNonlocalUses(&Arg, ColorsForEntry, F);
3358 }
3359
3360 void WinEHPrepare::cloneCommonBlocks(
3361     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3362   // We need to clone all blocks which belong to multiple funclets.  Values are
3363   // remapped throughout the funclet to propogate both the new instructions
3364   // *and* the new basic blocks themselves.
3365   for (BasicBlock *FuncletPadBB : EntryBlocks) {
3366     std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
3367
3368     std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3369     ValueToValueMapTy VMap;
3370     for (BasicBlock *BB : BlocksInFunclet) {
3371       std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3372       // We don't need to do anything if the block is monochromatic.
3373       size_t NumColorsForBB = ColorsForBB.size();
3374       if (NumColorsForBB == 1)
3375         continue;
3376
3377       // Create a new basic block and copy instructions into it!
3378       BasicBlock *CBB =
3379           CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
3380       // Insert the clone immediately after the original to ensure determinism
3381       // and to keep the same relative ordering of any funclet's blocks.
3382       CBB->insertInto(&F, BB->getNextNode());
3383
3384       // Add basic block mapping.
3385       VMap[BB] = CBB;
3386
3387       // Record delta operations that we need to perform to our color mappings.
3388       Orig2Clone[BB] = CBB;
3389     }
3390
3391     // Update our color mappings to reflect that one block has lost a color and
3392     // another has gained a color.
3393     for (auto &BBMapping : Orig2Clone) {
3394       BasicBlock *OldBlock = BBMapping.first;
3395       BasicBlock *NewBlock = BBMapping.second;
3396
3397       BlocksInFunclet.insert(NewBlock);
3398       BlockColors[NewBlock].insert(FuncletPadBB);
3399
3400       BlocksInFunclet.erase(OldBlock);
3401       BlockColors[OldBlock].erase(FuncletPadBB);
3402     }
3403
3404     // Loop over all of the instructions in the function, fixing up operand
3405     // references as we go.  This uses VMap to do all the hard work.
3406     for (BasicBlock *BB : BlocksInFunclet)
3407       // Loop over all instructions, fixing each one as we find it...
3408       for (Instruction &I : *BB)
3409         RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3410
3411     // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
3412     // the PHI nodes for NewBB now.
3413     for (auto &BBMapping : Orig2Clone) {
3414       BasicBlock *OldBlock = BBMapping.first;
3415       BasicBlock *NewBlock = BBMapping.second;
3416       for (BasicBlock *SuccBB : successors(NewBlock)) {
3417         for (Instruction &SuccI : *SuccBB) {
3418           auto *SuccPN = dyn_cast<PHINode>(&SuccI);
3419           if (!SuccPN)
3420             break;
3421
3422           // Ok, we have a PHI node.  Figure out what the incoming value was for
3423           // the OldBlock.
3424           int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
3425           if (OldBlockIdx == -1)
3426             break;
3427           Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
3428
3429           // Remap the value if necessary.
3430           if (auto *Inst = dyn_cast<Instruction>(IV)) {
3431             ValueToValueMapTy::iterator I = VMap.find(Inst);
3432             if (I != VMap.end())
3433               IV = I->second;
3434           }
3435
3436           SuccPN->addIncoming(IV, NewBlock);
3437         }
3438       }
3439     }
3440
3441     for (ValueToValueMapTy::value_type VT : VMap) {
3442       // If there were values defined in BB that are used outside the funclet,
3443       // then we now have to update all uses of the value to use either the
3444       // original value, the cloned value, or some PHI derived value.  This can
3445       // require arbitrary PHI insertion, of which we are prepared to do, clean
3446       // these up now.
3447       SmallVector<Use *, 16> UsesToRename;
3448
3449       auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
3450       if (!OldI)
3451         continue;
3452       auto *NewI = cast<Instruction>(VT.second);
3453       // Scan all uses of this instruction to see if it is used outside of its
3454       // funclet, and if so, record them in UsesToRename.
3455       for (Use &U : OldI->uses()) {
3456         Instruction *UserI = cast<Instruction>(U.getUser());
3457         BasicBlock *UserBB = UserI->getParent();
3458         std::set<BasicBlock *> &ColorsForUserBB = BlockColors[UserBB];
3459         assert(!ColorsForUserBB.empty());
3460         if (ColorsForUserBB.size() > 1 ||
3461             *ColorsForUserBB.begin() != FuncletPadBB)
3462           UsesToRename.push_back(&U);
3463       }
3464
3465       // If there are no uses outside the block, we're done with this
3466       // instruction.
3467       if (UsesToRename.empty())
3468         continue;
3469
3470       // We found a use of OldI outside of the funclet.  Rename all uses of OldI
3471       // that are outside its funclet to be uses of the appropriate PHI node
3472       // etc.
3473       SSAUpdater SSAUpdate;
3474       SSAUpdate.Initialize(OldI->getType(), OldI->getName());
3475       SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
3476       SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
3477
3478       while (!UsesToRename.empty())
3479         SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
3480     }
3481   }
3482 }
3483
3484 void WinEHPrepare::removeImplausibleTerminators(Function &F) {
3485   // Remove implausible terminators and replace them with UnreachableInst.
3486   for (auto &Funclet : FuncletBlocks) {
3487     BasicBlock *FuncletPadBB = Funclet.first;
3488     std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3489     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3490     auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3491     auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3492
3493     for (BasicBlock *BB : BlocksInFunclet) {
3494       TerminatorInst *TI = BB->getTerminator();
3495       // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3496       bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3497       // The token consumed by a CatchReturnInst must match the funclet token.
3498       bool IsUnreachableCatchret = false;
3499       if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
3500         IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
3501       // The token consumed by a CleanupReturnInst must match the funclet token.
3502       bool IsUnreachableCleanupret = false;
3503       if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
3504         IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
3505       // The token consumed by a CleanupEndPadInst must match the funclet token.
3506       bool IsUnreachableCleanupendpad = false;
3507       if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3508         IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
3509       if (IsUnreachableRet || IsUnreachableCatchret ||
3510           IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
3511         // Loop through all of our successors and make sure they know that one
3512         // of their predecessors is going away.
3513         for (BasicBlock *SuccBB : TI->successors())
3514           SuccBB->removePredecessor(BB);
3515
3516         new UnreachableInst(BB->getContext(), TI);
3517         TI->eraseFromParent();
3518       }
3519     }
3520   }
3521 }
3522
3523 void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
3524   // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3525   // branches, etc.
3526   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3527     BasicBlock *BB = FI++;
3528     SimplifyInstructionsInBlock(BB);
3529     ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3530     MergeBlockIntoPredecessor(BB);
3531   }
3532
3533   // We might have some unreachable blocks after cleaning up some impossible
3534   // control flow.
3535   removeUnreachableBlocks(F);
3536 }
3537
3538 void WinEHPrepare::verifyPreparedFunclets(Function &F) {
3539   // Recolor the CFG to verify that all is well.
3540   for (BasicBlock &BB : F) {
3541     size_t NumColors = BlockColors[&BB].size();
3542     assert(NumColors == 1 && "Expected monochromatic BB!");
3543     if (NumColors == 0)
3544       report_fatal_error("Uncolored BB!");
3545     if (NumColors > 1)
3546       report_fatal_error("Multicolor BB!");
3547     if (!DisableDemotion) {
3548       bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3549       assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3550       if (EHPadHasPHI)
3551         report_fatal_error("EH Pad still has a PHI!");
3552     }
3553   }
3554 }
3555
3556 bool WinEHPrepare::prepareExplicitEH(
3557     Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3558   // Remove unreachable blocks.  It is not valuable to assign them a color and
3559   // their existence can trick us into thinking values are alive when they are
3560   // not.
3561   removeUnreachableBlocks(F);
3562
3563   // Determine which blocks are reachable from which funclet entries.
3564   colorFunclets(F, EntryBlocks);
3565
3566   if (!DisableDemotion) {
3567     demotePHIsOnFunclets(F);
3568
3569     demoteUsesBetweenFunclets(F);
3570
3571     demoteArgumentUses(F);
3572   }
3573
3574   cloneCommonBlocks(F, EntryBlocks);
3575
3576   if (!DisableCleanups) {
3577     removeImplausibleTerminators(F);
3578
3579     cleanupPreparedFunclets(F);
3580   }
3581
3582   verifyPreparedFunclets(F);
3583
3584   BlockColors.clear();
3585   FuncletBlocks.clear();
3586   FuncletChildren.clear();
3587
3588   return true;
3589 }
3590
3591 // TODO: Share loads when one use dominates another, or when a catchpad exit
3592 // dominates uses (needs dominators).
3593 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3594   BasicBlock *PHIBlock = PN->getParent();
3595   AllocaInst *SpillSlot = nullptr;
3596
3597   if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3598     // Insert a load in place of the PHI and replace all uses.
3599     SpillSlot = new AllocaInst(PN->getType(), nullptr,
3600                                Twine(PN->getName(), ".wineh.spillslot"),
3601                                F.getEntryBlock().begin());
3602     Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3603                             PHIBlock->getFirstInsertionPt());
3604     PN->replaceAllUsesWith(V);
3605     return SpillSlot;
3606   }
3607
3608   DenseMap<BasicBlock *, Value *> Loads;
3609   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3610        UI != UE;) {
3611     Use &U = *UI++;
3612     auto *UsingInst = cast<Instruction>(U.getUser());
3613     BasicBlock *UsingBB = UsingInst->getParent();
3614     if (UsingBB->isEHPad()) {
3615       // Use is on an EH pad phi.  Leave it alone; we'll insert loads and
3616       // stores for it separately.
3617       assert(isa<PHINode>(UsingInst));
3618       continue;
3619     }
3620     replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3621   }
3622   return SpillSlot;
3623 }
3624
3625 // TODO: improve store placement.  Inserting at def is probably good, but need
3626 // to be careful not to introduce interfering stores (needs liveness analysis).
3627 // TODO: identify related phi nodes that can share spill slots, and share them
3628 // (also needs liveness).
3629 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3630                                    AllocaInst *SpillSlot) {
3631   // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3632   // stored to the spill slot by the end of the given Block.
3633   SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3634
3635   Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3636
3637   while (!Worklist.empty()) {
3638     BasicBlock *EHBlock;
3639     Value *InVal;
3640     std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3641
3642     PHINode *PN = dyn_cast<PHINode>(InVal);
3643     if (PN && PN->getParent() == EHBlock) {
3644       // The value is defined by another PHI we need to remove, with no room to
3645       // insert a store after the PHI, so each predecessor needs to store its
3646       // incoming value.
3647       for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3648         Value *PredVal = PN->getIncomingValue(i);
3649
3650         // Undef can safely be skipped.
3651         if (isa<UndefValue>(PredVal))
3652           continue;
3653
3654         insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3655       }
3656     } else {
3657       // We need to store InVal, which dominates EHBlock, but can't put a store
3658       // in EHBlock, so need to put stores in each predecessor.
3659       for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3660         insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3661       }
3662     }
3663   }
3664 }
3665
3666 void WinEHPrepare::insertPHIStore(
3667     BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3668     SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3669
3670   if (PredBlock->isEHPad() &&
3671       !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3672     // Pred is unsplittable, so we need to queue it on the worklist.
3673     Worklist.push_back({PredBlock, PredVal});
3674     return;
3675   }
3676
3677   // Otherwise, insert the store at the end of the basic block.
3678   new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3679 }
3680
3681 // TODO: Share loads for same-funclet uses (requires dominators if funclets
3682 // aren't properly nested).
3683 void WinEHPrepare::demoteNonlocalUses(Value *V,
3684                                       std::set<BasicBlock *> &ColorsForBB,
3685                                       Function &F) {
3686   // Tokens can only be used non-locally due to control flow involving
3687   // unreachable edges.  Don't try to demote the token usage, we'll simply
3688   // delete the cloned user later.
3689   if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3690     return;
3691
3692   DenseMap<BasicBlock *, Value *> Loads;
3693   AllocaInst *SpillSlot = nullptr;
3694   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3695     Use &U = *UI++;
3696     auto *UsingInst = cast<Instruction>(U.getUser());
3697     BasicBlock *UsingBB = UsingInst->getParent();
3698
3699     // Is the Use inside a block which is colored the same as the Def?
3700     // If so, we don't need to escape the Def because we will clone
3701     // ourselves our own private copy.
3702     std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3703     if (ColorsForUsingBB == ColorsForBB)
3704       continue;
3705
3706     replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3707   }
3708   if (SpillSlot) {
3709     // Insert stores of the computed value into the stack slot.
3710     // We have to be careful if I is an invoke instruction,
3711     // because we can't insert the store AFTER the terminator instruction.
3712     BasicBlock::iterator InsertPt;
3713     if (isa<Argument>(V)) {
3714       InsertPt = F.getEntryBlock().getTerminator();
3715     } else if (isa<TerminatorInst>(V)) {
3716       auto *II = cast<InvokeInst>(V);
3717       // We cannot demote invoke instructions to the stack if their normal
3718       // edge is critical. Therefore, split the critical edge and create a
3719       // basic block into which the store can be inserted.
3720       if (!II->getNormalDest()->getSinglePredecessor()) {
3721         unsigned SuccNum =
3722             GetSuccessorNumber(II->getParent(), II->getNormalDest());
3723         assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3724         BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3725         assert(NewBlock && "Unable to split critical edge.");
3726         // Update the color mapping for the newly split edge.
3727         std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3728         BlockColors[NewBlock] = ColorsForUsingBB;
3729         for (BasicBlock *FuncletPad : ColorsForUsingBB)
3730           FuncletBlocks[FuncletPad].insert(NewBlock);
3731       }
3732       InsertPt = II->getNormalDest()->getFirstInsertionPt();
3733     } else {
3734       InsertPt = cast<Instruction>(V);
3735       ++InsertPt;
3736       // Don't insert before PHI nodes or EH pad instrs.
3737       for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3738         ;
3739     }
3740     new StoreInst(V, SpillSlot, InsertPt);
3741   }
3742 }
3743
3744 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3745                                       DenseMap<BasicBlock *, Value *> &Loads,
3746                                       Function &F) {
3747   // Lazilly create the spill slot.
3748   if (!SpillSlot)
3749     SpillSlot = new AllocaInst(V->getType(), nullptr,
3750                                Twine(V->getName(), ".wineh.spillslot"),
3751                                F.getEntryBlock().begin());
3752
3753   auto *UsingInst = cast<Instruction>(U.getUser());
3754   if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3755     // If this is a PHI node, we can't insert a load of the value before
3756     // the use.  Instead insert the load in the predecessor block
3757     // corresponding to the incoming value.
3758     //
3759     // Note that if there are multiple edges from a basic block to this
3760     // PHI node that we cannot have multiple loads.  The problem is that
3761     // the resulting PHI node will have multiple values (from each load)
3762     // coming in from the same block, which is illegal SSA form.
3763     // For this reason, we keep track of and reuse loads we insert.
3764     BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
3765     if (auto *CatchRet =
3766             dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3767       // Putting a load above a catchret and use on the phi would still leave
3768       // a cross-funclet def/use.  We need to split the edge, change the
3769       // catchret to target the new block, and put the load there.
3770       BasicBlock *PHIBlock = UsingInst->getParent();
3771       BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3772       // SplitEdge gives us:
3773       //   IncomingBlock:
3774       //     ...
3775       //     br label %NewBlock
3776       //   NewBlock:
3777       //     catchret label %PHIBlock
3778       // But we need:
3779       //   IncomingBlock:
3780       //     ...
3781       //     catchret label %NewBlock
3782       //   NewBlock:
3783       //     br label %PHIBlock
3784       // So move the terminators to each others' blocks and swap their
3785       // successors.
3786       BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3787       Goto->removeFromParent();
3788       CatchRet->removeFromParent();
3789       IncomingBlock->getInstList().push_back(CatchRet);
3790       NewBlock->getInstList().push_back(Goto);
3791       Goto->setSuccessor(0, PHIBlock);
3792       CatchRet->setSuccessor(NewBlock);
3793       // Update the color mapping for the newly split edge.
3794       std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3795       BlockColors[NewBlock] = ColorsForPHIBlock;
3796       for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3797         FuncletBlocks[FuncletPad].insert(NewBlock);
3798       // Treat the new block as incoming for load insertion.
3799       IncomingBlock = NewBlock;
3800     }
3801     Value *&Load = Loads[IncomingBlock];
3802     // Insert the load into the predecessor block
3803     if (!Load)
3804       Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3805                           /*Volatile=*/false, IncomingBlock->getTerminator());
3806
3807     U.set(Load);
3808   } else {
3809     // Reload right before the old use.
3810     auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3811                               /*Volatile=*/false, UsingInst);
3812     U.set(Load);
3813   }
3814 }