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