Fixing a problem with insert location in WinEH outlining
[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/TinyPtrVector.h"
20 #include "llvm/Analysis/LibCallSemantics.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include <memory>
31
32 using namespace llvm;
33 using namespace llvm::PatternMatch;
34
35 #define DEBUG_TYPE "winehprepare"
36
37 namespace {
38
39 struct HandlerAllocas {
40   TinyPtrVector<AllocaInst *> Allocas;
41   int ParentFrameAllocationIndex;
42 };
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<AllocaInst *, HandlerAllocas> FrameVarInfoMap;
50
51 class WinEHPrepare : public FunctionPass {
52   std::unique_ptr<FunctionPass> DwarfPrepare;
53
54 public:
55   static char ID; // Pass identification, replacement for typeid.
56   WinEHPrepare(const TargetMachine *TM = nullptr)
57       : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {}
58
59   bool runOnFunction(Function &Fn) override;
60
61   bool doFinalization(Module &M) override;
62
63   void getAnalysisUsage(AnalysisUsage &AU) const override;
64
65   const char *getPassName() const override {
66     return "Windows exception handling preparation";
67   }
68
69 private:
70   bool prepareCPPEHHandlers(Function &F,
71                             SmallVectorImpl<LandingPadInst *> &LPads);
72   bool outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
73                            LandingPadInst *LPad, CallInst *&EHAlloc,
74                            AllocaInst *&EHObjPtr, FrameVarInfoMap &VarInfo);
75 };
76
77 class WinEHFrameVariableMaterializer : public ValueMaterializer {
78 public:
79   WinEHFrameVariableMaterializer(Function *OutlinedFn,
80                                  FrameVarInfoMap &FrameVarInfo);
81   ~WinEHFrameVariableMaterializer() {}
82
83   virtual Value *materializeValueFor(Value *V) override;
84
85 private:
86   FrameVarInfoMap &FrameVarInfo;
87   IRBuilder<> Builder;
88 };
89
90 class WinEHCatchDirector : public CloningDirector {
91 public:
92   WinEHCatchDirector(LandingPadInst *LPI, Function *CatchFn, Value *Selector,
93                      Value *EHObj, FrameVarInfoMap &VarInfo)
94       : LPI(LPI), CurrentSelector(Selector->stripPointerCasts()), EHObj(EHObj),
95         Materializer(CatchFn, VarInfo),
96         SelectorIDType(Type::getInt32Ty(LPI->getContext())),
97         Int8PtrType(Type::getInt8PtrTy(LPI->getContext())) {}
98
99   CloningAction handleInstruction(ValueToValueMapTy &VMap,
100                                   const Instruction *Inst,
101                                   BasicBlock *NewBB) override;
102
103   ValueMaterializer *getValueMaterializer() override { return &Materializer; }
104
105 private:
106   LandingPadInst *LPI;
107   Value *CurrentSelector;
108   Value *EHObj;
109   WinEHFrameVariableMaterializer Materializer;
110   Type *SelectorIDType;
111   Type *Int8PtrType;
112
113   const Value *ExtractedEHPtr;
114   const Value *ExtractedSelector;
115   const Value *EHPtrStoreAddr;
116   const Value *SelectorStoreAddr;
117 };
118 } // end anonymous namespace
119
120 char WinEHPrepare::ID = 0;
121 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
122                    false, false)
123
124 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
125   return new WinEHPrepare(TM);
126 }
127
128 static bool isMSVCPersonality(EHPersonality Pers) {
129   return Pers == EHPersonality::MSVC_Win64SEH ||
130          Pers == EHPersonality::MSVC_CXX;
131 }
132
133 bool WinEHPrepare::runOnFunction(Function &Fn) {
134   SmallVector<LandingPadInst *, 4> LPads;
135   SmallVector<ResumeInst *, 4> Resumes;
136   for (BasicBlock &BB : Fn) {
137     if (auto *LP = BB.getLandingPadInst())
138       LPads.push_back(LP);
139     if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
140       Resumes.push_back(Resume);
141   }
142
143   // No need to prepare functions that lack landing pads.
144   if (LPads.empty())
145     return false;
146
147   // Classify the personality to see what kind of preparation we need.
148   EHPersonality Pers = classifyEHPersonality(LPads.back()->getPersonalityFn());
149
150   // Delegate through to the DWARF pass if this is unrecognized.
151   if (!isMSVCPersonality(Pers))
152     return DwarfPrepare->runOnFunction(Fn);
153
154   // FIXME: This only returns true if the C++ EH handlers were outlined.
155   //        When that code is complete, it should always return whatever
156   //        prepareCPPEHHandlers returns.
157   if (Pers == EHPersonality::MSVC_CXX && prepareCPPEHHandlers(Fn, LPads))
158     return true;
159
160   // FIXME: SEH Cleanups are unimplemented. Replace them with unreachable.
161   if (Resumes.empty())
162     return false;
163
164   for (ResumeInst *Resume : Resumes) {
165     IRBuilder<>(Resume).CreateUnreachable();
166     Resume->eraseFromParent();
167   }
168
169   return true;
170 }
171
172 bool WinEHPrepare::doFinalization(Module &M) {
173   return DwarfPrepare->doFinalization(M);
174 }
175
176 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
177   DwarfPrepare->getAnalysisUsage(AU);
178 }
179
180 bool WinEHPrepare::prepareCPPEHHandlers(
181     Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
182   // These containers are used to re-map frame variables that are used in
183   // outlined catch and cleanup handlers.  They will be populated as the
184   // handlers are outlined.
185   FrameVarInfoMap FrameVarInfo;
186   SmallVector<CallInst *, 4> HandlerAllocs;
187   SmallVector<AllocaInst *, 4> HandlerEHObjPtrs;
188
189   bool HandlersOutlined = false;
190
191   for (LandingPadInst *LPad : LPads) {
192     // Look for evidence that this landingpad has already been processed.
193     bool LPadHasActionList = false;
194     BasicBlock *LPadBB = LPad->getParent();
195     for (Instruction &Inst : LPadBB->getInstList()) {
196       // FIXME: Make this an intrinsic.
197       if (auto *Call = dyn_cast<CallInst>(&Inst))
198         if (Call->getCalledFunction()->getName() == "llvm.eh.actions") {
199           LPadHasActionList = true;
200           break;
201         }
202     }
203
204     // If we've already outlined the handlers for this landingpad,
205     // there's nothing more to do here.
206     if (LPadHasActionList)
207       continue;
208
209     for (unsigned Idx = 0, NumClauses = LPad->getNumClauses(); Idx < NumClauses;
210          ++Idx) {
211       if (LPad->isCatch(Idx)) {
212         // Create a new instance of the handler data structure in the
213         // HandlerData vector.
214         CallInst *EHAlloc = nullptr;
215         AllocaInst *EHObjPtr = nullptr;
216         bool Outlined = outlineCatchHandler(&F, LPad->getClause(Idx), LPad,
217                                             EHAlloc, EHObjPtr, FrameVarInfo);
218         if (Outlined) {
219           HandlersOutlined = true;
220           // These values must be resolved after all handlers have been
221           // outlined.
222           if (EHAlloc)
223             HandlerAllocs.push_back(EHAlloc);
224           if (EHObjPtr)
225             HandlerEHObjPtrs.push_back(EHObjPtr);
226         }
227       } // End if (isCatch)
228     }   // End for each clause
229   }     // End for each landingpad
230
231   // If nothing got outlined, there is no more processing to be done.
232   if (!HandlersOutlined)
233     return false;
234
235   // FIXME: We will replace the landingpad bodies with llvm.eh.actions
236   //        calls and indirect branches here and then delete blocks
237   //        which are no longer reachable.  That will get rid of the
238   //        handlers that we have outlined.  There is code below
239   //        that looks for allocas with no uses in the parent function.
240   //        That will only happen after the pruning is implemented.
241
242   // Remap the frame variables.
243   SmallVector<Type *, 2> StructTys;
244   StructTys.push_back(Type::getInt32Ty(F.getContext()));   // EH state
245   StructTys.push_back(Type::getInt8PtrTy(F.getContext())); // EH object
246
247   // Start the index at two since we always have the above fields at 0 and 1.
248   int Idx = 2;
249
250   // FIXME: Sort the FrameVarInfo vector by the ParentAlloca size and alignment
251   //        and add padding as necessary to provide the proper alignment.
252
253   // Map the alloca instructions to the corresponding index in the
254   // frame allocation structure.  If any alloca is used only in a single
255   // handler and is not used in the parent frame after outlining, it will
256   // be assigned an index of -1, meaning the handler can keep its
257   // "temporary" alloca and the original alloca can be erased from the
258   // parent function.  If we later encounter this alloca in a second
259   // handler, we will assign it a place in the frame allocation structure
260   // at that time.  Since the instruction replacement doesn't happen until
261   // all the entries in the HandlerData have been processed this isn't a
262   // problem.
263   for (auto &VarInfoEntry : FrameVarInfo) {
264     AllocaInst *ParentAlloca = VarInfoEntry.first;
265     HandlerAllocas &AllocaInfo = VarInfoEntry.second;
266
267     // If the instruction still has uses in the parent function or if it is
268     // referenced by more than one handler, add it to the frame allocation
269     // structure.
270     if (ParentAlloca->getNumUses() != 0 || AllocaInfo.Allocas.size() > 1) {
271       Type *VarTy = ParentAlloca->getAllocatedType();
272       StructTys.push_back(VarTy);
273       AllocaInfo.ParentFrameAllocationIndex = Idx++;
274     } else {
275       // If the variable is not used in the parent frame and it is only used
276       // in one handler, the alloca can be removed from the parent frame
277       // and the handler will keep its "temporary" alloca to define the value.
278       // An element index of -1 is used to indicate this condition.
279       AllocaInfo.ParentFrameAllocationIndex = -1;
280     }
281   }
282
283   // Having filled the StructTys vector and assigned an index to each element,
284   // we can now create the structure.
285   StructType *EHDataStructTy = StructType::create(
286       F.getContext(), StructTys, "struct." + F.getName().str() + ".ehdata");
287   IRBuilder<> Builder(F.getParent()->getContext());
288
289   // Create a frame allocation.
290   Module *M = F.getParent();
291   LLVMContext &Context = M->getContext();
292   BasicBlock *Entry = &F.getEntryBlock();
293   Builder.SetInsertPoint(Entry->getFirstInsertionPt());
294   Function *FrameAllocFn =
295       Intrinsic::getDeclaration(M, Intrinsic::frameallocate);
296   uint64_t EHAllocSize = M->getDataLayout()->getTypeAllocSize(EHDataStructTy);
297   Value *FrameAllocArgs[] = {
298       ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)};
299   CallInst *FrameAlloc =
300       Builder.CreateCall(FrameAllocFn, FrameAllocArgs, "frame.alloc");
301
302   Value *FrameEHData = Builder.CreateBitCast(
303       FrameAlloc, EHDataStructTy->getPointerTo(), "eh.data");
304
305   // Now visit each handler that is using the structure and bitcast its EHAlloc
306   // value to be a pointer to the frame alloc structure.
307   DenseMap<Function *, Value *> EHDataMap;
308   for (CallInst *EHAlloc : HandlerAllocs) {
309     // The EHAlloc has no uses at this time, so we need to just insert the
310     // cast before the next instruction. There is always a next instruction.
311     BasicBlock::iterator II = EHAlloc;
312     ++II;
313     Builder.SetInsertPoint(cast<Instruction>(II));
314     Value *EHData = Builder.CreateBitCast(
315         EHAlloc, EHDataStructTy->getPointerTo(), "eh.data");
316     EHDataMap[EHAlloc->getParent()->getParent()] = EHData;
317   }
318
319   // Next, replace the place-holder EHObjPtr allocas with GEP instructions
320   // that pull the EHObjPtr from the frame alloc structure
321   for (AllocaInst *EHObjPtr : HandlerEHObjPtrs) {
322     Value *EHData = EHDataMap[EHObjPtr->getParent()->getParent()];
323     Builder.SetInsertPoint(EHObjPtr);
324     Value *ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, 1);
325     EHObjPtr->replaceAllUsesWith(ElementPtr);
326     EHObjPtr->removeFromParent();
327     ElementPtr->takeName(EHObjPtr);
328     delete EHObjPtr;
329   }
330
331   // Finally, replace all of the temporary allocas for frame variables used in
332   // the outlined handlers and the original frame allocas with GEP instructions
333   // that get the equivalent pointer from the frame allocation struct.
334   for (auto &VarInfoEntry : FrameVarInfo) {
335     AllocaInst *ParentAlloca = VarInfoEntry.first;
336     HandlerAllocas &AllocaInfo = VarInfoEntry.second;
337     int Idx = AllocaInfo.ParentFrameAllocationIndex;
338
339     // If we have an index of -1 for this instruction, it means it isn't used
340     // outside of this handler.  In that case, we just keep the "temporary"
341     // alloca in the handler and erase the original alloca from the parent.
342     if (Idx == -1) {
343       ParentAlloca->eraseFromParent();
344     } else {
345       // Otherwise, we replace the parent alloca and all outlined allocas
346       // which map to it with GEP instructions.
347
348       // First replace the original alloca.
349       Builder.SetInsertPoint(ParentAlloca);
350       Builder.SetCurrentDebugLocation(ParentAlloca->getDebugLoc());
351       Value *ElementPtr =
352           Builder.CreateConstInBoundsGEP2_32(FrameEHData, 0, Idx);
353       ParentAlloca->replaceAllUsesWith(ElementPtr);
354       ParentAlloca->removeFromParent();
355       ElementPtr->takeName(ParentAlloca);
356       delete ParentAlloca;
357
358       // Next replace all outlined allocas that are mapped to it.
359       for (AllocaInst *TempAlloca : AllocaInfo.Allocas) {
360         Value *EHData = EHDataMap[TempAlloca->getParent()->getParent()];
361         // FIXME: Sink this GEP into the blocks where it is used.
362         Builder.SetInsertPoint(TempAlloca);
363         Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
364         ElementPtr = Builder.CreateConstInBoundsGEP2_32(EHData, 0, Idx);
365         TempAlloca->replaceAllUsesWith(ElementPtr);
366         TempAlloca->removeFromParent();
367         ElementPtr->takeName(TempAlloca);
368         delete TempAlloca;
369       }
370     } // end else of if (Idx == -1)
371   }   // End for each FrameVarInfo entry.
372
373   return HandlersOutlined;
374 }
375
376 bool WinEHPrepare::outlineCatchHandler(Function *SrcFn, Constant *SelectorType,
377                                        LandingPadInst *LPad, CallInst *&EHAlloc,
378                                        AllocaInst *&EHObjPtr,
379                                        FrameVarInfoMap &VarInfo) {
380   Module *M = SrcFn->getParent();
381   LLVMContext &Context = M->getContext();
382
383   // Create a new function to receive the handler contents.
384   Type *Int8PtrType = Type::getInt8PtrTy(Context);
385   std::vector<Type *> ArgTys;
386   ArgTys.push_back(Int8PtrType);
387   ArgTys.push_back(Int8PtrType);
388   FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
389   Function *CatchHandler = Function::Create(
390       FnType, GlobalVariable::ExternalLinkage, SrcFn->getName() + ".catch", M);
391
392   // Generate a standard prolog to setup the frame recovery structure.
393   IRBuilder<> Builder(Context);
394   BasicBlock *Entry = BasicBlock::Create(Context, "catch.entry");
395   CatchHandler->getBasicBlockList().push_front(Entry);
396   Builder.SetInsertPoint(Entry);
397   Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
398
399   // The outlined handler will be called with the parent's frame pointer as
400   // its second argument. To enable the handler to access variables from
401   // the parent frame, we use that pointer to get locate a special block
402   // of memory that was allocated using llvm.eh.allocateframe for this
403   // purpose.  During the outlining process we will determine which frame
404   // variables are used in handlers and create a structure that maps these
405   // variables into the frame allocation block.
406   //
407   // The frame allocation block also contains an exception state variable
408   // used by the runtime and a pointer to the exception object pointer
409   // which will be filled in by the runtime for use in the handler.
410   Function *RecoverFrameFn =
411       Intrinsic::getDeclaration(M, Intrinsic::framerecover);
412   Value *RecoverArgs[] = {Builder.CreateBitCast(SrcFn, Int8PtrType, ""),
413                           &(CatchHandler->getArgumentList().back())};
414   EHAlloc = Builder.CreateCall(RecoverFrameFn, RecoverArgs, "eh.alloc");
415
416   // This alloca is only temporary.  We'll be replacing it once we know all the
417   // frame variables that need to go in the frame allocation structure.
418   EHObjPtr = Builder.CreateAlloca(Int8PtrType, 0, "eh.obj.ptr");
419
420   // This will give us a raw pointer to the exception object, which
421   // corresponds to the formal parameter of the catch statement.  If the
422   // handler uses this object, we will generate code during the outlining
423   // process to cast the pointer to the appropriate type and deference it
424   // as necessary.  The un-outlined landing pad code represents the
425   // exception object as the result of the llvm.eh.begincatch call.
426   Value *EHObj = Builder.CreateLoad(EHObjPtr, false, "eh.obj");
427
428   ValueToValueMapTy VMap;
429
430   // FIXME: Map other values referenced in the filter handler.
431
432   WinEHCatchDirector Director(LPad, CatchHandler, SelectorType, EHObj, VarInfo);
433
434   SmallVector<ReturnInst *, 8> Returns;
435   ClonedCodeInfo InlinedFunctionInfo;
436
437   BasicBlock::iterator II = LPad;
438
439   CloneAndPruneIntoFromInst(CatchHandler, SrcFn, ++II, VMap,
440                             /*ModuleLevelChanges=*/false, Returns, "",
441                             &InlinedFunctionInfo,
442                             SrcFn->getParent()->getDataLayout(), &Director);
443
444   // Move all the instructions in the first cloned block into our entry block.
445   BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
446   Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
447   FirstClonedBB->eraseFromParent();
448
449   return true;
450 }
451
452 CloningDirector::CloningAction WinEHCatchDirector::handleInstruction(
453     ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
454   // Intercept instructions which extract values from the landing pad aggregate.
455   if (auto *Extract = dyn_cast<ExtractValueInst>(Inst)) {
456     if (Extract->getAggregateOperand() == LPI) {
457       assert(Extract->getNumIndices() == 1 &&
458              "Unexpected operation: extracting both landing pad values");
459       assert((*(Extract->idx_begin()) == 0 || *(Extract->idx_begin()) == 1) &&
460              "Unexpected operation: extracting an unknown landing pad element");
461
462       if (*(Extract->idx_begin()) == 0) {
463         // Element 0 doesn't directly corresponds to anything in the WinEH
464         // scheme.
465         // It will be stored to a memory location, then later loaded and finally
466         // the loaded value will be used as the argument to an
467         // llvm.eh.begincatch
468         // call.  We're tracking it here so that we can skip the store and load.
469         ExtractedEHPtr = Inst;
470       } else {
471         // Element 1 corresponds to the filter selector.  We'll map it to 1 for
472         // matching purposes, but it will also probably be stored to memory and
473         // reloaded, so we need to track the instuction so that we can map the
474         // loaded value too.
475         VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
476         ExtractedSelector = Inst;
477       }
478
479       // Tell the caller not to clone this instruction.
480       return CloningDirector::SkipInstruction;
481     }
482     // Other extract value instructions just get cloned.
483     return CloningDirector::CloneInstruction;
484   }
485
486   if (auto *Store = dyn_cast<StoreInst>(Inst)) {
487     // Look for and suppress stores of the extracted landingpad values.
488     const Value *StoredValue = Store->getValueOperand();
489     if (StoredValue == ExtractedEHPtr) {
490       EHPtrStoreAddr = Store->getPointerOperand();
491       return CloningDirector::SkipInstruction;
492     }
493     if (StoredValue == ExtractedSelector) {
494       SelectorStoreAddr = Store->getPointerOperand();
495       return CloningDirector::SkipInstruction;
496     }
497
498     // Any other store just gets cloned.
499     return CloningDirector::CloneInstruction;
500   }
501
502   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
503     // Look for loads of (previously suppressed) landingpad values.
504     // The EHPtr load can be ignored (it should only be used as
505     // an argument to llvm.eh.begincatch), but the selector value
506     // needs to be mapped to a constant value of 1 to be used to
507     // simplify the branching to always flow to the current handler.
508     const Value *LoadAddr = Load->getPointerOperand();
509     if (LoadAddr == EHPtrStoreAddr) {
510       VMap[Inst] = UndefValue::get(Int8PtrType);
511       return CloningDirector::SkipInstruction;
512     }
513     if (LoadAddr == SelectorStoreAddr) {
514       VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
515       return CloningDirector::SkipInstruction;
516     }
517
518     // Any other loads just get cloned.
519     return CloningDirector::CloneInstruction;
520   }
521
522   if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) {
523     // The argument to the call is some form of the first element of the
524     // landingpad aggregate value, but that doesn't matter.  It isn't used
525     // here.
526     // The return value of this instruction, however, is used to access the
527     // EH object pointer.  We have generated an instruction to get that value
528     // from the EH alloc block, so we can just map to that here.
529     VMap[Inst] = EHObj;
530     return CloningDirector::SkipInstruction;
531   }
532   if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) {
533     auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
534     // It might be interesting to track whether or not we are inside a catch
535     // function, but that might make the algorithm more brittle than it needs
536     // to be.
537
538     // The end catch call can occur in one of two places: either in a
539     // landingpad
540     // block that is part of the catch handlers exception mechanism, or at the
541     // end of the catch block.  If it occurs in a landing pad, we must skip it
542     // and continue so that the landing pad gets cloned.
543     // FIXME: This case isn't fully supported yet and shouldn't turn up in any
544     //        of the test cases until it is.
545     if (IntrinCall->getParent()->isLandingPad())
546       return CloningDirector::SkipInstruction;
547
548     // If an end catch occurs anywhere else the next instruction should be an
549     // unconditional branch instruction that we want to replace with a return
550     // to the the address of the branch target.
551     const BasicBlock *EndCatchBB = IntrinCall->getParent();
552     const TerminatorInst *Terminator = EndCatchBB->getTerminator();
553     const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
554     assert(Branch && Branch->isUnconditional());
555     assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
556            BasicBlock::const_iterator(Branch));
557
558     ReturnInst::Create(NewBB->getContext(),
559                        BlockAddress::get(Branch->getSuccessor(0)), NewBB);
560
561     // We just added a terminator to the cloned block.
562     // Tell the caller to stop processing the current basic block so that
563     // the branch instruction will be skipped.
564     return CloningDirector::StopCloningBB;
565   }
566   if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) {
567     auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
568     Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
569     // This causes a replacement that will collapse the landing pad CFG based
570     // on the filter function we intend to match.
571     if (Selector == CurrentSelector)
572       VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
573     else
574       VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
575     // Tell the caller not to clone this instruction.
576     return CloningDirector::SkipInstruction;
577   }
578
579   // Continue with the default cloning behavior.
580   return CloningDirector::CloneInstruction;
581 }
582
583 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
584     Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
585     : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
586   Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
587   // FIXME: Do something with the FrameVarMapped so that it is shared across the
588   // function.
589 }
590
591 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
592   // If we're asked to materialize an alloca variable, we temporarily
593   // create a matching alloca in the outlined function.  When all the
594   // outlining is complete, we'll collect these into a structure and
595   // replace these temporary allocas with GEPs referencing the frame
596   // allocation block.
597   if (auto *AV = dyn_cast<AllocaInst>(V)) {
598     AllocaInst *NewAlloca = Builder.CreateAlloca(
599         AV->getAllocatedType(), AV->getArraySize(), AV->getName());
600     FrameVarInfo[AV].Allocas.push_back(NewAlloca);
601     return NewAlloca;
602   }
603
604 // FIXME: Do PHI nodes need special handling?
605
606 // FIXME: Are there other cases we can handle better?  GEP, ExtractValue, etc.
607
608 // FIXME: This doesn't work during cloning because it finds an instruction
609 //        in the use list that isn't yet part of a basic block.
610 #if 0
611   // If we're asked to remap some other instruction, we'll need to
612   // spill it to an alloca variable in the parent function and add a
613   // temporary alloca in the outlined function to be processed as
614   // described above.
615   Instruction *Inst = dyn_cast<Instruction>(V);
616   if (Inst) {
617     AllocaInst *Spill = DemoteRegToStack(*Inst, true);
618     AllocaInst *NewAlloca = Builder.CreateAlloca(Spill->getAllocatedType(),
619                                                  Spill->getArraySize());
620     FrameVarMap[AV] = NewAlloca;
621     return NewAlloca;
622   }
623 #endif
624
625   return nullptr;
626 }