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/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/Analysis/LibCallSemantics.h"
23 #include "llvm/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/Local.h"
40 using namespace llvm::PatternMatch;
42 #define DEBUG_TYPE "winehprepare"
46 // This map is used to model frame variable usage during outlining, to
47 // construct a structure type to hold the frame variables in a frame
48 // allocation block, and to remap the frame variable allocas (including
49 // spill locations as needed) to GEPs that get the variable from the
50 // frame allocation structure.
51 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
53 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
55 class LandingPadActions;
58 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
59 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
61 class WinEHPrepare : public FunctionPass {
63 static char ID; // Pass identification, replacement for typeid.
64 WinEHPrepare(const TargetMachine *TM = nullptr)
67 bool runOnFunction(Function &Fn) override;
69 bool doFinalization(Module &M) override;
71 void getAnalysisUsage(AnalysisUsage &AU) const override;
73 const char *getPassName() const override {
74 return "Windows exception handling preparation";
78 bool prepareExceptionHandlers(Function &F,
79 SmallVectorImpl<LandingPadInst *> &LPads);
80 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
81 LandingPadInst *LPad, BasicBlock *StartBB,
82 FrameVarInfoMap &VarInfo);
84 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
85 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
86 VisitedBlockSet &VisitedBlocks);
87 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
89 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
91 // All fields are reset by runOnFunction.
92 EHPersonality Personality;
93 CatchHandlerMapTy CatchHandlerMap;
94 CleanupHandlerMapTy CleanupHandlerMap;
95 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
98 class WinEHFrameVariableMaterializer : public ValueMaterializer {
100 WinEHFrameVariableMaterializer(Function *OutlinedFn,
101 FrameVarInfoMap &FrameVarInfo);
102 ~WinEHFrameVariableMaterializer() {}
104 virtual Value *materializeValueFor(Value *V) override;
107 FrameVarInfoMap &FrameVarInfo;
111 class LandingPadMap {
113 LandingPadMap() : OriginLPad(nullptr) {}
114 void mapLandingPad(const LandingPadInst *LPad);
116 bool isInitialized() { return OriginLPad != nullptr; }
118 bool mapIfEHPtrLoad(const LoadInst *Load) {
119 return mapIfEHLoad(Load, EHPtrStores, EHPtrStoreAddrs);
121 bool mapIfSelectorLoad(const LoadInst *Load) {
122 return mapIfEHLoad(Load, SelectorStores, SelectorStoreAddrs);
125 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
126 bool isLandingPadSpecificInst(const Instruction *Inst) const;
128 void remapSelector(ValueToValueMapTy &VMap, Value *MappedValue) const;
131 bool mapIfEHLoad(const LoadInst *Load,
132 SmallVectorImpl<const StoreInst *> &Stores,
133 SmallVectorImpl<const Value *> &StoreAddrs);
135 const LandingPadInst *OriginLPad;
136 // We will normally only see one of each of these instructions, but
137 // if more than one occurs for some reason we can handle that.
138 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
139 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
141 // In optimized code, there will typically be at most one instance of
142 // each of the following, but in unoptimized IR it is not uncommon
143 // for the values to be stored, loaded and then stored again. In that
144 // case we will create a second entry for each store and store address.
145 SmallVector<const StoreInst *, 2> EHPtrStores;
146 SmallVector<const StoreInst *, 2> SelectorStores;
147 SmallVector<const Value *, 2> EHPtrStoreAddrs;
148 SmallVector<const Value *, 2> SelectorStoreAddrs;
151 class WinEHCloningDirectorBase : public CloningDirector {
153 WinEHCloningDirectorBase(Function *HandlerFn,
154 FrameVarInfoMap &VarInfo,
155 LandingPadMap &LPadMap)
156 : Materializer(HandlerFn, VarInfo),
157 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
158 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
161 CloningAction handleInstruction(ValueToValueMapTy &VMap,
162 const Instruction *Inst,
163 BasicBlock *NewBB) override;
165 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
166 const Instruction *Inst,
167 BasicBlock *NewBB) = 0;
168 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
169 const Instruction *Inst,
170 BasicBlock *NewBB) = 0;
171 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
172 const Instruction *Inst,
173 BasicBlock *NewBB) = 0;
174 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
175 const InvokeInst *Invoke,
176 BasicBlock *NewBB) = 0;
177 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
178 const ResumeInst *Resume,
179 BasicBlock *NewBB) = 0;
181 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
184 WinEHFrameVariableMaterializer Materializer;
185 Type *SelectorIDType;
187 LandingPadMap &LPadMap;
190 class WinEHCatchDirector : public WinEHCloningDirectorBase {
192 WinEHCatchDirector(Function *CatchFn, Value *Selector,
193 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
194 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
195 CurrentSelector(Selector->stripPointerCasts()),
196 ExceptionObjectVar(nullptr) {}
198 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
199 const Instruction *Inst,
200 BasicBlock *NewBB) override;
201 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
202 BasicBlock *NewBB) override;
203 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
204 const Instruction *Inst,
205 BasicBlock *NewBB) override;
206 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
207 BasicBlock *NewBB) override;
208 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
209 BasicBlock *NewBB) override;
211 const Value *getExceptionVar() { return ExceptionObjectVar; }
212 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
215 Value *CurrentSelector;
217 const Value *ExceptionObjectVar;
218 TinyPtrVector<BasicBlock *> ReturnTargets;
221 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
223 WinEHCleanupDirector(Function *CleanupFn,
224 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
225 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
227 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) override;
230 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
231 BasicBlock *NewBB) override;
232 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
233 const Instruction *Inst,
234 BasicBlock *NewBB) override;
235 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
236 BasicBlock *NewBB) override;
237 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
238 BasicBlock *NewBB) override;
241 class LandingPadActions {
243 LandingPadActions() : HasCleanupHandlers(false) {}
245 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
246 void insertCleanupHandler(CleanupHandler *Action) {
247 Actions.push_back(Action);
248 HasCleanupHandlers = true;
251 bool includesCleanup() const { return HasCleanupHandlers; }
253 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
254 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
255 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
258 // Note that this class does not own the ActionHandler objects in this vector.
259 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
260 // in the WinEHPrepare class.
261 SmallVector<ActionHandler *, 4> Actions;
262 bool HasCleanupHandlers;
265 } // end anonymous namespace
267 char WinEHPrepare::ID = 0;
268 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
271 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
272 return new WinEHPrepare(TM);
275 // FIXME: Remove this once the backend can handle the prepared IR.
277 SEHPrepare("sehprepare", cl::Hidden,
278 cl::desc("Prepare functions with SEH personalities"));
280 bool WinEHPrepare::runOnFunction(Function &Fn) {
281 SmallVector<LandingPadInst *, 4> LPads;
282 SmallVector<ResumeInst *, 4> Resumes;
283 for (BasicBlock &BB : Fn) {
284 if (auto *LP = BB.getLandingPadInst())
286 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
287 Resumes.push_back(Resume);
290 // No need to prepare functions that lack landing pads.
294 // Classify the personality to see what kind of preparation we need.
295 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
297 // Do nothing if this is not an MSVC personality.
298 if (!isMSVCEHPersonality(Personality))
301 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
302 // Replace all resume instructions with unreachable.
303 // FIXME: Remove this once the backend can handle the prepared IR.
304 for (ResumeInst *Resume : Resumes) {
305 IRBuilder<>(Resume).CreateUnreachable();
306 Resume->eraseFromParent();
311 // If there were any landing pads, prepareExceptionHandlers will make changes.
312 prepareExceptionHandlers(Fn, LPads);
316 bool WinEHPrepare::doFinalization(Module &M) {
320 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
322 bool WinEHPrepare::prepareExceptionHandlers(
323 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
324 // These containers are used to re-map frame variables that are used in
325 // outlined catch and cleanup handlers. They will be populated as the
326 // handlers are outlined.
327 FrameVarInfoMap FrameVarInfo;
329 bool HandlersOutlined = false;
331 Module *M = F.getParent();
332 LLVMContext &Context = M->getContext();
334 // Create a new function to receive the handler contents.
335 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
336 Type *Int32Type = Type::getInt32Ty(Context);
337 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
339 for (LandingPadInst *LPad : LPads) {
340 // Look for evidence that this landingpad has already been processed.
341 bool LPadHasActionList = false;
342 BasicBlock *LPadBB = LPad->getParent();
343 for (Instruction &Inst : *LPadBB) {
344 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
345 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
346 LPadHasActionList = true;
350 // FIXME: This is here to help with the development of nested landing pad
351 // outlining. It should be removed when that is finished.
352 if (isa<UnreachableInst>(Inst)) {
353 LPadHasActionList = true;
358 // If we've already outlined the handlers for this landingpad,
359 // there's nothing more to do here.
360 if (LPadHasActionList)
363 LandingPadActions Actions;
364 mapLandingPadBlocks(LPad, Actions);
366 for (ActionHandler *Action : Actions) {
367 if (Action->hasBeenProcessed())
369 BasicBlock *StartBB = Action->getStartBlock();
371 // SEH doesn't do any outlining for catches. Instead, pass the handler
372 // basic block addr to llvm.eh.actions and list the block as a return
374 if (isAsynchronousEHPersonality(Personality)) {
375 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
376 processSEHCatchHandler(CatchAction, StartBB);
377 HandlersOutlined = true;
382 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
383 HandlersOutlined = true;
385 } // End for each Action
387 // FIXME: We need a guard against partially outlined functions.
388 if (!HandlersOutlined)
391 // Replace the landing pad with a new llvm.eh.action based landing pad.
392 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
393 assert(!isa<PHINode>(LPadBB->begin()));
394 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
395 NewLPadBB->getInstList().push_back(NewLPad);
396 while (!pred_empty(LPadBB)) {
397 auto *pred = *pred_begin(LPadBB);
398 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
399 Invoke->setUnwindDest(NewLPadBB);
402 // Replace uses of the old lpad in phis with this block and delete the old
404 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
405 LPadBB->getTerminator()->eraseFromParent();
406 new UnreachableInst(LPadBB->getContext(), LPadBB);
408 // Add a call to describe the actions for this landing pad.
409 std::vector<Value *> ActionArgs;
410 for (ActionHandler *Action : Actions) {
411 // Action codes from docs are: 0 cleanup, 1 catch.
412 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
413 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
414 ActionArgs.push_back(CatchAction->getSelector());
415 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
417 ActionArgs.push_back(EHObj);
419 ActionArgs.push_back(ConstantPointerNull::get(Int8PtrType));
421 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
423 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
426 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
428 // Add an indirect branch listing possible successors of the catch handlers.
429 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
430 for (ActionHandler *Action : Actions) {
431 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
432 for (auto *Target : CatchAction->getReturnTargets()) {
433 Branch->addDestination(Target);
437 } // End for each landingpad
439 // If nothing got outlined, there is no more processing to be done.
440 if (!HandlersOutlined)
443 F.addFnAttr("wineh-parent", F.getName());
445 // Delete any blocks that were only used by handlers that were outlined above.
446 removeUnreachableBlocks(F);
448 BasicBlock *Entry = &F.getEntryBlock();
449 IRBuilder<> Builder(F.getParent()->getContext());
450 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
452 Function *FrameEscapeFn =
453 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
454 Function *RecoverFrameFn =
455 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
457 // Finally, replace all of the temporary allocas for frame variables used in
458 // the outlined handlers with calls to llvm.framerecover.
459 BasicBlock::iterator II = Entry->getFirstInsertionPt();
460 Instruction *AllocaInsertPt = II;
461 SmallVector<Value *, 8> AllocasToEscape;
462 for (auto &VarInfoEntry : FrameVarInfo) {
463 Value *ParentVal = VarInfoEntry.first;
464 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
466 // If the mapped value isn't already an alloca, we need to spill it if it
467 // is a computed value or copy it if it is an argument.
468 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
470 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
471 // Lower this argument to a copy and then demote that to the stack.
472 // We can't just use the argument location because the handler needs
473 // it to be in the frame allocation block.
474 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
475 Value *TrueValue = ConstantInt::getTrue(Context);
476 Value *UndefValue = UndefValue::get(Arg->getType());
478 SelectInst::Create(TrueValue, Arg, UndefValue,
479 Arg->getName() + ".tmp", AllocaInsertPt);
480 Arg->replaceAllUsesWith(SI);
481 // Reset the select operand, because it was clobbered by the RAUW above.
482 SI->setOperand(1, Arg);
483 ParentAlloca = DemoteRegToStack(*SI, true, SI);
484 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
485 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
487 Instruction *ParentInst = cast<Instruction>(ParentVal);
488 // FIXME: This is a work-around to temporarily handle the case where an
489 // instruction that is only used in handlers is not sunk.
490 // Without uses, DemoteRegToStack would just eliminate the value.
491 // This will fail if ParentInst is an invoke.
492 if (ParentInst->getNumUses() == 0) {
493 BasicBlock::iterator InsertPt = ParentInst;
496 new AllocaInst(ParentInst->getType(), nullptr,
497 ParentInst->getName() + ".reg2mem", InsertPt);
498 new StoreInst(ParentInst, ParentAlloca, InsertPt);
500 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
505 // If the parent alloca is no longer used and only one of the handlers used
506 // it, erase the parent and leave the copy in the outlined handler.
507 if (ParentAlloca->getNumUses() == 0 && Allocas.size() == 1) {
508 ParentAlloca->eraseFromParent();
512 // Add this alloca to the list of things to escape.
513 AllocasToEscape.push_back(ParentAlloca);
515 // Next replace all outlined allocas that are mapped to it.
516 for (AllocaInst *TempAlloca : Allocas) {
517 Function *HandlerFn = TempAlloca->getParent()->getParent();
518 // FIXME: Sink this GEP into the blocks where it is used.
519 Builder.SetInsertPoint(TempAlloca);
520 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
521 Value *RecoverArgs[] = {
522 Builder.CreateBitCast(&F, Int8PtrType, ""),
523 &(HandlerFn->getArgumentList().back()),
524 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
525 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
526 // Add a pointer bitcast if the alloca wasn't an i8.
527 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
528 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
530 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
532 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
533 TempAlloca->removeFromParent();
534 RecoveredAlloca->takeName(TempAlloca);
537 } // End for each FrameVarInfo entry.
539 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
541 Builder.SetInsertPoint(&F.getEntryBlock().back());
542 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
544 // Insert an alloca for the EH state in the entry block. On x86, we will also
545 // insert stores to update the EH state, but on other ISAs, the runtime does
547 // FIXME: This record is different on x86.
548 Type *UnwindHelpTy = Type::getInt64Ty(Context);
549 AllocaInst *UnwindHelp =
550 new AllocaInst(UnwindHelpTy, "unwindhelp", &F.getEntryBlock().front());
551 Builder.CreateStore(llvm::ConstantInt::get(UnwindHelpTy, -2), UnwindHelp,
552 /*isVolatile=*/true);
553 Function *UnwindHelpFn =
554 Intrinsic::getDeclaration(M, Intrinsic::eh_unwindhelp);
555 Builder.CreateCall(UnwindHelpFn,
556 Builder.CreateBitCast(UnwindHelp, Int8PtrType));
558 // Clean up the handler action maps we created for this function
559 DeleteContainerSeconds(CatchHandlerMap);
560 CatchHandlerMap.clear();
561 DeleteContainerSeconds(CleanupHandlerMap);
562 CleanupHandlerMap.clear();
564 return HandlersOutlined;
567 // This function examines a block to determine whether the block ends with a
568 // conditional branch to a catch handler based on a selector comparison.
569 // This function is used both by the WinEHPrepare::findSelectorComparison() and
570 // WinEHCleanupDirector::handleTypeIdFor().
571 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
572 Constant *&Selector, BasicBlock *&NextBB) {
573 ICmpInst::Predicate Pred;
574 BasicBlock *TBB, *FBB;
577 if (!match(BB->getTerminator(),
578 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
582 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
583 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
586 if (Pred == CmpInst::ICMP_EQ) {
592 if (Pred == CmpInst::ICMP_NE) {
601 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
602 LandingPadInst *LPad, BasicBlock *StartBB,
603 FrameVarInfoMap &VarInfo) {
604 Module *M = SrcFn->getParent();
605 LLVMContext &Context = M->getContext();
607 // Create a new function to receive the handler contents.
608 Type *Int8PtrType = Type::getInt8PtrTy(Context);
609 std::vector<Type *> ArgTys;
610 ArgTys.push_back(Int8PtrType);
611 ArgTys.push_back(Int8PtrType);
613 if (Action->getType() == Catch) {
614 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
615 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
616 SrcFn->getName() + ".catch", M);
618 FunctionType *FnType =
619 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
620 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
621 SrcFn->getName() + ".cleanup", M);
624 Handler->addFnAttr("wineh-parent", SrcFn->getName());
626 // Generate a standard prolog to setup the frame recovery structure.
627 IRBuilder<> Builder(Context);
628 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
629 Handler->getBasicBlockList().push_front(Entry);
630 Builder.SetInsertPoint(Entry);
631 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
633 std::unique_ptr<WinEHCloningDirectorBase> Director;
635 ValueToValueMapTy VMap;
637 LandingPadMap &LPadMap = LPadMaps[LPad];
638 if (!LPadMap.isInitialized())
639 LPadMap.mapLandingPad(LPad);
640 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
641 // Insert an alloca for the object which holds the address of the parent's
642 // frame pointer. The stack offset of this object needs to be encoded in
644 AllocaInst *ParentFrame = new AllocaInst(Int8PtrType, "parentframe", Entry);
645 Builder.CreateStore(&Handler->getArgumentList().back(), ParentFrame,
647 Function *ParentFrameFn =
648 Intrinsic::getDeclaration(M, Intrinsic::eh_parentframe);
649 Builder.CreateCall(ParentFrameFn, ParentFrame);
651 Constant *Sel = CatchAction->getSelector();
652 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap));
653 LPadMap.remapSelector(VMap, ConstantInt::get(Type::getInt32Ty(Context), 1));
655 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
658 SmallVector<ReturnInst *, 8> Returns;
659 ClonedCodeInfo OutlinedFunctionInfo;
661 // If the start block contains PHI nodes, we need to map them.
662 BasicBlock::iterator II = StartBB->begin();
663 while (auto *PN = dyn_cast<PHINode>(II)) {
665 // Look for PHI values that we have already mapped (such as the selector).
666 for (Value *Val : PN->incoming_values()) {
667 if (VMap.count(Val)) {
668 VMap[PN] = VMap[Val];
672 // If we didn't find a match for this value, map it as an undef.
674 VMap[PN] = UndefValue::get(PN->getType());
679 // Skip over PHIs and, if applicable, landingpad instructions.
680 II = StartBB->getFirstInsertionPt();
682 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
683 /*ModuleLevelChanges=*/false, Returns, "",
684 &OutlinedFunctionInfo, Director.get());
686 // Move all the instructions in the first cloned block into our entry block.
687 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
688 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
689 FirstClonedBB->eraseFromParent();
691 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
692 WinEHCatchDirector *CatchDirector =
693 reinterpret_cast<WinEHCatchDirector *>(Director.get());
694 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
695 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
698 Action->setHandlerBlockOrFunc(Handler);
703 /// This BB must end in a selector dispatch. All we need to do is pass the
704 /// handler block to llvm.eh.actions and list it as a possible indirectbr
706 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
707 BasicBlock *StartBB) {
708 BasicBlock *HandlerBB;
711 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
713 // If this was EH dispatch, this must be a conditional branch to the handler
715 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
716 // leading to crashes if some optimization hoists stuff here.
717 assert(CatchAction->getSelector() && HandlerBB &&
718 "expected catch EH dispatch");
720 // This must be a catch-all. Split the block after the landingpad.
721 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
723 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
725 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
726 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
727 CatchAction->setReturnTargets(Targets);
730 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
731 // Each instance of this class should only ever be used to map a single
733 assert(OriginLPad == nullptr || OriginLPad == LPad);
735 // If the landing pad has already been mapped, there's nothing more to do.
736 if (OriginLPad == LPad)
741 // The landingpad instruction returns an aggregate value. Typically, its
742 // value will be passed to a pair of extract value instructions and the
743 // results of those extracts are often passed to store instructions.
744 // In unoptimized code the stored value will often be loaded and then stored
746 for (auto *U : LPad->users()) {
747 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
750 assert(Extract->getNumIndices() == 1 &&
751 "Unexpected operation: extracting both landing pad values");
752 unsigned int Idx = *(Extract->idx_begin());
753 assert((Idx == 0 || Idx == 1) &&
754 "Unexpected operation: extracting an unknown landing pad element");
756 // Element 0 doesn't directly corresponds to anything in the WinEH
758 // It will be stored to a memory location, then later loaded and finally
759 // the loaded value will be used as the argument to an
760 // llvm.eh.begincatch
761 // call. We're tracking it here so that we can skip the store and load.
762 ExtractedEHPtrs.push_back(Extract);
763 } else if (Idx == 1) {
764 // Element 1 corresponds to the filter selector. We'll map it to 1 for
765 // matching purposes, but it will also probably be stored to memory and
766 // reloaded, so we need to track the instuction so that we can map the
768 ExtractedSelectors.push_back(Extract);
771 // Look for stores of the extracted values.
772 for (auto *EU : Extract->users()) {
773 if (auto *Store = dyn_cast<StoreInst>(EU)) {
775 SelectorStores.push_back(Store);
776 SelectorStoreAddrs.push_back(Store->getPointerOperand());
778 EHPtrStores.push_back(Store);
779 EHPtrStoreAddrs.push_back(Store->getPointerOperand());
786 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
787 return BB->getLandingPadInst() == OriginLPad;
790 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
791 if (Inst == OriginLPad)
793 for (auto *Extract : ExtractedEHPtrs) {
797 for (auto *Extract : ExtractedSelectors) {
801 for (auto *Store : EHPtrStores) {
805 for (auto *Store : SelectorStores) {
813 void LandingPadMap::remapSelector(ValueToValueMapTy &VMap,
814 Value *MappedValue) const {
815 // Remap all selector extract instructions to the specified value.
816 for (auto *Extract : ExtractedSelectors)
817 VMap[Extract] = MappedValue;
820 bool LandingPadMap::mapIfEHLoad(const LoadInst *Load,
821 SmallVectorImpl<const StoreInst *> &Stores,
822 SmallVectorImpl<const Value *> &StoreAddrs) {
823 // This makes the assumption that a store we've previously seen dominates
824 // this load instruction. That might seem like a rather huge assumption,
825 // but given the way that landingpads are constructed its fairly safe.
826 // FIXME: Add debug/assert code that verifies this.
827 const Value *LoadAddr = Load->getPointerOperand();
828 for (auto *StoreAddr : StoreAddrs) {
829 if (LoadAddr == StoreAddr) {
830 // Handle the common debug scenario where this loaded value is stored
831 // to a different location.
832 for (auto *U : Load->users()) {
833 if (auto *Store = dyn_cast<StoreInst>(U)) {
834 Stores.push_back(Store);
835 StoreAddrs.push_back(Store->getPointerOperand());
844 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
845 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
846 // If this is one of the boilerplate landing pad instructions, skip it.
847 // The instruction will have already been remapped in VMap.
848 if (LPadMap.isLandingPadSpecificInst(Inst))
849 return CloningDirector::SkipInstruction;
851 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
852 // Look for loads of (previously suppressed) landingpad values.
853 // The EHPtr load can be mapped to an undef value as it should only be used
854 // as an argument to llvm.eh.begincatch, but the selector value needs to be
855 // mapped to a constant value of 1. This value will be used to simplify the
856 // branching to always flow to the current handler.
857 if (LPadMap.mapIfSelectorLoad(Load)) {
858 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
859 return CloningDirector::SkipInstruction;
861 if (LPadMap.mapIfEHPtrLoad(Load)) {
862 VMap[Inst] = UndefValue::get(Int8PtrType);
863 return CloningDirector::SkipInstruction;
866 // Any other loads just get cloned.
867 return CloningDirector::CloneInstruction;
870 // Nested landing pads will be cloned as stubs, with just the
871 // landingpad instruction and an unreachable instruction. When
872 // all landingpads have been outlined, we'll replace this with the
873 // llvm.eh.actions call and indirect branch created when the
874 // landing pad was outlined.
875 if (auto *NestedLPad = dyn_cast<LandingPadInst>(Inst)) {
876 Instruction *NewInst = NestedLPad->clone();
877 if (NestedLPad->hasName())
878 NewInst->setName(NestedLPad->getName());
879 // FIXME: Store this mapping somewhere else also.
880 VMap[NestedLPad] = NewInst;
881 BasicBlock::InstListType &InstList = NewBB->getInstList();
882 InstList.push_back(NewInst);
883 InstList.push_back(new UnreachableInst(NewBB->getContext()));
884 return CloningDirector::StopCloningBB;
887 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
888 return handleInvoke(VMap, Invoke, NewBB);
890 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
891 return handleResume(VMap, Resume, NewBB);
893 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
894 return handleBeginCatch(VMap, Inst, NewBB);
895 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
896 return handleEndCatch(VMap, Inst, NewBB);
897 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
898 return handleTypeIdFor(VMap, Inst, NewBB);
900 // Continue with the default cloning behavior.
901 return CloningDirector::CloneInstruction;
904 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
905 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
906 // The argument to the call is some form of the first element of the
907 // landingpad aggregate value, but that doesn't matter. It isn't used
909 // The second argument is an outparameter where the exception object will be
910 // stored. Typically the exception object is a scalar, but it can be an
911 // aggregate when catching by value.
912 // FIXME: Leave something behind to indicate where the exception object lives
913 // for this handler. Should it be part of llvm.eh.actions?
914 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
915 "llvm.eh.begincatch found while "
916 "outlining catch handler.");
917 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
918 return CloningDirector::SkipInstruction;
921 CloningDirector::CloningAction
922 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
923 const Instruction *Inst, BasicBlock *NewBB) {
924 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
925 // It might be interesting to track whether or not we are inside a catch
926 // function, but that might make the algorithm more brittle than it needs
929 // The end catch call can occur in one of two places: either in a
930 // landingpad block that is part of the catch handlers exception mechanism,
931 // or at the end of the catch block. However, a catch-all handler may call
932 // end catch from the original landing pad. If the call occurs in a nested
933 // landing pad block, we must skip it and continue so that the landing pad
935 auto *ParentBB = IntrinCall->getParent();
936 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
937 return CloningDirector::SkipInstruction;
939 // If an end catch occurs anywhere else the next instruction should be an
940 // unconditional branch instruction that we want to replace with a return
941 // to the the address of the branch target.
942 const BasicBlock *EndCatchBB = IntrinCall->getParent();
943 const TerminatorInst *Terminator = EndCatchBB->getTerminator();
944 const BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
945 assert(Branch && Branch->isUnconditional());
946 assert(std::next(BasicBlock::const_iterator(IntrinCall)) ==
947 BasicBlock::const_iterator(Branch));
949 BasicBlock *ContinueLabel = Branch->getSuccessor(0);
950 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueLabel),
952 ReturnTargets.push_back(ContinueLabel);
954 // We just added a terminator to the cloned block.
955 // Tell the caller to stop processing the current basic block so that
956 // the branch instruction will be skipped.
957 return CloningDirector::StopCloningBB;
960 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
961 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
962 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
963 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
964 // This causes a replacement that will collapse the landing pad CFG based
965 // on the filter function we intend to match.
966 if (Selector == CurrentSelector)
967 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
969 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
970 // Tell the caller not to clone this instruction.
971 return CloningDirector::SkipInstruction;
974 CloningDirector::CloningAction
975 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
976 const InvokeInst *Invoke, BasicBlock *NewBB) {
977 return CloningDirector::CloneInstruction;
980 CloningDirector::CloningAction
981 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
982 const ResumeInst *Resume, BasicBlock *NewBB) {
983 // Resume instructions shouldn't be reachable from catch handlers.
984 // We still need to handle it, but it will be pruned.
985 BasicBlock::InstListType &InstList = NewBB->getInstList();
986 InstList.push_back(new UnreachableInst(NewBB->getContext()));
987 return CloningDirector::StopCloningBB;
990 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
991 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
992 // Catch blocks within cleanup handlers will always be unreachable.
993 // We'll insert an unreachable instruction now, but it will be pruned
994 // before the cloning process is complete.
995 BasicBlock::InstListType &InstList = NewBB->getInstList();
996 InstList.push_back(new UnreachableInst(NewBB->getContext()));
997 return CloningDirector::StopCloningBB;
1000 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1001 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1002 // Catch blocks within cleanup handlers will always be unreachable.
1003 // We'll insert an unreachable instruction now, but it will be pruned
1004 // before the cloning process is complete.
1005 BasicBlock::InstListType &InstList = NewBB->getInstList();
1006 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1007 return CloningDirector::StopCloningBB;
1010 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1011 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1012 // If we encounter a selector comparison while cloning a cleanup handler,
1013 // we want to stop cloning immediately. Anything after the dispatch
1014 // will be outlined into a different handler.
1015 BasicBlock *CatchHandler;
1018 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1019 CatchHandler, Selector, NextBB)) {
1020 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1021 return CloningDirector::StopCloningBB;
1023 // If eg.typeid.for is called for any other reason, it can be ignored.
1024 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1025 return CloningDirector::SkipInstruction;
1028 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1029 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1030 // All invokes in cleanup handlers can be replaced with calls.
1031 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1032 // Insert a normal call instruction...
1034 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1035 Invoke->getName(), NewBB);
1036 NewCall->setCallingConv(Invoke->getCallingConv());
1037 NewCall->setAttributes(Invoke->getAttributes());
1038 NewCall->setDebugLoc(Invoke->getDebugLoc());
1039 VMap[Invoke] = NewCall;
1041 // Insert an unconditional branch to the normal destination.
1042 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1044 // The unwind destination won't be cloned into the new function, so
1045 // we don't need to clean up its phi nodes.
1047 // We just added a terminator to the cloned block.
1048 // Tell the caller to stop processing the current basic block.
1049 return CloningDirector::StopCloningBB;
1052 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1053 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1054 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1056 // We just added a terminator to the cloned block.
1057 // Tell the caller to stop processing the current basic block so that
1058 // the branch instruction will be skipped.
1059 return CloningDirector::StopCloningBB;
1062 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1063 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1064 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1065 Builder.SetInsertPoint(&OutlinedFn->getEntryBlock());
1068 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1069 // If we're asked to materialize a value that is an instruction, we
1070 // temporarily create an alloca in the outlined function and add this
1071 // to the FrameVarInfo map. When all the outlining is complete, we'll
1072 // collect these into a structure, spilling non-alloca values in the
1073 // parent frame as necessary, and replace these temporary allocas with
1074 // GEPs referencing the frame allocation block.
1076 // If the value is an alloca, the mapping is direct.
1077 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1078 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1079 Builder.Insert(NewAlloca, AV->getName());
1080 FrameVarInfo[AV].push_back(NewAlloca);
1084 // For other types of instructions or arguments, we need an alloca based on
1085 // the value's type and a load of the alloca. The alloca will be replaced
1086 // by a GEP, but the load will stay. In the parent function, the value will
1087 // be spilled to a location in the frame allocation block.
1088 if (isa<Instruction>(V) || isa<Argument>(V)) {
1089 AllocaInst *NewAlloca =
1090 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1091 FrameVarInfo[V].push_back(NewAlloca);
1092 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1096 // Don't materialize other values.
1100 // This function maps the catch and cleanup handlers that are reachable from the
1101 // specified landing pad. The landing pad sequence will have this basic shape:
1103 // <cleanup handler>
1104 // <selector comparison>
1106 // <cleanup handler>
1107 // <selector comparison>
1109 // <cleanup handler>
1112 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1113 // any arbitrary control flow, but all paths through the cleanup code must
1114 // eventually reach the next selector comparison and no path can skip to a
1115 // different selector comparisons, though some paths may terminate abnormally.
1116 // Therefore, we will use a depth first search from the start of any given
1117 // cleanup block and stop searching when we find the next selector comparison.
1119 // If the landingpad instruction does not have a catch clause, we will assume
1120 // that any instructions other than selector comparisons and catch handlers can
1121 // be ignored. In practice, these will only be the boilerplate instructions.
1123 // The catch handlers may also have any control structure, but we are only
1124 // interested in the start of the catch handlers, so we don't need to actually
1125 // follow the flow of the catch handlers. The start of the catch handlers can
1126 // be located from the compare instructions, but they can be skipped in the
1127 // flow by following the contrary branch.
1128 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1129 LandingPadActions &Actions) {
1130 unsigned int NumClauses = LPad->getNumClauses();
1131 unsigned int HandlersFound = 0;
1132 BasicBlock *BB = LPad->getParent();
1134 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1136 if (NumClauses == 0) {
1137 // This landing pad contains only cleanup code.
1138 CleanupHandler *Action = new CleanupHandler(BB);
1139 CleanupHandlerMap[BB] = Action;
1140 Actions.insertCleanupHandler(Action);
1141 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1143 assert(LPad->isCleanup());
1147 VisitedBlockSet VisitedBlocks;
1149 while (HandlersFound != NumClauses) {
1150 BasicBlock *NextBB = nullptr;
1152 // See if the clause we're looking for is a catch-all.
1153 // If so, the catch begins immediately.
1154 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1155 // The catch all must occur last.
1156 assert(HandlersFound == NumClauses - 1);
1158 // For C++ EH, check if there is any interesting cleanup code before we
1159 // begin the catch. This is important because cleanups cannot rethrow
1160 // exceptions but code called from catches can. For SEH, it isn't
1161 // important if some finally code before a catch-all is executed out of
1162 // line or after recovering from the exception.
1163 if (Personality == EHPersonality::MSVC_CXX) {
1164 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1165 // Add a cleanup entry to the list
1166 Actions.insertCleanupHandler(CleanupAction);
1167 DEBUG(dbgs() << " Found cleanup code in block "
1168 << CleanupAction->getStartBlock()->getName() << "\n");
1172 // Add the catch handler to the action list.
1173 CatchHandler *Action =
1174 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1175 CatchHandlerMap[BB] = Action;
1176 Actions.insertCatchHandler(Action);
1177 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1180 // Once we reach a catch-all, don't expect to hit a resume instruction.
1185 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1186 // See if there is any interesting code executed before the dispatch.
1187 if (auto *CleanupAction =
1188 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1189 // Add a cleanup entry to the list
1190 Actions.insertCleanupHandler(CleanupAction);
1191 DEBUG(dbgs() << " Found cleanup code in block "
1192 << CleanupAction->getStartBlock()->getName() << "\n");
1195 assert(CatchAction);
1198 // Add the catch handler to the action list.
1199 Actions.insertCatchHandler(CatchAction);
1200 DEBUG(dbgs() << " Found catch dispatch in block "
1201 << CatchAction->getStartBlock()->getName() << "\n");
1203 // Move on to the block after the catch handler.
1207 // If we didn't wind up in a catch-all, see if there is any interesting code
1208 // executed before the resume.
1209 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1210 // Add a cleanup entry to the list
1211 Actions.insertCleanupHandler(CleanupAction);
1212 DEBUG(dbgs() << " Found cleanup code in block "
1213 << CleanupAction->getStartBlock()->getName() << "\n");
1216 // It's possible that some optimization moved code into a landingpad that
1218 // previously being used for cleanup. If that happens, we need to execute
1220 // extra code from a cleanup handler.
1221 if (Actions.includesCleanup() && !LPad->isCleanup())
1222 LPad->setCleanup(true);
1225 // This function searches starting with the input block for the next
1226 // block that terminates with a branch whose condition is based on a selector
1227 // comparison. This may be the input block. See the mapLandingPadBlocks
1228 // comments for a discussion of control flow assumptions.
1230 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1231 BasicBlock *&NextBB,
1232 VisitedBlockSet &VisitedBlocks) {
1233 // See if we've already found a catch handler use it.
1234 // Call count() first to avoid creating a null entry for blocks
1235 // we haven't seen before.
1236 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1237 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1238 NextBB = Action->getNextBB();
1242 // VisitedBlocks applies only to the current search. We still
1243 // need to consider blocks that we've visited while mapping other
1245 VisitedBlocks.insert(BB);
1247 BasicBlock *CatchBlock = nullptr;
1248 Constant *Selector = nullptr;
1250 // If this is the first time we've visited this block from any landing pad
1251 // look to see if it is a selector dispatch block.
1252 if (!CatchHandlerMap.count(BB)) {
1253 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1254 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1255 CatchHandlerMap[BB] = Action;
1260 // Visit each successor, looking for the dispatch.
1261 // FIXME: We expect to find the dispatch quickly, so this will probably
1262 // work better as a breadth first search.
1263 for (BasicBlock *Succ : successors(BB)) {
1264 if (VisitedBlocks.count(Succ))
1267 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1274 // These are helper functions to combine repeated code from findCleanupHandler.
1275 static CleanupHandler *createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap,
1277 CleanupHandler *Action = new CleanupHandler(BB);
1278 CleanupHandlerMap[BB] = Action;
1282 // This function searches starting with the input block for the next block that
1283 // contains code that is not part of a catch handler and would not be eliminated
1284 // during handler outlining.
1286 CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1287 BasicBlock *EndBB) {
1288 // Here we will skip over the following:
1290 // landing pad prolog:
1292 // Unconditional branches
1294 // Selector dispatch
1298 // Anything else marks the start of an interesting block
1300 BasicBlock *BB = StartBB;
1301 // Anything other than an unconditional branch will kick us out of this loop
1302 // one way or another.
1304 // If we've already scanned this block, don't scan it again. If it is
1305 // a cleanup block, there will be an action in the CleanupHandlerMap.
1306 // If we've scanned it and it is not a cleanup block, there will be a
1307 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1308 // be no entry in the CleanupHandlerMap. We must call count() first to
1309 // avoid creating a null entry for blocks we haven't scanned.
1310 if (CleanupHandlerMap.count(BB)) {
1311 if (auto *Action = CleanupHandlerMap[BB]) {
1312 return cast<CleanupHandler>(Action);
1314 // Here we handle the case where the cleanup handler map contains a
1315 // value for this block but the value is a nullptr. This means that
1316 // we have previously analyzed the block and determined that it did
1317 // not contain any cleanup code. Based on the earlier analysis, we
1318 // know the the block must end in either an unconditional branch, a
1319 // resume or a conditional branch that is predicated on a comparison
1320 // with a selector. Either the resume or the selector dispatch
1321 // would terminate the search for cleanup code, so the unconditional
1322 // branch is the only case for which we might need to continue
1327 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1334 // Create an entry in the cleanup handler map for this block. Initially
1335 // we create an entry that says this isn't a cleanup block. If we find
1336 // cleanup code, the caller will replace this entry.
1337 CleanupHandlerMap[BB] = nullptr;
1339 TerminatorInst *Terminator = BB->getTerminator();
1341 // Landing pad blocks have extra instructions we need to accept.
1342 LandingPadMap *LPadMap = nullptr;
1343 if (BB->isLandingPad()) {
1344 LandingPadInst *LPad = BB->getLandingPadInst();
1345 LPadMap = &LPadMaps[LPad];
1346 if (!LPadMap->isInitialized())
1347 LPadMap->mapLandingPad(LPad);
1350 // Look for the bare resume pattern:
1351 // %exn2 = load i8** %exn.slot
1352 // %sel2 = load i32* %ehselector.slot
1353 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn2, 0
1354 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel2, 1
1355 // resume { i8*, i32 } %lpad.val2
1356 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1357 InsertValueInst *Insert1 = nullptr;
1358 InsertValueInst *Insert2 = nullptr;
1359 Value *ResumeVal = Resume->getOperand(0);
1360 // If there is only one landingpad, we may use the lpad directly with no
1362 if (isa<LandingPadInst>(ResumeVal))
1364 if (!isa<PHINode>(ResumeVal)) {
1365 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1367 return createCleanupHandler(CleanupHandlerMap, BB);
1368 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1370 return createCleanupHandler(CleanupHandlerMap, BB);
1372 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1374 Instruction *Inst = II;
1375 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1377 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1379 if (!Inst->hasOneUse() ||
1380 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1381 return createCleanupHandler(CleanupHandlerMap, BB);
1387 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1389 if (Branch->isConditional()) {
1390 // Look for the selector dispatch.
1391 // %sel = load i32* %ehselector.slot
1392 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1393 // %matches = icmp eq i32 %sel12, %2
1394 // br i1 %matches, label %catch14, label %eh.resume
1395 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1396 if (!Compare || !Compare->isEquality())
1397 return createCleanupHandler(CleanupHandlerMap, BB);
1398 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1401 Instruction *Inst = II;
1402 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1404 if (Inst == Compare || Inst == Branch)
1406 if (!Inst->hasOneUse() || (Inst->user_back() != Compare))
1407 return createCleanupHandler(CleanupHandlerMap, BB);
1408 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1410 if (!isa<LoadInst>(Inst))
1411 return createCleanupHandler(CleanupHandlerMap, BB);
1413 // The selector dispatch block should always terminate our search.
1414 assert(BB == EndBB);
1417 // Look for empty blocks with unconditional branches.
1418 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(),
1421 Instruction *Inst = II;
1422 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1426 // This can happen with a catch-all handler.
1427 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1429 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1431 // Anything else makes this interesting cleanup code.
1432 return createCleanupHandler(CleanupHandlerMap, BB);
1436 // The branch was unconditional.
1437 BB = Branch->getSuccessor(0);
1439 } // End else of if branch was conditional
1442 // Anything else makes this interesting cleanup code.
1443 return createCleanupHandler(CleanupHandlerMap, BB);