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/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/Utils/Local.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/SSAUpdater.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "winehprepare"
40 
41 static cl::opt<bool> DisableDemotion(
42     "disable-demotion", cl::Hidden,
43     cl::desc(
44         "Clone multicolor basic blocks but do not demote cross scopes"),
45     cl::init(false));
46 
47 static cl::opt<bool> DisableCleanups(
48     "disable-cleanups", cl::Hidden,
49     cl::desc("Do not remove implausible terminators or other similar cleanups"),
50     cl::init(false));
51 
52 namespace {
53 
54 class WinEHPrepare : public FunctionPass {
55 public:
56   static char ID; // Pass identification, replacement for typeid.
57   WinEHPrepare() : FunctionPass(ID) {}
58 
59   bool runOnFunction(Function &Fn) override;
60 
61   bool doFinalization(Module &M) override;
62 
63   void getAnalysisUsage(AnalysisUsage &AU) const override;
64 
65   StringRef getPassName() const override {
66     return "Windows exception handling preparation";
67   }
68 
69 private:
70   void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
71   void
72   insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
73                  SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
74   AllocaInst *insertPHILoads(PHINode *PN, Function &F);
75   void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
76                           DenseMap<BasicBlock *, Value *> &Loads, Function &F);
77   bool prepareExplicitEH(Function &F);
78   void colorFunclets(Function &F);
79 
80   void demotePHIsOnFunclets(Function &F);
81   void cloneCommonBlocks(Function &F);
82   void removeImplausibleInstructions(Function &F);
83   void cleanupPreparedFunclets(Function &F);
84   void verifyPreparedFunclets(Function &F);
85 
86   // All fields are reset by runOnFunction.
87   EHPersonality Personality = EHPersonality::Unknown;
88 
89   const DataLayout *DL = nullptr;
90   DenseMap<BasicBlock *, ColorVector> BlockColors;
91   MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
92 };
93 
94 } // end anonymous namespace
95 
96 char WinEHPrepare::ID = 0;
97 INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",
98                 false, false)
99 
100 FunctionPass *llvm::createWinEHPass() { return new WinEHPrepare(); }
101 
102 bool WinEHPrepare::runOnFunction(Function &Fn) {
103   if (!Fn.hasPersonalityFn())
104     return false;
105 
106   // Classify the personality to see what kind of preparation we need.
107   Personality = classifyEHPersonality(Fn.getPersonalityFn());
108 
109   // Do nothing if this is not a scope-based personality.
110   if (!isScopedEHPersonality(Personality))
111     return false;
112 
113   DL = &Fn.getParent()->getDataLayout();
114   return prepareExplicitEH(Fn);
115 }
116 
117 bool WinEHPrepare::doFinalization(Module &M) { return false; }
118 
119 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
120 
121 static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
122                              const BasicBlock *BB) {
123   CxxUnwindMapEntry UME;
124   UME.ToState = ToState;
125   UME.Cleanup = BB;
126   FuncInfo.CxxUnwindMap.push_back(UME);
127   return FuncInfo.getLastStateNumber();
128 }
129 
130 static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
131                                 int TryHigh, int CatchHigh,
132                                 ArrayRef<const CatchPadInst *> Handlers) {
133   WinEHTryBlockMapEntry TBME;
134   TBME.TryLow = TryLow;
135   TBME.TryHigh = TryHigh;
136   TBME.CatchHigh = CatchHigh;
137   assert(TBME.TryLow <= TBME.TryHigh);
138   for (const CatchPadInst *CPI : Handlers) {
139     WinEHHandlerType HT;
140     Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
141     if (TypeInfo->isNullValue())
142       HT.TypeDescriptor = nullptr;
143     else
144       HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
145     HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
146     HT.Handler = CPI->getParent();
147     if (auto *AI =
148             dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
149       HT.CatchObj.Alloca = AI;
150     else
151       HT.CatchObj.Alloca = nullptr;
152     TBME.HandlerArray.push_back(HT);
153   }
154   FuncInfo.TryBlockMap.push_back(TBME);
155 }
156 
157 static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
158   for (const User *U : CleanupPad->users())
159     if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
160       return CRI->getUnwindDest();
161   return nullptr;
162 }
163 
164 static void calculateStateNumbersForInvokes(const Function *Fn,
165                                             WinEHFuncInfo &FuncInfo) {
166   auto *F = const_cast<Function *>(Fn);
167   DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
168   for (BasicBlock &BB : *F) {
169     auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
170     if (!II)
171       continue;
172 
173     auto &BBColors = BlockColors[&BB];
174     assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
175     BasicBlock *FuncletEntryBB = BBColors.front();
176 
177     BasicBlock *FuncletUnwindDest;
178     auto *FuncletPad =
179         dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
180     assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
181     if (!FuncletPad)
182       FuncletUnwindDest = nullptr;
183     else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
184       FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
185     else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
186       FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
187     else
188       llvm_unreachable("unexpected funclet pad!");
189 
190     BasicBlock *InvokeUnwindDest = II->getUnwindDest();
191     int BaseState = -1;
192     if (FuncletUnwindDest == InvokeUnwindDest) {
193       auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
194       if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
195         BaseState = BaseStateI->second;
196     }
197 
198     if (BaseState != -1) {
199       FuncInfo.InvokeStateMap[II] = BaseState;
200     } else {
201       Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
202       assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
203       FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
204     }
205   }
206 }
207 
208 // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
209 // to. If the unwind edge came from an invoke, return null.
210 static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
211                                                  Value *ParentPad) {
212   const TerminatorInst *TI = BB->getTerminator();
213   if (isa<InvokeInst>(TI))
214     return nullptr;
215   if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
216     if (CatchSwitch->getParentPad() != ParentPad)
217       return nullptr;
218     return BB;
219   }
220   assert(!TI->isEHPad() && "unexpected EHPad!");
221   auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
222   if (CleanupPad->getParentPad() != ParentPad)
223     return nullptr;
224   return CleanupPad->getParent();
225 }
226 
227 static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
228                                      const Instruction *FirstNonPHI,
229                                      int ParentState) {
230   const BasicBlock *BB = FirstNonPHI->getParent();
231   assert(BB->isEHPad() && "not a funclet!");
232 
233   if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
234     assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
235            "shouldn't revist catch funclets!");
236 
237     SmallVector<const CatchPadInst *, 2> Handlers;
238     for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
239       auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
240       Handlers.push_back(CatchPad);
241     }
242     int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
243     FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
244     for (const BasicBlock *PredBlock : predecessors(BB))
245       if ((PredBlock = getEHPadFromPredecessor(PredBlock,
246                                                CatchSwitch->getParentPad())))
247         calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
248                                  TryLow);
249     int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
250 
251     // catchpads are separate funclets in C++ EH due to the way rethrow works.
252     int TryHigh = CatchLow - 1;
253     for (const auto *CatchPad : Handlers) {
254       FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
255       for (const User *U : CatchPad->users()) {
256         const auto *UserI = cast<Instruction>(U);
257         if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
258           BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
259           if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
260             calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
261         }
262         if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
263           BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
264           // If a nested cleanup pad reports a null unwind destination and the
265           // enclosing catch pad doesn't it must be post-dominated by an
266           // unreachable instruction.
267           if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
268             calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
269         }
270       }
271     }
272     int CatchHigh = FuncInfo.getLastStateNumber();
273     addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
274     LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
275     LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
276                       << '\n');
277     LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
278                       << '\n');
279   } else {
280     auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
281 
282     // It's possible for a cleanup to be visited twice: it might have multiple
283     // cleanupret instructions.
284     if (FuncInfo.EHPadStateMap.count(CleanupPad))
285       return;
286 
287     int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
288     FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
289     LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
290                       << BB->getName() << '\n');
291     for (const BasicBlock *PredBlock : predecessors(BB)) {
292       if ((PredBlock = getEHPadFromPredecessor(PredBlock,
293                                                CleanupPad->getParentPad()))) {
294         calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
295                                  CleanupState);
296       }
297     }
298     for (const User *U : CleanupPad->users()) {
299       const auto *UserI = cast<Instruction>(U);
300       if (UserI->isEHPad())
301         report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
302                            "contain exceptional actions");
303     }
304   }
305 }
306 
307 static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
308                         const Function *Filter, const BasicBlock *Handler) {
309   SEHUnwindMapEntry Entry;
310   Entry.ToState = ParentState;
311   Entry.IsFinally = false;
312   Entry.Filter = Filter;
313   Entry.Handler = Handler;
314   FuncInfo.SEHUnwindMap.push_back(Entry);
315   return FuncInfo.SEHUnwindMap.size() - 1;
316 }
317 
318 static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
319                          const BasicBlock *Handler) {
320   SEHUnwindMapEntry Entry;
321   Entry.ToState = ParentState;
322   Entry.IsFinally = true;
323   Entry.Filter = nullptr;
324   Entry.Handler = Handler;
325   FuncInfo.SEHUnwindMap.push_back(Entry);
326   return FuncInfo.SEHUnwindMap.size() - 1;
327 }
328 
329 static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
330                                      const Instruction *FirstNonPHI,
331                                      int ParentState) {
332   const BasicBlock *BB = FirstNonPHI->getParent();
333   assert(BB->isEHPad() && "no a funclet!");
334 
335   if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
336     assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
337            "shouldn't revist catch funclets!");
338 
339     // Extract the filter function and the __except basic block and create a
340     // state for them.
341     assert(CatchSwitch->getNumHandlers() == 1 &&
342            "SEH doesn't have multiple handlers per __try");
343     const auto *CatchPad =
344         cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
345     const BasicBlock *CatchPadBB = CatchPad->getParent();
346     const Constant *FilterOrNull =
347         cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
348     const Function *Filter = dyn_cast<Function>(FilterOrNull);
349     assert((Filter || FilterOrNull->isNullValue()) &&
350            "unexpected filter value");
351     int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
352 
353     // Everything in the __try block uses TryState as its parent state.
354     FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
355     LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
356                       << CatchPadBB->getName() << '\n');
357     for (const BasicBlock *PredBlock : predecessors(BB))
358       if ((PredBlock = getEHPadFromPredecessor(PredBlock,
359                                                CatchSwitch->getParentPad())))
360         calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
361                                  TryState);
362 
363     // Everything in the __except block unwinds to ParentState, just like code
364     // outside the __try.
365     for (const User *U : CatchPad->users()) {
366       const auto *UserI = cast<Instruction>(U);
367       if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
368         BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
369         if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
370           calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
371       }
372       if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
373         BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
374         // If a nested cleanup pad reports a null unwind destination and the
375         // enclosing catch pad doesn't it must be post-dominated by an
376         // unreachable instruction.
377         if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
378           calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
379       }
380     }
381   } else {
382     auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
383 
384     // It's possible for a cleanup to be visited twice: it might have multiple
385     // cleanupret instructions.
386     if (FuncInfo.EHPadStateMap.count(CleanupPad))
387       return;
388 
389     int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
390     FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
391     LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
392                       << BB->getName() << '\n');
393     for (const BasicBlock *PredBlock : predecessors(BB))
394       if ((PredBlock =
395                getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
396         calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
397                                  CleanupState);
398     for (const User *U : CleanupPad->users()) {
399       const auto *UserI = cast<Instruction>(U);
400       if (UserI->isEHPad())
401         report_fatal_error("Cleanup funclets for the SEH personality cannot "
402                            "contain exceptional actions");
403     }
404   }
405 }
406 
407 static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
408   if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
409     return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
410            CatchSwitch->unwindsToCaller();
411   if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
412     return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
413            getCleanupRetUnwindDest(CleanupPad) == nullptr;
414   if (isa<CatchPadInst>(EHPad))
415     return false;
416   llvm_unreachable("unexpected EHPad!");
417 }
418 
419 void llvm::calculateSEHStateNumbers(const Function *Fn,
420                                     WinEHFuncInfo &FuncInfo) {
421   // Don't compute state numbers twice.
422   if (!FuncInfo.SEHUnwindMap.empty())
423     return;
424 
425   for (const BasicBlock &BB : *Fn) {
426     if (!BB.isEHPad())
427       continue;
428     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
429     if (!isTopLevelPadForMSVC(FirstNonPHI))
430       continue;
431     ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
432   }
433 
434   calculateStateNumbersForInvokes(Fn, FuncInfo);
435 }
436 
437 void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
438                                          WinEHFuncInfo &FuncInfo) {
439   // Return if it's already been done.
440   if (!FuncInfo.EHPadStateMap.empty())
441     return;
442 
443   for (const BasicBlock &BB : *Fn) {
444     if (!BB.isEHPad())
445       continue;
446     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
447     if (!isTopLevelPadForMSVC(FirstNonPHI))
448       continue;
449     calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
450   }
451 
452   calculateStateNumbersForInvokes(Fn, FuncInfo);
453 }
454 
455 static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
456                            int TryParentState, ClrHandlerType HandlerType,
457                            uint32_t TypeToken, const BasicBlock *Handler) {
458   ClrEHUnwindMapEntry Entry;
459   Entry.HandlerParentState = HandlerParentState;
460   Entry.TryParentState = TryParentState;
461   Entry.Handler = Handler;
462   Entry.HandlerType = HandlerType;
463   Entry.TypeToken = TypeToken;
464   FuncInfo.ClrEHUnwindMap.push_back(Entry);
465   return FuncInfo.ClrEHUnwindMap.size() - 1;
466 }
467 
468 void llvm::calculateClrEHStateNumbers(const Function *Fn,
469                                       WinEHFuncInfo &FuncInfo) {
470   // Return if it's already been done.
471   if (!FuncInfo.EHPadStateMap.empty())
472     return;
473 
474   // This numbering assigns one state number to each catchpad and cleanuppad.
475   // It also computes two tree-like relations over states:
476   // 1) Each state has a "HandlerParentState", which is the state of the next
477   //    outer handler enclosing this state's handler (same as nearest ancestor
478   //    per the ParentPad linkage on EH pads, but skipping over catchswitches).
479   // 2) Each state has a "TryParentState", which:
480   //    a) for a catchpad that's not the last handler on its catchswitch, is
481   //       the state of the next catchpad on that catchswitch
482   //    b) for all other pads, is the state of the pad whose try region is the
483   //       next outer try region enclosing this state's try region.  The "try
484   //       regions are not present as such in the IR, but will be inferred
485   //       based on the placement of invokes and pads which reach each other
486   //       by exceptional exits
487   // Catchswitches do not get their own states, but each gets mapped to the
488   // state of its first catchpad.
489 
490   // Step one: walk down from outermost to innermost funclets, assigning each
491   // catchpad and cleanuppad a state number.  Add an entry to the
492   // ClrEHUnwindMap for each state, recording its HandlerParentState and
493   // handler attributes.  Record the TryParentState as well for each catchpad
494   // that's not the last on its catchswitch, but initialize all other entries'
495   // TryParentStates to a sentinel -1 value that the next pass will update.
496 
497   // Seed a worklist with pads that have no parent.
498   SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
499   for (const BasicBlock &BB : *Fn) {
500     const Instruction *FirstNonPHI = BB.getFirstNonPHI();
501     const Value *ParentPad;
502     if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
503       ParentPad = CPI->getParentPad();
504     else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
505       ParentPad = CSI->getParentPad();
506     else
507       continue;
508     if (isa<ConstantTokenNone>(ParentPad))
509       Worklist.emplace_back(FirstNonPHI, -1);
510   }
511 
512   // Use the worklist to visit all pads, from outer to inner.  Record
513   // HandlerParentState for all pads.  Record TryParentState only for catchpads
514   // that aren't the last on their catchswitch (setting all other entries'
515   // TryParentStates to an initial value of -1).  This loop is also responsible
516   // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
517   // catchswitches.
518   while (!Worklist.empty()) {
519     const Instruction *Pad;
520     int HandlerParentState;
521     std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
522 
523     if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
524       // Create the entry for this cleanup with the appropriate handler
525       // properties.  Finally and fault handlers are distinguished by arity.
526       ClrHandlerType HandlerType =
527           (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
528                                         : ClrHandlerType::Finally);
529       int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
530                                          HandlerType, 0, Pad->getParent());
531       // Queue any child EH pads on the worklist.
532       for (const User *U : Cleanup->users())
533         if (const auto *I = dyn_cast<Instruction>(U))
534           if (I->isEHPad())
535             Worklist.emplace_back(I, CleanupState);
536       // Remember this pad's state.
537       FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
538     } else {
539       // Walk the handlers of this catchswitch in reverse order since all but
540       // the last need to set the following one as its TryParentState.
541       const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
542       int CatchState = -1, FollowerState = -1;
543       SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
544       for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
545            CBI != CBE; ++CBI, FollowerState = CatchState) {
546         const BasicBlock *CatchBlock = *CBI;
547         // Create the entry for this catch with the appropriate handler
548         // properties.
549         const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
550         uint32_t TypeToken = static_cast<uint32_t>(
551             cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
552         CatchState =
553             addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
554                             ClrHandlerType::Catch, TypeToken, CatchBlock);
555         // Queue any child EH pads on the worklist.
556         for (const User *U : Catch->users())
557           if (const auto *I = dyn_cast<Instruction>(U))
558             if (I->isEHPad())
559               Worklist.emplace_back(I, CatchState);
560         // Remember this catch's state.
561         FuncInfo.EHPadStateMap[Catch] = CatchState;
562       }
563       // Associate the catchswitch with the state of its first catch.
564       assert(CatchSwitch->getNumHandlers());
565       FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
566     }
567   }
568 
569   // Step two: record the TryParentState of each state.  For cleanuppads that
570   // don't have cleanuprets, we may need to infer this from their child pads,
571   // so visit pads in descendant-most to ancestor-most order.
572   for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
573             End = FuncInfo.ClrEHUnwindMap.rend();
574        Entry != End; ++Entry) {
575     const Instruction *Pad =
576         Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
577     // For most pads, the TryParentState is the state associated with the
578     // unwind dest of exceptional exits from it.
579     const BasicBlock *UnwindDest;
580     if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
581       // If a catch is not the last in its catchswitch, its TryParentState is
582       // the state associated with the next catch in the switch, even though
583       // that's not the unwind dest of exceptions escaping the catch.  Those
584       // cases were already assigned a TryParentState in the first pass, so
585       // skip them.
586       if (Entry->TryParentState != -1)
587         continue;
588       // Otherwise, get the unwind dest from the catchswitch.
589       UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
590     } else {
591       const auto *Cleanup = cast<CleanupPadInst>(Pad);
592       UnwindDest = nullptr;
593       for (const User *U : Cleanup->users()) {
594         if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
595           // Common and unambiguous case -- cleanupret indicates cleanup's
596           // unwind dest.
597           UnwindDest = CleanupRet->getUnwindDest();
598           break;
599         }
600 
601         // Get an unwind dest for the user
602         const BasicBlock *UserUnwindDest = nullptr;
603         if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
604           UserUnwindDest = Invoke->getUnwindDest();
605         } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
606           UserUnwindDest = CatchSwitch->getUnwindDest();
607         } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
608           int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
609           int UserUnwindState =
610               FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
611           if (UserUnwindState != -1)
612             UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
613                                  .Handler.get<const BasicBlock *>();
614         }
615 
616         // Not having an unwind dest for this user might indicate that it
617         // doesn't unwind, so can't be taken as proof that the cleanup itself
618         // may unwind to caller (see e.g. SimplifyUnreachable and
619         // RemoveUnwindEdge).
620         if (!UserUnwindDest)
621           continue;
622 
623         // Now we have an unwind dest for the user, but we need to see if it
624         // unwinds all the way out of the cleanup or if it stays within it.
625         const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
626         const Value *UserUnwindParent;
627         if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
628           UserUnwindParent = CSI->getParentPad();
629         else
630           UserUnwindParent =
631               cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
632 
633         // The unwind stays within the cleanup iff it targets a child of the
634         // cleanup.
635         if (UserUnwindParent == Cleanup)
636           continue;
637 
638         // This unwind exits the cleanup, so its dest is the cleanup's dest.
639         UnwindDest = UserUnwindDest;
640         break;
641       }
642     }
643 
644     // Record the state of the unwind dest as the TryParentState.
645     int UnwindDestState;
646 
647     // If UnwindDest is null at this point, either the pad in question can
648     // be exited by unwind to caller, or it cannot be exited by unwind.  In
649     // either case, reporting such cases as unwinding to caller is correct.
650     // This can lead to EH tables that "look strange" -- if this pad's is in
651     // a parent funclet which has other children that do unwind to an enclosing
652     // pad, the try region for this pad will be missing the "duplicate" EH
653     // clause entries that you'd expect to see covering the whole parent.  That
654     // should be benign, since the unwind never actually happens.  If it were
655     // an issue, we could add a subsequent pass that pushes unwind dests down
656     // from parents that have them to children that appear to unwind to caller.
657     if (!UnwindDest) {
658       UnwindDestState = -1;
659     } else {
660       UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
661     }
662 
663     Entry->TryParentState = UnwindDestState;
664   }
665 
666   // Step three: transfer information from pads to invokes.
667   calculateStateNumbersForInvokes(Fn, FuncInfo);
668 }
669 
670 void WinEHPrepare::colorFunclets(Function &F) {
671   BlockColors = colorEHFunclets(F);
672 
673   // Invert the map from BB to colors to color to BBs.
674   for (BasicBlock &BB : F) {
675     ColorVector &Colors = BlockColors[&BB];
676     for (BasicBlock *Color : Colors)
677       FuncletBlocks[Color].push_back(&BB);
678   }
679 }
680 
681 void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
682   // Strip PHI nodes off of EH pads.
683   SmallVector<PHINode *, 16> PHINodes;
684   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
685     BasicBlock *BB = &*FI++;
686     if (!BB->isEHPad())
687       continue;
688     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
689       Instruction *I = &*BI++;
690       auto *PN = dyn_cast<PHINode>(I);
691       // Stop at the first non-PHI.
692       if (!PN)
693         break;
694 
695       AllocaInst *SpillSlot = insertPHILoads(PN, F);
696       if (SpillSlot)
697         insertPHIStores(PN, SpillSlot);
698 
699       PHINodes.push_back(PN);
700     }
701   }
702 
703   for (auto *PN : PHINodes) {
704     // There may be lingering uses on other EH PHIs being removed
705     PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
706     PN->eraseFromParent();
707   }
708 }
709 
710 void WinEHPrepare::cloneCommonBlocks(Function &F) {
711   // We need to clone all blocks which belong to multiple funclets.  Values are
712   // remapped throughout the funclet to propagate both the new instructions
713   // *and* the new basic blocks themselves.
714   for (auto &Funclets : FuncletBlocks) {
715     BasicBlock *FuncletPadBB = Funclets.first;
716     std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
717     Value *FuncletToken;
718     if (FuncletPadBB == &F.getEntryBlock())
719       FuncletToken = ConstantTokenNone::get(F.getContext());
720     else
721       FuncletToken = FuncletPadBB->getFirstNonPHI();
722 
723     std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
724     ValueToValueMapTy VMap;
725     for (BasicBlock *BB : BlocksInFunclet) {
726       ColorVector &ColorsForBB = BlockColors[BB];
727       // We don't need to do anything if the block is monochromatic.
728       size_t NumColorsForBB = ColorsForBB.size();
729       if (NumColorsForBB == 1)
730         continue;
731 
732       DEBUG_WITH_TYPE("winehprepare-coloring",
733                       dbgs() << "  Cloning block \'" << BB->getName()
734                               << "\' for funclet \'" << FuncletPadBB->getName()
735                               << "\'.\n");
736 
737       // Create a new basic block and copy instructions into it!
738       BasicBlock *CBB =
739           CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
740       // Insert the clone immediately after the original to ensure determinism
741       // and to keep the same relative ordering of any funclet's blocks.
742       CBB->insertInto(&F, BB->getNextNode());
743 
744       // Add basic block mapping.
745       VMap[BB] = CBB;
746 
747       // Record delta operations that we need to perform to our color mappings.
748       Orig2Clone.emplace_back(BB, CBB);
749     }
750 
751     // If nothing was cloned, we're done cloning in this funclet.
752     if (Orig2Clone.empty())
753       continue;
754 
755     // Update our color mappings to reflect that one block has lost a color and
756     // another has gained a color.
757     for (auto &BBMapping : Orig2Clone) {
758       BasicBlock *OldBlock = BBMapping.first;
759       BasicBlock *NewBlock = BBMapping.second;
760 
761       BlocksInFunclet.push_back(NewBlock);
762       ColorVector &NewColors = BlockColors[NewBlock];
763       assert(NewColors.empty() && "A new block should only have one color!");
764       NewColors.push_back(FuncletPadBB);
765 
766       DEBUG_WITH_TYPE("winehprepare-coloring",
767                       dbgs() << "  Assigned color \'" << FuncletPadBB->getName()
768                               << "\' to block \'" << NewBlock->getName()
769                               << "\'.\n");
770 
771       BlocksInFunclet.erase(
772           std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
773           BlocksInFunclet.end());
774       ColorVector &OldColors = BlockColors[OldBlock];
775       OldColors.erase(
776           std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
777           OldColors.end());
778 
779       DEBUG_WITH_TYPE("winehprepare-coloring",
780                       dbgs() << "  Removed color \'" << FuncletPadBB->getName()
781                               << "\' from block \'" << OldBlock->getName()
782                               << "\'.\n");
783     }
784 
785     // Loop over all of the instructions in this funclet, fixing up operand
786     // references as we go.  This uses VMap to do all the hard work.
787     for (BasicBlock *BB : BlocksInFunclet)
788       // Loop over all instructions, fixing each one as we find it...
789       for (Instruction &I : *BB)
790         RemapInstruction(&I, VMap,
791                          RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
792 
793     // Catchrets targeting cloned blocks need to be updated separately from
794     // the loop above because they are not in the current funclet.
795     SmallVector<CatchReturnInst *, 2> FixupCatchrets;
796     for (auto &BBMapping : Orig2Clone) {
797       BasicBlock *OldBlock = BBMapping.first;
798       BasicBlock *NewBlock = BBMapping.second;
799 
800       FixupCatchrets.clear();
801       for (BasicBlock *Pred : predecessors(OldBlock))
802         if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
803           if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
804             FixupCatchrets.push_back(CatchRet);
805 
806       for (CatchReturnInst *CatchRet : FixupCatchrets)
807         CatchRet->setSuccessor(NewBlock);
808     }
809 
810     auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
811       unsigned NumPreds = PN->getNumIncomingValues();
812       for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
813            ++PredIdx) {
814         BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
815         bool EdgeTargetsFunclet;
816         if (auto *CRI =
817                 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
818           EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
819         } else {
820           ColorVector &IncomingColors = BlockColors[IncomingBlock];
821           assert(!IncomingColors.empty() && "Block not colored!");
822           assert((IncomingColors.size() == 1 ||
823                   llvm::all_of(IncomingColors,
824                                [&](BasicBlock *Color) {
825                                  return Color != FuncletPadBB;
826                                })) &&
827                  "Cloning should leave this funclet's blocks monochromatic");
828           EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
829         }
830         if (IsForOldBlock != EdgeTargetsFunclet)
831           continue;
832         PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
833         // Revisit the next entry.
834         --PredIdx;
835         --PredEnd;
836       }
837     };
838 
839     for (auto &BBMapping : Orig2Clone) {
840       BasicBlock *OldBlock = BBMapping.first;
841       BasicBlock *NewBlock = BBMapping.second;
842       for (PHINode &OldPN : OldBlock->phis()) {
843         UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
844       }
845       for (PHINode &NewPN : NewBlock->phis()) {
846         UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
847       }
848     }
849 
850     // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
851     // the PHI nodes for NewBB now.
852     for (auto &BBMapping : Orig2Clone) {
853       BasicBlock *OldBlock = BBMapping.first;
854       BasicBlock *NewBlock = BBMapping.second;
855       for (BasicBlock *SuccBB : successors(NewBlock)) {
856         for (PHINode &SuccPN : SuccBB->phis()) {
857           // Ok, we have a PHI node.  Figure out what the incoming value was for
858           // the OldBlock.
859           int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
860           if (OldBlockIdx == -1)
861             break;
862           Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
863 
864           // Remap the value if necessary.
865           if (auto *Inst = dyn_cast<Instruction>(IV)) {
866             ValueToValueMapTy::iterator I = VMap.find(Inst);
867             if (I != VMap.end())
868               IV = I->second;
869           }
870 
871           SuccPN.addIncoming(IV, NewBlock);
872         }
873       }
874     }
875 
876     for (ValueToValueMapTy::value_type VT : VMap) {
877       // If there were values defined in BB that are used outside the funclet,
878       // then we now have to update all uses of the value to use either the
879       // original value, the cloned value, or some PHI derived value.  This can
880       // require arbitrary PHI insertion, of which we are prepared to do, clean
881       // these up now.
882       SmallVector<Use *, 16> UsesToRename;
883 
884       auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
885       if (!OldI)
886         continue;
887       auto *NewI = cast<Instruction>(VT.second);
888       // Scan all uses of this instruction to see if it is used outside of its
889       // funclet, and if so, record them in UsesToRename.
890       for (Use &U : OldI->uses()) {
891         Instruction *UserI = cast<Instruction>(U.getUser());
892         BasicBlock *UserBB = UserI->getParent();
893         ColorVector &ColorsForUserBB = BlockColors[UserBB];
894         assert(!ColorsForUserBB.empty());
895         if (ColorsForUserBB.size() > 1 ||
896             *ColorsForUserBB.begin() != FuncletPadBB)
897           UsesToRename.push_back(&U);
898       }
899 
900       // If there are no uses outside the block, we're done with this
901       // instruction.
902       if (UsesToRename.empty())
903         continue;
904 
905       // We found a use of OldI outside of the funclet.  Rename all uses of OldI
906       // that are outside its funclet to be uses of the appropriate PHI node
907       // etc.
908       SSAUpdater SSAUpdate;
909       SSAUpdate.Initialize(OldI->getType(), OldI->getName());
910       SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
911       SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
912 
913       while (!UsesToRename.empty())
914         SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
915     }
916   }
917 }
918 
919 void WinEHPrepare::removeImplausibleInstructions(Function &F) {
920   // Remove implausible terminators and replace them with UnreachableInst.
921   for (auto &Funclet : FuncletBlocks) {
922     BasicBlock *FuncletPadBB = Funclet.first;
923     std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
924     Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
925     auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
926     auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
927     auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
928 
929     for (BasicBlock *BB : BlocksInFunclet) {
930       for (Instruction &I : *BB) {
931         CallSite CS(&I);
932         if (!CS)
933           continue;
934 
935         Value *FuncletBundleOperand = nullptr;
936         if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
937           FuncletBundleOperand = BU->Inputs.front();
938 
939         if (FuncletBundleOperand == FuncletPad)
940           continue;
941 
942         // Skip call sites which are nounwind intrinsics or inline asm.
943         auto *CalledFn =
944             dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
945         if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
946                          CS.isInlineAsm()))
947           continue;
948 
949         // This call site was not part of this funclet, remove it.
950         if (CS.isInvoke()) {
951           // Remove the unwind edge if it was an invoke.
952           removeUnwindEdge(BB);
953           // Get a pointer to the new call.
954           BasicBlock::iterator CallI =
955               std::prev(BB->getTerminator()->getIterator());
956           auto *CI = cast<CallInst>(&*CallI);
957           changeToUnreachable(CI, /*UseLLVMTrap=*/false);
958         } else {
959           changeToUnreachable(&I, /*UseLLVMTrap=*/false);
960         }
961 
962         // There are no more instructions in the block (except for unreachable),
963         // we are done.
964         break;
965       }
966 
967       TerminatorInst *TI = BB->getTerminator();
968       // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
969       bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
970       // The token consumed by a CatchReturnInst must match the funclet token.
971       bool IsUnreachableCatchret = false;
972       if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
973         IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
974       // The token consumed by a CleanupReturnInst must match the funclet token.
975       bool IsUnreachableCleanupret = false;
976       if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
977         IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
978       if (IsUnreachableRet || IsUnreachableCatchret ||
979           IsUnreachableCleanupret) {
980         changeToUnreachable(TI, /*UseLLVMTrap=*/false);
981       } else if (isa<InvokeInst>(TI)) {
982         if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
983           // Invokes within a cleanuppad for the MSVC++ personality never
984           // transfer control to their unwind edge: the personality will
985           // terminate the program.
986           removeUnwindEdge(BB);
987         }
988       }
989     }
990   }
991 }
992 
993 void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
994   // Clean-up some of the mess we made by removing useles PHI nodes, trivial
995   // branches, etc.
996   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
997     BasicBlock *BB = &*FI++;
998     SimplifyInstructionsInBlock(BB);
999     ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1000     MergeBlockIntoPredecessor(BB);
1001   }
1002 
1003   // We might have some unreachable blocks after cleaning up some impossible
1004   // control flow.
1005   removeUnreachableBlocks(F);
1006 }
1007 
1008 #ifndef NDEBUG
1009 void WinEHPrepare::verifyPreparedFunclets(Function &F) {
1010   for (BasicBlock &BB : F) {
1011     size_t NumColors = BlockColors[&BB].size();
1012     assert(NumColors == 1 && "Expected monochromatic BB!");
1013     if (NumColors == 0)
1014       report_fatal_error("Uncolored BB!");
1015     if (NumColors > 1)
1016       report_fatal_error("Multicolor BB!");
1017     assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1018            "EH Pad still has a PHI!");
1019   }
1020 }
1021 #endif
1022 
1023 bool WinEHPrepare::prepareExplicitEH(Function &F) {
1024   // Remove unreachable blocks.  It is not valuable to assign them a color and
1025   // their existence can trick us into thinking values are alive when they are
1026   // not.
1027   removeUnreachableBlocks(F);
1028 
1029   // Determine which blocks are reachable from which funclet entries.
1030   colorFunclets(F);
1031 
1032   cloneCommonBlocks(F);
1033 
1034   if (!DisableDemotion)
1035     demotePHIsOnFunclets(F);
1036 
1037   if (!DisableCleanups) {
1038     LLVM_DEBUG(verifyFunction(F));
1039     removeImplausibleInstructions(F);
1040 
1041     LLVM_DEBUG(verifyFunction(F));
1042     cleanupPreparedFunclets(F);
1043   }
1044 
1045   LLVM_DEBUG(verifyPreparedFunclets(F));
1046   // Recolor the CFG to verify that all is well.
1047   LLVM_DEBUG(colorFunclets(F));
1048   LLVM_DEBUG(verifyPreparedFunclets(F));
1049 
1050   BlockColors.clear();
1051   FuncletBlocks.clear();
1052 
1053   return true;
1054 }
1055 
1056 // TODO: Share loads when one use dominates another, or when a catchpad exit
1057 // dominates uses (needs dominators).
1058 AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1059   BasicBlock *PHIBlock = PN->getParent();
1060   AllocaInst *SpillSlot = nullptr;
1061   Instruction *EHPad = PHIBlock->getFirstNonPHI();
1062 
1063   if (!isa<TerminatorInst>(EHPad)) {
1064     // If the EHPad isn't a terminator, then we can insert a load in this block
1065     // that will dominate all uses.
1066     SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
1067                                Twine(PN->getName(), ".wineh.spillslot"),
1068                                &F.getEntryBlock().front());
1069     Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
1070                             &*PHIBlock->getFirstInsertionPt());
1071     PN->replaceAllUsesWith(V);
1072     return SpillSlot;
1073   }
1074 
1075   // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1076   // loads of the slot before every use.
1077   DenseMap<BasicBlock *, Value *> Loads;
1078   for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1079        UI != UE;) {
1080     Use &U = *UI++;
1081     auto *UsingInst = cast<Instruction>(U.getUser());
1082     if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
1083       // Use is on an EH pad phi.  Leave it alone; we'll insert loads and
1084       // stores for it separately.
1085       continue;
1086     }
1087     replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1088   }
1089   return SpillSlot;
1090 }
1091 
1092 // TODO: improve store placement.  Inserting at def is probably good, but need
1093 // to be careful not to introduce interfering stores (needs liveness analysis).
1094 // TODO: identify related phi nodes that can share spill slots, and share them
1095 // (also needs liveness).
1096 void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1097                                    AllocaInst *SpillSlot) {
1098   // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1099   // stored to the spill slot by the end of the given Block.
1100   SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1101 
1102   Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1103 
1104   while (!Worklist.empty()) {
1105     BasicBlock *EHBlock;
1106     Value *InVal;
1107     std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1108 
1109     PHINode *PN = dyn_cast<PHINode>(InVal);
1110     if (PN && PN->getParent() == EHBlock) {
1111       // The value is defined by another PHI we need to remove, with no room to
1112       // insert a store after the PHI, so each predecessor needs to store its
1113       // incoming value.
1114       for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1115         Value *PredVal = PN->getIncomingValue(i);
1116 
1117         // Undef can safely be skipped.
1118         if (isa<UndefValue>(PredVal))
1119           continue;
1120 
1121         insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1122       }
1123     } else {
1124       // We need to store InVal, which dominates EHBlock, but can't put a store
1125       // in EHBlock, so need to put stores in each predecessor.
1126       for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1127         insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1128       }
1129     }
1130   }
1131 }
1132 
1133 void WinEHPrepare::insertPHIStore(
1134     BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1135     SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1136 
1137   if (PredBlock->isEHPad() &&
1138       isa<TerminatorInst>(PredBlock->getFirstNonPHI())) {
1139     // Pred is unsplittable, so we need to queue it on the worklist.
1140     Worklist.push_back({PredBlock, PredVal});
1141     return;
1142   }
1143 
1144   // Otherwise, insert the store at the end of the basic block.
1145   new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1146 }
1147 
1148 void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1149                                       DenseMap<BasicBlock *, Value *> &Loads,
1150                                       Function &F) {
1151   // Lazilly create the spill slot.
1152   if (!SpillSlot)
1153     SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
1154                                Twine(V->getName(), ".wineh.spillslot"),
1155                                &F.getEntryBlock().front());
1156 
1157   auto *UsingInst = cast<Instruction>(U.getUser());
1158   if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1159     // If this is a PHI node, we can't insert a load of the value before
1160     // the use.  Instead insert the load in the predecessor block
1161     // corresponding to the incoming value.
1162     //
1163     // Note that if there are multiple edges from a basic block to this
1164     // PHI node that we cannot have multiple loads.  The problem is that
1165     // the resulting PHI node will have multiple values (from each load)
1166     // coming in from the same block, which is illegal SSA form.
1167     // For this reason, we keep track of and reuse loads we insert.
1168     BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
1169     if (auto *CatchRet =
1170             dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1171       // Putting a load above a catchret and use on the phi would still leave
1172       // a cross-funclet def/use.  We need to split the edge, change the
1173       // catchret to target the new block, and put the load there.
1174       BasicBlock *PHIBlock = UsingInst->getParent();
1175       BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1176       // SplitEdge gives us:
1177       //   IncomingBlock:
1178       //     ...
1179       //     br label %NewBlock
1180       //   NewBlock:
1181       //     catchret label %PHIBlock
1182       // But we need:
1183       //   IncomingBlock:
1184       //     ...
1185       //     catchret label %NewBlock
1186       //   NewBlock:
1187       //     br label %PHIBlock
1188       // So move the terminators to each others' blocks and swap their
1189       // successors.
1190       BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1191       Goto->removeFromParent();
1192       CatchRet->removeFromParent();
1193       IncomingBlock->getInstList().push_back(CatchRet);
1194       NewBlock->getInstList().push_back(Goto);
1195       Goto->setSuccessor(0, PHIBlock);
1196       CatchRet->setSuccessor(NewBlock);
1197       // Update the color mapping for the newly split edge.
1198       // Grab a reference to the ColorVector to be inserted before getting the
1199       // reference to the vector we are copying because inserting the new
1200       // element in BlockColors might cause the map to be reallocated.
1201       ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
1202       ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
1203       ColorsForNewBlock = ColorsForPHIBlock;
1204       for (BasicBlock *FuncletPad : ColorsForPHIBlock)
1205         FuncletBlocks[FuncletPad].push_back(NewBlock);
1206       // Treat the new block as incoming for load insertion.
1207       IncomingBlock = NewBlock;
1208     }
1209     Value *&Load = Loads[IncomingBlock];
1210     // Insert the load into the predecessor block
1211     if (!Load)
1212       Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1213                           /*Volatile=*/false, IncomingBlock->getTerminator());
1214 
1215     U.set(Load);
1216   } else {
1217     // Reload right before the old use.
1218     auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1219                               /*Volatile=*/false, UsingInst);
1220     U.set(Load);
1221   }
1222 }
1223 
1224 void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
1225                                       MCSymbol *InvokeBegin,
1226                                       MCSymbol *InvokeEnd) {
1227   assert(InvokeStateMap.count(II) &&
1228          "should get invoke with precomputed state");
1229   LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
1230 }
1231 
1232 WinEHFuncInfo::WinEHFuncInfo() {}
1233