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