[WinEH] Demote values and phis live across exception handlers up front
[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. It snifs the personality function to see which kind of
12 // preparation is necessary. If the personality function uses the Itanium LSDA,
13 // this pass delegates to the DWARF EH preparation pass.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/TinyPtrVector.h"
23 #include "llvm/Analysis/LibCallSemantics.h"
24 #include "llvm/CodeGen/WinEHFuncInfo.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
40 #include <memory>
41
42 using namespace llvm;
43 using namespace llvm::PatternMatch;
44
45 #define DEBUG_TYPE "winehprepare"
46
47 namespace {
48
49 // This map is used to model frame variable usage during outlining, to
50 // construct a structure type to hold the frame variables in a frame
51 // allocation block, and to remap the frame variable allocas (including
52 // spill locations as needed) to GEPs that get the variable from the
53 // frame allocation structure.
54 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
55
56 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
57 // quite null.
58 AllocaInst *getCatchObjectSentinel() {
59   return static_cast<AllocaInst *>(nullptr) + 1;
60 }
61
62 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
63
64 class LandingPadActions;
65 class LandingPadMap;
66
67 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
68 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
69
70 class WinEHPrepare : public FunctionPass {
71 public:
72   static char ID; // Pass identification, replacement for typeid.
73   WinEHPrepare(const TargetMachine *TM = nullptr)
74       : FunctionPass(ID), DT(nullptr) {}
75
76   bool runOnFunction(Function &Fn) override;
77
78   bool doFinalization(Module &M) override;
79
80   void getAnalysisUsage(AnalysisUsage &AU) const override;
81
82   const char *getPassName() const override {
83     return "Windows exception handling preparation";
84   }
85
86 private:
87   bool prepareExceptionHandlers(Function &F,
88                                 SmallVectorImpl<LandingPadInst *> &LPads);
89   void promoteLandingPadValues(LandingPadInst *LPad);
90   void demoteValuesLiveAcrossHandlers(Function &F,
91                                       SmallVectorImpl<LandingPadInst *> &LPads);
92   void completeNestedLandingPad(Function *ParentFn,
93                                 LandingPadInst *OutlinedLPad,
94                                 const LandingPadInst *OriginalLPad,
95                                 FrameVarInfoMap &VarInfo);
96   bool outlineHandler(ActionHandler *Action, Function *SrcFn,
97                       LandingPadInst *LPad, BasicBlock *StartBB,
98                       FrameVarInfoMap &VarInfo);
99   void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
100
101   void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
102   CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
103                                  VisitedBlockSet &VisitedBlocks);
104   void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
105                            BasicBlock *EndBB);
106
107   void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
108
109   // All fields are reset by runOnFunction.
110   DominatorTree *DT;
111   EHPersonality Personality;
112   CatchHandlerMapTy CatchHandlerMap;
113   CleanupHandlerMapTy CleanupHandlerMap;
114   DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
115
116   // This maps landing pad instructions found in outlined handlers to
117   // the landing pad instruction in the parent function from which they
118   // were cloned.  The cloned/nested landing pad is used as the key
119   // because the landing pad may be cloned into multiple handlers.
120   // This map will be used to add the llvm.eh.actions call to the nested
121   // landing pads after all handlers have been outlined.
122   DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
123
124   // This maps blocks in the parent function which are destinations of
125   // catch handlers to cloned blocks in (other) outlined handlers. This
126   // handles the case where a nested landing pads has a catch handler that
127   // returns to a handler function rather than the parent function.
128   // The original block is used as the key here because there should only
129   // ever be one handler function from which the cloned block is not pruned.
130   // The original block will be pruned from the parent function after all
131   // handlers have been outlined.  This map will be used to adjust the
132   // return instructions of handlers which return to the block that was
133   // outlined into a handler.  This is done after all handlers have been
134   // outlined but before the outlined code is pruned from the parent function.
135   DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
136 };
137
138 class WinEHFrameVariableMaterializer : public ValueMaterializer {
139 public:
140   WinEHFrameVariableMaterializer(Function *OutlinedFn,
141                                  FrameVarInfoMap &FrameVarInfo);
142   ~WinEHFrameVariableMaterializer() override {}
143
144   Value *materializeValueFor(Value *V) override;
145
146   void escapeCatchObject(Value *V);
147
148 private:
149   FrameVarInfoMap &FrameVarInfo;
150   IRBuilder<> Builder;
151 };
152
153 class LandingPadMap {
154 public:
155   LandingPadMap() : OriginLPad(nullptr) {}
156   void mapLandingPad(const LandingPadInst *LPad);
157
158   bool isInitialized() { return OriginLPad != nullptr; }
159
160   bool isOriginLandingPadBlock(const BasicBlock *BB) const;
161   bool isLandingPadSpecificInst(const Instruction *Inst) const;
162
163   void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
164                      Value *SelectorValue) const;
165
166 private:
167   const LandingPadInst *OriginLPad;
168   // We will normally only see one of each of these instructions, but
169   // if more than one occurs for some reason we can handle that.
170   TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
171   TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
172 };
173
174 class WinEHCloningDirectorBase : public CloningDirector {
175 public:
176   WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
177                            LandingPadMap &LPadMap)
178       : Materializer(HandlerFn, VarInfo),
179         SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
180         Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
181         LPadMap(LPadMap) {
182     auto AI = HandlerFn->getArgumentList().begin();
183     ++AI;
184     EstablisherFrame = AI;
185   }
186
187   CloningAction handleInstruction(ValueToValueMapTy &VMap,
188                                   const Instruction *Inst,
189                                   BasicBlock *NewBB) override;
190
191   virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
192                                          const Instruction *Inst,
193                                          BasicBlock *NewBB) = 0;
194   virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
195                                        const Instruction *Inst,
196                                        BasicBlock *NewBB) = 0;
197   virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
198                                         const Instruction *Inst,
199                                         BasicBlock *NewBB) = 0;
200   virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
201                                      const InvokeInst *Invoke,
202                                      BasicBlock *NewBB) = 0;
203   virtual CloningAction handleResume(ValueToValueMapTy &VMap,
204                                      const ResumeInst *Resume,
205                                      BasicBlock *NewBB) = 0;
206   virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
207                                       const CmpInst *Compare,
208                                       BasicBlock *NewBB) = 0;
209   virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
210                                          const LandingPadInst *LPad,
211                                          BasicBlock *NewBB) = 0;
212
213   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
214
215 protected:
216   WinEHFrameVariableMaterializer Materializer;
217   Type *SelectorIDType;
218   Type *Int8PtrType;
219   LandingPadMap &LPadMap;
220
221   /// The value representing the parent frame pointer.
222   Value *EstablisherFrame;
223 };
224
225 class WinEHCatchDirector : public WinEHCloningDirectorBase {
226 public:
227   WinEHCatchDirector(
228       Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
229       LandingPadMap &LPadMap,
230       DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
231       : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
232         CurrentSelector(Selector->stripPointerCasts()),
233         ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
234
235   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
236                                  const Instruction *Inst,
237                                  BasicBlock *NewBB) override;
238   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
239                                BasicBlock *NewBB) override;
240   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
241                                 const Instruction *Inst,
242                                 BasicBlock *NewBB) override;
243   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
244                              BasicBlock *NewBB) override;
245   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
246                              BasicBlock *NewBB) override;
247   CloningAction handleCompare(ValueToValueMapTy &VMap,
248                               const CmpInst *Compare, BasicBlock *NewBB) override;
249   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
250                                  const LandingPadInst *LPad,
251                                  BasicBlock *NewBB) override;
252
253   Value *getExceptionVar() { return ExceptionObjectVar; }
254   TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
255
256 private:
257   Value *CurrentSelector;
258
259   Value *ExceptionObjectVar;
260   TinyPtrVector<BasicBlock *> ReturnTargets;
261
262   // This will be a reference to the field of the same name in the WinEHPrepare
263   // object which instantiates this WinEHCatchDirector object.
264   DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
265 };
266
267 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
268 public:
269   WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
270                        LandingPadMap &LPadMap)
271       : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
272
273   CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
274                                  const Instruction *Inst,
275                                  BasicBlock *NewBB) override;
276   CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
277                                BasicBlock *NewBB) override;
278   CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
279                                 const Instruction *Inst,
280                                 BasicBlock *NewBB) override;
281   CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
282                              BasicBlock *NewBB) override;
283   CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
284                              BasicBlock *NewBB) override;
285   CloningAction handleCompare(ValueToValueMapTy &VMap,
286                               const CmpInst *Compare, BasicBlock *NewBB) override;
287   CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288                                  const LandingPadInst *LPad,
289                                  BasicBlock *NewBB) override;
290 };
291
292 class LandingPadActions {
293 public:
294   LandingPadActions() : HasCleanupHandlers(false) {}
295
296   void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
297   void insertCleanupHandler(CleanupHandler *Action) {
298     Actions.push_back(Action);
299     HasCleanupHandlers = true;
300   }
301
302   bool includesCleanup() const { return HasCleanupHandlers; }
303
304   SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
305   SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
306   SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
307
308 private:
309   // Note that this class does not own the ActionHandler objects in this vector.
310   // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
311   // in the WinEHPrepare class.
312   SmallVector<ActionHandler *, 4> Actions;
313   bool HasCleanupHandlers;
314 };
315
316 } // end anonymous namespace
317
318 char WinEHPrepare::ID = 0;
319 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
320                    false, false)
321
322 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
323   return new WinEHPrepare(TM);
324 }
325
326 // FIXME: Remove this once the backend can handle the prepared IR.
327 static cl::opt<bool>
328     SEHPrepare("sehprepare", cl::Hidden,
329                cl::desc("Prepare functions with SEH personalities"));
330
331 bool WinEHPrepare::runOnFunction(Function &Fn) {
332   // No need to prepare outlined handlers.
333   if (Fn.hasFnAttribute("wineh-parent"))
334     return false;
335
336   SmallVector<LandingPadInst *, 4> LPads;
337   SmallVector<ResumeInst *, 4> Resumes;
338   for (BasicBlock &BB : Fn) {
339     if (auto *LP = BB.getLandingPadInst())
340       LPads.push_back(LP);
341     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
342       Resumes.push_back(Resume);
343   }
344
345   // No need to prepare functions that lack landing pads.
346   if (LPads.empty())
347     return false;
348
349   // Classify the personality to see what kind of preparation we need.
350   Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
351
352   // Do nothing if this is not an MSVC personality.
353   if (!isMSVCEHPersonality(Personality))
354     return false;
355
356   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
357
358   if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
359     // Replace all resume instructions with unreachable.
360     // FIXME: Remove this once the backend can handle the prepared IR.
361     for (ResumeInst *Resume : Resumes) {
362       IRBuilder<>(Resume).CreateUnreachable();
363       Resume->eraseFromParent();
364     }
365     return true;
366   }
367
368   // If there were any landing pads, prepareExceptionHandlers will make changes.
369   prepareExceptionHandlers(Fn, LPads);
370   return true;
371 }
372
373 bool WinEHPrepare::doFinalization(Module &M) { return false; }
374
375 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
376   AU.addRequired<DominatorTreeWrapperPass>();
377 }
378
379 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
380                                Constant *&Selector, BasicBlock *&NextBB);
381
382 // Finds blocks reachable from the starting set Worklist. Does not follow unwind
383 // edges or blocks listed in StopPoints.
384 static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
385                                 SetVector<BasicBlock *> &Worklist,
386                                 const SetVector<BasicBlock *> *StopPoints) {
387   while (!Worklist.empty()) {
388     BasicBlock *BB = Worklist.pop_back_val();
389
390     // Don't cross blocks that we should stop at.
391     if (StopPoints && StopPoints->count(BB))
392       continue;
393
394     if (!ReachableBBs.insert(BB).second)
395       continue; // Already visited.
396
397     // Don't follow unwind edges of invokes.
398     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
399       Worklist.insert(II->getNormalDest());
400       continue;
401     }
402
403     // Otherwise, follow all successors.
404     Worklist.insert(succ_begin(BB), succ_end(BB));
405   }
406 }
407
408 /// Find all points where exceptional control rejoins normal control flow via
409 /// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
410 static void findCXXEHReturnPoints(Function &F,
411                                   SetVector<BasicBlock *> &EHReturnBlocks) {
412   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
413     BasicBlock *BB = BBI;
414     for (Instruction &I : *BB) {
415       if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
416         // Split the block after the call to llvm.eh.endcatch if there is
417         // anything other than an unconditional branch, or if the successor
418         // starts with a phi.
419         auto *Br = dyn_cast<BranchInst>(I.getNextNode());
420         if (!Br || !Br->isUnconditional() ||
421             isa<PHINode>(Br->getSuccessor(0)->begin())) {
422           DEBUG(dbgs() << "splitting block " << BB->getName()
423                        << " with llvm.eh.endcatch\n");
424           BBI = BB->splitBasicBlock(I.getNextNode(), "ehreturn");
425         }
426         // The next BB is normal control flow.
427         EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
428         break;
429       }
430     }
431   }
432 }
433
434 static bool isCatchAllLandingPad(const BasicBlock *BB) {
435   const LandingPadInst *LP = BB->getLandingPadInst();
436   if (!LP)
437     return false;
438   unsigned N = LP->getNumClauses();
439   return (N > 0 && LP->isCatch(N - 1) &&
440           isa<ConstantPointerNull>(LP->getClause(N - 1)));
441 }
442
443 /// Find all points where exceptions control rejoins normal control flow via
444 /// selector dispatch.
445 static void findSEHEHReturnPoints(Function &F,
446                                   SetVector<BasicBlock *> &EHReturnBlocks) {
447   for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
448     BasicBlock *BB = BBI;
449     // If the landingpad is a catch-all, treat the whole lpad as if it is
450     // reachable from normal control flow.
451     // FIXME: This is imprecise. We need a better way of identifying where a
452     // catch-all starts and cleanups stop. As far as LLVM is concerned, there
453     // is no difference.
454     if (isCatchAllLandingPad(BB)) {
455       EHReturnBlocks.insert(BB);
456       continue;
457     }
458
459     BasicBlock *CatchHandler;
460     BasicBlock *NextBB;
461     Constant *Selector;
462     if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
463       // Split the edge if there is a phi node. Returning from EH to a phi node
464       // is just as impossible as having a phi after an indirectbr.
465       if (isa<PHINode>(CatchHandler->begin())) {
466         DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
467                      << " to " << CatchHandler->getName() << '\n');
468         BBI = CatchHandler = SplitCriticalEdge(
469             BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
470       }
471       EHReturnBlocks.insert(CatchHandler);
472     }
473   }
474 }
475
476 /// Ensure that all values live into and out of exception handlers are stored
477 /// in memory.
478 /// FIXME: This falls down when values are defined in one handler and live into
479 /// another handler. For example, a cleanup defines a value used only by a
480 /// catch handler.
481 void WinEHPrepare::demoteValuesLiveAcrossHandlers(
482     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
483   DEBUG(dbgs() << "Demoting values live across exception handlers in function "
484                << F.getName() << '\n');
485
486   // Build a set of all non-exceptional blocks and exceptional blocks.
487   // - Non-exceptional blocks are blocks reachable from the entry block while
488   //   not following invoke unwind edges.
489   // - Exceptional blocks are blocks reachable from landingpads. Analysis does
490   //   not follow llvm.eh.endcatch blocks, which mark a transition from
491   //   exceptional to normal control.
492   SmallPtrSet<BasicBlock *, 4> NormalBlocks;
493   SmallPtrSet<BasicBlock *, 4> EHBlocks;
494   SetVector<BasicBlock *> EHReturnBlocks;
495   SetVector<BasicBlock *> Worklist;
496
497   if (Personality == EHPersonality::MSVC_CXX)
498     findCXXEHReturnPoints(F, EHReturnBlocks);
499   else
500     findSEHEHReturnPoints(F, EHReturnBlocks);
501
502   DEBUG({
503     dbgs() << "identified the following blocks as EH return points:\n";
504     for (BasicBlock *BB : EHReturnBlocks)
505       dbgs() << "  " << BB->getName() << '\n';
506   });
507
508   // Join points should not have phis at this point, unless they are a
509   // landingpad, in which case we will demote their phis later.
510 #ifndef NDEBUG
511   for (BasicBlock *BB : EHReturnBlocks)
512     assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
513            "non-lpad EH return block has phi");
514 #endif
515
516   // Normal blocks are the blocks reachable from the entry block and all EH
517   // return points.
518   Worklist = EHReturnBlocks;
519   Worklist.insert(&F.getEntryBlock());
520   findReachableBlocks(NormalBlocks, Worklist, nullptr);
521   DEBUG({
522     dbgs() << "marked the following blocks as normal:\n";
523     for (BasicBlock *BB : NormalBlocks)
524       dbgs() << "  " << BB->getName() << '\n';
525   });
526
527   // Exceptional blocks are the blocks reachable from landingpads that don't
528   // cross EH return points.
529   Worklist.clear();
530   for (auto *LPI : LPads)
531     Worklist.insert(LPI->getParent());
532   findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
533   DEBUG({
534     dbgs() << "marked the following blocks as exceptional:\n";
535     for (BasicBlock *BB : EHBlocks)
536       dbgs() << "  " << BB->getName() << '\n';
537   });
538
539   SetVector<Argument *> ArgsToDemote;
540   SetVector<Instruction *> InstrsToDemote;
541   for (BasicBlock &BB : F) {
542     bool IsNormalBB = NormalBlocks.count(&BB);
543     bool IsEHBB = EHBlocks.count(&BB);
544     if (!IsNormalBB && !IsEHBB)
545       continue; // Blocks that are neither normal nor EH are unreachable.
546     for (Instruction &I : BB) {
547       for (Value *Op : I.operands()) {
548         // Don't demote static allocas, constants, and labels.
549         if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
550           continue;
551         auto *AI = dyn_cast<AllocaInst>(Op);
552         if (AI && AI->isStaticAlloca())
553           continue;
554
555         if (auto *Arg = dyn_cast<Argument>(Op)) {
556           if (IsEHBB) {
557             DEBUG(dbgs() << "Demoting argument " << *Arg
558                          << " used by EH instr: " << I << "\n");
559             ArgsToDemote.insert(Arg);
560           }
561           continue;
562         }
563
564         auto *OpI = cast<Instruction>(Op);
565         BasicBlock *OpBB = OpI->getParent();
566         // If a value is produced and consumed in the same BB, we don't need to
567         // demote it.
568         if (OpBB == &BB)
569           continue;
570         bool IsOpNormalBB = NormalBlocks.count(OpBB);
571         bool IsOpEHBB = EHBlocks.count(OpBB);
572         if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
573           DEBUG({
574             dbgs() << "Demoting instruction live in-out from EH:\n";
575             dbgs() << "Instr: " << *OpI << '\n';
576             dbgs() << "User: " << I << '\n';
577           });
578           InstrsToDemote.insert(OpI);
579         }
580       }
581     }
582   }
583
584   // Demote values live into and out of handlers.
585   // FIXME: This demotion is inefficient. We should insert spills at the point
586   // of definition, insert one reload in each handler that uses the value, and
587   // insert reloads in the BB used to rejoin normal control flow.
588   Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
589   for (Instruction *I : InstrsToDemote)
590     DemoteRegToStack(*I, false, AllocaInsertPt);
591
592   // Demote arguments separately, and only for uses in EH blocks.
593   for (Argument *Arg : ArgsToDemote) {
594     auto *Slot = new AllocaInst(Arg->getType(), nullptr,
595                                 Arg->getName() + ".reg2mem", AllocaInsertPt);
596     SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
597     for (User *U : Users) {
598       auto *I = dyn_cast<Instruction>(U);
599       if (I && EHBlocks.count(I->getParent())) {
600         auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
601         U->replaceUsesOfWith(Arg, Reload);
602       }
603     }
604     new StoreInst(Arg, Slot, AllocaInsertPt);
605   }
606
607   // Demote landingpad phis, as the landingpad will be removed from the machine
608   // CFG.
609   for (LandingPadInst *LPI : LPads) {
610     BasicBlock *BB = LPI->getParent();
611     while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
612       DemotePHIToStack(Phi, AllocaInsertPt);
613   }
614
615   DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
616                << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
617 }
618
619 bool WinEHPrepare::prepareExceptionHandlers(
620     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
621   // Don't run on functions that are already prepared.
622   for (LandingPadInst *LPad : LPads) {
623     BasicBlock *LPadBB = LPad->getParent();
624     for (Instruction &Inst : *LPadBB)
625       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
626         return false;
627   }
628
629   demoteValuesLiveAcrossHandlers(F, LPads);
630
631   // These containers are used to re-map frame variables that are used in
632   // outlined catch and cleanup handlers.  They will be populated as the
633   // handlers are outlined.
634   FrameVarInfoMap FrameVarInfo;
635
636   bool HandlersOutlined = false;
637
638   Module *M = F.getParent();
639   LLVMContext &Context = M->getContext();
640
641   // Create a new function to receive the handler contents.
642   PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
643   Type *Int32Type = Type::getInt32Ty(Context);
644   Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
645
646   for (LandingPadInst *LPad : LPads) {
647     // Look for evidence that this landingpad has already been processed.
648     bool LPadHasActionList = false;
649     BasicBlock *LPadBB = LPad->getParent();
650     for (Instruction &Inst : *LPadBB) {
651       if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
652         LPadHasActionList = true;
653         break;
654       }
655       // FIXME: This is here to help with the development of nested landing pad
656       //        outlining.  It should be removed when that is finished.
657       if (isa<UnreachableInst>(Inst)) {
658         LPadHasActionList = true;
659         break;
660       }
661     }
662
663     // If we've already outlined the handlers for this landingpad,
664     // there's nothing more to do here.
665     if (LPadHasActionList)
666       continue;
667
668     // If either of the values in the aggregate returned by the landing pad is
669     // extracted and stored to memory, promote the stored value to a register.
670     promoteLandingPadValues(LPad);
671
672     LandingPadActions Actions;
673     mapLandingPadBlocks(LPad, Actions);
674
675     HandlersOutlined |= !Actions.actions().empty();
676     for (ActionHandler *Action : Actions) {
677       if (Action->hasBeenProcessed())
678         continue;
679       BasicBlock *StartBB = Action->getStartBlock();
680
681       // SEH doesn't do any outlining for catches. Instead, pass the handler
682       // basic block addr to llvm.eh.actions and list the block as a return
683       // target.
684       if (isAsynchronousEHPersonality(Personality)) {
685         if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
686           processSEHCatchHandler(CatchAction, StartBB);
687           continue;
688         }
689       }
690
691       outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
692     }
693
694     // Replace the landing pad with a new llvm.eh.action based landing pad.
695     BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
696     assert(!isa<PHINode>(LPadBB->begin()));
697     auto *NewLPad = cast<LandingPadInst>(LPad->clone());
698     NewLPadBB->getInstList().push_back(NewLPad);
699     while (!pred_empty(LPadBB)) {
700       auto *pred = *pred_begin(LPadBB);
701       InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
702       Invoke->setUnwindDest(NewLPadBB);
703     }
704
705     // If anyone is still using the old landingpad value, just give them undef
706     // instead. The eh pointer and selector values are not real.
707     LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
708
709     // Replace the mapping of any nested landing pad that previously mapped
710     // to this landing pad with a referenced to the cloned version.
711     for (auto &LPadPair : NestedLPtoOriginalLP) {
712       const LandingPadInst *OriginalLPad = LPadPair.second;
713       if (OriginalLPad == LPad) {
714         LPadPair.second = NewLPad;
715       }
716     }
717
718     // Replace uses of the old lpad in phis with this block and delete the old
719     // block.
720     LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
721     LPadBB->getTerminator()->eraseFromParent();
722     new UnreachableInst(LPadBB->getContext(), LPadBB);
723
724     // Add a call to describe the actions for this landing pad.
725     std::vector<Value *> ActionArgs;
726     for (ActionHandler *Action : Actions) {
727       // Action codes from docs are: 0 cleanup, 1 catch.
728       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
729         ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
730         ActionArgs.push_back(CatchAction->getSelector());
731         // Find the frame escape index of the exception object alloca in the
732         // parent.
733         int FrameEscapeIdx = -1;
734         Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
735         if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
736           auto I = FrameVarInfo.find(EHObj);
737           assert(I != FrameVarInfo.end() &&
738                  "failed to map llvm.eh.begincatch var");
739           FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
740         }
741         ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
742       } else {
743         ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
744       }
745       ActionArgs.push_back(Action->getHandlerBlockOrFunc());
746     }
747     CallInst *Recover =
748         CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
749
750     // Add an indirect branch listing possible successors of the catch handlers.
751     SetVector<BasicBlock *> ReturnTargets;
752     for (ActionHandler *Action : Actions) {
753       if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
754         const auto &CatchTargets = CatchAction->getReturnTargets();
755         ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
756       }
757     }
758     IndirectBrInst *Branch =
759         IndirectBrInst::Create(Recover, ReturnTargets.size(), NewLPadBB);
760     for (BasicBlock *Target : ReturnTargets)
761       Branch->addDestination(Target);
762   } // End for each landingpad
763
764   // If nothing got outlined, there is no more processing to be done.
765   if (!HandlersOutlined)
766     return false;
767
768   // Replace any nested landing pad stubs with the correct action handler.
769   // This must be done before we remove unreachable blocks because it
770   // cleans up references to outlined blocks that will be deleted.
771   for (auto &LPadPair : NestedLPtoOriginalLP)
772     completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
773   NestedLPtoOriginalLP.clear();
774
775   F.addFnAttr("wineh-parent", F.getName());
776
777   // Delete any blocks that were only used by handlers that were outlined above.
778   removeUnreachableBlocks(F);
779
780   BasicBlock *Entry = &F.getEntryBlock();
781   IRBuilder<> Builder(F.getParent()->getContext());
782   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
783
784   Function *FrameEscapeFn =
785       Intrinsic::getDeclaration(M, Intrinsic::frameescape);
786   Function *RecoverFrameFn =
787       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
788   SmallVector<Value *, 8> AllocasToEscape;
789
790   // Scan the entry block for an existing call to llvm.frameescape. We need to
791   // keep escaping those objects.
792   for (Instruction &I : F.front()) {
793     auto *II = dyn_cast<IntrinsicInst>(&I);
794     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
795       auto Args = II->arg_operands();
796       AllocasToEscape.append(Args.begin(), Args.end());
797       II->eraseFromParent();
798       break;
799     }
800   }
801
802   // Finally, replace all of the temporary allocas for frame variables used in
803   // the outlined handlers with calls to llvm.framerecover.
804   for (auto &VarInfoEntry : FrameVarInfo) {
805     Value *ParentVal = VarInfoEntry.first;
806     TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
807     AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
808
809     // FIXME: We should try to sink unescaped allocas from the parent frame into
810     // the child frame. If the alloca is escaped, we have to use the lifetime
811     // markers to ensure that the alloca is only live within the child frame.
812
813     // Add this alloca to the list of things to escape.
814     AllocasToEscape.push_back(ParentAlloca);
815
816     // Next replace all outlined allocas that are mapped to it.
817     for (AllocaInst *TempAlloca : Allocas) {
818       if (TempAlloca == getCatchObjectSentinel())
819         continue; // Skip catch parameter sentinels.
820       Function *HandlerFn = TempAlloca->getParent()->getParent();
821       // FIXME: Sink this GEP into the blocks where it is used.
822       Builder.SetInsertPoint(TempAlloca);
823       Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
824       Value *RecoverArgs[] = {
825           Builder.CreateBitCast(&F, Int8PtrType, ""),
826           &(HandlerFn->getArgumentList().back()),
827           llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
828       Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
829       // Add a pointer bitcast if the alloca wasn't an i8.
830       if (RecoveredAlloca->getType() != TempAlloca->getType()) {
831         RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
832         RecoveredAlloca =
833             Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
834       }
835       TempAlloca->replaceAllUsesWith(RecoveredAlloca);
836       TempAlloca->removeFromParent();
837       RecoveredAlloca->takeName(TempAlloca);
838       delete TempAlloca;
839     }
840   } // End for each FrameVarInfo entry.
841
842   // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
843   // block.
844   Builder.SetInsertPoint(&F.getEntryBlock().back());
845   Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
846
847   // Clean up the handler action maps we created for this function
848   DeleteContainerSeconds(CatchHandlerMap);
849   CatchHandlerMap.clear();
850   DeleteContainerSeconds(CleanupHandlerMap);
851   CleanupHandlerMap.clear();
852
853   return HandlersOutlined;
854 }
855
856 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
857   // If the return values of the landing pad instruction are extracted and
858   // stored to memory, we want to promote the store locations to reg values.
859   SmallVector<AllocaInst *, 2> EHAllocas;
860
861   // The landingpad instruction returns an aggregate value.  Typically, its
862   // value will be passed to a pair of extract value instructions and the
863   // results of those extracts are often passed to store instructions.
864   // In unoptimized code the stored value will often be loaded and then stored
865   // again.
866   for (auto *U : LPad->users()) {
867     ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
868     if (!Extract)
869       continue;
870
871     for (auto *EU : Extract->users()) {
872       if (auto *Store = dyn_cast<StoreInst>(EU)) {
873         auto *AV = cast<AllocaInst>(Store->getPointerOperand());
874         EHAllocas.push_back(AV);
875       }
876     }
877   }
878
879   // We can't do this without a dominator tree.
880   assert(DT);
881
882   if (!EHAllocas.empty()) {
883     PromoteMemToReg(EHAllocas, *DT);
884     EHAllocas.clear();
885   }
886
887   // After promotion, some extracts may be trivially dead. Remove them.
888   SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
889   for (auto *U : Users)
890     RecursivelyDeleteTriviallyDeadInstructions(U);
891 }
892
893 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
894                                             LandingPadInst *OutlinedLPad,
895                                             const LandingPadInst *OriginalLPad,
896                                             FrameVarInfoMap &FrameVarInfo) {
897   // Get the nested block and erase the unreachable instruction that was
898   // temporarily inserted as its terminator.
899   LLVMContext &Context = ParentFn->getContext();
900   BasicBlock *OutlinedBB = OutlinedLPad->getParent();
901   assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
902   OutlinedBB->getTerminator()->eraseFromParent();
903   // That should leave OutlinedLPad as the last instruction in its block.
904   assert(&OutlinedBB->back() == OutlinedLPad);
905
906   // The original landing pad will have already had its action intrinsic
907   // built by the outlining loop.  We need to clone that into the outlined
908   // location.  It may also be necessary to add references to the exception
909   // variables to the outlined handler in which this landing pad is nested
910   // and remap return instructions in the nested handlers that should return
911   // to an address in the outlined handler.
912   Function *OutlinedHandlerFn = OutlinedBB->getParent();
913   BasicBlock::const_iterator II = OriginalLPad;
914   ++II;
915   // The instruction after the landing pad should now be a call to eh.actions.
916   const Instruction *Recover = II;
917   assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
918   IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
919
920   // Remap the exception variables into the outlined function.
921   WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
922   SmallVector<BlockAddress *, 4> ActionTargets;
923   SmallVector<ActionHandler *, 4> ActionList;
924   parseEHActions(EHActions, ActionList);
925   for (auto *Action : ActionList) {
926     auto *Catch = dyn_cast<CatchHandler>(Action);
927     if (!Catch)
928       continue;
929     // The dyn_cast to function here selects C++ catch handlers and skips
930     // SEH catch handlers.
931     auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
932     if (!Handler)
933       continue;
934     // Visit all the return instructions, looking for places that return
935     // to a location within OutlinedHandlerFn.
936     for (BasicBlock &NestedHandlerBB : *Handler) {
937       auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
938       if (!Ret)
939         continue;
940
941       // Handler functions must always return a block address.
942       BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
943       // The original target will have been in the main parent function,
944       // but if it is the address of a block that has been outlined, it
945       // should be a block that was outlined into OutlinedHandlerFn.
946       assert(BA->getFunction() == ParentFn);
947
948       // Ignore targets that aren't part of OutlinedHandlerFn.
949       if (!LPadTargetBlocks.count(BA->getBasicBlock()))
950         continue;
951
952       // If the return value is the address ofF a block that we
953       // previously outlined into the parent handler function, replace
954       // the return instruction and add the mapped target to the list
955       // of possible return addresses.
956       BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
957       assert(MappedBB->getParent() == OutlinedHandlerFn);
958       BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
959       Ret->eraseFromParent();
960       ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
961       ActionTargets.push_back(NewBA);
962     }
963   }
964   DeleteContainerPointers(ActionList);
965   ActionList.clear();
966   OutlinedBB->getInstList().push_back(EHActions);
967
968   // Insert an indirect branch into the outlined landing pad BB.
969   IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
970   // Add the previously collected action targets.
971   for (auto *Target : ActionTargets)
972     IBr->addDestination(Target->getBasicBlock());
973 }
974
975 // This function examines a block to determine whether the block ends with a
976 // conditional branch to a catch handler based on a selector comparison.
977 // This function is used both by the WinEHPrepare::findSelectorComparison() and
978 // WinEHCleanupDirector::handleTypeIdFor().
979 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
980                                Constant *&Selector, BasicBlock *&NextBB) {
981   ICmpInst::Predicate Pred;
982   BasicBlock *TBB, *FBB;
983   Value *LHS, *RHS;
984
985   if (!match(BB->getTerminator(),
986              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
987     return false;
988
989   if (!match(LHS,
990              m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
991       !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
992     return false;
993
994   if (Pred == CmpInst::ICMP_EQ) {
995     CatchHandler = TBB;
996     NextBB = FBB;
997     return true;
998   }
999
1000   if (Pred == CmpInst::ICMP_NE) {
1001     CatchHandler = FBB;
1002     NextBB = TBB;
1003     return true;
1004   }
1005
1006   return false;
1007 }
1008
1009 static bool isCatchBlock(BasicBlock *BB) {
1010   for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1011        II != IE; ++II) {
1012     if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1013       return true;
1014   }
1015   return false;
1016 }
1017
1018 static BasicBlock *createStubLandingPad(Function *Handler,
1019                                         Value *PersonalityFn) {
1020   // FIXME: Finish this!
1021   LLVMContext &Context = Handler->getContext();
1022   BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1023   Handler->getBasicBlockList().push_back(StubBB);
1024   IRBuilder<> Builder(StubBB);
1025   LandingPadInst *LPad = Builder.CreateLandingPad(
1026       llvm::StructType::get(Type::getInt8PtrTy(Context),
1027                             Type::getInt32Ty(Context), nullptr),
1028       PersonalityFn, 0);
1029   LPad->setCleanup(true);
1030   Builder.CreateUnreachable();
1031   return StubBB;
1032 }
1033
1034 // Cycles through the blocks in an outlined handler function looking for an
1035 // invoke instruction and inserts an invoke of llvm.donothing with an empty
1036 // landing pad if none is found.  The code that generates the .xdata tables for
1037 // the handler needs at least one landing pad to identify the parent function's
1038 // personality.
1039 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1040                                                   Value *PersonalityFn) {
1041   ReturnInst *Ret = nullptr;
1042   for (BasicBlock &BB : *Handler) {
1043     TerminatorInst *Terminator = BB.getTerminator();
1044     // If we find an invoke, there is nothing to be done.
1045     auto *II = dyn_cast<InvokeInst>(Terminator);
1046     if (II)
1047       return;
1048     // If we've already recorded a return instruction, keep looking for invokes.
1049     if (Ret)
1050       continue;
1051     // If we haven't recorded a return instruction yet, try this terminator.
1052     Ret = dyn_cast<ReturnInst>(Terminator);
1053   }
1054
1055   // If we got this far, the handler contains no invokes.  We should have seen
1056   // at least one return.  We'll insert an invoke of llvm.donothing ahead of
1057   // that return.
1058   assert(Ret);
1059   BasicBlock *OldRetBB = Ret->getParent();
1060   BasicBlock *NewRetBB = SplitBlock(OldRetBB, Ret);
1061   // SplitBlock adds an unconditional branch instruction at the end of the
1062   // parent block.  We want to replace that with an invoke call, so we can
1063   // erase it now.
1064   OldRetBB->getTerminator()->eraseFromParent();
1065   BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1066   Function *F =
1067       Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1068   InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1069 }
1070
1071 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1072                                   LandingPadInst *LPad, BasicBlock *StartBB,
1073                                   FrameVarInfoMap &VarInfo) {
1074   Module *M = SrcFn->getParent();
1075   LLVMContext &Context = M->getContext();
1076
1077   // Create a new function to receive the handler contents.
1078   Type *Int8PtrType = Type::getInt8PtrTy(Context);
1079   std::vector<Type *> ArgTys;
1080   ArgTys.push_back(Int8PtrType);
1081   ArgTys.push_back(Int8PtrType);
1082   Function *Handler;
1083   if (Action->getType() == Catch) {
1084     FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
1085     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1086                                SrcFn->getName() + ".catch", M);
1087   } else {
1088     FunctionType *FnType =
1089         FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
1090     Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1091                                SrcFn->getName() + ".cleanup", M);
1092   }
1093
1094   Handler->addFnAttr("wineh-parent", SrcFn->getName());
1095
1096   // Generate a standard prolog to setup the frame recovery structure.
1097   IRBuilder<> Builder(Context);
1098   BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1099   Handler->getBasicBlockList().push_front(Entry);
1100   Builder.SetInsertPoint(Entry);
1101   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1102
1103   std::unique_ptr<WinEHCloningDirectorBase> Director;
1104
1105   ValueToValueMapTy VMap;
1106
1107   LandingPadMap &LPadMap = LPadMaps[LPad];
1108   if (!LPadMap.isInitialized())
1109     LPadMap.mapLandingPad(LPad);
1110   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1111     Constant *Sel = CatchAction->getSelector();
1112     Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
1113                                           NestedLPtoOriginalLP));
1114     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1115                           ConstantInt::get(Type::getInt32Ty(Context), 1));
1116   } else {
1117     Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
1118     LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1119                           UndefValue::get(Type::getInt32Ty(Context)));
1120   }
1121
1122   SmallVector<ReturnInst *, 8> Returns;
1123   ClonedCodeInfo OutlinedFunctionInfo;
1124
1125   // If the start block contains PHI nodes, we need to map them.
1126   BasicBlock::iterator II = StartBB->begin();
1127   while (auto *PN = dyn_cast<PHINode>(II)) {
1128     bool Mapped = false;
1129     // Look for PHI values that we have already mapped (such as the selector).
1130     for (Value *Val : PN->incoming_values()) {
1131       if (VMap.count(Val)) {
1132         VMap[PN] = VMap[Val];
1133         Mapped = true;
1134       }
1135     }
1136     // If we didn't find a match for this value, map it as an undef.
1137     if (!Mapped) {
1138       VMap[PN] = UndefValue::get(PN->getType());
1139     }
1140     ++II;
1141   }
1142
1143   // The landing pad value may be used by PHI nodes.  It will ultimately be
1144   // eliminated, but we need it in the map for intermediate handling.
1145   VMap[LPad] = UndefValue::get(LPad->getType());
1146
1147   // Skip over PHIs and, if applicable, landingpad instructions.
1148   II = StartBB->getFirstInsertionPt();
1149
1150   CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
1151                             /*ModuleLevelChanges=*/false, Returns, "",
1152                             &OutlinedFunctionInfo, Director.get());
1153
1154   // Move all the instructions in the first cloned block into our entry block.
1155   BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
1156   Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
1157   FirstClonedBB->eraseFromParent();
1158
1159   // Make sure we can identify the handler's personality later.
1160   addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1161
1162   if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1163     WinEHCatchDirector *CatchDirector =
1164         reinterpret_cast<WinEHCatchDirector *>(Director.get());
1165     CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1166     CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
1167
1168     // Look for blocks that are not part of the landing pad that we just
1169     // outlined but terminate with a call to llvm.eh.endcatch and a
1170     // branch to a block that is in the handler we just outlined.
1171     // These blocks will be part of a nested landing pad that intends to
1172     // return to an address in this handler.  This case is best handled
1173     // after both landing pads have been outlined, so for now we'll just
1174     // save the association of the blocks in LPadTargetBlocks.  The
1175     // return instructions which are created from these branches will be
1176     // replaced after all landing pads have been outlined.
1177     for (const auto MapEntry : VMap) {
1178       // VMap maps all values and blocks that were just cloned, but dead
1179       // blocks which were pruned will map to nullptr.
1180       if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1181         continue;
1182       const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1183       for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1184         auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1185         if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1186           continue;
1187         BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1188         --II;
1189         if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1190           // This would indicate that a nested landing pad wants to return
1191           // to a block that is outlined into two different handlers.
1192           assert(!LPadTargetBlocks.count(MappedBB));
1193           LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1194         }
1195       }
1196     }
1197   } // End if (CatchAction)
1198
1199   Action->setHandlerBlockOrFunc(Handler);
1200
1201   return true;
1202 }
1203
1204 /// This BB must end in a selector dispatch. All we need to do is pass the
1205 /// handler block to llvm.eh.actions and list it as a possible indirectbr
1206 /// target.
1207 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1208                                           BasicBlock *StartBB) {
1209   BasicBlock *HandlerBB;
1210   BasicBlock *NextBB;
1211   Constant *Selector;
1212   bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1213   if (Res) {
1214     // If this was EH dispatch, this must be a conditional branch to the handler
1215     // block.
1216     // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1217     // leading to crashes if some optimization hoists stuff here.
1218     assert(CatchAction->getSelector() && HandlerBB &&
1219            "expected catch EH dispatch");
1220   } else {
1221     // This must be a catch-all. Split the block after the landingpad.
1222     assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1223     HandlerBB =
1224         StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
1225   }
1226   CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1227   TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1228   CatchAction->setReturnTargets(Targets);
1229 }
1230
1231 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1232   // Each instance of this class should only ever be used to map a single
1233   // landing pad.
1234   assert(OriginLPad == nullptr || OriginLPad == LPad);
1235
1236   // If the landing pad has already been mapped, there's nothing more to do.
1237   if (OriginLPad == LPad)
1238     return;
1239
1240   OriginLPad = LPad;
1241
1242   // The landingpad instruction returns an aggregate value.  Typically, its
1243   // value will be passed to a pair of extract value instructions and the
1244   // results of those extracts will have been promoted to reg values before
1245   // this routine is called.
1246   for (auto *U : LPad->users()) {
1247     const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1248     if (!Extract)
1249       continue;
1250     assert(Extract->getNumIndices() == 1 &&
1251            "Unexpected operation: extracting both landing pad values");
1252     unsigned int Idx = *(Extract->idx_begin());
1253     assert((Idx == 0 || Idx == 1) &&
1254            "Unexpected operation: extracting an unknown landing pad element");
1255     if (Idx == 0) {
1256       ExtractedEHPtrs.push_back(Extract);
1257     } else if (Idx == 1) {
1258       ExtractedSelectors.push_back(Extract);
1259     }
1260   }
1261 }
1262
1263 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1264   return BB->getLandingPadInst() == OriginLPad;
1265 }
1266
1267 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1268   if (Inst == OriginLPad)
1269     return true;
1270   for (auto *Extract : ExtractedEHPtrs) {
1271     if (Inst == Extract)
1272       return true;
1273   }
1274   for (auto *Extract : ExtractedSelectors) {
1275     if (Inst == Extract)
1276       return true;
1277   }
1278   return false;
1279 }
1280
1281 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1282                                   Value *SelectorValue) const {
1283   // Remap all landing pad extract instructions to the specified values.
1284   for (auto *Extract : ExtractedEHPtrs)
1285     VMap[Extract] = EHPtrValue;
1286   for (auto *Extract : ExtractedSelectors)
1287     VMap[Extract] = SelectorValue;
1288 }
1289
1290 static bool isFrameAddressCall(const Value *V) {
1291   return match(const_cast<Value *>(V),
1292                m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1293 }
1294
1295 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1296     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1297   // If this is one of the boilerplate landing pad instructions, skip it.
1298   // The instruction will have already been remapped in VMap.
1299   if (LPadMap.isLandingPadSpecificInst(Inst))
1300     return CloningDirector::SkipInstruction;
1301
1302   // Nested landing pads will be cloned as stubs, with just the
1303   // landingpad instruction and an unreachable instruction. When
1304   // all landingpads have been outlined, we'll replace this with the
1305   // llvm.eh.actions call and indirect branch created when the
1306   // landing pad was outlined.
1307   if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1308     return handleLandingPad(VMap, LPad, NewBB);
1309   }
1310
1311   if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1312     return handleInvoke(VMap, Invoke, NewBB);
1313
1314   if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1315     return handleResume(VMap, Resume, NewBB);
1316
1317   if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1318     return handleCompare(VMap, Cmp, NewBB);
1319
1320   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1321     return handleBeginCatch(VMap, Inst, NewBB);
1322   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1323     return handleEndCatch(VMap, Inst, NewBB);
1324   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1325     return handleTypeIdFor(VMap, Inst, NewBB);
1326
1327   // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1328   // which is the FP of the parent.
1329   if (isFrameAddressCall(Inst)) {
1330     VMap[Inst] = EstablisherFrame;
1331     return CloningDirector::SkipInstruction;
1332   }
1333
1334   // Continue with the default cloning behavior.
1335   return CloningDirector::CloneInstruction;
1336 }
1337
1338 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1339     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1340   Instruction *NewInst = LPad->clone();
1341   if (LPad->hasName())
1342     NewInst->setName(LPad->getName());
1343   // Save this correlation for later processing.
1344   NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1345   VMap[LPad] = NewInst;
1346   BasicBlock::InstListType &InstList = NewBB->getInstList();
1347   InstList.push_back(NewInst);
1348   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1349   return CloningDirector::StopCloningBB;
1350 }
1351
1352 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1353     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1354   // The argument to the call is some form of the first element of the
1355   // landingpad aggregate value, but that doesn't matter.  It isn't used
1356   // here.
1357   // The second argument is an outparameter where the exception object will be
1358   // stored. Typically the exception object is a scalar, but it can be an
1359   // aggregate when catching by value.
1360   // FIXME: Leave something behind to indicate where the exception object lives
1361   // for this handler. Should it be part of llvm.eh.actions?
1362   assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1363                                           "llvm.eh.begincatch found while "
1364                                           "outlining catch handler.");
1365   ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1366   if (isa<ConstantPointerNull>(ExceptionObjectVar))
1367     return CloningDirector::SkipInstruction;
1368   assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1369          "catch parameter is not static alloca");
1370   Materializer.escapeCatchObject(ExceptionObjectVar);
1371   return CloningDirector::SkipInstruction;
1372 }
1373
1374 CloningDirector::CloningAction
1375 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1376                                    const Instruction *Inst, BasicBlock *NewBB) {
1377   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1378   // It might be interesting to track whether or not we are inside a catch
1379   // function, but that might make the algorithm more brittle than it needs
1380   // to be.
1381
1382   // The end catch call can occur in one of two places: either in a
1383   // landingpad block that is part of the catch handlers exception mechanism,
1384   // or at the end of the catch block.  However, a catch-all handler may call
1385   // end catch from the original landing pad.  If the call occurs in a nested
1386   // landing pad block, we must skip it and continue so that the landing pad
1387   // gets cloned.
1388   auto *ParentBB = IntrinCall->getParent();
1389   if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1390     return CloningDirector::SkipInstruction;
1391
1392   // If an end catch occurs anywhere else we want to terminate the handler
1393   // with a return to the code that follows the endcatch call.  If the
1394   // next instruction is not an unconditional branch, we need to split the
1395   // block to provide a clear target for the return instruction.
1396   BasicBlock *ContinueBB;
1397   auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1398   const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1399   if (!Branch || !Branch->isUnconditional()) {
1400     // We're interrupting the cloning process at this location, so the
1401     // const_cast we're doing here will not cause a problem.
1402     ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1403                             const_cast<Instruction *>(cast<Instruction>(Next)));
1404   } else {
1405     ContinueBB = Branch->getSuccessor(0);
1406   }
1407
1408   ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1409   ReturnTargets.push_back(ContinueBB);
1410
1411   // We just added a terminator to the cloned block.
1412   // Tell the caller to stop processing the current basic block so that
1413   // the branch instruction will be skipped.
1414   return CloningDirector::StopCloningBB;
1415 }
1416
1417 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1418     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1419   auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1420   Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1421   // This causes a replacement that will collapse the landing pad CFG based
1422   // on the filter function we intend to match.
1423   if (Selector == CurrentSelector)
1424     VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1425   else
1426     VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1427   // Tell the caller not to clone this instruction.
1428   return CloningDirector::SkipInstruction;
1429 }
1430
1431 CloningDirector::CloningAction
1432 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1433                                  const InvokeInst *Invoke, BasicBlock *NewBB) {
1434   return CloningDirector::CloneInstruction;
1435 }
1436
1437 CloningDirector::CloningAction
1438 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1439                                  const ResumeInst *Resume, BasicBlock *NewBB) {
1440   // Resume instructions shouldn't be reachable from catch handlers.
1441   // We still need to handle it, but it will be pruned.
1442   BasicBlock::InstListType &InstList = NewBB->getInstList();
1443   InstList.push_back(new UnreachableInst(NewBB->getContext()));
1444   return CloningDirector::StopCloningBB;
1445 }
1446
1447 CloningDirector::CloningAction
1448 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1449                                   const CmpInst *Compare, BasicBlock *NewBB) {
1450   const IntrinsicInst *IntrinCall = nullptr;
1451   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1452     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1453   } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1454     IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1455   }
1456   if (IntrinCall) {
1457     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1458     // This causes a replacement that will collapse the landing pad CFG based
1459     // on the filter function we intend to match.
1460     if (Selector == CurrentSelector->stripPointerCasts()) {
1461       VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1462     }
1463     else {
1464       VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1465     }
1466     return CloningDirector::SkipInstruction;
1467   }
1468   return CloningDirector::CloneInstruction;
1469 }
1470
1471 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1472     ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1473   // The MS runtime will terminate the process if an exception occurs in a
1474   // cleanup handler, so we shouldn't encounter landing pads in the actual
1475   // cleanup code, but they may appear in catch blocks.  Depending on where
1476   // we started cloning we may see one, but it will get dropped during dead
1477   // block pruning.
1478   Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1479   VMap[LPad] = NewInst;
1480   BasicBlock::InstListType &InstList = NewBB->getInstList();
1481   InstList.push_back(NewInst);
1482   return CloningDirector::StopCloningBB;
1483 }
1484
1485 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1486     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1487   // Cleanup code may flow into catch blocks or the catch block may be part
1488   // of a branch that will be optimized away.  We'll insert a return
1489   // instruction now, but it may be pruned before the cloning process is
1490   // complete.
1491   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1492   return CloningDirector::StopCloningBB;
1493 }
1494
1495 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1496     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1497   // Cleanup handlers nested within catch handlers may begin with a call to
1498   // eh.endcatch.  We can just ignore that instruction.
1499   return CloningDirector::SkipInstruction;
1500 }
1501
1502 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1503     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1504   // If we encounter a selector comparison while cloning a cleanup handler,
1505   // we want to stop cloning immediately.  Anything after the dispatch
1506   // will be outlined into a different handler.
1507   BasicBlock *CatchHandler;
1508   Constant *Selector;
1509   BasicBlock *NextBB;
1510   if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1511                          CatchHandler, Selector, NextBB)) {
1512     ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1513     return CloningDirector::StopCloningBB;
1514   }
1515   // If eg.typeid.for is called for any other reason, it can be ignored.
1516   VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1517   return CloningDirector::SkipInstruction;
1518 }
1519
1520 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1521     ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1522   // All invokes in cleanup handlers can be replaced with calls.
1523   SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1524   // Insert a normal call instruction...
1525   CallInst *NewCall =
1526       CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1527                        Invoke->getName(), NewBB);
1528   NewCall->setCallingConv(Invoke->getCallingConv());
1529   NewCall->setAttributes(Invoke->getAttributes());
1530   NewCall->setDebugLoc(Invoke->getDebugLoc());
1531   VMap[Invoke] = NewCall;
1532
1533   // Remap the operands.
1534   llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1535
1536   // Insert an unconditional branch to the normal destination.
1537   BranchInst::Create(Invoke->getNormalDest(), NewBB);
1538
1539   // The unwind destination won't be cloned into the new function, so
1540   // we don't need to clean up its phi nodes.
1541
1542   // We just added a terminator to the cloned block.
1543   // Tell the caller to stop processing the current basic block.
1544   return CloningDirector::CloneSuccessors;
1545 }
1546
1547 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1548     ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1549   ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1550
1551   // We just added a terminator to the cloned block.
1552   // Tell the caller to stop processing the current basic block so that
1553   // the branch instruction will be skipped.
1554   return CloningDirector::StopCloningBB;
1555 }
1556
1557 CloningDirector::CloningAction
1558 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1559                                     const CmpInst *Compare, BasicBlock *NewBB) {
1560   if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1561       match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1562     VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1563     return CloningDirector::SkipInstruction;
1564   }
1565   return CloningDirector::CloneInstruction;
1566
1567 }
1568
1569 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1570     Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1571     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1572   BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1573   Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1574 }
1575
1576 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1577   // If we're asked to materialize a static alloca, we temporarily create an
1578   // alloca in the outlined function and add this to the FrameVarInfo map.  When
1579   // all the outlining is complete, we'll replace these temporary allocas with
1580   // calls to llvm.framerecover.
1581   if (auto *AV = dyn_cast<AllocaInst>(V)) {
1582     assert(AV->isStaticAlloca() &&
1583            "cannot materialize un-demoted dynamic alloca");
1584     AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1585     Builder.Insert(NewAlloca, AV->getName());
1586     FrameVarInfo[AV].push_back(NewAlloca);
1587     return NewAlloca;
1588   }
1589
1590   if (isa<Instruction>(V) || isa<Argument>(V)) {
1591     errs() << "Failed to demote instruction used in exception handler:\n";
1592     errs() << "  " << *V << '\n';
1593     report_fatal_error("WinEHPrepare failed to demote instruction");
1594   }
1595
1596   // Don't materialize other values.
1597   return nullptr;
1598 }
1599
1600 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1601   // Catch parameter objects have to live in the parent frame. When we see a use
1602   // of a catch parameter, add a sentinel to the multimap to indicate that it's
1603   // used from another handler. This will prevent us from trying to sink the
1604   // alloca into the handler and ensure that the catch parameter is present in
1605   // the call to llvm.frameescape.
1606   FrameVarInfo[V].push_back(getCatchObjectSentinel());
1607 }
1608
1609 // This function maps the catch and cleanup handlers that are reachable from the
1610 // specified landing pad. The landing pad sequence will have this basic shape:
1611 //
1612 //  <cleanup handler>
1613 //  <selector comparison>
1614 //  <catch handler>
1615 //  <cleanup handler>
1616 //  <selector comparison>
1617 //  <catch handler>
1618 //  <cleanup handler>
1619 //  ...
1620 //
1621 // Any of the cleanup slots may be absent.  The cleanup slots may be occupied by
1622 // any arbitrary control flow, but all paths through the cleanup code must
1623 // eventually reach the next selector comparison and no path can skip to a
1624 // different selector comparisons, though some paths may terminate abnormally.
1625 // Therefore, we will use a depth first search from the start of any given
1626 // cleanup block and stop searching when we find the next selector comparison.
1627 //
1628 // If the landingpad instruction does not have a catch clause, we will assume
1629 // that any instructions other than selector comparisons and catch handlers can
1630 // be ignored.  In practice, these will only be the boilerplate instructions.
1631 //
1632 // The catch handlers may also have any control structure, but we are only
1633 // interested in the start of the catch handlers, so we don't need to actually
1634 // follow the flow of the catch handlers.  The start of the catch handlers can
1635 // be located from the compare instructions, but they can be skipped in the
1636 // flow by following the contrary branch.
1637 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1638                                        LandingPadActions &Actions) {
1639   unsigned int NumClauses = LPad->getNumClauses();
1640   unsigned int HandlersFound = 0;
1641   BasicBlock *BB = LPad->getParent();
1642
1643   DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1644
1645   if (NumClauses == 0) {
1646     findCleanupHandlers(Actions, BB, nullptr);
1647     return;
1648   }
1649
1650   VisitedBlockSet VisitedBlocks;
1651
1652   while (HandlersFound != NumClauses) {
1653     BasicBlock *NextBB = nullptr;
1654
1655     // See if the clause we're looking for is a catch-all.
1656     // If so, the catch begins immediately.
1657     Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1658     if (isa<ConstantPointerNull>(ExpectedSelector)) {
1659       // The catch all must occur last.
1660       assert(HandlersFound == NumClauses - 1);
1661
1662       // There can be additional selector dispatches in the call chain that we
1663       // need to ignore.
1664       BasicBlock *CatchBlock = nullptr;
1665       Constant *Selector;
1666       while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1667         DEBUG(dbgs() << "  Found extra catch dispatch in block "
1668           << CatchBlock->getName() << "\n");
1669         BB = NextBB;
1670       }
1671
1672       // For C++ EH, check if there is any interesting cleanup code before we
1673       // begin the catch. This is important because cleanups cannot rethrow
1674       // exceptions but code called from catches can. For SEH, it isn't
1675       // important if some finally code before a catch-all is executed out of
1676       // line or after recovering from the exception.
1677       if (Personality == EHPersonality::MSVC_CXX)
1678         findCleanupHandlers(Actions, BB, BB);
1679
1680       // Add the catch handler to the action list.
1681       CatchHandler *Action = nullptr;
1682       if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1683         // If the CatchHandlerMap already has an entry for this BB, re-use it.
1684         Action = CatchHandlerMap[BB];
1685         assert(Action->getSelector() == ExpectedSelector);
1686       } else {
1687         // Since this is a catch-all handler, the selector won't actually appear
1688         // in the code anywhere.  ExpectedSelector here is the constant null ptr
1689         // that we got from the landing pad instruction.
1690         Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1691         CatchHandlerMap[BB] = Action;
1692       }
1693       Actions.insertCatchHandler(Action);
1694       DEBUG(dbgs() << "  Catch all handler at block " << BB->getName() << "\n");
1695       ++HandlersFound;
1696
1697       // Once we reach a catch-all, don't expect to hit a resume instruction.
1698       BB = nullptr;
1699       break;
1700     }
1701
1702     CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1703     assert(CatchAction);
1704
1705     // See if there is any interesting code executed before the dispatch.
1706     findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1707
1708     // When the source program contains multiple nested try blocks the catch
1709     // handlers can get strung together in such a way that we can encounter
1710     // a dispatch for a selector that we've already had a handler for.
1711     if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1712       ++HandlersFound;
1713
1714       // Add the catch handler to the action list.
1715       DEBUG(dbgs() << "  Found catch dispatch in block "
1716                    << CatchAction->getStartBlock()->getName() << "\n");
1717       Actions.insertCatchHandler(CatchAction);
1718     } else {
1719       // Under some circumstances optimized IR will flow unconditionally into a
1720       // handler block without checking the selector.  This can only happen if
1721       // the landing pad has a catch-all handler and the handler for the
1722       // preceeding catch clause is identical to the catch-call handler
1723       // (typically an empty catch).  In this case, the handler must be shared
1724       // by all remaining clauses.
1725       if (isa<ConstantPointerNull>(
1726               CatchAction->getSelector()->stripPointerCasts())) {
1727         DEBUG(dbgs() << "  Applying early catch-all handler in block "
1728                      << CatchAction->getStartBlock()->getName()
1729                      << "  to all remaining clauses.\n");
1730         Actions.insertCatchHandler(CatchAction);
1731         return;
1732       }
1733
1734       DEBUG(dbgs() << "  Found extra catch dispatch in block "
1735                    << CatchAction->getStartBlock()->getName() << "\n");
1736     }
1737
1738     // Move on to the block after the catch handler.
1739     BB = NextBB;
1740   }
1741
1742   // If we didn't wind up in a catch-all, see if there is any interesting code
1743   // executed before the resume.
1744   findCleanupHandlers(Actions, BB, BB);
1745
1746   // It's possible that some optimization moved code into a landingpad that
1747   // wasn't
1748   // previously being used for cleanup.  If that happens, we need to execute
1749   // that
1750   // extra code from a cleanup handler.
1751   if (Actions.includesCleanup() && !LPad->isCleanup())
1752     LPad->setCleanup(true);
1753 }
1754
1755 // This function searches starting with the input block for the next
1756 // block that terminates with a branch whose condition is based on a selector
1757 // comparison.  This may be the input block.  See the mapLandingPadBlocks
1758 // comments for a discussion of control flow assumptions.
1759 //
1760 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1761                                              BasicBlock *&NextBB,
1762                                              VisitedBlockSet &VisitedBlocks) {
1763   // See if we've already found a catch handler use it.
1764   // Call count() first to avoid creating a null entry for blocks
1765   // we haven't seen before.
1766   if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1767     CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1768     NextBB = Action->getNextBB();
1769     return Action;
1770   }
1771
1772   // VisitedBlocks applies only to the current search.  We still
1773   // need to consider blocks that we've visited while mapping other
1774   // landing pads.
1775   VisitedBlocks.insert(BB);
1776
1777   BasicBlock *CatchBlock = nullptr;
1778   Constant *Selector = nullptr;
1779
1780   // If this is the first time we've visited this block from any landing pad
1781   // look to see if it is a selector dispatch block.
1782   if (!CatchHandlerMap.count(BB)) {
1783     if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1784       CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1785       CatchHandlerMap[BB] = Action;
1786       return Action;
1787     }
1788     // If we encounter a block containing an llvm.eh.begincatch before we
1789     // find a selector dispatch block, the handler is assumed to be
1790     // reached unconditionally.  This happens for catch-all blocks, but
1791     // it can also happen for other catch handlers that have been combined
1792     // with the catch-all handler during optimization.
1793     if (isCatchBlock(BB)) {
1794       PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1795       Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1796       CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1797       CatchHandlerMap[BB] = Action;
1798       return Action;
1799     }
1800   }
1801
1802   // Visit each successor, looking for the dispatch.
1803   // FIXME: We expect to find the dispatch quickly, so this will probably
1804   //        work better as a breadth first search.
1805   for (BasicBlock *Succ : successors(BB)) {
1806     if (VisitedBlocks.count(Succ))
1807       continue;
1808
1809     CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1810     if (Action)
1811       return Action;
1812   }
1813   return nullptr;
1814 }
1815
1816 // These are helper functions to combine repeated code from findCleanupHandlers.
1817 static void createCleanupHandler(LandingPadActions &Actions,
1818                                  CleanupHandlerMapTy &CleanupHandlerMap,
1819                                  BasicBlock *BB) {
1820   CleanupHandler *Action = new CleanupHandler(BB);
1821   CleanupHandlerMap[BB] = Action;
1822   Actions.insertCleanupHandler(Action);
1823   DEBUG(dbgs() << "  Found cleanup code in block "
1824                << Action->getStartBlock()->getName() << "\n");
1825 }
1826
1827 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1828                                          Instruction *MaybeCall) {
1829   // Look for finally blocks that Clang has already outlined for us.
1830   //   %fp = call i8* @llvm.frameaddress(i32 0)
1831   //   call void @"fin$parent"(iN 1, i8* %fp)
1832   if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1833     MaybeCall = MaybeCall->getNextNode();
1834   CallSite FinallyCall(MaybeCall);
1835   if (!FinallyCall || FinallyCall.arg_size() != 2)
1836     return CallSite();
1837   if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1838     return CallSite();
1839   if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1840     return CallSite();
1841   return FinallyCall;
1842 }
1843
1844 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1845   // Skip single ubr blocks.
1846   while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1847     auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1848     if (Br && Br->isUnconditional())
1849       BB = Br->getSuccessor(0);
1850     else
1851       return BB;
1852   }
1853   return BB;
1854 }
1855
1856 // This function searches starting with the input block for the next block that
1857 // contains code that is not part of a catch handler and would not be eliminated
1858 // during handler outlining.
1859 //
1860 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1861                                        BasicBlock *StartBB, BasicBlock *EndBB) {
1862   // Here we will skip over the following:
1863   //
1864   // landing pad prolog:
1865   //
1866   // Unconditional branches
1867   //
1868   // Selector dispatch
1869   //
1870   // Resume pattern
1871   //
1872   // Anything else marks the start of an interesting block
1873
1874   BasicBlock *BB = StartBB;
1875   // Anything other than an unconditional branch will kick us out of this loop
1876   // one way or another.
1877   while (BB) {
1878     BB = followSingleUnconditionalBranches(BB);
1879     // If we've already scanned this block, don't scan it again.  If it is
1880     // a cleanup block, there will be an action in the CleanupHandlerMap.
1881     // If we've scanned it and it is not a cleanup block, there will be a
1882     // nullptr in the CleanupHandlerMap.  If we have not scanned it, there will
1883     // be no entry in the CleanupHandlerMap.  We must call count() first to
1884     // avoid creating a null entry for blocks we haven't scanned.
1885     if (CleanupHandlerMap.count(BB)) {
1886       if (auto *Action = CleanupHandlerMap[BB]) {
1887         Actions.insertCleanupHandler(Action);
1888         DEBUG(dbgs() << "  Found cleanup code in block "
1889               << Action->getStartBlock()->getName() << "\n");
1890         // FIXME: This cleanup might chain into another, and we need to discover
1891         // that.
1892         return;
1893       } else {
1894         // Here we handle the case where the cleanup handler map contains a
1895         // value for this block but the value is a nullptr.  This means that
1896         // we have previously analyzed the block and determined that it did
1897         // not contain any cleanup code.  Based on the earlier analysis, we
1898         // know the the block must end in either an unconditional branch, a
1899         // resume or a conditional branch that is predicated on a comparison
1900         // with a selector.  Either the resume or the selector dispatch
1901         // would terminate the search for cleanup code, so the unconditional
1902         // branch is the only case for which we might need to continue
1903         // searching.
1904         BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1905         if (SuccBB == BB || SuccBB == EndBB)
1906           return;
1907         BB = SuccBB;
1908         continue;
1909       }
1910     }
1911
1912     // Create an entry in the cleanup handler map for this block.  Initially
1913     // we create an entry that says this isn't a cleanup block.  If we find
1914     // cleanup code, the caller will replace this entry.
1915     CleanupHandlerMap[BB] = nullptr;
1916
1917     TerminatorInst *Terminator = BB->getTerminator();
1918
1919     // Landing pad blocks have extra instructions we need to accept.
1920     LandingPadMap *LPadMap = nullptr;
1921     if (BB->isLandingPad()) {
1922       LandingPadInst *LPad = BB->getLandingPadInst();
1923       LPadMap = &LPadMaps[LPad];
1924       if (!LPadMap->isInitialized())
1925         LPadMap->mapLandingPad(LPad);
1926     }
1927
1928     // Look for the bare resume pattern:
1929     //   %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1930     //   %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1931     //   resume { i8*, i32 } %lpad.val2
1932     if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1933       InsertValueInst *Insert1 = nullptr;
1934       InsertValueInst *Insert2 = nullptr;
1935       Value *ResumeVal = Resume->getOperand(0);
1936       // If the resume value isn't a phi or landingpad value, it should be a
1937       // series of insertions. Identify them so we can avoid them when scanning
1938       // for cleanups.
1939       if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1940         Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1941         if (!Insert2)
1942           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1943         Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1944         if (!Insert1)
1945           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1946       }
1947       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1948            II != IE; ++II) {
1949         Instruction *Inst = II;
1950         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1951           continue;
1952         if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1953           continue;
1954         if (!Inst->hasOneUse() ||
1955             (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1956           return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1957         }
1958       }
1959       return;
1960     }
1961
1962     BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1963     if (Branch && Branch->isConditional()) {
1964       // Look for the selector dispatch.
1965       //   %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1966       //   %matches = icmp eq i32 %sel, %2
1967       //   br i1 %matches, label %catch14, label %eh.resume
1968       CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1969       if (!Compare || !Compare->isEquality())
1970         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1971       for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1972            II != IE; ++II) {
1973         Instruction *Inst = II;
1974         if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1975           continue;
1976         if (Inst == Compare || Inst == Branch)
1977           continue;
1978         if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1979           continue;
1980         return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1981       }
1982       // The selector dispatch block should always terminate our search.
1983       assert(BB == EndBB);
1984       return;
1985     }
1986
1987     if (isAsynchronousEHPersonality(Personality)) {
1988       // If this is a landingpad block, split the block at the first non-landing
1989       // pad instruction.
1990       Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1991       if (LPadMap) {
1992         while (MaybeCall != BB->getTerminator() &&
1993                LPadMap->isLandingPadSpecificInst(MaybeCall))
1994           MaybeCall = MaybeCall->getNextNode();
1995       }
1996
1997       // Look for outlined finally calls.
1998       if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
1999         Function *Fin = FinallyCall.getCalledFunction();
2000         assert(Fin && "outlined finally call should be direct");
2001         auto *Action = new CleanupHandler(BB);
2002         Action->setHandlerBlockOrFunc(Fin);
2003         Actions.insertCleanupHandler(Action);
2004         CleanupHandlerMap[BB] = Action;
2005         DEBUG(dbgs() << "  Found frontend-outlined finally call to "
2006                      << Fin->getName() << " in block "
2007                      << Action->getStartBlock()->getName() << "\n");
2008
2009         // Split the block if there were more interesting instructions and look
2010         // for finally calls in the normal successor block.
2011         BasicBlock *SuccBB = BB;
2012         if (FinallyCall.getInstruction() != BB->getTerminator() &&
2013             FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
2014           SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
2015         } else {
2016           if (FinallyCall.isInvoke()) {
2017             SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2018           } else {
2019             SuccBB = BB->getUniqueSuccessor();
2020             assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
2021           }
2022         }
2023         BB = SuccBB;
2024         if (BB == EndBB)
2025           return;
2026         continue;
2027       }
2028     }
2029
2030     // Anything else is either a catch block or interesting cleanup code.
2031     for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2032          II != IE; ++II) {
2033       Instruction *Inst = II;
2034       if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2035         continue;
2036       // Unconditional branches fall through to this loop.
2037       if (Inst == Branch)
2038         continue;
2039       // If this is a catch block, there is no cleanup code to be found.
2040       if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
2041         return;
2042       // If this a nested landing pad, it may contain an endcatch call.
2043       if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
2044         return;
2045       // Anything else makes this interesting cleanup code.
2046       return createCleanupHandler(Actions, CleanupHandlerMap, BB);
2047     }
2048
2049     // Only unconditional branches in empty blocks should get this far.
2050     assert(Branch && Branch->isUnconditional());
2051     if (BB == EndBB)
2052       return;
2053     BB = Branch->getSuccessor(0);
2054   }
2055 }
2056
2057 // This is a public function, declared in WinEHFuncInfo.h and is also
2058 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2059 void llvm::parseEHActions(const IntrinsicInst *II,
2060                           SmallVectorImpl<ActionHandler *> &Actions) {
2061   for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2062     uint64_t ActionKind =
2063         cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
2064     if (ActionKind == /*catch=*/1) {
2065       auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2066       ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2067       int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2068       Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2069       I += 4;
2070       auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2071       CH->setHandlerBlockOrFunc(Handler);
2072       CH->setExceptionVarIndex(EHObjIndexVal);
2073       Actions.push_back(CH);
2074     } else if (ActionKind == 0) {
2075       Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2076       I += 2;
2077       auto *CH = new CleanupHandler(/*BB=*/nullptr);
2078       CH->setHandlerBlockOrFunc(Handler);
2079       Actions.push_back(CH);
2080     } else {
2081       llvm_unreachable("Expected either a catch or cleanup handler!");
2082     }
2083   }
2084   std::reverse(Actions.begin(), Actions.end());
2085 }