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