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