1 //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
38 using namespace llvm::PatternMatch;
40 #define DEBUG_TYPE "winehprepare"
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;
51 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
53 enum ActionType { Catch, Cleanup };
55 class LandingPadActions;
61 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
62 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
64 class WinEHPrepare : public FunctionPass {
66 static char ID; // Pass identification, replacement for typeid.
67 WinEHPrepare(const TargetMachine *TM = nullptr)
70 bool runOnFunction(Function &Fn) override;
72 bool doFinalization(Module &M) override;
74 void getAnalysisUsage(AnalysisUsage &AU) const override;
76 const char *getPassName() const override {
77 return "Windows exception handling preparation";
81 bool prepareExceptionHandlers(Function &F,
82 SmallVectorImpl<LandingPadInst *> &LPads);
83 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
84 LandingPadInst *LPad, BasicBlock *StartBB,
85 FrameVarInfoMap &VarInfo);
87 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
88 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
89 VisitedBlockSet &VisitedBlocks);
90 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
92 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
94 // All fields are reset by runOnFunction.
95 EHPersonality Personality;
96 CatchHandlerMapTy CatchHandlerMap;
97 CleanupHandlerMapTy CleanupHandlerMap;
98 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
101 class WinEHFrameVariableMaterializer : public ValueMaterializer {
103 WinEHFrameVariableMaterializer(Function *OutlinedFn,
104 FrameVarInfoMap &FrameVarInfo);
105 ~WinEHFrameVariableMaterializer() {}
107 virtual Value *materializeValueFor(Value *V) override;
110 FrameVarInfoMap &FrameVarInfo;
114 class LandingPadMap {
116 LandingPadMap() : OriginLPad(nullptr) {}
117 void mapLandingPad(const LandingPadInst *LPad);
119 bool isInitialized() { return OriginLPad != nullptr; }
121 bool mapIfEHPtrLoad(const LoadInst *Load) {
122 return mapIfEHLoad(Load, EHPtrStores, EHPtrStoreAddrs);
124 bool mapIfSelectorLoad(const LoadInst *Load) {
125 return mapIfEHLoad(Load, SelectorStores, SelectorStoreAddrs);
128 bool isLandingPadSpecificInst(const Instruction *Inst) const;
130 void remapSelector(ValueToValueMapTy &VMap, Value *MappedValue) const;
133 bool mapIfEHLoad(const LoadInst *Load,
134 SmallVectorImpl<const StoreInst *> &Stores,
135 SmallVectorImpl<const Value *> &StoreAddrs);
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;
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;
153 class WinEHCloningDirectorBase : public CloningDirector {
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())),
163 CloningAction handleInstruction(ValueToValueMapTy &VMap,
164 const Instruction *Inst,
165 BasicBlock *NewBB) override;
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;
183 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
186 WinEHFrameVariableMaterializer Materializer;
187 Type *SelectorIDType;
189 LandingPadMap &LPadMap;
192 class WinEHCatchDirector : public WinEHCloningDirectorBase {
194 WinEHCatchDirector(Function *CatchFn, Value *Selector,
195 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
196 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
197 CurrentSelector(Selector->stripPointerCasts()),
198 ExceptionObjectVar(nullptr) {}
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;
213 const Value *getExceptionVar() { return ExceptionObjectVar; }
214 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
217 Value *CurrentSelector;
219 const Value *ExceptionObjectVar;
220 TinyPtrVector<BasicBlock *> ReturnTargets;
223 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
225 WinEHCleanupDirector(Function *CleanupFn,
226 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
227 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
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;
243 class ActionHandler {
245 ActionHandler(BasicBlock *BB, ActionType Type)
246 : StartBB(BB), Type(Type), HandlerBlockOrFunc(nullptr) {}
248 ActionType getType() const { return Type; }
249 BasicBlock *getStartBlock() const { return StartBB; }
251 bool hasBeenProcessed() { return HandlerBlockOrFunc != nullptr; }
253 void setHandlerBlockOrFunc(Constant *F) { HandlerBlockOrFunc = F; }
254 Constant *getHandlerBlockOrFunc() { return HandlerBlockOrFunc; }
260 // Can be either a BlockAddress or a Function depending on the EH personality.
261 Constant *HandlerBlockOrFunc;
264 class CatchHandler : public ActionHandler {
266 CatchHandler(BasicBlock *BB, Constant *Selector, BasicBlock *NextBB)
267 : ActionHandler(BB, ActionType::Catch), Selector(Selector),
268 NextBB(NextBB), ExceptionObjectVar(nullptr) {}
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;
275 Constant *getSelector() const { return Selector; }
276 BasicBlock *getNextBB() const { return NextBB; }
278 const Value *getExceptionVar() { return ExceptionObjectVar; }
279 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
281 void setExceptionVar(const Value *Val) { ExceptionObjectVar = Val; }
282 void setReturnTargets(TinyPtrVector<BasicBlock *> &Targets) {
283 ReturnTargets = Targets;
289 const Value *ExceptionObjectVar;
290 TinyPtrVector<BasicBlock *> ReturnTargets;
293 class CleanupHandler : public ActionHandler {
295 CleanupHandler(BasicBlock *BB) : ActionHandler(BB, ActionType::Cleanup) {}
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;
303 class LandingPadActions {
305 LandingPadActions() : HasCleanupHandlers(false) {}
307 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
308 void insertCleanupHandler(CleanupHandler *Action) {
309 Actions.push_back(Action);
310 HasCleanupHandlers = true;
313 bool includesCleanup() const { return HasCleanupHandlers; }
315 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
316 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
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;
326 } // end anonymous namespace
328 char WinEHPrepare::ID = 0;
329 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
332 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
333 return new WinEHPrepare(TM);
336 // FIXME: Remove this once the backend can handle the prepared IR.
338 SEHPrepare("sehprepare", cl::Hidden,
339 cl::desc("Prepare functions with SEH personalities"));
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())
347 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
348 Resumes.push_back(Resume);
351 // No need to prepare functions that lack landing pads.
355 // Classify the personality to see what kind of preparation we need.
356 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
358 // Do nothing if this is not an MSVC personality.
359 if (!isMSVCEHPersonality(Personality))
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();
372 // If there were any landing pads, prepareExceptionHandlers will make changes.
373 prepareExceptionHandlers(Fn, LPads);
377 bool WinEHPrepare::doFinalization(Module &M) {
381 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
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;
390 bool HandlersOutlined = false;
392 Module *M = F.getParent();
393 LLVMContext &Context = M->getContext();
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);
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) {
405 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
406 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
407 LPadHasActionList = true;
411 // FIXME: This is here to help with the development of nested landing pad
412 // outlining. It should be removed when that is finished.
413 if (isa<UnreachableInst>(Inst)) {
414 LPadHasActionList = true;
419 // If we've already outlined the handlers for this landingpad,
420 // there's nothing more to do here.
421 if (LPadHasActionList)
424 LandingPadActions Actions;
425 mapLandingPadBlocks(LPad, Actions);
427 for (ActionHandler *Action : Actions) {
428 if (Action->hasBeenProcessed())
430 BasicBlock *StartBB = Action->getStartBlock();
432 // SEH doesn't do any outlining for catches. Instead, pass the handler
433 // basic block addr to llvm.eh.actions and list the block as a return
435 if (isAsynchronousEHPersonality(Personality)) {
436 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
437 processSEHCatchHandler(CatchAction, StartBB);
438 HandlersOutlined = true;
443 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
444 HandlersOutlined = true;
446 } // End for each Action
448 // FIXME: We need a guard against partially outlined functions.
449 if (!HandlersOutlined)
452 // Replace the landing pad with a new llvm.eh.action based landing pad.
453 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
454 assert(!isa<PHINode>(LPadBB->begin()));
455 Instruction *NewLPad = LPad->clone();
456 NewLPadBB->getInstList().push_back(NewLPad);
457 while (!pred_empty(LPadBB)) {
458 auto *pred = *pred_begin(LPadBB);
459 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
460 Invoke->setUnwindDest(NewLPadBB);
463 // Replace uses of the old lpad in phis with this block and delete the old
465 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
466 LPadBB->getTerminator()->eraseFromParent();
467 new UnreachableInst(LPadBB->getContext(), LPadBB);
469 // Add a call to describe the actions for this landing pad.
470 std::vector<Value *> ActionArgs;
471 for (ActionHandler *Action : Actions) {
472 // Action codes from docs are: 0 cleanup, 1 catch.
473 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
474 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
475 ActionArgs.push_back(CatchAction->getSelector());
476 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
478 ActionArgs.push_back(EHObj);
480 ActionArgs.push_back(ConstantPointerNull::get(Int8PtrType));
482 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
484 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
487 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
489 // Add an indirect branch listing possible successors of the catch handlers.
490 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
491 for (ActionHandler *Action : Actions) {
492 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
493 for (auto *Target : CatchAction->getReturnTargets()) {
494 Branch->addDestination(Target);
498 } // End for each landingpad
500 // If nothing got outlined, there is no more processing to be done.
501 if (!HandlersOutlined)
504 // Delete any blocks that were only used by handlers that were outlined above.
505 removeUnreachableBlocks(F);
507 BasicBlock *Entry = &F.getEntryBlock();
508 IRBuilder<> Builder(F.getParent()->getContext());
509 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
511 Function *FrameEscapeFn =
512 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
513 Function *RecoverFrameFn =
514 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
516 // Finally, replace all of the temporary allocas for frame variables used in
517 // the outlined handlers with calls to llvm.framerecover.
518 BasicBlock::iterator II = Entry->getFirstInsertionPt();
519 Instruction *AllocaInsertPt = II;
520 SmallVector<Value *, 8> AllocasToEscape;
521 for (auto &VarInfoEntry : FrameVarInfo) {
522 Value *ParentVal = VarInfoEntry.first;
523 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
525 // If the mapped value isn't already an alloca, we need to spill it if it
526 // is a computed value or copy it if it is an argument.
527 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
529 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
530 // Lower this argument to a copy and then demote that to the stack.
531 // We can't just use the argument location because the handler needs
532 // it to be in the frame allocation block.
533 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
534 Value *TrueValue = ConstantInt::getTrue(Context);
535 Value *UndefValue = UndefValue::get(Arg->getType());
537 SelectInst::Create(TrueValue, Arg, UndefValue,
538 Arg->getName() + ".tmp", AllocaInsertPt);
539 Arg->replaceAllUsesWith(SI);
540 // Reset the select operand, because it was clobbered by the RAUW above.
541 SI->setOperand(1, Arg);
542 ParentAlloca = DemoteRegToStack(*SI, true, SI);
543 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
544 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
546 Instruction *ParentInst = cast<Instruction>(ParentVal);
547 // FIXME: This is a work-around to temporarily handle the case where an
548 // instruction that is only used in handlers is not sunk.
549 // Without uses, DemoteRegToStack would just eliminate the value.
550 // This will fail if ParentInst is an invoke.
551 if (ParentInst->getNumUses() == 0) {
552 BasicBlock::iterator InsertPt = ParentInst;
555 new AllocaInst(ParentInst->getType(), nullptr,
556 ParentInst->getName() + ".reg2mem", InsertPt);
557 new StoreInst(ParentInst, ParentAlloca, InsertPt);
559 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
564 // If the parent alloca is no longer used and only one of the handlers used
565 // it, erase the parent and leave the copy in the outlined handler.
566 if (ParentAlloca->getNumUses() == 0 && Allocas.size() == 1) {
567 ParentAlloca->eraseFromParent();
571 // Add this alloca to the list of things to escape.
572 AllocasToEscape.push_back(ParentAlloca);
574 // Next replace all outlined allocas that are mapped to it.
575 for (AllocaInst *TempAlloca : Allocas) {
576 Function *HandlerFn = TempAlloca->getParent()->getParent();
577 // FIXME: Sink this GEP into the blocks where it is used.
578 Builder.SetInsertPoint(TempAlloca);
579 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
580 Value *RecoverArgs[] = {
581 Builder.CreateBitCast(&F, Int8PtrType, ""),
582 &(HandlerFn->getArgumentList().back()),
583 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
584 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
585 // Add a pointer bitcast if the alloca wasn't an i8.
586 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
587 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
589 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
591 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
592 TempAlloca->removeFromParent();
593 RecoveredAlloca->takeName(TempAlloca);
596 } // End for each FrameVarInfo entry.
598 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
600 Builder.SetInsertPoint(&F.getEntryBlock().back());
601 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
603 // Clean up the handler action maps we created for this function
604 DeleteContainerSeconds(CatchHandlerMap);
605 CatchHandlerMap.clear();
606 DeleteContainerSeconds(CleanupHandlerMap);
607 CleanupHandlerMap.clear();
609 return HandlersOutlined;
612 // This function examines a block to determine whether the block ends with a
613 // conditional branch to a catch handler based on a selector comparison.
614 // This function is used both by the WinEHPrepare::findSelectorComparison() and
615 // WinEHCleanupDirector::handleTypeIdFor().
616 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
617 Constant *&Selector, BasicBlock *&NextBB) {
618 ICmpInst::Predicate Pred;
619 BasicBlock *TBB, *FBB;
622 if (!match(BB->getTerminator(),
623 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
627 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
628 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
631 if (Pred == CmpInst::ICMP_EQ) {
637 if (Pred == CmpInst::ICMP_NE) {
646 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
647 LandingPadInst *LPad, BasicBlock *StartBB,
648 FrameVarInfoMap &VarInfo) {
649 Module *M = SrcFn->getParent();
650 LLVMContext &Context = M->getContext();
652 // Create a new function to receive the handler contents.
653 Type *Int8PtrType = Type::getInt8PtrTy(Context);
654 std::vector<Type *> ArgTys;
655 ArgTys.push_back(Int8PtrType);
656 ArgTys.push_back(Int8PtrType);
658 if (Action->getType() == Catch) {
659 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
660 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
661 SrcFn->getName() + ".catch", M);
663 FunctionType *FnType =
664 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
665 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
666 SrcFn->getName() + ".cleanup", M);
669 // Generate a standard prolog to setup the frame recovery structure.
670 IRBuilder<> Builder(Context);
671 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
672 Handler->getBasicBlockList().push_front(Entry);
673 Builder.SetInsertPoint(Entry);
674 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
676 std::unique_ptr<WinEHCloningDirectorBase> Director;
678 ValueToValueMapTy VMap;
680 LandingPadMap &LPadMap = LPadMaps[LPad];
681 if (!LPadMap.isInitialized())
682 LPadMap.mapLandingPad(LPad);
683 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
684 Constant *Sel = CatchAction->getSelector();
685 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap));
686 LPadMap.remapSelector(VMap, ConstantInt::get(Type::getInt32Ty(Context), 1));
688 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
691 SmallVector<ReturnInst *, 8> Returns;
692 ClonedCodeInfo OutlinedFunctionInfo;
694 // If the start block contains PHI nodes, we need to map them.
695 BasicBlock::iterator II = StartBB->begin();
696 while (auto *PN = dyn_cast<PHINode>(II)) {
698 // Look for PHI values that we have already mapped (such as the selector).
699 for (Value *Val : PN->incoming_values()) {
700 if (VMap.count(Val)) {
701 VMap[PN] = VMap[Val];
705 // If we didn't find a match for this value, map it as an undef.
707 VMap[PN] = UndefValue::get(PN->getType());
712 // Skip over PHIs and, if applicable, landingpad instructions.
713 II = StartBB->getFirstInsertionPt();
715 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
716 /*ModuleLevelChanges=*/false, Returns, "",
717 &OutlinedFunctionInfo, Director.get());
719 // Move all the instructions in the first cloned block into our entry block.
720 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
721 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
722 FirstClonedBB->eraseFromParent();
724 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
725 WinEHCatchDirector *CatchDirector =
726 reinterpret_cast<WinEHCatchDirector *>(Director.get());
727 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
728 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
731 Action->setHandlerBlockOrFunc(Handler);
736 /// This BB must end in a selector dispatch. All we need to do is pass the
737 /// handler block to llvm.eh.actions and list it as a possible indirectbr
739 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
740 BasicBlock *StartBB) {
741 BasicBlock *HandlerBB;
744 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
746 // If this was EH dispatch, this must be a conditional branch to the handler
748 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
749 // leading to crashes if some optimization hoists stuff here.
750 assert(CatchAction->getSelector() && HandlerBB &&
751 "expected catch EH dispatch");
753 // This must be a catch-all. Split the block after the landingpad.
754 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
756 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
758 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
759 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
760 CatchAction->setReturnTargets(Targets);
763 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
764 // Each instance of this class should only ever be used to map a single
766 assert(OriginLPad == nullptr || OriginLPad == LPad);
768 // If the landing pad has already been mapped, there's nothing more to do.
769 if (OriginLPad == LPad)
774 // The landingpad instruction returns an aggregate value. Typically, its
775 // value will be passed to a pair of extract value instructions and the
776 // results of those extracts are often passed to store instructions.
777 // In unoptimized code the stored value will often be loaded and then stored
779 for (auto *U : LPad->users()) {
780 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
783 assert(Extract->getNumIndices() == 1 &&
784 "Unexpected operation: extracting both landing pad values");
785 unsigned int Idx = *(Extract->idx_begin());
786 assert((Idx == 0 || Idx == 1) &&
787 "Unexpected operation: extracting an unknown landing pad element");
789 // Element 0 doesn't directly corresponds to anything in the WinEH
791 // It will be stored to a memory location, then later loaded and finally
792 // the loaded value will be used as the argument to an
793 // llvm.eh.begincatch
794 // call. We're tracking it here so that we can skip the store and load.
795 ExtractedEHPtrs.push_back(Extract);
796 } else if (Idx == 1) {
797 // Element 1 corresponds to the filter selector. We'll map it to 1 for
798 // matching purposes, but it will also probably be stored to memory and
799 // reloaded, so we need to track the instuction so that we can map the
801 ExtractedSelectors.push_back(Extract);
804 // Look for stores of the extracted values.
805 for (auto *EU : Extract->users()) {
806 if (auto *Store = dyn_cast<StoreInst>(EU)) {
808 SelectorStores.push_back(Store);
809 SelectorStoreAddrs.push_back(Store->getPointerOperand());
811 EHPtrStores.push_back(Store);
812 EHPtrStoreAddrs.push_back(Store->getPointerOperand());
819 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
820 if (Inst == OriginLPad)
822 for (auto *Extract : ExtractedEHPtrs) {
826 for (auto *Extract : ExtractedSelectors) {
830 for (auto *Store : EHPtrStores) {
834 for (auto *Store : SelectorStores) {
842 void LandingPadMap::remapSelector(ValueToValueMapTy &VMap,
843 Value *MappedValue) const {
844 // Remap all selector extract instructions to the specified value.
845 for (auto *Extract : ExtractedSelectors)
846 VMap[Extract] = MappedValue;
849 bool LandingPadMap::mapIfEHLoad(const LoadInst *Load,
850 SmallVectorImpl<const StoreInst *> &Stores,
851 SmallVectorImpl<const Value *> &StoreAddrs) {
852 // This makes the assumption that a store we've previously seen dominates
853 // this load instruction. That might seem like a rather huge assumption,
854 // but given the way that landingpads are constructed its fairly safe.
855 // FIXME: Add debug/assert code that verifies this.
856 const Value *LoadAddr = Load->getPointerOperand();
857 for (auto *StoreAddr : StoreAddrs) {
858 if (LoadAddr == StoreAddr) {
859 // Handle the common debug scenario where this loaded value is stored
860 // to a different location.
861 for (auto *U : Load->users()) {
862 if (auto *Store = dyn_cast<StoreInst>(U)) {
863 Stores.push_back(Store);
864 StoreAddrs.push_back(Store->getPointerOperand());
873 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
874 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
875 // If this is one of the boilerplate landing pad instructions, skip it.
876 // The instruction will have already been remapped in VMap.
877 if (LPadMap.isLandingPadSpecificInst(Inst))
878 return CloningDirector::SkipInstruction;
880 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
881 // Look for loads of (previously suppressed) landingpad values.
882 // The EHPtr load can be mapped to an undef value as it should only be used
883 // as an argument to llvm.eh.begincatch, but the selector value needs to be
884 // mapped to a constant value of 1. This value will be used to simplify the
885 // branching to always flow to the current handler.
886 if (LPadMap.mapIfSelectorLoad(Load)) {
887 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
888 return CloningDirector::SkipInstruction;
890 if (LPadMap.mapIfEHPtrLoad(Load)) {
891 VMap[Inst] = UndefValue::get(Int8PtrType);
892 return CloningDirector::SkipInstruction;
895 // Any other loads just get cloned.
896 return CloningDirector::CloneInstruction;
899 // Nested landing pads will be cloned as stubs, with just the
900 // landingpad instruction and an unreachable instruction. When
901 // all landingpads have been outlined, we'll replace this with the
902 // llvm.eh.actions call and indirect branch created when the
903 // landing pad was outlined.
904 if (auto *NestedLPad = dyn_cast<LandingPadInst>(Inst)) {
905 Instruction *NewInst = NestedLPad->clone();
906 if (NestedLPad->hasName())
907 NewInst->setName(NestedLPad->getName());
908 // FIXME: Store this mapping somewhere else also.
909 VMap[NestedLPad] = NewInst;
910 BasicBlock::InstListType &InstList = NewBB->getInstList();
911 InstList.push_back(NewInst);
912 InstList.push_back(new UnreachableInst(NewBB->getContext()));
913 return CloningDirector::StopCloningBB;
916 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
917 return handleInvoke(VMap, Invoke, NewBB);
919 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
920 return handleResume(VMap, Resume, NewBB);
922 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
923 return handleBeginCatch(VMap, Inst, NewBB);
924 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
925 return handleEndCatch(VMap, Inst, NewBB);
926 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
927 return handleTypeIdFor(VMap, Inst, NewBB);
929 // Continue with the default cloning behavior.
930 return CloningDirector::CloneInstruction;
933 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
934 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
935 // The argument to the call is some form of the first element of the
936 // landingpad aggregate value, but that doesn't matter. It isn't used
938 // The second argument is an outparameter where the exception object will be
939 // stored. Typically the exception object is a scalar, but it can be an
940 // aggregate when catching by value.
941 // FIXME: Leave something behind to indicate where the exception object lives
942 // for this handler. Should it be part of llvm.eh.actions?
943 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
944 "llvm.eh.begincatch found while "
945 "outlining catch handler.");
946 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
947 return CloningDirector::SkipInstruction;
950 CloningDirector::CloningAction
951 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
952 const Instruction *Inst, BasicBlock *NewBB) {
953 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
954 // It might be interesting to track whether or not we are inside a catch
955 // function, but that might make the algorithm more brittle than it needs
958 // The end catch call can occur in one of two places: either in a
959 // landingpad block that is part of the catch handlers exception mechanism,
960 // or at the end of the catch block. If it occurs in a landing pad, we must
961 // skip it and continue so that the landing pad gets cloned.
962 // FIXME: This case isn't fully supported yet and shouldn't turn up in any
963 // of the test cases until it is.
964 if (IntrinCall->getParent()->isLandingPad())
965 return CloningDirector::SkipInstruction;
967 // If an end catch occurs anywhere else the next instruction should be an
968 // unconditional branch instruction that we want to replace with a return
969 // to the the address of the branch target.
970 const BasicBlock *EndCatchBB = IntrinCall->getParent();
971 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
972 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
973 assert(Branch && Branch->isUnconditional());
974 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
975 BasicBlock::const_iterator(Branch));
977 BasicBlock *ContinueLabel = Branch->getSuccessor(0);
978 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueLabel),
980 ReturnTargets.push_back(ContinueLabel);
982 // We just added a terminator to the cloned block.
983 // Tell the caller to stop processing the current basic block so that
984 // the branch instruction will be skipped.
985 return CloningDirector::StopCloningBB;
988 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
989 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
990 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
991 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
992 // This causes a replacement that will collapse the landing pad CFG based
993 // on the filter function we intend to match.
994 if (Selector == CurrentSelector)
995 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
997 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
998 // Tell the caller not to clone this instruction.
999 return CloningDirector::SkipInstruction;
1002 CloningDirector::CloningAction
1003 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1004 const InvokeInst *Invoke, BasicBlock *NewBB) {
1005 return CloningDirector::CloneInstruction;
1008 CloningDirector::CloningAction
1009 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1010 const ResumeInst *Resume, BasicBlock *NewBB) {
1011 // Resume instructions shouldn't be reachable from catch handlers.
1012 // We still need to handle it, but it will be pruned.
1013 BasicBlock::InstListType &InstList = NewBB->getInstList();
1014 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1015 return CloningDirector::StopCloningBB;
1018 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1019 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1020 // Catch blocks within cleanup handlers will always be unreachable.
1021 // We'll insert an unreachable instruction now, but it will be pruned
1022 // before the cloning process is complete.
1023 BasicBlock::InstListType &InstList = NewBB->getInstList();
1024 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1025 return CloningDirector::StopCloningBB;
1028 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1029 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1030 // Catch blocks within cleanup handlers will always be unreachable.
1031 // We'll insert an unreachable instruction now, but it will be pruned
1032 // before the cloning process is complete.
1033 BasicBlock::InstListType &InstList = NewBB->getInstList();
1034 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1035 return CloningDirector::StopCloningBB;
1038 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1039 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1040 // If we encounter a selector comparison while cloning a cleanup handler,
1041 // we want to stop cloning immediately. Anything after the dispatch
1042 // will be outlined into a different handler.
1043 BasicBlock *CatchHandler;
1046 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1047 CatchHandler, Selector, NextBB)) {
1048 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1049 return CloningDirector::StopCloningBB;
1051 // If eg.typeid.for is called for any other reason, it can be ignored.
1052 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1053 return CloningDirector::SkipInstruction;
1056 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1057 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1058 // All invokes in cleanup handlers can be replaced with calls.
1059 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1060 // Insert a normal call instruction...
1062 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1063 Invoke->getName(), NewBB);
1064 NewCall->setCallingConv(Invoke->getCallingConv());
1065 NewCall->setAttributes(Invoke->getAttributes());
1066 NewCall->setDebugLoc(Invoke->getDebugLoc());
1067 VMap[Invoke] = NewCall;
1069 // Insert an unconditional branch to the normal destination.
1070 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1072 // The unwind destination won't be cloned into the new function, so
1073 // we don't need to clean up its phi nodes.
1075 // We just added a terminator to the cloned block.
1076 // Tell the caller to stop processing the current basic block.
1077 return CloningDirector::StopCloningBB;
1080 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1081 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1082 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1084 // We just added a terminator to the cloned block.
1085 // Tell the caller to stop processing the current basic block so that
1086 // the branch instruction will be skipped.
1087 return CloningDirector::StopCloningBB;
1090 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1091 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1092 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1093 Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
1096 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1097 // If we're asked to materialize a value that is an instruction, we
1098 // temporarily create an alloca in the outlined function and add this
1099 // to the FrameVarInfo map. When all the outlining is complete, we'll
1100 // collect these into a structure, spilling non-alloca values in the
1101 // parent frame as necessary, and replace these temporary allocas with
1102 // GEPs referencing the frame allocation block.
1104 // If the value is an alloca, the mapping is direct.
1105 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1106 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1107 Builder.Insert(NewAlloca, AV->getName());
1108 FrameVarInfo[AV].push_back(NewAlloca);
1112 // For other types of instructions or arguments, we need an alloca based on
1113 // the value's type and a load of the alloca. The alloca will be replaced
1114 // by a GEP, but the load will stay. In the parent function, the value will
1115 // be spilled to a location in the frame allocation block.
1116 if (isa<Instruction>(V) || isa<Argument>(V)) {
1117 AllocaInst *NewAlloca =
1118 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1119 FrameVarInfo[V].push_back(NewAlloca);
1120 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1124 // Don't materialize other values.
1128 // This function maps the catch and cleanup handlers that are reachable from the
1129 // specified landing pad. The landing pad sequence will have this basic shape:
1131 // <cleanup handler>
1132 // <selector comparison>
1134 // <cleanup handler>
1135 // <selector comparison>
1137 // <cleanup handler>
1140 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1141 // any arbitrary control flow, but all paths through the cleanup code must
1142 // eventually reach the next selector comparison and no path can skip to a
1143 // different selector comparisons, though some paths may terminate abnormally.
1144 // Therefore, we will use a depth first search from the start of any given
1145 // cleanup block and stop searching when we find the next selector comparison.
1147 // If the landingpad instruction does not have a catch clause, we will assume
1148 // that any instructions other than selector comparisons and catch handlers can
1149 // be ignored. In practice, these will only be the boilerplate instructions.
1151 // The catch handlers may also have any control structure, but we are only
1152 // interested in the start of the catch handlers, so we don't need to actually
1153 // follow the flow of the catch handlers. The start of the catch handlers can
1154 // be located from the compare instructions, but they can be skipped in the
1155 // flow by following the contrary branch.
1156 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1157 LandingPadActions &Actions) {
1158 unsigned int NumClauses = LPad->getNumClauses();
1159 unsigned int HandlersFound = 0;
1160 BasicBlock *BB = LPad->getParent();
1162 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1164 if (NumClauses == 0) {
1165 // This landing pad contains only cleanup code.
1166 CleanupHandler *Action = new CleanupHandler(BB);
1167 CleanupHandlerMap[BB] = Action;
1168 Actions.insertCleanupHandler(Action);
1169 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1171 assert(LPad->isCleanup());
1175 VisitedBlockSet VisitedBlocks;
1177 while (HandlersFound != NumClauses) {
1178 BasicBlock *NextBB = nullptr;
1180 // See if the clause we're looking for is a catch-all.
1181 // If so, the catch begins immediately.
1182 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1183 // The catch all must occur last.
1184 assert(HandlersFound == NumClauses - 1);
1186 // For C++ EH, check if there is any interesting cleanup code before we
1187 // begin the catch. This is important because cleanups cannot rethrow
1188 // exceptions but code called from catches can. For SEH, it isn't
1189 // important if some finally code before a catch-all is executed out of
1190 // line or after recovering from the exception.
1191 if (Personality == EHPersonality::MSVC_CXX) {
1192 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1193 // Add a cleanup entry to the list
1194 Actions.insertCleanupHandler(CleanupAction);
1195 DEBUG(dbgs() << " Found cleanup code in block "
1196 << CleanupAction->getStartBlock()->getName() << "\n");
1200 // Add the catch handler to the action list.
1201 CatchHandler *Action =
1202 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1203 CatchHandlerMap[BB] = Action;
1204 Actions.insertCatchHandler(Action);
1205 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1208 // Once we reach a catch-all, don't expect to hit a resume instruction.
1213 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1214 // See if there is any interesting code executed before the dispatch.
1215 if (auto *CleanupAction =
1216 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1217 // Add a cleanup entry to the list
1218 Actions.insertCleanupHandler(CleanupAction);
1219 DEBUG(dbgs() << " Found cleanup code in block "
1220 << CleanupAction->getStartBlock()->getName() << "\n");
1223 assert(CatchAction);
1226 // Add the catch handler to the action list.
1227 Actions.insertCatchHandler(CatchAction);
1228 DEBUG(dbgs() << " Found catch dispatch in block "
1229 << CatchAction->getStartBlock()->getName() << "\n");
1231 // Move on to the block after the catch handler.
1235 // If we didn't wind up in a catch-all, see if there is any interesting code
1236 // executed before the resume.
1237 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1238 // Add a cleanup entry to the list
1239 Actions.insertCleanupHandler(CleanupAction);
1240 DEBUG(dbgs() << " Found cleanup code in block "
1241 << CleanupAction->getStartBlock()->getName() << "\n");
1244 // It's possible that some optimization moved code into a landingpad that
1246 // previously being used for cleanup. If that happens, we need to execute
1248 // extra code from a cleanup handler.
1249 if (Actions.includesCleanup() && !LPad->isCleanup())
1250 LPad->setCleanup(true);
1253 // This function searches starting with the input block for the next
1254 // block that terminates with a branch whose condition is based on a selector
1255 // comparison. This may be the input block. See the mapLandingPadBlocks
1256 // comments for a discussion of control flow assumptions.
1258 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1259 BasicBlock *&NextBB,
1260 VisitedBlockSet &VisitedBlocks) {
1261 // See if we've already found a catch handler use it.
1262 // Call count() first to avoid creating a null entry for blocks
1263 // we haven't seen before.
1264 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1265 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1266 NextBB = Action->getNextBB();
1270 // VisitedBlocks applies only to the current search. We still
1271 // need to consider blocks that we've visited while mapping other
1273 VisitedBlocks.insert(BB);
1275 BasicBlock *CatchBlock = nullptr;
1276 Constant *Selector = nullptr;
1278 // If this is the first time we've visited this block from any landing pad
1279 // look to see if it is a selector dispatch block.
1280 if (!CatchHandlerMap.count(BB)) {
1281 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1282 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1283 CatchHandlerMap[BB] = Action;
1288 // Visit each successor, looking for the dispatch.
1289 // FIXME: We expect to find the dispatch quickly, so this will probably
1290 // work better as a breadth first search.
1291 for (BasicBlock *Succ : successors(BB)) {
1292 if (VisitedBlocks.count(Succ))
1295 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1302 // These are helper functions to combine repeated code from findCleanupHandler.
1303 static CleanupHandler *createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap,
1305 CleanupHandler *Action = new CleanupHandler(BB);
1306 CleanupHandlerMap[BB] = Action;
1310 // This function searches starting with the input block for the next block that
1311 // contains code that is not part of a catch handler and would not be eliminated
1312 // during handler outlining.
1314 CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1315 BasicBlock *EndBB) {
1316 // Here we will skip over the following:
1318 // landing pad prolog:
1320 // Unconditional branches
1322 // Selector dispatch
1326 // Anything else marks the start of an interesting block
1328 BasicBlock *BB = StartBB;
1329 // Anything other than an unconditional branch will kick us out of this loop
1330 // one way or another.
1332 // If we've already scanned this block, don't scan it again. If it is
1333 // a cleanup block, there will be an action in the CleanupHandlerMap.
1334 // If we've scanned it and it is not a cleanup block, there will be a
1335 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1336 // be no entry in the CleanupHandlerMap. We must call count() first to
1337 // avoid creating a null entry for blocks we haven't scanned.
1338 if (CleanupHandlerMap.count(BB)) {
1339 if (auto *Action = CleanupHandlerMap[BB]) {
1340 return cast<CleanupHandler>(Action);
1342 // Here we handle the case where the cleanup handler map contains a
1343 // value for this block but the value is a nullptr. This means that
1344 // we have previously analyzed the block and determined that it did
1345 // not contain any cleanup code. Based on the earlier analysis, we
1346 // know the the block must end in either an unconditional branch, a
1347 // resume or a conditional branch that is predicated on a comparison
1348 // with a selector. Either the resume or the selector dispatch
1349 // would terminate the search for cleanup code, so the unconditional
1350 // branch is the only case for which we might need to continue
1355 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1362 // Create an entry in the cleanup handler map for this block. Initially
1363 // we create an entry that says this isn't a cleanup block. If we find
1364 // cleanup code, the caller will replace this entry.
1365 CleanupHandlerMap[BB] = nullptr;
1367 TerminatorInst *Terminator = BB->getTerminator();
1369 // Landing pad blocks have extra instructions we need to accept.
1370 LandingPadMap *LPadMap = nullptr;
1371 if (BB->isLandingPad()) {
1372 LandingPadInst *LPad = BB->getLandingPadInst();
1373 LPadMap = &LPadMaps[LPad];
1374 if (!LPadMap->isInitialized())
1375 LPadMap->mapLandingPad(LPad);
1378 // Look for the bare resume pattern:
1379 // %exn2 = load i8** %exn.slot
1380 // %sel2 = load i32* %ehselector.slot
1381 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn2, 0
1382 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel2, 1
1383 // resume { i8*, i32 } %lpad.val2
1384 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1385 InsertValueInst *Insert1 = nullptr;
1386 InsertValueInst *Insert2 = nullptr;
1387 Value *ResumeVal = Resume->getOperand(0);
1388 // If there is only one landingpad, we may use the lpad directly with no
1390 if (isa<LandingPadInst>(ResumeVal))
1392 if (!isa<PHINode>(ResumeVal)) {
1393 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1395 return createCleanupHandler(CleanupHandlerMap, BB);
1396 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1398 return createCleanupHandler(CleanupHandlerMap, BB);
1400 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1402 Instruction *Inst = II;
1403 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1405 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1407 if (!Inst->hasOneUse() ||
1408 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1409 return createCleanupHandler(CleanupHandlerMap, BB);
1415 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1417 if (Branch->isConditional()) {
1418 // Look for the selector dispatch.
1419 // %sel = load i32* %ehselector.slot
1420 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1421 // %matches = icmp eq i32 %sel12, %2
1422 // br i1 %matches, label %catch14, label %eh.resume
1423 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1424 if (!Compare || !Compare->isEquality())
1425 return createCleanupHandler(CleanupHandlerMap, BB);
1426 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1429 Instruction *Inst = II;
1430 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1432 if (Inst == Compare || Inst == Branch)
1434 if (!Inst->hasOneUse() || (Inst->user_back() != Compare))
1435 return createCleanupHandler(CleanupHandlerMap, BB);
1436 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1438 if (!isa<LoadInst>(Inst))
1439 return createCleanupHandler(CleanupHandlerMap, BB);
1441 // The selector dispatch block should always terminate our search.
1442 assert(BB == EndBB);
1445 // Look for empty blocks with unconditional branches.
1446 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1449 Instruction *Inst = II;
1450 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1454 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1456 // Anything else makes this interesting cleanup code.
1457 return createCleanupHandler(CleanupHandlerMap, BB);
1461 // The branch was unconditional.
1462 BB = Branch->getSuccessor(0);
1464 } // End else of if branch was conditional
1467 // Anything else makes this interesting cleanup code.
1468 return createCleanupHandler(CleanupHandlerMap, BB);