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