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/Dominators.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PatternMatch.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Cloning.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
42 using namespace llvm::PatternMatch;
44 #define DEBUG_TYPE "winehprepare"
48 // This map is used to model frame variable usage during outlining, to
49 // construct a structure type to hold the frame variables in a frame
50 // allocation block, and to remap the frame variable allocas (including
51 // spill locations as needed) to GEPs that get the variable from the
52 // frame allocation structure.
53 typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
55 // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
57 AllocaInst *getCatchObjectSentinel() {
58 return static_cast<AllocaInst *>(nullptr) + 1;
61 typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
63 class LandingPadActions;
66 typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
67 typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
69 class WinEHPrepare : public FunctionPass {
71 static char ID; // Pass identification, replacement for typeid.
72 WinEHPrepare(const TargetMachine *TM = nullptr)
73 : FunctionPass(ID), DT(nullptr) {}
75 bool runOnFunction(Function &Fn) override;
77 bool doFinalization(Module &M) override;
79 void getAnalysisUsage(AnalysisUsage &AU) const override;
81 const char *getPassName() const override {
82 return "Windows exception handling preparation";
86 bool prepareExceptionHandlers(Function &F,
87 SmallVectorImpl<LandingPadInst *> &LPads);
88 void promoteLandingPadValues(LandingPadInst *LPad);
89 void completeNestedLandingPad(Function *ParentFn,
90 LandingPadInst *OutlinedLPad,
91 const LandingPadInst *OriginalLPad,
92 FrameVarInfoMap &VarInfo);
93 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
94 LandingPadInst *LPad, BasicBlock *StartBB,
95 FrameVarInfoMap &VarInfo);
96 void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
98 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
99 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
100 VisitedBlockSet &VisitedBlocks);
101 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
104 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
106 // All fields are reset by runOnFunction.
108 EHPersonality Personality;
109 CatchHandlerMapTy CatchHandlerMap;
110 CleanupHandlerMapTy CleanupHandlerMap;
111 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
113 // This maps landing pad instructions found in outlined handlers to
114 // the landing pad instruction in the parent function from which they
115 // were cloned. The cloned/nested landing pad is used as the key
116 // because the landing pad may be cloned into multiple handlers.
117 // This map will be used to add the llvm.eh.actions call to the nested
118 // landing pads after all handlers have been outlined.
119 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
121 // This maps blocks in the parent function which are destinations of
122 // catch handlers to cloned blocks in (other) outlined handlers. This
123 // handles the case where a nested landing pads has a catch handler that
124 // returns to a handler function rather than the parent function.
125 // The original block is used as the key here because there should only
126 // ever be one handler function from which the cloned block is not pruned.
127 // The original block will be pruned from the parent function after all
128 // handlers have been outlined. This map will be used to adjust the
129 // return instructions of handlers which return to the block that was
130 // outlined into a handler. This is done after all handlers have been
131 // outlined but before the outlined code is pruned from the parent function.
132 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
135 class WinEHFrameVariableMaterializer : public ValueMaterializer {
137 WinEHFrameVariableMaterializer(Function *OutlinedFn,
138 FrameVarInfoMap &FrameVarInfo);
139 ~WinEHFrameVariableMaterializer() override {}
141 Value *materializeValueFor(Value *V) override;
143 void escapeCatchObject(Value *V);
146 FrameVarInfoMap &FrameVarInfo;
150 class LandingPadMap {
152 LandingPadMap() : OriginLPad(nullptr) {}
153 void mapLandingPad(const LandingPadInst *LPad);
155 bool isInitialized() { return OriginLPad != nullptr; }
157 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
158 bool isLandingPadSpecificInst(const Instruction *Inst) const;
160 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
161 Value *SelectorValue) const;
164 const LandingPadInst *OriginLPad;
165 // We will normally only see one of each of these instructions, but
166 // if more than one occurs for some reason we can handle that.
167 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
168 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
171 class WinEHCloningDirectorBase : public CloningDirector {
173 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
174 LandingPadMap &LPadMap)
175 : Materializer(HandlerFn, VarInfo),
176 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
177 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
179 auto AI = HandlerFn->getArgumentList().begin();
181 EstablisherFrame = AI;
184 CloningAction handleInstruction(ValueToValueMapTy &VMap,
185 const Instruction *Inst,
186 BasicBlock *NewBB) override;
188 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
189 const Instruction *Inst,
190 BasicBlock *NewBB) = 0;
191 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
192 const Instruction *Inst,
193 BasicBlock *NewBB) = 0;
194 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
195 const Instruction *Inst,
196 BasicBlock *NewBB) = 0;
197 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
198 const InvokeInst *Invoke,
199 BasicBlock *NewBB) = 0;
200 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
201 const ResumeInst *Resume,
202 BasicBlock *NewBB) = 0;
203 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
204 const CmpInst *Compare,
205 BasicBlock *NewBB) = 0;
206 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
207 const LandingPadInst *LPad,
208 BasicBlock *NewBB) = 0;
210 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
213 WinEHFrameVariableMaterializer Materializer;
214 Type *SelectorIDType;
216 LandingPadMap &LPadMap;
218 /// The value representing the parent frame pointer.
219 Value *EstablisherFrame;
222 class WinEHCatchDirector : public WinEHCloningDirectorBase {
225 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
226 LandingPadMap &LPadMap,
227 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
228 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
229 CurrentSelector(Selector->stripPointerCasts()),
230 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
232 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
233 const Instruction *Inst,
234 BasicBlock *NewBB) override;
235 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
236 BasicBlock *NewBB) override;
237 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
238 const Instruction *Inst,
239 BasicBlock *NewBB) override;
240 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
241 BasicBlock *NewBB) override;
242 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
243 BasicBlock *NewBB) override;
244 CloningAction handleCompare(ValueToValueMapTy &VMap,
245 const CmpInst *Compare, BasicBlock *NewBB) override;
246 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
247 const LandingPadInst *LPad,
248 BasicBlock *NewBB) override;
250 Value *getExceptionVar() { return ExceptionObjectVar; }
251 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
254 Value *CurrentSelector;
256 Value *ExceptionObjectVar;
257 TinyPtrVector<BasicBlock *> ReturnTargets;
259 // This will be a reference to the field of the same name in the WinEHPrepare
260 // object which instantiates this WinEHCatchDirector object.
261 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
264 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
266 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
267 LandingPadMap &LPadMap)
268 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
270 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
271 const Instruction *Inst,
272 BasicBlock *NewBB) override;
273 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
274 BasicBlock *NewBB) override;
275 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
276 const Instruction *Inst,
277 BasicBlock *NewBB) override;
278 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
279 BasicBlock *NewBB) override;
280 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
281 BasicBlock *NewBB) override;
282 CloningAction handleCompare(ValueToValueMapTy &VMap,
283 const CmpInst *Compare, BasicBlock *NewBB) override;
284 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
285 const LandingPadInst *LPad,
286 BasicBlock *NewBB) override;
289 class LandingPadActions {
291 LandingPadActions() : HasCleanupHandlers(false) {}
293 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
294 void insertCleanupHandler(CleanupHandler *Action) {
295 Actions.push_back(Action);
296 HasCleanupHandlers = true;
299 bool includesCleanup() const { return HasCleanupHandlers; }
301 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
302 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
303 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
306 // Note that this class does not own the ActionHandler objects in this vector.
307 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
308 // in the WinEHPrepare class.
309 SmallVector<ActionHandler *, 4> Actions;
310 bool HasCleanupHandlers;
313 } // end anonymous namespace
315 char WinEHPrepare::ID = 0;
316 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
319 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
320 return new WinEHPrepare(TM);
323 // FIXME: Remove this once the backend can handle the prepared IR.
325 SEHPrepare("sehprepare", cl::Hidden,
326 cl::desc("Prepare functions with SEH personalities"));
328 bool WinEHPrepare::runOnFunction(Function &Fn) {
329 SmallVector<LandingPadInst *, 4> LPads;
330 SmallVector<ResumeInst *, 4> Resumes;
331 for (BasicBlock &BB : Fn) {
332 if (auto *LP = BB.getLandingPadInst())
334 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
335 Resumes.push_back(Resume);
338 // No need to prepare functions that lack landing pads.
342 // Classify the personality to see what kind of preparation we need.
343 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
345 // Do nothing if this is not an MSVC personality.
346 if (!isMSVCEHPersonality(Personality))
349 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
351 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
352 // Replace all resume instructions with unreachable.
353 // FIXME: Remove this once the backend can handle the prepared IR.
354 for (ResumeInst *Resume : Resumes) {
355 IRBuilder<>(Resume).CreateUnreachable();
356 Resume->eraseFromParent();
361 // If there were any landing pads, prepareExceptionHandlers will make changes.
362 prepareExceptionHandlers(Fn, LPads);
366 bool WinEHPrepare::doFinalization(Module &M) { return false; }
368 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.addRequired<DominatorTreeWrapperPass>();
372 bool WinEHPrepare::prepareExceptionHandlers(
373 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
374 // These containers are used to re-map frame variables that are used in
375 // outlined catch and cleanup handlers. They will be populated as the
376 // handlers are outlined.
377 FrameVarInfoMap FrameVarInfo;
379 bool HandlersOutlined = false;
381 Module *M = F.getParent();
382 LLVMContext &Context = M->getContext();
384 // Create a new function to receive the handler contents.
385 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
386 Type *Int32Type = Type::getInt32Ty(Context);
387 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
389 for (LandingPadInst *LPad : LPads) {
390 // Look for evidence that this landingpad has already been processed.
391 bool LPadHasActionList = false;
392 BasicBlock *LPadBB = LPad->getParent();
393 for (Instruction &Inst : *LPadBB) {
394 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
395 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
396 LPadHasActionList = true;
400 // FIXME: This is here to help with the development of nested landing pad
401 // outlining. It should be removed when that is finished.
402 if (isa<UnreachableInst>(Inst)) {
403 LPadHasActionList = true;
408 // If we've already outlined the handlers for this landingpad,
409 // there's nothing more to do here.
410 if (LPadHasActionList)
413 // If either of the values in the aggregate returned by the landing pad is
414 // extracted and stored to memory, promote the stored value to a register.
415 promoteLandingPadValues(LPad);
417 LandingPadActions Actions;
418 mapLandingPadBlocks(LPad, Actions);
420 HandlersOutlined |= !Actions.actions().empty();
421 for (ActionHandler *Action : Actions) {
422 if (Action->hasBeenProcessed())
424 BasicBlock *StartBB = Action->getStartBlock();
426 // SEH doesn't do any outlining for catches. Instead, pass the handler
427 // basic block addr to llvm.eh.actions and list the block as a return
429 if (isAsynchronousEHPersonality(Personality)) {
430 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
431 processSEHCatchHandler(CatchAction, StartBB);
436 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
439 // Replace the landing pad with a new llvm.eh.action based landing pad.
440 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
441 assert(!isa<PHINode>(LPadBB->begin()));
442 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
443 NewLPadBB->getInstList().push_back(NewLPad);
444 while (!pred_empty(LPadBB)) {
445 auto *pred = *pred_begin(LPadBB);
446 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
447 Invoke->setUnwindDest(NewLPadBB);
450 // If anyone is still using the old landingpad value, just give them undef
451 // instead. The eh pointer and selector values are not real.
452 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
454 // Replace the mapping of any nested landing pad that previously mapped
455 // to this landing pad with a referenced to the cloned version.
456 for (auto &LPadPair : NestedLPtoOriginalLP) {
457 const LandingPadInst *OriginalLPad = LPadPair.second;
458 if (OriginalLPad == LPad) {
459 LPadPair.second = NewLPad;
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 // Find the frame escape index of the exception object alloca in the
478 int FrameEscapeIdx = -1;
479 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
480 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
481 auto I = FrameVarInfo.find(EHObj);
482 assert(I != FrameVarInfo.end() &&
483 "failed to map llvm.eh.begincatch var");
484 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
486 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
488 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
490 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
493 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
495 // Add an indirect branch listing possible successors of the catch handlers.
496 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
497 for (ActionHandler *Action : Actions) {
498 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
499 for (auto *Target : CatchAction->getReturnTargets()) {
500 Branch->addDestination(Target);
504 } // End for each landingpad
506 // If nothing got outlined, there is no more processing to be done.
507 if (!HandlersOutlined)
510 // Replace any nested landing pad stubs with the correct action handler.
511 // This must be done before we remove unreachable blocks because it
512 // cleans up references to outlined blocks that will be deleted.
513 for (auto &LPadPair : NestedLPtoOriginalLP)
514 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
515 NestedLPtoOriginalLP.clear();
517 F.addFnAttr("wineh-parent", F.getName());
519 // Delete any blocks that were only used by handlers that were outlined above.
520 removeUnreachableBlocks(F);
522 BasicBlock *Entry = &F.getEntryBlock();
523 IRBuilder<> Builder(F.getParent()->getContext());
524 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
526 Function *FrameEscapeFn =
527 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
528 Function *RecoverFrameFn =
529 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
530 SmallVector<Value *, 8> AllocasToEscape;
532 // Scan the entry block for an existing call to llvm.frameescape. We need to
533 // keep escaping those objects.
534 for (Instruction &I : F.front()) {
535 auto *II = dyn_cast<IntrinsicInst>(&I);
536 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
537 auto Args = II->arg_operands();
538 AllocasToEscape.append(Args.begin(), Args.end());
539 II->eraseFromParent();
544 // Finally, replace all of the temporary allocas for frame variables used in
545 // the outlined handlers with calls to llvm.framerecover.
546 BasicBlock::iterator II = Entry->getFirstInsertionPt();
547 Instruction *AllocaInsertPt = II;
548 for (auto &VarInfoEntry : FrameVarInfo) {
549 Value *ParentVal = VarInfoEntry.first;
550 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
552 // If the mapped value isn't already an alloca, we need to spill it if it
553 // is a computed value or copy it if it is an argument.
554 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
556 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
557 // Lower this argument to a copy and then demote that to the stack.
558 // We can't just use the argument location because the handler needs
559 // it to be in the frame allocation block.
560 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
561 Value *TrueValue = ConstantInt::getTrue(Context);
562 Value *UndefValue = UndefValue::get(Arg->getType());
564 SelectInst::Create(TrueValue, Arg, UndefValue,
565 Arg->getName() + ".tmp", AllocaInsertPt);
566 Arg->replaceAllUsesWith(SI);
567 // Reset the select operand, because it was clobbered by the RAUW above.
568 SI->setOperand(1, Arg);
569 ParentAlloca = DemoteRegToStack(*SI, true, SI);
570 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
571 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
573 Instruction *ParentInst = cast<Instruction>(ParentVal);
574 // FIXME: This is a work-around to temporarily handle the case where an
575 // instruction that is only used in handlers is not sunk.
576 // Without uses, DemoteRegToStack would just eliminate the value.
577 // This will fail if ParentInst is an invoke.
578 if (ParentInst->getNumUses() == 0) {
579 BasicBlock::iterator InsertPt = ParentInst;
582 new AllocaInst(ParentInst->getType(), nullptr,
583 ParentInst->getName() + ".reg2mem",
585 new StoreInst(ParentInst, ParentAlloca, InsertPt);
587 ParentAlloca = DemoteRegToStack(*ParentInst, true, AllocaInsertPt);
592 // FIXME: We should try to sink unescaped allocas from the parent frame into
593 // the child frame. If the alloca is escaped, we have to use the lifetime
594 // markers to ensure that the alloca is only live within the child frame.
596 // Add this alloca to the list of things to escape.
597 AllocasToEscape.push_back(ParentAlloca);
599 // Next replace all outlined allocas that are mapped to it.
600 for (AllocaInst *TempAlloca : Allocas) {
601 if (TempAlloca == getCatchObjectSentinel())
602 continue; // Skip catch parameter sentinels.
603 Function *HandlerFn = TempAlloca->getParent()->getParent();
604 // FIXME: Sink this GEP into the blocks where it is used.
605 Builder.SetInsertPoint(TempAlloca);
606 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
607 Value *RecoverArgs[] = {
608 Builder.CreateBitCast(&F, Int8PtrType, ""),
609 &(HandlerFn->getArgumentList().back()),
610 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
611 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
612 // Add a pointer bitcast if the alloca wasn't an i8.
613 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
614 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
616 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
618 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
619 TempAlloca->removeFromParent();
620 RecoveredAlloca->takeName(TempAlloca);
623 } // End for each FrameVarInfo entry.
625 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
627 Builder.SetInsertPoint(&F.getEntryBlock().back());
628 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
630 // Clean up the handler action maps we created for this function
631 DeleteContainerSeconds(CatchHandlerMap);
632 CatchHandlerMap.clear();
633 DeleteContainerSeconds(CleanupHandlerMap);
634 CleanupHandlerMap.clear();
636 return HandlersOutlined;
639 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
640 // If the return values of the landing pad instruction are extracted and
641 // stored to memory, we want to promote the store locations to reg values.
642 SmallVector<AllocaInst *, 2> EHAllocas;
644 // The landingpad instruction returns an aggregate value. Typically, its
645 // value will be passed to a pair of extract value instructions and the
646 // results of those extracts are often passed to store instructions.
647 // In unoptimized code the stored value will often be loaded and then stored
649 for (auto *U : LPad->users()) {
650 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
654 for (auto *EU : Extract->users()) {
655 if (auto *Store = dyn_cast<StoreInst>(EU)) {
656 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
657 EHAllocas.push_back(AV);
662 // We can't do this without a dominator tree.
665 if (!EHAllocas.empty()) {
666 PromoteMemToReg(EHAllocas, *DT);
670 // After promotion, some extracts may be trivially dead. Remove them.
671 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
672 for (auto *U : Users)
673 RecursivelyDeleteTriviallyDeadInstructions(U);
676 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
677 LandingPadInst *OutlinedLPad,
678 const LandingPadInst *OriginalLPad,
679 FrameVarInfoMap &FrameVarInfo) {
680 // Get the nested block and erase the unreachable instruction that was
681 // temporarily inserted as its terminator.
682 LLVMContext &Context = ParentFn->getContext();
683 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
684 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
685 OutlinedBB->getTerminator()->eraseFromParent();
686 // That should leave OutlinedLPad as the last instruction in its block.
687 assert(&OutlinedBB->back() == OutlinedLPad);
689 // The original landing pad will have already had its action intrinsic
690 // built by the outlining loop. We need to clone that into the outlined
691 // location. It may also be necessary to add references to the exception
692 // variables to the outlined handler in which this landing pad is nested
693 // and remap return instructions in the nested handlers that should return
694 // to an address in the outlined handler.
695 Function *OutlinedHandlerFn = OutlinedBB->getParent();
696 BasicBlock::const_iterator II = OriginalLPad;
698 // The instruction after the landing pad should now be a call to eh.actions.
699 const Instruction *Recover = II;
700 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
701 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
703 // Remap the exception variables into the outlined function.
704 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
705 SmallVector<BlockAddress *, 4> ActionTargets;
706 SmallVector<ActionHandler *, 4> ActionList;
707 parseEHActions(EHActions, ActionList);
708 for (auto *Action : ActionList) {
709 auto *Catch = dyn_cast<CatchHandler>(Action);
712 // The dyn_cast to function here selects C++ catch handlers and skips
713 // SEH catch handlers.
714 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
717 // Visit all the return instructions, looking for places that return
718 // to a location within OutlinedHandlerFn.
719 for (BasicBlock &NestedHandlerBB : *Handler) {
720 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
724 // Handler functions must always return a block address.
725 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
726 // The original target will have been in the main parent function,
727 // but if it is the address of a block that has been outlined, it
728 // should be a block that was outlined into OutlinedHandlerFn.
729 assert(BA->getFunction() == ParentFn);
731 // Ignore targets that aren't part of OutlinedHandlerFn.
732 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
735 // If the return value is the address ofF a block that we
736 // previously outlined into the parent handler function, replace
737 // the return instruction and add the mapped target to the list
738 // of possible return addresses.
739 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
740 assert(MappedBB->getParent() == OutlinedHandlerFn);
741 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
742 Ret->eraseFromParent();
743 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
744 ActionTargets.push_back(NewBA);
747 DeleteContainerPointers(ActionList);
749 OutlinedBB->getInstList().push_back(EHActions);
751 // Insert an indirect branch into the outlined landing pad BB.
752 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
753 // Add the previously collected action targets.
754 for (auto *Target : ActionTargets)
755 IBr->addDestination(Target->getBasicBlock());
758 // This function examines a block to determine whether the block ends with a
759 // conditional branch to a catch handler based on a selector comparison.
760 // This function is used both by the WinEHPrepare::findSelectorComparison() and
761 // WinEHCleanupDirector::handleTypeIdFor().
762 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
763 Constant *&Selector, BasicBlock *&NextBB) {
764 ICmpInst::Predicate Pred;
765 BasicBlock *TBB, *FBB;
768 if (!match(BB->getTerminator(),
769 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
773 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
774 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
777 if (Pred == CmpInst::ICMP_EQ) {
783 if (Pred == CmpInst::ICMP_NE) {
792 static bool isCatchBlock(BasicBlock *BB) {
793 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
795 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
801 static BasicBlock *createStubLandingPad(Function *Handler,
802 Value *PersonalityFn) {
803 // FIXME: Finish this!
804 LLVMContext &Context = Handler->getContext();
805 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
806 Handler->getBasicBlockList().push_back(StubBB);
807 IRBuilder<> Builder(StubBB);
808 LandingPadInst *LPad = Builder.CreateLandingPad(
809 llvm::StructType::get(Type::getInt8PtrTy(Context),
810 Type::getInt32Ty(Context), nullptr),
812 LPad->setCleanup(true);
813 Builder.CreateUnreachable();
817 // Cycles through the blocks in an outlined handler function looking for an
818 // invoke instruction and inserts an invoke of llvm.donothing with an empty
819 // landing pad if none is found. The code that generates the .xdata tables for
820 // the handler needs at least one landing pad to identify the parent function's
822 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
823 Value *PersonalityFn) {
824 ReturnInst *Ret = nullptr;
825 for (BasicBlock &BB : *Handler) {
826 TerminatorInst *Terminator = BB.getTerminator();
827 // If we find an invoke, there is nothing to be done.
828 auto *II = dyn_cast<InvokeInst>(Terminator);
831 // If we've already recorded a return instruction, keep looking for invokes.
834 // If we haven't recorded a return instruction yet, try this terminator.
835 Ret = dyn_cast<ReturnInst>(Terminator);
838 // If we got this far, the handler contains no invokes. We should have seen
839 // at least one return. We'll insert an invoke of llvm.donothing ahead of
842 BasicBlock *OldRetBB = Ret->getParent();
843 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Ret);
844 // SplitBlock adds an unconditional branch instruction at the end of the
845 // parent block. We want to replace that with an invoke call, so we can
847 OldRetBB->getTerminator()->eraseFromParent();
848 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
850 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
851 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
854 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
855 LandingPadInst *LPad, BasicBlock *StartBB,
856 FrameVarInfoMap &VarInfo) {
857 Module *M = SrcFn->getParent();
858 LLVMContext &Context = M->getContext();
860 // Create a new function to receive the handler contents.
861 Type *Int8PtrType = Type::getInt8PtrTy(Context);
862 std::vector<Type *> ArgTys;
863 ArgTys.push_back(Int8PtrType);
864 ArgTys.push_back(Int8PtrType);
866 if (Action->getType() == Catch) {
867 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
868 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
869 SrcFn->getName() + ".catch", M);
871 FunctionType *FnType =
872 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
873 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
874 SrcFn->getName() + ".cleanup", M);
877 Handler->addFnAttr("wineh-parent", SrcFn->getName());
879 // Generate a standard prolog to setup the frame recovery structure.
880 IRBuilder<> Builder(Context);
881 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
882 Handler->getBasicBlockList().push_front(Entry);
883 Builder.SetInsertPoint(Entry);
884 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
886 std::unique_ptr<WinEHCloningDirectorBase> Director;
888 ValueToValueMapTy VMap;
890 LandingPadMap &LPadMap = LPadMaps[LPad];
891 if (!LPadMap.isInitialized())
892 LPadMap.mapLandingPad(LPad);
893 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
894 Constant *Sel = CatchAction->getSelector();
895 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
896 NestedLPtoOriginalLP));
897 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
898 ConstantInt::get(Type::getInt32Ty(Context), 1));
900 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
901 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
902 UndefValue::get(Type::getInt32Ty(Context)));
905 SmallVector<ReturnInst *, 8> Returns;
906 ClonedCodeInfo OutlinedFunctionInfo;
908 // If the start block contains PHI nodes, we need to map them.
909 BasicBlock::iterator II = StartBB->begin();
910 while (auto *PN = dyn_cast<PHINode>(II)) {
912 // Look for PHI values that we have already mapped (such as the selector).
913 for (Value *Val : PN->incoming_values()) {
914 if (VMap.count(Val)) {
915 VMap[PN] = VMap[Val];
919 // If we didn't find a match for this value, map it as an undef.
921 VMap[PN] = UndefValue::get(PN->getType());
926 // The landing pad value may be used by PHI nodes. It will ultimately be
927 // eliminated, but we need it in the map for intermediate handling.
928 VMap[LPad] = UndefValue::get(LPad->getType());
930 // Skip over PHIs and, if applicable, landingpad instructions.
931 II = StartBB->getFirstInsertionPt();
933 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
934 /*ModuleLevelChanges=*/false, Returns, "",
935 &OutlinedFunctionInfo, Director.get());
937 // Move all the instructions in the first cloned block into our entry block.
938 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
939 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
940 FirstClonedBB->eraseFromParent();
942 // Make sure we can identify the handler's personality later.
943 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
945 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
946 WinEHCatchDirector *CatchDirector =
947 reinterpret_cast<WinEHCatchDirector *>(Director.get());
948 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
949 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
951 // Look for blocks that are not part of the landing pad that we just
952 // outlined but terminate with a call to llvm.eh.endcatch and a
953 // branch to a block that is in the handler we just outlined.
954 // These blocks will be part of a nested landing pad that intends to
955 // return to an address in this handler. This case is best handled
956 // after both landing pads have been outlined, so for now we'll just
957 // save the association of the blocks in LPadTargetBlocks. The
958 // return instructions which are created from these branches will be
959 // replaced after all landing pads have been outlined.
960 for (const auto MapEntry : VMap) {
961 // VMap maps all values and blocks that were just cloned, but dead
962 // blocks which were pruned will map to nullptr.
963 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
965 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
966 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
967 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
968 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
970 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
972 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
973 // This would indicate that a nested landing pad wants to return
974 // to a block that is outlined into two different handlers.
975 assert(!LPadTargetBlocks.count(MappedBB));
976 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
980 } // End if (CatchAction)
982 Action->setHandlerBlockOrFunc(Handler);
987 /// This BB must end in a selector dispatch. All we need to do is pass the
988 /// handler block to llvm.eh.actions and list it as a possible indirectbr
990 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
991 BasicBlock *StartBB) {
992 BasicBlock *HandlerBB;
995 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
997 // If this was EH dispatch, this must be a conditional branch to the handler
999 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1000 // leading to crashes if some optimization hoists stuff here.
1001 assert(CatchAction->getSelector() && HandlerBB &&
1002 "expected catch EH dispatch");
1004 // This must be a catch-all. Split the block after the landingpad.
1005 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1007 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
1009 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1010 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1011 CatchAction->setReturnTargets(Targets);
1014 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1015 // Each instance of this class should only ever be used to map a single
1017 assert(OriginLPad == nullptr || OriginLPad == LPad);
1019 // If the landing pad has already been mapped, there's nothing more to do.
1020 if (OriginLPad == LPad)
1025 // The landingpad instruction returns an aggregate value. Typically, its
1026 // value will be passed to a pair of extract value instructions and the
1027 // results of those extracts will have been promoted to reg values before
1028 // this routine is called.
1029 for (auto *U : LPad->users()) {
1030 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1033 assert(Extract->getNumIndices() == 1 &&
1034 "Unexpected operation: extracting both landing pad values");
1035 unsigned int Idx = *(Extract->idx_begin());
1036 assert((Idx == 0 || Idx == 1) &&
1037 "Unexpected operation: extracting an unknown landing pad element");
1039 ExtractedEHPtrs.push_back(Extract);
1040 } else if (Idx == 1) {
1041 ExtractedSelectors.push_back(Extract);
1046 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1047 return BB->getLandingPadInst() == OriginLPad;
1050 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1051 if (Inst == OriginLPad)
1053 for (auto *Extract : ExtractedEHPtrs) {
1054 if (Inst == Extract)
1057 for (auto *Extract : ExtractedSelectors) {
1058 if (Inst == Extract)
1064 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1065 Value *SelectorValue) const {
1066 // Remap all landing pad extract instructions to the specified values.
1067 for (auto *Extract : ExtractedEHPtrs)
1068 VMap[Extract] = EHPtrValue;
1069 for (auto *Extract : ExtractedSelectors)
1070 VMap[Extract] = SelectorValue;
1073 static bool isFrameAddressCall(const Value *V) {
1074 return match(const_cast<Value *>(V),
1075 m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1078 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1079 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1080 // If this is one of the boilerplate landing pad instructions, skip it.
1081 // The instruction will have already been remapped in VMap.
1082 if (LPadMap.isLandingPadSpecificInst(Inst))
1083 return CloningDirector::SkipInstruction;
1085 // Nested landing pads will be cloned as stubs, with just the
1086 // landingpad instruction and an unreachable instruction. When
1087 // all landingpads have been outlined, we'll replace this with the
1088 // llvm.eh.actions call and indirect branch created when the
1089 // landing pad was outlined.
1090 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1091 return handleLandingPad(VMap, LPad, NewBB);
1094 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1095 return handleInvoke(VMap, Invoke, NewBB);
1097 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1098 return handleResume(VMap, Resume, NewBB);
1100 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1101 return handleCompare(VMap, Cmp, NewBB);
1103 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1104 return handleBeginCatch(VMap, Inst, NewBB);
1105 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1106 return handleEndCatch(VMap, Inst, NewBB);
1107 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1108 return handleTypeIdFor(VMap, Inst, NewBB);
1110 // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1111 // which is the FP of the parent.
1112 if (isFrameAddressCall(Inst)) {
1113 VMap[Inst] = EstablisherFrame;
1114 return CloningDirector::SkipInstruction;
1117 // Continue with the default cloning behavior.
1118 return CloningDirector::CloneInstruction;
1121 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1122 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1123 Instruction *NewInst = LPad->clone();
1124 if (LPad->hasName())
1125 NewInst->setName(LPad->getName());
1126 // Save this correlation for later processing.
1127 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1128 VMap[LPad] = NewInst;
1129 BasicBlock::InstListType &InstList = NewBB->getInstList();
1130 InstList.push_back(NewInst);
1131 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1132 return CloningDirector::StopCloningBB;
1135 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1136 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1137 // The argument to the call is some form of the first element of the
1138 // landingpad aggregate value, but that doesn't matter. It isn't used
1140 // The second argument is an outparameter where the exception object will be
1141 // stored. Typically the exception object is a scalar, but it can be an
1142 // aggregate when catching by value.
1143 // FIXME: Leave something behind to indicate where the exception object lives
1144 // for this handler. Should it be part of llvm.eh.actions?
1145 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1146 "llvm.eh.begincatch found while "
1147 "outlining catch handler.");
1148 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1149 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1150 return CloningDirector::SkipInstruction;
1151 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1152 "catch parameter is not static alloca");
1153 Materializer.escapeCatchObject(ExceptionObjectVar);
1154 return CloningDirector::SkipInstruction;
1157 CloningDirector::CloningAction
1158 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1159 const Instruction *Inst, BasicBlock *NewBB) {
1160 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1161 // It might be interesting to track whether or not we are inside a catch
1162 // function, but that might make the algorithm more brittle than it needs
1165 // The end catch call can occur in one of two places: either in a
1166 // landingpad block that is part of the catch handlers exception mechanism,
1167 // or at the end of the catch block. However, a catch-all handler may call
1168 // end catch from the original landing pad. If the call occurs in a nested
1169 // landing pad block, we must skip it and continue so that the landing pad
1171 auto *ParentBB = IntrinCall->getParent();
1172 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1173 return CloningDirector::SkipInstruction;
1175 // If an end catch occurs anywhere else we want to terminate the handler
1176 // with a return to the code that follows the endcatch call. If the
1177 // next instruction is not an unconditional branch, we need to split the
1178 // block to provide a clear target for the return instruction.
1179 BasicBlock *ContinueBB;
1180 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1181 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1182 if (!Branch || !Branch->isUnconditional()) {
1183 // We're interrupting the cloning process at this location, so the
1184 // const_cast we're doing here will not cause a problem.
1185 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1186 const_cast<Instruction *>(cast<Instruction>(Next)));
1188 ContinueBB = Branch->getSuccessor(0);
1191 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1192 ReturnTargets.push_back(ContinueBB);
1194 // We just added a terminator to the cloned block.
1195 // Tell the caller to stop processing the current basic block so that
1196 // the branch instruction will be skipped.
1197 return CloningDirector::StopCloningBB;
1200 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1201 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1202 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1203 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1204 // This causes a replacement that will collapse the landing pad CFG based
1205 // on the filter function we intend to match.
1206 if (Selector == CurrentSelector)
1207 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1209 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1210 // Tell the caller not to clone this instruction.
1211 return CloningDirector::SkipInstruction;
1214 CloningDirector::CloningAction
1215 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1216 const InvokeInst *Invoke, BasicBlock *NewBB) {
1217 return CloningDirector::CloneInstruction;
1220 CloningDirector::CloningAction
1221 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1222 const ResumeInst *Resume, BasicBlock *NewBB) {
1223 // Resume instructions shouldn't be reachable from catch handlers.
1224 // We still need to handle it, but it will be pruned.
1225 BasicBlock::InstListType &InstList = NewBB->getInstList();
1226 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1227 return CloningDirector::StopCloningBB;
1230 CloningDirector::CloningAction
1231 WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1232 const CmpInst *Compare, BasicBlock *NewBB) {
1233 const IntrinsicInst *IntrinCall = nullptr;
1234 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1235 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1236 } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1237 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1240 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1241 // This causes a replacement that will collapse the landing pad CFG based
1242 // on the filter function we intend to match.
1243 if (Selector == CurrentSelector->stripPointerCasts()) {
1244 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1247 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1249 return CloningDirector::SkipInstruction;
1251 return CloningDirector::CloneInstruction;
1254 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1255 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1256 // The MS runtime will terminate the process if an exception occurs in a
1257 // cleanup handler, so we shouldn't encounter landing pads in the actual
1258 // cleanup code, but they may appear in catch blocks. Depending on where
1259 // we started cloning we may see one, but it will get dropped during dead
1261 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1262 VMap[LPad] = NewInst;
1263 BasicBlock::InstListType &InstList = NewBB->getInstList();
1264 InstList.push_back(NewInst);
1265 return CloningDirector::StopCloningBB;
1268 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1269 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1270 // Cleanup code may flow into catch blocks or the catch block may be part
1271 // of a branch that will be optimized away. We'll insert a return
1272 // instruction now, but it may be pruned before the cloning process is
1274 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1275 return CloningDirector::StopCloningBB;
1278 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1279 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1280 // Cleanup handlers nested within catch handlers may begin with a call to
1281 // eh.endcatch. We can just ignore that instruction.
1282 return CloningDirector::SkipInstruction;
1285 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1286 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1287 // If we encounter a selector comparison while cloning a cleanup handler,
1288 // we want to stop cloning immediately. Anything after the dispatch
1289 // will be outlined into a different handler.
1290 BasicBlock *CatchHandler;
1293 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1294 CatchHandler, Selector, NextBB)) {
1295 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1296 return CloningDirector::StopCloningBB;
1298 // If eg.typeid.for is called for any other reason, it can be ignored.
1299 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1300 return CloningDirector::SkipInstruction;
1303 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1304 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1305 // All invokes in cleanup handlers can be replaced with calls.
1306 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1307 // Insert a normal call instruction...
1309 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1310 Invoke->getName(), NewBB);
1311 NewCall->setCallingConv(Invoke->getCallingConv());
1312 NewCall->setAttributes(Invoke->getAttributes());
1313 NewCall->setDebugLoc(Invoke->getDebugLoc());
1314 VMap[Invoke] = NewCall;
1316 // Remap the operands.
1317 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1319 // Insert an unconditional branch to the normal destination.
1320 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1322 // The unwind destination won't be cloned into the new function, so
1323 // we don't need to clean up its phi nodes.
1325 // We just added a terminator to the cloned block.
1326 // Tell the caller to stop processing the current basic block.
1327 return CloningDirector::CloneSuccessors;
1330 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1331 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1332 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1334 // We just added a terminator to the cloned block.
1335 // Tell the caller to stop processing the current basic block so that
1336 // the branch instruction will be skipped.
1337 return CloningDirector::StopCloningBB;
1340 CloningDirector::CloningAction
1341 WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1342 const CmpInst *Compare, BasicBlock *NewBB) {
1343 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1344 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1345 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1346 return CloningDirector::SkipInstruction;
1348 return CloningDirector::CloneInstruction;
1352 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1353 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1354 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1355 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1356 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1359 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1360 // If we're asked to materialize a value that is an instruction, we
1361 // temporarily create an alloca in the outlined function and add this
1362 // to the FrameVarInfo map. When all the outlining is complete, we'll
1363 // collect these into a structure, spilling non-alloca values in the
1364 // parent frame as necessary, and replace these temporary allocas with
1365 // GEPs referencing the frame allocation block.
1367 // If the value is an alloca, the mapping is direct.
1368 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1369 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1370 Builder.Insert(NewAlloca, AV->getName());
1371 FrameVarInfo[AV].push_back(NewAlloca);
1375 // For other types of instructions or arguments, we need an alloca based on
1376 // the value's type and a load of the alloca. The alloca will be replaced
1377 // by a GEP, but the load will stay. In the parent function, the value will
1378 // be spilled to a location in the frame allocation block.
1379 if (isa<Instruction>(V) || isa<Argument>(V)) {
1380 AllocaInst *NewAlloca =
1381 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1382 FrameVarInfo[V].push_back(NewAlloca);
1383 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1387 // Don't materialize other values.
1391 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1392 // Catch parameter objects have to live in the parent frame. When we see a use
1393 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1394 // used from another handler. This will prevent us from trying to sink the
1395 // alloca into the handler and ensure that the catch parameter is present in
1396 // the call to llvm.frameescape.
1397 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1400 // This function maps the catch and cleanup handlers that are reachable from the
1401 // specified landing pad. The landing pad sequence will have this basic shape:
1403 // <cleanup handler>
1404 // <selector comparison>
1406 // <cleanup handler>
1407 // <selector comparison>
1409 // <cleanup handler>
1412 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1413 // any arbitrary control flow, but all paths through the cleanup code must
1414 // eventually reach the next selector comparison and no path can skip to a
1415 // different selector comparisons, though some paths may terminate abnormally.
1416 // Therefore, we will use a depth first search from the start of any given
1417 // cleanup block and stop searching when we find the next selector comparison.
1419 // If the landingpad instruction does not have a catch clause, we will assume
1420 // that any instructions other than selector comparisons and catch handlers can
1421 // be ignored. In practice, these will only be the boilerplate instructions.
1423 // The catch handlers may also have any control structure, but we are only
1424 // interested in the start of the catch handlers, so we don't need to actually
1425 // follow the flow of the catch handlers. The start of the catch handlers can
1426 // be located from the compare instructions, but they can be skipped in the
1427 // flow by following the contrary branch.
1428 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1429 LandingPadActions &Actions) {
1430 unsigned int NumClauses = LPad->getNumClauses();
1431 unsigned int HandlersFound = 0;
1432 BasicBlock *BB = LPad->getParent();
1434 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1436 if (NumClauses == 0) {
1437 findCleanupHandlers(Actions, BB, nullptr);
1441 VisitedBlockSet VisitedBlocks;
1443 while (HandlersFound != NumClauses) {
1444 BasicBlock *NextBB = nullptr;
1446 // See if the clause we're looking for is a catch-all.
1447 // If so, the catch begins immediately.
1448 Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1449 if (isa<ConstantPointerNull>(ExpectedSelector)) {
1450 // The catch all must occur last.
1451 assert(HandlersFound == NumClauses - 1);
1453 // There can be additional selector dispatches in the call chain that we
1455 BasicBlock *CatchBlock = nullptr;
1457 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1458 DEBUG(dbgs() << " Found extra catch dispatch in block "
1459 << CatchBlock->getName() << "\n");
1463 // For C++ EH, check if there is any interesting cleanup code before we
1464 // begin the catch. This is important because cleanups cannot rethrow
1465 // exceptions but code called from catches can. For SEH, it isn't
1466 // important if some finally code before a catch-all is executed out of
1467 // line or after recovering from the exception.
1468 if (Personality == EHPersonality::MSVC_CXX)
1469 findCleanupHandlers(Actions, BB, BB);
1471 // Add the catch handler to the action list.
1472 CatchHandler *Action = nullptr;
1473 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1474 // If the CatchHandlerMap already has an entry for this BB, re-use it.
1475 Action = CatchHandlerMap[BB];
1476 assert(Action->getSelector() == ExpectedSelector);
1478 // Since this is a catch-all handler, the selector won't actually appear
1479 // in the code anywhere. ExpectedSelector here is the constant null ptr
1480 // that we got from the landing pad instruction.
1481 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1482 CatchHandlerMap[BB] = Action;
1484 Actions.insertCatchHandler(Action);
1485 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1488 // Once we reach a catch-all, don't expect to hit a resume instruction.
1493 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1494 assert(CatchAction);
1496 // See if there is any interesting code executed before the dispatch.
1497 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1499 // When the source program contains multiple nested try blocks the catch
1500 // handlers can get strung together in such a way that we can encounter
1501 // a dispatch for a selector that we've already had a handler for.
1502 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1505 // Add the catch handler to the action list.
1506 DEBUG(dbgs() << " Found catch dispatch in block "
1507 << CatchAction->getStartBlock()->getName() << "\n");
1508 Actions.insertCatchHandler(CatchAction);
1510 // Under some circumstances optimized IR will flow unconditionally into a
1511 // handler block without checking the selector. This can only happen if
1512 // the landing pad has a catch-all handler and the handler for the
1513 // preceeding catch clause is identical to the catch-call handler
1514 // (typically an empty catch). In this case, the handler must be shared
1515 // by all remaining clauses.
1516 if (isa<ConstantPointerNull>(
1517 CatchAction->getSelector()->stripPointerCasts())) {
1518 DEBUG(dbgs() << " Applying early catch-all handler in block "
1519 << CatchAction->getStartBlock()->getName()
1520 << " to all remaining clauses.\n");
1521 Actions.insertCatchHandler(CatchAction);
1525 DEBUG(dbgs() << " Found extra catch dispatch in block "
1526 << CatchAction->getStartBlock()->getName() << "\n");
1529 // Move on to the block after the catch handler.
1533 // If we didn't wind up in a catch-all, see if there is any interesting code
1534 // executed before the resume.
1535 findCleanupHandlers(Actions, BB, BB);
1537 // It's possible that some optimization moved code into a landingpad that
1539 // previously being used for cleanup. If that happens, we need to execute
1541 // extra code from a cleanup handler.
1542 if (Actions.includesCleanup() && !LPad->isCleanup())
1543 LPad->setCleanup(true);
1546 // This function searches starting with the input block for the next
1547 // block that terminates with a branch whose condition is based on a selector
1548 // comparison. This may be the input block. See the mapLandingPadBlocks
1549 // comments for a discussion of control flow assumptions.
1551 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1552 BasicBlock *&NextBB,
1553 VisitedBlockSet &VisitedBlocks) {
1554 // See if we've already found a catch handler use it.
1555 // Call count() first to avoid creating a null entry for blocks
1556 // we haven't seen before.
1557 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1558 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1559 NextBB = Action->getNextBB();
1563 // VisitedBlocks applies only to the current search. We still
1564 // need to consider blocks that we've visited while mapping other
1566 VisitedBlocks.insert(BB);
1568 BasicBlock *CatchBlock = nullptr;
1569 Constant *Selector = nullptr;
1571 // If this is the first time we've visited this block from any landing pad
1572 // look to see if it is a selector dispatch block.
1573 if (!CatchHandlerMap.count(BB)) {
1574 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1575 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1576 CatchHandlerMap[BB] = Action;
1579 // If we encounter a block containing an llvm.eh.begincatch before we
1580 // find a selector dispatch block, the handler is assumed to be
1581 // reached unconditionally. This happens for catch-all blocks, but
1582 // it can also happen for other catch handlers that have been combined
1583 // with the catch-all handler during optimization.
1584 if (isCatchBlock(BB)) {
1585 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1586 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1587 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1588 CatchHandlerMap[BB] = Action;
1593 // Visit each successor, looking for the dispatch.
1594 // FIXME: We expect to find the dispatch quickly, so this will probably
1595 // work better as a breadth first search.
1596 for (BasicBlock *Succ : successors(BB)) {
1597 if (VisitedBlocks.count(Succ))
1600 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1607 // These are helper functions to combine repeated code from findCleanupHandlers.
1608 static void createCleanupHandler(LandingPadActions &Actions,
1609 CleanupHandlerMapTy &CleanupHandlerMap,
1611 CleanupHandler *Action = new CleanupHandler(BB);
1612 CleanupHandlerMap[BB] = Action;
1613 Actions.insertCleanupHandler(Action);
1614 DEBUG(dbgs() << " Found cleanup code in block "
1615 << Action->getStartBlock()->getName() << "\n");
1618 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1619 Instruction *MaybeCall) {
1620 // Look for finally blocks that Clang has already outlined for us.
1621 // %fp = call i8* @llvm.frameaddress(i32 0)
1622 // call void @"fin$parent"(iN 1, i8* %fp)
1623 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1624 MaybeCall = MaybeCall->getNextNode();
1625 CallSite FinallyCall(MaybeCall);
1626 if (!FinallyCall || FinallyCall.arg_size() != 2)
1628 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1630 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1635 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1636 // Skip single ubr blocks.
1637 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1638 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1639 if (Br && Br->isUnconditional())
1640 BB = Br->getSuccessor(0);
1647 // This function searches starting with the input block for the next block that
1648 // contains code that is not part of a catch handler and would not be eliminated
1649 // during handler outlining.
1651 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1652 BasicBlock *StartBB, BasicBlock *EndBB) {
1653 // Here we will skip over the following:
1655 // landing pad prolog:
1657 // Unconditional branches
1659 // Selector dispatch
1663 // Anything else marks the start of an interesting block
1665 BasicBlock *BB = StartBB;
1666 // Anything other than an unconditional branch will kick us out of this loop
1667 // one way or another.
1669 BB = followSingleUnconditionalBranches(BB);
1670 // If we've already scanned this block, don't scan it again. If it is
1671 // a cleanup block, there will be an action in the CleanupHandlerMap.
1672 // If we've scanned it and it is not a cleanup block, there will be a
1673 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1674 // be no entry in the CleanupHandlerMap. We must call count() first to
1675 // avoid creating a null entry for blocks we haven't scanned.
1676 if (CleanupHandlerMap.count(BB)) {
1677 if (auto *Action = CleanupHandlerMap[BB]) {
1678 Actions.insertCleanupHandler(Action);
1679 DEBUG(dbgs() << " Found cleanup code in block "
1680 << Action->getStartBlock()->getName() << "\n");
1681 // FIXME: This cleanup might chain into another, and we need to discover
1685 // Here we handle the case where the cleanup handler map contains a
1686 // value for this block but the value is a nullptr. This means that
1687 // we have previously analyzed the block and determined that it did
1688 // not contain any cleanup code. Based on the earlier analysis, we
1689 // know the the block must end in either an unconditional branch, a
1690 // resume or a conditional branch that is predicated on a comparison
1691 // with a selector. Either the resume or the selector dispatch
1692 // would terminate the search for cleanup code, so the unconditional
1693 // branch is the only case for which we might need to continue
1695 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1696 if (SuccBB == BB || SuccBB == EndBB)
1703 // Create an entry in the cleanup handler map for this block. Initially
1704 // we create an entry that says this isn't a cleanup block. If we find
1705 // cleanup code, the caller will replace this entry.
1706 CleanupHandlerMap[BB] = nullptr;
1708 TerminatorInst *Terminator = BB->getTerminator();
1710 // Landing pad blocks have extra instructions we need to accept.
1711 LandingPadMap *LPadMap = nullptr;
1712 if (BB->isLandingPad()) {
1713 LandingPadInst *LPad = BB->getLandingPadInst();
1714 LPadMap = &LPadMaps[LPad];
1715 if (!LPadMap->isInitialized())
1716 LPadMap->mapLandingPad(LPad);
1719 // Look for the bare resume pattern:
1720 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1721 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1722 // resume { i8*, i32 } %lpad.val2
1723 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1724 InsertValueInst *Insert1 = nullptr;
1725 InsertValueInst *Insert2 = nullptr;
1726 Value *ResumeVal = Resume->getOperand(0);
1727 // If the resume value isn't a phi or landingpad value, it should be a
1728 // series of insertions. Identify them so we can avoid them when scanning
1730 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1731 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1733 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1734 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1736 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1738 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1740 Instruction *Inst = II;
1741 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1743 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1745 if (!Inst->hasOneUse() ||
1746 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1747 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1753 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1754 if (Branch && Branch->isConditional()) {
1755 // Look for the selector dispatch.
1756 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1757 // %matches = icmp eq i32 %sel, %2
1758 // br i1 %matches, label %catch14, label %eh.resume
1759 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1760 if (!Compare || !Compare->isEquality())
1761 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1762 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1764 Instruction *Inst = II;
1765 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1767 if (Inst == Compare || Inst == Branch)
1769 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1771 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1773 // The selector dispatch block should always terminate our search.
1774 assert(BB == EndBB);
1778 if (isAsynchronousEHPersonality(Personality)) {
1779 // If this is a landingpad block, split the block at the first non-landing
1781 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1783 while (MaybeCall != BB->getTerminator() &&
1784 LPadMap->isLandingPadSpecificInst(MaybeCall))
1785 MaybeCall = MaybeCall->getNextNode();
1788 // Look for outlined finally calls.
1789 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
1790 Function *Fin = FinallyCall.getCalledFunction();
1791 assert(Fin && "outlined finally call should be direct");
1792 auto *Action = new CleanupHandler(BB);
1793 Action->setHandlerBlockOrFunc(Fin);
1794 Actions.insertCleanupHandler(Action);
1795 CleanupHandlerMap[BB] = Action;
1796 DEBUG(dbgs() << " Found frontend-outlined finally call to "
1797 << Fin->getName() << " in block "
1798 << Action->getStartBlock()->getName() << "\n");
1800 // Split the block if there were more interesting instructions and look
1801 // for finally calls in the normal successor block.
1802 BasicBlock *SuccBB = BB;
1803 if (FinallyCall.getInstruction() != BB->getTerminator() &&
1804 FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
1805 SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
1807 if (FinallyCall.isInvoke()) {
1808 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
1810 SuccBB = BB->getUniqueSuccessor();
1811 assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
1821 // Anything else is either a catch block or interesting cleanup code.
1822 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1824 Instruction *Inst = II;
1825 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1827 // Unconditional branches fall through to this loop.
1830 // If this is a catch block, there is no cleanup code to be found.
1831 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1833 // If this a nested landing pad, it may contain an endcatch call.
1834 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1836 // Anything else makes this interesting cleanup code.
1837 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1840 // Only unconditional branches in empty blocks should get this far.
1841 assert(Branch && Branch->isUnconditional());
1844 BB = Branch->getSuccessor(0);
1848 // This is a public function, declared in WinEHFuncInfo.h and is also
1849 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1850 void llvm::parseEHActions(const IntrinsicInst *II,
1851 SmallVectorImpl<ActionHandler *> &Actions) {
1852 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1853 uint64_t ActionKind =
1854 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1855 if (ActionKind == /*catch=*/1) {
1856 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1857 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1858 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1859 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1861 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1862 CH->setHandlerBlockOrFunc(Handler);
1863 CH->setExceptionVarIndex(EHObjIndexVal);
1864 Actions.push_back(CH);
1865 } else if (ActionKind == 0) {
1866 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1868 auto *CH = new CleanupHandler(/*BB=*/nullptr);
1869 CH->setHandlerBlockOrFunc(Handler);
1870 Actions.push_back(CH);
1872 llvm_unreachable("Expected either a catch or cleanup handler!");
1875 std::reverse(Actions.begin(), Actions.end());