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 CleanupHandler *findCleanupHandler(BasicBlock *StartBB, BasicBlock *EndBB);
103 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
105 // All fields are reset by runOnFunction.
107 EHPersonality Personality;
108 CatchHandlerMapTy CatchHandlerMap;
109 CleanupHandlerMapTy CleanupHandlerMap;
110 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
112 // This maps landing pad instructions found in outlined handlers to
113 // the landing pad instruction in the parent function from which they
114 // were cloned. The cloned/nested landing pad is used as the key
115 // because the landing pad may be cloned into multiple handlers.
116 // This map will be used to add the llvm.eh.actions call to the nested
117 // landing pads after all handlers have been outlined.
118 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
120 // This maps blocks in the parent function which are destinations of
121 // catch handlers to cloned blocks in (other) outlined handlers. This
122 // handles the case where a nested landing pads has a catch handler that
123 // returns to a handler function rather than the parent function.
124 // The original block is used as the key here because there should only
125 // ever be one handler function from which the cloned block is not pruned.
126 // The original block will be pruned from the parent function after all
127 // handlers have been outlined. This map will be used to adjust the
128 // return instructions of handlers which return to the block that was
129 // outlined into a handler. This is done after all handlers have been
130 // outlined but before the outlined code is pruned from the parent function.
131 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
134 class WinEHFrameVariableMaterializer : public ValueMaterializer {
136 WinEHFrameVariableMaterializer(Function *OutlinedFn,
137 FrameVarInfoMap &FrameVarInfo);
138 ~WinEHFrameVariableMaterializer() {}
140 virtual Value *materializeValueFor(Value *V) override;
142 void escapeCatchObject(Value *V);
145 FrameVarInfoMap &FrameVarInfo;
149 class LandingPadMap {
151 LandingPadMap() : OriginLPad(nullptr) {}
152 void mapLandingPad(const LandingPadInst *LPad);
154 bool isInitialized() { return OriginLPad != nullptr; }
156 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
157 bool isLandingPadSpecificInst(const Instruction *Inst) const;
159 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
160 Value *SelectorValue) const;
163 const LandingPadInst *OriginLPad;
164 // We will normally only see one of each of these instructions, but
165 // if more than one occurs for some reason we can handle that.
166 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
167 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
170 class WinEHCloningDirectorBase : public CloningDirector {
172 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
173 LandingPadMap &LPadMap)
174 : Materializer(HandlerFn, VarInfo),
175 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
176 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
179 CloningAction handleInstruction(ValueToValueMapTy &VMap,
180 const Instruction *Inst,
181 BasicBlock *NewBB) override;
183 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
184 const Instruction *Inst,
185 BasicBlock *NewBB) = 0;
186 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
187 const Instruction *Inst,
188 BasicBlock *NewBB) = 0;
189 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
190 const Instruction *Inst,
191 BasicBlock *NewBB) = 0;
192 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
193 const InvokeInst *Invoke,
194 BasicBlock *NewBB) = 0;
195 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
196 const ResumeInst *Resume,
197 BasicBlock *NewBB) = 0;
198 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
199 const LandingPadInst *LPad,
200 BasicBlock *NewBB) = 0;
202 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
205 WinEHFrameVariableMaterializer Materializer;
206 Type *SelectorIDType;
208 LandingPadMap &LPadMap;
211 class WinEHCatchDirector : public WinEHCloningDirectorBase {
214 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
215 LandingPadMap &LPadMap,
216 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
217 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
218 CurrentSelector(Selector->stripPointerCasts()),
219 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
221 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
222 const Instruction *Inst,
223 BasicBlock *NewBB) override;
224 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
225 BasicBlock *NewBB) override;
226 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
227 const Instruction *Inst,
228 BasicBlock *NewBB) override;
229 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
230 BasicBlock *NewBB) override;
231 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
232 BasicBlock *NewBB) override;
233 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
234 const LandingPadInst *LPad,
235 BasicBlock *NewBB) override;
237 Value *getExceptionVar() { return ExceptionObjectVar; }
238 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
241 Value *CurrentSelector;
243 Value *ExceptionObjectVar;
244 TinyPtrVector<BasicBlock *> ReturnTargets;
246 // This will be a reference to the field of the same name in the WinEHPrepare
247 // object which instantiates this WinEHCatchDirector object.
248 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
251 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
253 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
254 LandingPadMap &LPadMap)
255 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
257 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
258 const Instruction *Inst,
259 BasicBlock *NewBB) override;
260 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
261 BasicBlock *NewBB) override;
262 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
263 const Instruction *Inst,
264 BasicBlock *NewBB) override;
265 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
266 BasicBlock *NewBB) override;
267 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
268 BasicBlock *NewBB) override;
269 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
270 const LandingPadInst *LPad,
271 BasicBlock *NewBB) override;
274 class LandingPadActions {
276 LandingPadActions() : HasCleanupHandlers(false) {}
278 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
279 void insertCleanupHandler(CleanupHandler *Action) {
280 Actions.push_back(Action);
281 HasCleanupHandlers = true;
284 bool includesCleanup() const { return HasCleanupHandlers; }
286 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
287 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
288 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
291 // Note that this class does not own the ActionHandler objects in this vector.
292 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
293 // in the WinEHPrepare class.
294 SmallVector<ActionHandler *, 4> Actions;
295 bool HasCleanupHandlers;
298 } // end anonymous namespace
300 char WinEHPrepare::ID = 0;
301 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
304 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
305 return new WinEHPrepare(TM);
308 // FIXME: Remove this once the backend can handle the prepared IR.
310 SEHPrepare("sehprepare", cl::Hidden,
311 cl::desc("Prepare functions with SEH personalities"));
313 bool WinEHPrepare::runOnFunction(Function &Fn) {
314 SmallVector<LandingPadInst *, 4> LPads;
315 SmallVector<ResumeInst *, 4> Resumes;
316 for (BasicBlock &BB : Fn) {
317 if (auto *LP = BB.getLandingPadInst())
319 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
320 Resumes.push_back(Resume);
323 // No need to prepare functions that lack landing pads.
327 // Classify the personality to see what kind of preparation we need.
328 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
330 // Do nothing if this is not an MSVC personality.
331 if (!isMSVCEHPersonality(Personality))
334 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
336 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
337 // Replace all resume instructions with unreachable.
338 // FIXME: Remove this once the backend can handle the prepared IR.
339 for (ResumeInst *Resume : Resumes) {
340 IRBuilder<>(Resume).CreateUnreachable();
341 Resume->eraseFromParent();
346 // If there were any landing pads, prepareExceptionHandlers will make changes.
347 prepareExceptionHandlers(Fn, LPads);
351 bool WinEHPrepare::doFinalization(Module &M) { return false; }
353 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
354 AU.addRequired<DominatorTreeWrapperPass>();
357 bool WinEHPrepare::prepareExceptionHandlers(
358 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
359 // These containers are used to re-map frame variables that are used in
360 // outlined catch and cleanup handlers. They will be populated as the
361 // handlers are outlined.
362 FrameVarInfoMap FrameVarInfo;
364 bool HandlersOutlined = false;
366 Module *M = F.getParent();
367 LLVMContext &Context = M->getContext();
369 // Create a new function to receive the handler contents.
370 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
371 Type *Int32Type = Type::getInt32Ty(Context);
372 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
374 for (LandingPadInst *LPad : LPads) {
375 // Look for evidence that this landingpad has already been processed.
376 bool LPadHasActionList = false;
377 BasicBlock *LPadBB = LPad->getParent();
378 for (Instruction &Inst : *LPadBB) {
379 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
380 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
381 LPadHasActionList = true;
385 // FIXME: This is here to help with the development of nested landing pad
386 // outlining. It should be removed when that is finished.
387 if (isa<UnreachableInst>(Inst)) {
388 LPadHasActionList = true;
393 // If we've already outlined the handlers for this landingpad,
394 // there's nothing more to do here.
395 if (LPadHasActionList)
398 // If either of the values in the aggregate returned by the landing pad is
399 // extracted and stored to memory, promote the stored value to a register.
400 promoteLandingPadValues(LPad);
402 LandingPadActions Actions;
403 mapLandingPadBlocks(LPad, Actions);
405 for (ActionHandler *Action : Actions) {
406 if (Action->hasBeenProcessed())
408 BasicBlock *StartBB = Action->getStartBlock();
410 // SEH doesn't do any outlining for catches. Instead, pass the handler
411 // basic block addr to llvm.eh.actions and list the block as a return
413 if (isAsynchronousEHPersonality(Personality)) {
414 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
415 processSEHCatchHandler(CatchAction, StartBB);
416 HandlersOutlined = true;
421 if (outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo)) {
422 HandlersOutlined = true;
424 } // End for each Action
426 // FIXME: We need a guard against partially outlined functions.
427 if (!HandlersOutlined)
430 // Replace the landing pad with a new llvm.eh.action based landing pad.
431 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
432 assert(!isa<PHINode>(LPadBB->begin()));
433 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
434 NewLPadBB->getInstList().push_back(NewLPad);
435 while (!pred_empty(LPadBB)) {
436 auto *pred = *pred_begin(LPadBB);
437 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
438 Invoke->setUnwindDest(NewLPadBB);
441 // Replace the mapping of any nested landing pad that previously mapped
442 // to this landing pad with a referenced to the cloned version.
443 for (auto &LPadPair : NestedLPtoOriginalLP) {
444 const LandingPadInst *OriginalLPad = LPadPair.second;
445 if (OriginalLPad == LPad) {
446 LPadPair.second = NewLPad;
450 // Replace uses of the old lpad in phis with this block and delete the old
452 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
453 LPadBB->getTerminator()->eraseFromParent();
454 new UnreachableInst(LPadBB->getContext(), LPadBB);
456 // Add a call to describe the actions for this landing pad.
457 std::vector<Value *> ActionArgs;
458 for (ActionHandler *Action : Actions) {
459 // Action codes from docs are: 0 cleanup, 1 catch.
460 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
461 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
462 ActionArgs.push_back(CatchAction->getSelector());
463 // Find the frame escape index of the exception object alloca in the
465 int FrameEscapeIdx = -1;
466 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
467 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
468 auto I = FrameVarInfo.find(EHObj);
469 assert(I != FrameVarInfo.end() &&
470 "failed to map llvm.eh.begincatch var");
471 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
473 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
475 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
477 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
480 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
482 // Add an indirect branch listing possible successors of the catch handlers.
483 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
484 for (ActionHandler *Action : Actions) {
485 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
486 for (auto *Target : CatchAction->getReturnTargets()) {
487 Branch->addDestination(Target);
491 } // End for each landingpad
493 // If nothing got outlined, there is no more processing to be done.
494 if (!HandlersOutlined)
497 // Replace any nested landing pad stubs with the correct action handler.
498 // This must be done before we remove unreachable blocks because it
499 // cleans up references to outlined blocks that will be deleted.
500 for (auto &LPadPair : NestedLPtoOriginalLP)
501 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
503 F.addFnAttr("wineh-parent", F.getName());
505 // Delete any blocks that were only used by handlers that were outlined above.
506 removeUnreachableBlocks(F);
508 BasicBlock *Entry = &F.getEntryBlock();
509 IRBuilder<> Builder(F.getParent()->getContext());
510 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
512 Function *FrameEscapeFn =
513 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
514 Function *RecoverFrameFn =
515 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
517 // Finally, replace all of the temporary allocas for frame variables used in
518 // the outlined handlers with calls to llvm.framerecover.
519 BasicBlock::iterator II = Entry->getFirstInsertionPt();
520 Instruction *AllocaInsertPt = II;
521 SmallVector<Value *, 8> AllocasToEscape;
522 for (auto &VarInfoEntry : FrameVarInfo) {
523 Value *ParentVal = VarInfoEntry.first;
524 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
526 // If the mapped value isn't already an alloca, we need to spill it if it
527 // is a computed value or copy it if it is an argument.
528 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
530 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
531 // Lower this argument to a copy and then demote that to the stack.
532 // We can't just use the argument location because the handler needs
533 // it to be in the frame allocation block.
534 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
535 Value *TrueValue = ConstantInt::getTrue(Context);
536 Value *UndefValue = UndefValue::get(Arg->getType());
538 SelectInst::Create(TrueValue, Arg, UndefValue,
539 Arg->getName() + ".tmp", AllocaInsertPt);
540 Arg->replaceAllUsesWith(SI);
541 // Reset the select operand, because it was clobbered by the RAUW above.
542 SI->setOperand(1, Arg);
543 ParentAlloca = DemoteRegToStack(*SI, true, SI);
544 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
545 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
547 Instruction *ParentInst = cast<Instruction>(ParentVal);
548 // FIXME: This is a work-around to temporarily handle the case where an
549 // instruction that is only used in handlers is not sunk.
550 // Without uses, DemoteRegToStack would just eliminate the value.
551 // This will fail if ParentInst is an invoke.
552 if (ParentInst->getNumUses() == 0) {
553 BasicBlock::iterator InsertPt = ParentInst;
556 new AllocaInst(ParentInst->getType(), nullptr,
557 ParentInst->getName() + ".reg2mem", InsertPt);
558 new StoreInst(ParentInst, ParentAlloca, InsertPt);
560 ParentAlloca = DemoteRegToStack(*ParentInst, true, ParentInst);
565 // FIXME: We should try to sink unescaped allocas from the parent frame into
566 // the child frame. If the alloca is escaped, we have to use the lifetime
567 // markers to ensure that the alloca is only live within the child frame.
569 // Add this alloca to the list of things to escape.
570 AllocasToEscape.push_back(ParentAlloca);
572 // Next replace all outlined allocas that are mapped to it.
573 for (AllocaInst *TempAlloca : Allocas) {
574 if (TempAlloca == getCatchObjectSentinel())
575 continue; // Skip catch parameter sentinels.
576 Function *HandlerFn = TempAlloca->getParent()->getParent();
577 // FIXME: Sink this GEP into the blocks where it is used.
578 Builder.SetInsertPoint(TempAlloca);
579 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
580 Value *RecoverArgs[] = {
581 Builder.CreateBitCast(&F, Int8PtrType, ""),
582 &(HandlerFn->getArgumentList().back()),
583 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
584 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
585 // Add a pointer bitcast if the alloca wasn't an i8.
586 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
587 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
589 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
591 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
592 TempAlloca->removeFromParent();
593 RecoveredAlloca->takeName(TempAlloca);
596 } // End for each FrameVarInfo entry.
598 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
600 Builder.SetInsertPoint(&F.getEntryBlock().back());
601 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
603 // Clean up the handler action maps we created for this function
604 DeleteContainerSeconds(CatchHandlerMap);
605 CatchHandlerMap.clear();
606 DeleteContainerSeconds(CleanupHandlerMap);
607 CleanupHandlerMap.clear();
609 return HandlersOutlined;
612 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
613 // If the return values of the landing pad instruction are extracted and
614 // stored to memory, we want to promote the store locations to reg values.
615 SmallVector<AllocaInst *, 2> EHAllocas;
617 // The landingpad instruction returns an aggregate value. Typically, its
618 // value will be passed to a pair of extract value instructions and the
619 // results of those extracts are often passed to store instructions.
620 // In unoptimized code the stored value will often be loaded and then stored
622 for (auto *U : LPad->users()) {
623 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
627 for (auto *EU : Extract->users()) {
628 if (auto *Store = dyn_cast<StoreInst>(EU)) {
629 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
630 EHAllocas.push_back(AV);
635 // We can't do this without a dominator tree.
638 if (!EHAllocas.empty()) {
639 PromoteMemToReg(EHAllocas, *DT);
644 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
645 LandingPadInst *OutlinedLPad,
646 const LandingPadInst *OriginalLPad,
647 FrameVarInfoMap &FrameVarInfo) {
648 // Get the nested block and erase the unreachable instruction that was
649 // temporarily inserted as its terminator.
650 LLVMContext &Context = ParentFn->getContext();
651 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
652 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
653 OutlinedBB->getTerminator()->eraseFromParent();
654 // That should leave OutlinedLPad as the last instruction in its block.
655 assert(&OutlinedBB->back() == OutlinedLPad);
657 // The original landing pad will have already had its action intrinsic
658 // built by the outlining loop. We need to clone that into the outlined
659 // location. It may also be necessary to add references to the exception
660 // variables to the outlined handler in which this landing pad is nested
661 // and remap return instructions in the nested handlers that should return
662 // to an address in the outlined handler.
663 Function *OutlinedHandlerFn = OutlinedBB->getParent();
664 BasicBlock::const_iterator II = OriginalLPad;
666 // The instruction after the landing pad should now be a call to eh.actions.
667 const Instruction *Recover = II;
668 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
669 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
671 // Remap the exception variables into the outlined function.
672 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
673 SmallVector<BlockAddress *, 4> ActionTargets;
674 SmallVector<ActionHandler *, 4> ActionList;
675 parseEHActions(EHActions, ActionList);
676 for (auto *Action : ActionList) {
677 auto *Catch = dyn_cast<CatchHandler>(Action);
680 // The dyn_cast to function here selects C++ catch handlers and skips
681 // SEH catch handlers.
682 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
685 // Visit all the return instructions, looking for places that return
686 // to a location within OutlinedHandlerFn.
687 for (BasicBlock &NestedHandlerBB : *Handler) {
688 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
692 // Handler functions must always return a block address.
693 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
694 // The original target will have been in the main parent function,
695 // but if it is the address of a block that has been outlined, it
696 // should be a block that was outlined into OutlinedHandlerFn.
697 assert(BA->getFunction() == ParentFn);
699 // Ignore targets that aren't part of OutlinedHandlerFn.
700 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
703 // If the return value is the address ofF a block that we
704 // previously outlined into the parent handler function, replace
705 // the return instruction and add the mapped target to the list
706 // of possible return addresses.
707 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
708 assert(MappedBB->getParent() == OutlinedHandlerFn);
709 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
710 Ret->eraseFromParent();
711 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
712 ActionTargets.push_back(NewBA);
715 DeleteContainerPointers(ActionList);
717 OutlinedBB->getInstList().push_back(EHActions);
719 // Insert an indirect branch into the outlined landing pad BB.
720 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
721 // Add the previously collected action targets.
722 for (auto *Target : ActionTargets)
723 IBr->addDestination(Target->getBasicBlock());
726 // This function examines a block to determine whether the block ends with a
727 // conditional branch to a catch handler based on a selector comparison.
728 // This function is used both by the WinEHPrepare::findSelectorComparison() and
729 // WinEHCleanupDirector::handleTypeIdFor().
730 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
731 Constant *&Selector, BasicBlock *&NextBB) {
732 ICmpInst::Predicate Pred;
733 BasicBlock *TBB, *FBB;
736 if (!match(BB->getTerminator(),
737 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
741 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
742 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
745 if (Pred == CmpInst::ICMP_EQ) {
751 if (Pred == CmpInst::ICMP_NE) {
760 static BasicBlock *createStubLandingPad(Function *Handler,
761 Value *PersonalityFn) {
762 // FIXME: Finish this!
763 LLVMContext &Context = Handler->getContext();
764 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
765 Handler->getBasicBlockList().push_back(StubBB);
766 IRBuilder<> Builder(StubBB);
767 LandingPadInst *LPad = Builder.CreateLandingPad(
768 llvm::StructType::get(Type::getInt8PtrTy(Context),
769 Type::getInt32Ty(Context), nullptr),
771 LPad->setCleanup(true);
772 Builder.CreateUnreachable();
776 // Cycles through the blocks in an outlined handler function looking for an
777 // invoke instruction and inserts an invoke of llvm.donothing with an empty
778 // landing pad if none is found. The code that generates the .xdata tables for
779 // the handler needs at least one landing pad to identify the parent function's
781 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
782 Value *PersonalityFn) {
783 ReturnInst *Ret = nullptr;
784 for (BasicBlock &BB : *Handler) {
785 TerminatorInst *Terminator = BB.getTerminator();
786 // If we find an invoke, there is nothing to be done.
787 auto *II = dyn_cast<InvokeInst>(Terminator);
790 // If we've already recorded a return instruction, keep looking for invokes.
793 // If we haven't recorded a return instruction yet, try this terminator.
794 Ret = dyn_cast<ReturnInst>(Terminator);
797 // If we got this far, the handler contains no invokes. We should have seen
798 // at least one return. We'll insert an invoke of llvm.donothing ahead of
801 BasicBlock *OldRetBB = Ret->getParent();
802 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Ret);
803 // SplitBlock adds an unconditional branch instruction at the end of the
804 // parent block. We want to replace that with an invoke call, so we can
806 OldRetBB->getTerminator()->eraseFromParent();
807 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
809 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
810 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
813 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
814 LandingPadInst *LPad, BasicBlock *StartBB,
815 FrameVarInfoMap &VarInfo) {
816 Module *M = SrcFn->getParent();
817 LLVMContext &Context = M->getContext();
819 // Create a new function to receive the handler contents.
820 Type *Int8PtrType = Type::getInt8PtrTy(Context);
821 std::vector<Type *> ArgTys;
822 ArgTys.push_back(Int8PtrType);
823 ArgTys.push_back(Int8PtrType);
825 if (Action->getType() == Catch) {
826 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
827 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
828 SrcFn->getName() + ".catch", M);
830 FunctionType *FnType =
831 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
832 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
833 SrcFn->getName() + ".cleanup", M);
836 Handler->addFnAttr("wineh-parent", SrcFn->getName());
838 // Generate a standard prolog to setup the frame recovery structure.
839 IRBuilder<> Builder(Context);
840 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
841 Handler->getBasicBlockList().push_front(Entry);
842 Builder.SetInsertPoint(Entry);
843 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
845 std::unique_ptr<WinEHCloningDirectorBase> Director;
847 ValueToValueMapTy VMap;
849 LandingPadMap &LPadMap = LPadMaps[LPad];
850 if (!LPadMap.isInitialized())
851 LPadMap.mapLandingPad(LPad);
852 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
853 Constant *Sel = CatchAction->getSelector();
854 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
855 NestedLPtoOriginalLP));
856 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
857 ConstantInt::get(Type::getInt32Ty(Context), 1));
859 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
860 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
861 UndefValue::get(Type::getInt32Ty(Context)));
864 SmallVector<ReturnInst *, 8> Returns;
865 ClonedCodeInfo OutlinedFunctionInfo;
867 // If the start block contains PHI nodes, we need to map them.
868 BasicBlock::iterator II = StartBB->begin();
869 while (auto *PN = dyn_cast<PHINode>(II)) {
871 // Look for PHI values that we have already mapped (such as the selector).
872 for (Value *Val : PN->incoming_values()) {
873 if (VMap.count(Val)) {
874 VMap[PN] = VMap[Val];
878 // If we didn't find a match for this value, map it as an undef.
880 VMap[PN] = UndefValue::get(PN->getType());
885 // Skip over PHIs and, if applicable, landingpad instructions.
886 II = StartBB->getFirstInsertionPt();
888 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
889 /*ModuleLevelChanges=*/false, Returns, "",
890 &OutlinedFunctionInfo, Director.get());
892 // Move all the instructions in the first cloned block into our entry block.
893 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
894 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
895 FirstClonedBB->eraseFromParent();
897 // Make sure we can identify the handler's personality later.
898 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
900 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
901 WinEHCatchDirector *CatchDirector =
902 reinterpret_cast<WinEHCatchDirector *>(Director.get());
903 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
904 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
906 // Look for blocks that are not part of the landing pad that we just
907 // outlined but terminate with a call to llvm.eh.endcatch and a
908 // branch to a block that is in the handler we just outlined.
909 // These blocks will be part of a nested landing pad that intends to
910 // return to an address in this handler. This case is best handled
911 // after both landing pads have been outlined, so for now we'll just
912 // save the association of the blocks in LPadTargetBlocks. The
913 // return instructions which are created from these branches will be
914 // replaced after all landing pads have been outlined.
915 for (const auto &MapEntry : VMap) {
916 // VMap maps all values and blocks that were just cloned, but dead
917 // blocks which were pruned will map to nullptr.
918 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
920 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
921 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
922 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
923 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
925 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
927 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
928 // This would indicate that a nested landing pad wants to return
929 // to a block that is outlined into two different handlers.
930 assert(!LPadTargetBlocks.count(MappedBB));
931 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
935 } // End if (CatchAction)
937 Action->setHandlerBlockOrFunc(Handler);
942 /// This BB must end in a selector dispatch. All we need to do is pass the
943 /// handler block to llvm.eh.actions and list it as a possible indirectbr
945 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
946 BasicBlock *StartBB) {
947 BasicBlock *HandlerBB;
950 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
952 // If this was EH dispatch, this must be a conditional branch to the handler
954 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
955 // leading to crashes if some optimization hoists stuff here.
956 assert(CatchAction->getSelector() && HandlerBB &&
957 "expected catch EH dispatch");
959 // This must be a catch-all. Split the block after the landingpad.
960 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
962 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
964 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
965 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
966 CatchAction->setReturnTargets(Targets);
969 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
970 // Each instance of this class should only ever be used to map a single
972 assert(OriginLPad == nullptr || OriginLPad == LPad);
974 // If the landing pad has already been mapped, there's nothing more to do.
975 if (OriginLPad == LPad)
980 // The landingpad instruction returns an aggregate value. Typically, its
981 // value will be passed to a pair of extract value instructions and the
982 // results of those extracts will have been promoted to reg values before
983 // this routine is called.
984 for (auto *U : LPad->users()) {
985 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
988 assert(Extract->getNumIndices() == 1 &&
989 "Unexpected operation: extracting both landing pad values");
990 unsigned int Idx = *(Extract->idx_begin());
991 assert((Idx == 0 || Idx == 1) &&
992 "Unexpected operation: extracting an unknown landing pad element");
994 ExtractedEHPtrs.push_back(Extract);
995 } else if (Idx == 1) {
996 ExtractedSelectors.push_back(Extract);
1001 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1002 return BB->getLandingPadInst() == OriginLPad;
1005 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1006 if (Inst == OriginLPad)
1008 for (auto *Extract : ExtractedEHPtrs) {
1009 if (Inst == Extract)
1012 for (auto *Extract : ExtractedSelectors) {
1013 if (Inst == Extract)
1019 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1020 Value *SelectorValue) const {
1021 // Remap all landing pad extract instructions to the specified values.
1022 for (auto *Extract : ExtractedEHPtrs)
1023 VMap[Extract] = EHPtrValue;
1024 for (auto *Extract : ExtractedSelectors)
1025 VMap[Extract] = SelectorValue;
1028 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1029 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1030 // If this is one of the boilerplate landing pad instructions, skip it.
1031 // The instruction will have already been remapped in VMap.
1032 if (LPadMap.isLandingPadSpecificInst(Inst))
1033 return CloningDirector::SkipInstruction;
1035 // Nested landing pads will be cloned as stubs, with just the
1036 // landingpad instruction and an unreachable instruction. When
1037 // all landingpads have been outlined, we'll replace this with the
1038 // llvm.eh.actions call and indirect branch created when the
1039 // landing pad was outlined.
1040 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1041 return handleLandingPad(VMap, LPad, NewBB);
1044 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1045 return handleInvoke(VMap, Invoke, NewBB);
1047 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1048 return handleResume(VMap, Resume, NewBB);
1050 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1051 return handleBeginCatch(VMap, Inst, NewBB);
1052 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1053 return handleEndCatch(VMap, Inst, NewBB);
1054 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1055 return handleTypeIdFor(VMap, Inst, NewBB);
1057 // Continue with the default cloning behavior.
1058 return CloningDirector::CloneInstruction;
1061 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1062 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1063 Instruction *NewInst = LPad->clone();
1064 if (LPad->hasName())
1065 NewInst->setName(LPad->getName());
1066 // Save this correlation for later processing.
1067 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1068 VMap[LPad] = NewInst;
1069 BasicBlock::InstListType &InstList = NewBB->getInstList();
1070 InstList.push_back(NewInst);
1071 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1072 return CloningDirector::StopCloningBB;
1075 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1076 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1077 // The argument to the call is some form of the first element of the
1078 // landingpad aggregate value, but that doesn't matter. It isn't used
1080 // The second argument is an outparameter where the exception object will be
1081 // stored. Typically the exception object is a scalar, but it can be an
1082 // aggregate when catching by value.
1083 // FIXME: Leave something behind to indicate where the exception object lives
1084 // for this handler. Should it be part of llvm.eh.actions?
1085 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1086 "llvm.eh.begincatch found while "
1087 "outlining catch handler.");
1088 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1089 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1090 return CloningDirector::SkipInstruction;
1091 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1092 "catch parameter is not static alloca");
1093 Materializer.escapeCatchObject(ExceptionObjectVar);
1094 return CloningDirector::SkipInstruction;
1097 CloningDirector::CloningAction
1098 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1099 const Instruction *Inst, BasicBlock *NewBB) {
1100 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1101 // It might be interesting to track whether or not we are inside a catch
1102 // function, but that might make the algorithm more brittle than it needs
1105 // The end catch call can occur in one of two places: either in a
1106 // landingpad block that is part of the catch handlers exception mechanism,
1107 // or at the end of the catch block. However, a catch-all handler may call
1108 // end catch from the original landing pad. If the call occurs in a nested
1109 // landing pad block, we must skip it and continue so that the landing pad
1111 auto *ParentBB = IntrinCall->getParent();
1112 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1113 return CloningDirector::SkipInstruction;
1115 // If an end catch occurs anywhere else we want to terminate the handler
1116 // with a return to the code that follows the endcatch call. If the
1117 // next instruction is not an unconditional branch, we need to split the
1118 // block to provide a clear target for the return instruction.
1119 BasicBlock *ContinueBB;
1120 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1121 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1122 if (!Branch || !Branch->isUnconditional()) {
1123 // We're interrupting the cloning process at this location, so the
1124 // const_cast we're doing here will not cause a problem.
1125 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1126 const_cast<Instruction *>(cast<Instruction>(Next)));
1128 ContinueBB = Branch->getSuccessor(0);
1131 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1132 ReturnTargets.push_back(ContinueBB);
1134 // We just added a terminator to the cloned block.
1135 // Tell the caller to stop processing the current basic block so that
1136 // the branch instruction will be skipped.
1137 return CloningDirector::StopCloningBB;
1140 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1141 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1142 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1143 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1144 // This causes a replacement that will collapse the landing pad CFG based
1145 // on the filter function we intend to match.
1146 if (Selector == CurrentSelector)
1147 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1149 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1150 // Tell the caller not to clone this instruction.
1151 return CloningDirector::SkipInstruction;
1154 CloningDirector::CloningAction
1155 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1156 const InvokeInst *Invoke, BasicBlock *NewBB) {
1157 return CloningDirector::CloneInstruction;
1160 CloningDirector::CloningAction
1161 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1162 const ResumeInst *Resume, BasicBlock *NewBB) {
1163 // Resume instructions shouldn't be reachable from catch handlers.
1164 // We still need to handle it, but it will be pruned.
1165 BasicBlock::InstListType &InstList = NewBB->getInstList();
1166 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1167 return CloningDirector::StopCloningBB;
1170 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1171 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1172 // The MS runtime will terminate the process if an exception occurs in a
1173 // cleanup handler, so we shouldn't encounter landing pads in the actual
1174 // cleanup code, but they may appear in catch blocks. Depending on where
1175 // we started cloning we may see one, but it will get dropped during dead
1177 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1178 VMap[LPad] = NewInst;
1179 BasicBlock::InstListType &InstList = NewBB->getInstList();
1180 InstList.push_back(NewInst);
1181 return CloningDirector::StopCloningBB;
1184 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1185 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1186 // Catch blocks within cleanup handlers will always be unreachable.
1187 // We'll insert an unreachable instruction now, but it will be pruned
1188 // before the cloning process is complete.
1189 BasicBlock::InstListType &InstList = NewBB->getInstList();
1190 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1191 return CloningDirector::StopCloningBB;
1194 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1195 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1196 // Cleanup handlers nested within catch handlers may begin with a call to
1197 // eh.endcatch. We can just ignore that instruction.
1198 return CloningDirector::SkipInstruction;
1201 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1202 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1203 // If we encounter a selector comparison while cloning a cleanup handler,
1204 // we want to stop cloning immediately. Anything after the dispatch
1205 // will be outlined into a different handler.
1206 BasicBlock *CatchHandler;
1209 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1210 CatchHandler, Selector, NextBB)) {
1211 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1212 return CloningDirector::StopCloningBB;
1214 // If eg.typeid.for is called for any other reason, it can be ignored.
1215 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1216 return CloningDirector::SkipInstruction;
1219 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1220 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1221 // All invokes in cleanup handlers can be replaced with calls.
1222 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1223 // Insert a normal call instruction...
1225 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1226 Invoke->getName(), NewBB);
1227 NewCall->setCallingConv(Invoke->getCallingConv());
1228 NewCall->setAttributes(Invoke->getAttributes());
1229 NewCall->setDebugLoc(Invoke->getDebugLoc());
1230 VMap[Invoke] = NewCall;
1232 // Insert an unconditional branch to the normal destination.
1233 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1235 // The unwind destination won't be cloned into the new function, so
1236 // we don't need to clean up its phi nodes.
1238 // We just added a terminator to the cloned block.
1239 // Tell the caller to stop processing the current basic block.
1240 return CloningDirector::StopCloningBB;
1243 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1244 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1245 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1247 // We just added a terminator to the cloned block.
1248 // Tell the caller to stop processing the current basic block so that
1249 // the branch instruction will be skipped.
1250 return CloningDirector::StopCloningBB;
1253 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1254 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1255 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1256 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1257 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1260 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1261 // If we're asked to materialize a value that is an instruction, we
1262 // temporarily create an alloca in the outlined function and add this
1263 // to the FrameVarInfo map. When all the outlining is complete, we'll
1264 // collect these into a structure, spilling non-alloca values in the
1265 // parent frame as necessary, and replace these temporary allocas with
1266 // GEPs referencing the frame allocation block.
1268 // If the value is an alloca, the mapping is direct.
1269 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1270 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1271 Builder.Insert(NewAlloca, AV->getName());
1272 FrameVarInfo[AV].push_back(NewAlloca);
1276 // For other types of instructions or arguments, we need an alloca based on
1277 // the value's type and a load of the alloca. The alloca will be replaced
1278 // by a GEP, but the load will stay. In the parent function, the value will
1279 // be spilled to a location in the frame allocation block.
1280 if (isa<Instruction>(V) || isa<Argument>(V)) {
1281 AllocaInst *NewAlloca =
1282 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1283 FrameVarInfo[V].push_back(NewAlloca);
1284 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1288 // Don't materialize other values.
1292 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1293 // Catch parameter objects have to live in the parent frame. When we see a use
1294 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1295 // used from another handler. This will prevent us from trying to sink the
1296 // alloca into the handler and ensure that the catch parameter is present in
1297 // the call to llvm.frameescape.
1298 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1301 // This function maps the catch and cleanup handlers that are reachable from the
1302 // specified landing pad. The landing pad sequence will have this basic shape:
1304 // <cleanup handler>
1305 // <selector comparison>
1307 // <cleanup handler>
1308 // <selector comparison>
1310 // <cleanup handler>
1313 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1314 // any arbitrary control flow, but all paths through the cleanup code must
1315 // eventually reach the next selector comparison and no path can skip to a
1316 // different selector comparisons, though some paths may terminate abnormally.
1317 // Therefore, we will use a depth first search from the start of any given
1318 // cleanup block and stop searching when we find the next selector comparison.
1320 // If the landingpad instruction does not have a catch clause, we will assume
1321 // that any instructions other than selector comparisons and catch handlers can
1322 // be ignored. In practice, these will only be the boilerplate instructions.
1324 // The catch handlers may also have any control structure, but we are only
1325 // interested in the start of the catch handlers, so we don't need to actually
1326 // follow the flow of the catch handlers. The start of the catch handlers can
1327 // be located from the compare instructions, but they can be skipped in the
1328 // flow by following the contrary branch.
1329 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1330 LandingPadActions &Actions) {
1331 unsigned int NumClauses = LPad->getNumClauses();
1332 unsigned int HandlersFound = 0;
1333 BasicBlock *BB = LPad->getParent();
1335 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1337 if (NumClauses == 0) {
1338 // This landing pad contains only cleanup code.
1339 CleanupHandler *Action = new CleanupHandler(BB);
1340 CleanupHandlerMap[BB] = Action;
1341 Actions.insertCleanupHandler(Action);
1342 DEBUG(dbgs() << " Assuming cleanup code in block " << BB->getName()
1344 assert(LPad->isCleanup());
1348 VisitedBlockSet VisitedBlocks;
1350 while (HandlersFound != NumClauses) {
1351 BasicBlock *NextBB = nullptr;
1353 // See if the clause we're looking for is a catch-all.
1354 // If so, the catch begins immediately.
1355 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1356 // The catch all must occur last.
1357 assert(HandlersFound == NumClauses - 1);
1359 // For C++ EH, check if there is any interesting cleanup code before we
1360 // begin the catch. This is important because cleanups cannot rethrow
1361 // exceptions but code called from catches can. For SEH, it isn't
1362 // important if some finally code before a catch-all is executed out of
1363 // line or after recovering from the exception.
1364 if (Personality == EHPersonality::MSVC_CXX) {
1365 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1366 // Add a cleanup entry to the list
1367 Actions.insertCleanupHandler(CleanupAction);
1368 DEBUG(dbgs() << " Found cleanup code in block "
1369 << CleanupAction->getStartBlock()->getName() << "\n");
1373 // Add the catch handler to the action list.
1374 CatchHandler *Action =
1375 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1376 CatchHandlerMap[BB] = Action;
1377 Actions.insertCatchHandler(Action);
1378 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1381 // Once we reach a catch-all, don't expect to hit a resume instruction.
1386 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1387 // See if there is any interesting code executed before the dispatch.
1388 if (auto *CleanupAction =
1389 findCleanupHandler(BB, CatchAction->getStartBlock())) {
1390 // Add a cleanup entry to the list
1391 Actions.insertCleanupHandler(CleanupAction);
1392 DEBUG(dbgs() << " Found cleanup code in block "
1393 << CleanupAction->getStartBlock()->getName() << "\n");
1396 assert(CatchAction);
1399 // Add the catch handler to the action list.
1400 Actions.insertCatchHandler(CatchAction);
1401 DEBUG(dbgs() << " Found catch dispatch in block "
1402 << CatchAction->getStartBlock()->getName() << "\n");
1404 // Move on to the block after the catch handler.
1408 // If we didn't wind up in a catch-all, see if there is any interesting code
1409 // executed before the resume.
1410 if (auto *CleanupAction = findCleanupHandler(BB, BB)) {
1411 // Add a cleanup entry to the list
1412 Actions.insertCleanupHandler(CleanupAction);
1413 DEBUG(dbgs() << " Found cleanup code in block "
1414 << CleanupAction->getStartBlock()->getName() << "\n");
1417 // It's possible that some optimization moved code into a landingpad that
1419 // previously being used for cleanup. If that happens, we need to execute
1421 // extra code from a cleanup handler.
1422 if (Actions.includesCleanup() && !LPad->isCleanup())
1423 LPad->setCleanup(true);
1426 // This function searches starting with the input block for the next
1427 // block that terminates with a branch whose condition is based on a selector
1428 // comparison. This may be the input block. See the mapLandingPadBlocks
1429 // comments for a discussion of control flow assumptions.
1431 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1432 BasicBlock *&NextBB,
1433 VisitedBlockSet &VisitedBlocks) {
1434 // See if we've already found a catch handler use it.
1435 // Call count() first to avoid creating a null entry for blocks
1436 // we haven't seen before.
1437 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1438 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1439 NextBB = Action->getNextBB();
1443 // VisitedBlocks applies only to the current search. We still
1444 // need to consider blocks that we've visited while mapping other
1446 VisitedBlocks.insert(BB);
1448 BasicBlock *CatchBlock = nullptr;
1449 Constant *Selector = nullptr;
1451 // If this is the first time we've visited this block from any landing pad
1452 // look to see if it is a selector dispatch block.
1453 if (!CatchHandlerMap.count(BB)) {
1454 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1455 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1456 CatchHandlerMap[BB] = Action;
1461 // Visit each successor, looking for the dispatch.
1462 // FIXME: We expect to find the dispatch quickly, so this will probably
1463 // work better as a breadth first search.
1464 for (BasicBlock *Succ : successors(BB)) {
1465 if (VisitedBlocks.count(Succ))
1468 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1475 // These are helper functions to combine repeated code from findCleanupHandler.
1476 static CleanupHandler *
1477 createCleanupHandler(CleanupHandlerMapTy &CleanupHandlerMap, BasicBlock *BB) {
1478 CleanupHandler *Action = new CleanupHandler(BB);
1479 CleanupHandlerMap[BB] = Action;
1483 // This function searches starting with the input block for the next block that
1484 // contains code that is not part of a catch handler and would not be eliminated
1485 // during handler outlining.
1487 CleanupHandler *WinEHPrepare::findCleanupHandler(BasicBlock *StartBB,
1488 BasicBlock *EndBB) {
1489 // Here we will skip over the following:
1491 // landing pad prolog:
1493 // Unconditional branches
1495 // Selector dispatch
1499 // Anything else marks the start of an interesting block
1501 BasicBlock *BB = StartBB;
1502 // Anything other than an unconditional branch will kick us out of this loop
1503 // one way or another.
1505 // If we've already scanned this block, don't scan it again. If it is
1506 // a cleanup block, there will be an action in the CleanupHandlerMap.
1507 // If we've scanned it and it is not a cleanup block, there will be a
1508 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1509 // be no entry in the CleanupHandlerMap. We must call count() first to
1510 // avoid creating a null entry for blocks we haven't scanned.
1511 if (CleanupHandlerMap.count(BB)) {
1512 if (auto *Action = CleanupHandlerMap[BB]) {
1513 return cast<CleanupHandler>(Action);
1515 // Here we handle the case where the cleanup handler map contains a
1516 // value for this block but the value is a nullptr. This means that
1517 // we have previously analyzed the block and determined that it did
1518 // not contain any cleanup code. Based on the earlier analysis, we
1519 // know the the block must end in either an unconditional branch, a
1520 // resume or a conditional branch that is predicated on a comparison
1521 // with a selector. Either the resume or the selector dispatch
1522 // would terminate the search for cleanup code, so the unconditional
1523 // branch is the only case for which we might need to continue
1528 if (!match(BB->getTerminator(), m_UnconditionalBr(SuccBB)))
1535 // Create an entry in the cleanup handler map for this block. Initially
1536 // we create an entry that says this isn't a cleanup block. If we find
1537 // cleanup code, the caller will replace this entry.
1538 CleanupHandlerMap[BB] = nullptr;
1540 TerminatorInst *Terminator = BB->getTerminator();
1542 // Landing pad blocks have extra instructions we need to accept.
1543 LandingPadMap *LPadMap = nullptr;
1544 if (BB->isLandingPad()) {
1545 LandingPadInst *LPad = BB->getLandingPadInst();
1546 LPadMap = &LPadMaps[LPad];
1547 if (!LPadMap->isInitialized())
1548 LPadMap->mapLandingPad(LPad);
1551 // Look for the bare resume pattern:
1552 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1553 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1554 // resume { i8*, i32 } %lpad.val2
1555 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1556 InsertValueInst *Insert1 = nullptr;
1557 InsertValueInst *Insert2 = nullptr;
1558 Value *ResumeVal = Resume->getOperand(0);
1559 // If there is only one landingpad, we may use the lpad directly with no
1561 if (isa<LandingPadInst>(ResumeVal))
1563 if (!isa<PHINode>(ResumeVal)) {
1564 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1566 return createCleanupHandler(CleanupHandlerMap, BB);
1567 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1569 return createCleanupHandler(CleanupHandlerMap, BB);
1571 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1573 Instruction *Inst = II;
1574 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1576 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1578 if (!Inst->hasOneUse() ||
1579 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1580 return createCleanupHandler(CleanupHandlerMap, BB);
1586 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1587 if (Branch && Branch->isConditional()) {
1588 // Look for the selector dispatch.
1589 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1590 // %matches = icmp eq i32 %sel, %2
1591 // br i1 %matches, label %catch14, label %eh.resume
1592 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1593 if (!Compare || !Compare->isEquality())
1594 return createCleanupHandler(CleanupHandlerMap, BB);
1595 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1597 Instruction *Inst = II;
1598 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1600 if (Inst == Compare || Inst == Branch)
1602 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1604 return createCleanupHandler(CleanupHandlerMap, BB);
1606 // The selector dispatch block should always terminate our search.
1607 assert(BB == EndBB);
1611 // Anything else is either a catch block or interesting cleanup code.
1612 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1614 Instruction *Inst = II;
1615 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1617 // Unconditional branches fall through to this loop.
1620 // If this is a catch block, there is no cleanup code to be found.
1621 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1623 // If this a nested landing pad, it may contain an endcatch call.
1624 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1626 // Anything else makes this interesting cleanup code.
1627 return createCleanupHandler(CleanupHandlerMap, BB);
1630 // Only unconditional branches in empty blocks should get this far.
1631 assert(Branch && Branch->isUnconditional());
1634 BB = Branch->getSuccessor(0);
1639 // This is a public function, declared in WinEHFuncInfo.h and is also
1640 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1641 void llvm::parseEHActions(const IntrinsicInst *II,
1642 SmallVectorImpl<ActionHandler *> &Actions) {
1643 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1644 uint64_t ActionKind =
1645 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1646 if (ActionKind == /*catch=*/1) {
1647 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1648 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1649 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1650 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1652 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1653 CH->setHandlerBlockOrFunc(Handler);
1654 CH->setExceptionVarIndex(EHObjIndexVal);
1655 Actions.push_back(CH);
1656 } else if (ActionKind == 0) {
1657 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1659 auto *CH = new CleanupHandler(/*BB=*/nullptr);
1660 CH->setHandlerBlockOrFunc(Handler);
1661 Actions.push_back(CH);
1663 llvm_unreachable("Expected either a catch or cleanup handler!");
1666 std::reverse(Actions.begin(), Actions.end());