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())),
180 CloningAction handleInstruction(ValueToValueMapTy &VMap,
181 const Instruction *Inst,
182 BasicBlock *NewBB) override;
184 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
185 const Instruction *Inst,
186 BasicBlock *NewBB) = 0;
187 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
188 const Instruction *Inst,
189 BasicBlock *NewBB) = 0;
190 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
191 const Instruction *Inst,
192 BasicBlock *NewBB) = 0;
193 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
194 const InvokeInst *Invoke,
195 BasicBlock *NewBB) = 0;
196 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
197 const ResumeInst *Resume,
198 BasicBlock *NewBB) = 0;
199 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
200 const LandingPadInst *LPad,
201 BasicBlock *NewBB) = 0;
203 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
206 WinEHFrameVariableMaterializer Materializer;
207 Type *SelectorIDType;
209 LandingPadMap &LPadMap;
212 class WinEHCatchDirector : public WinEHCloningDirectorBase {
215 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
216 LandingPadMap &LPadMap,
217 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
218 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
219 CurrentSelector(Selector->stripPointerCasts()),
220 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
222 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
223 const Instruction *Inst,
224 BasicBlock *NewBB) override;
225 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
226 BasicBlock *NewBB) override;
227 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) override;
230 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
231 BasicBlock *NewBB) override;
232 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
233 BasicBlock *NewBB) override;
234 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
235 const LandingPadInst *LPad,
236 BasicBlock *NewBB) override;
238 Value *getExceptionVar() { return ExceptionObjectVar; }
239 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
242 Value *CurrentSelector;
244 Value *ExceptionObjectVar;
245 TinyPtrVector<BasicBlock *> ReturnTargets;
247 // This will be a reference to the field of the same name in the WinEHPrepare
248 // object which instantiates this WinEHCatchDirector object.
249 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
252 class WinEHCleanupDirector : public WinEHCloningDirectorBase {
254 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
255 LandingPadMap &LPadMap)
256 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
258 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
259 const Instruction *Inst,
260 BasicBlock *NewBB) override;
261 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
262 BasicBlock *NewBB) override;
263 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
264 const Instruction *Inst,
265 BasicBlock *NewBB) override;
266 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
267 BasicBlock *NewBB) override;
268 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
269 BasicBlock *NewBB) override;
270 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
271 const LandingPadInst *LPad,
272 BasicBlock *NewBB) override;
275 class LandingPadActions {
277 LandingPadActions() : HasCleanupHandlers(false) {}
279 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
280 void insertCleanupHandler(CleanupHandler *Action) {
281 Actions.push_back(Action);
282 HasCleanupHandlers = true;
285 bool includesCleanup() const { return HasCleanupHandlers; }
287 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
288 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
289 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
292 // Note that this class does not own the ActionHandler objects in this vector.
293 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
294 // in the WinEHPrepare class.
295 SmallVector<ActionHandler *, 4> Actions;
296 bool HasCleanupHandlers;
299 } // end anonymous namespace
301 char WinEHPrepare::ID = 0;
302 INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
305 FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
306 return new WinEHPrepare(TM);
309 bool WinEHPrepare::runOnFunction(Function &Fn) {
310 SmallVector<LandingPadInst *, 4> LPads;
311 SmallVector<ResumeInst *, 4> Resumes;
312 for (BasicBlock &BB : Fn) {
313 if (auto *LP = BB.getLandingPadInst())
315 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
316 Resumes.push_back(Resume);
319 // No need to prepare functions that lack landing pads.
323 // Classify the personality to see what kind of preparation we need.
324 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
326 // Do nothing if this is not an MSVC personality.
327 if (!isMSVCEHPersonality(Personality))
330 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
332 // If there were any landing pads, prepareExceptionHandlers will make changes.
333 prepareExceptionHandlers(Fn, LPads);
337 bool WinEHPrepare::doFinalization(Module &M) { return false; }
339 void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
340 AU.addRequired<DominatorTreeWrapperPass>();
343 bool WinEHPrepare::prepareExceptionHandlers(
344 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
345 // These containers are used to re-map frame variables that are used in
346 // outlined catch and cleanup handlers. They will be populated as the
347 // handlers are outlined.
348 FrameVarInfoMap FrameVarInfo;
350 bool HandlersOutlined = false;
352 Module *M = F.getParent();
353 LLVMContext &Context = M->getContext();
355 // Create a new function to receive the handler contents.
356 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
357 Type *Int32Type = Type::getInt32Ty(Context);
358 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
360 for (LandingPadInst *LPad : LPads) {
361 // Look for evidence that this landingpad has already been processed.
362 bool LPadHasActionList = false;
363 BasicBlock *LPadBB = LPad->getParent();
364 for (Instruction &Inst : *LPadBB) {
365 if (auto *IntrinCall = dyn_cast<IntrinsicInst>(&Inst)) {
366 if (IntrinCall->getIntrinsicID() == Intrinsic::eh_actions) {
367 LPadHasActionList = true;
371 // FIXME: This is here to help with the development of nested landing pad
372 // outlining. It should be removed when that is finished.
373 if (isa<UnreachableInst>(Inst)) {
374 LPadHasActionList = true;
379 // If we've already outlined the handlers for this landingpad,
380 // there's nothing more to do here.
381 if (LPadHasActionList)
384 // If either of the values in the aggregate returned by the landing pad is
385 // extracted and stored to memory, promote the stored value to a register.
386 promoteLandingPadValues(LPad);
388 LandingPadActions Actions;
389 mapLandingPadBlocks(LPad, Actions);
391 HandlersOutlined |= !Actions.actions().empty();
392 for (ActionHandler *Action : Actions) {
393 if (Action->hasBeenProcessed())
395 BasicBlock *StartBB = Action->getStartBlock();
397 // SEH doesn't do any outlining for catches. Instead, pass the handler
398 // basic block addr to llvm.eh.actions and list the block as a return
400 if (isAsynchronousEHPersonality(Personality)) {
401 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
402 processSEHCatchHandler(CatchAction, StartBB);
407 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
410 // Replace the landing pad with a new llvm.eh.action based landing pad.
411 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
412 assert(!isa<PHINode>(LPadBB->begin()));
413 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
414 NewLPadBB->getInstList().push_back(NewLPad);
415 while (!pred_empty(LPadBB)) {
416 auto *pred = *pred_begin(LPadBB);
417 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
418 Invoke->setUnwindDest(NewLPadBB);
421 // If anyone is still using the old landingpad value, just give them undef
422 // instead. The eh pointer and selector values are not real.
423 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
425 // Replace the mapping of any nested landing pad that previously mapped
426 // to this landing pad with a referenced to the cloned version.
427 for (auto &LPadPair : NestedLPtoOriginalLP) {
428 const LandingPadInst *OriginalLPad = LPadPair.second;
429 if (OriginalLPad == LPad) {
430 LPadPair.second = NewLPad;
434 // Replace uses of the old lpad in phis with this block and delete the old
436 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
437 LPadBB->getTerminator()->eraseFromParent();
438 new UnreachableInst(LPadBB->getContext(), LPadBB);
440 // Add a call to describe the actions for this landing pad.
441 std::vector<Value *> ActionArgs;
442 for (ActionHandler *Action : Actions) {
443 // Action codes from docs are: 0 cleanup, 1 catch.
444 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
445 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
446 ActionArgs.push_back(CatchAction->getSelector());
447 // Find the frame escape index of the exception object alloca in the
449 int FrameEscapeIdx = -1;
450 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
451 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
452 auto I = FrameVarInfo.find(EHObj);
453 assert(I != FrameVarInfo.end() &&
454 "failed to map llvm.eh.begincatch var");
455 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
457 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
459 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
461 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
464 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
466 // Add an indirect branch listing possible successors of the catch handlers.
467 IndirectBrInst *Branch = IndirectBrInst::Create(Recover, 0, NewLPadBB);
468 for (ActionHandler *Action : Actions) {
469 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
470 for (auto *Target : CatchAction->getReturnTargets()) {
471 Branch->addDestination(Target);
475 } // End for each landingpad
477 // If nothing got outlined, there is no more processing to be done.
478 if (!HandlersOutlined)
481 // Replace any nested landing pad stubs with the correct action handler.
482 // This must be done before we remove unreachable blocks because it
483 // cleans up references to outlined blocks that will be deleted.
484 for (auto &LPadPair : NestedLPtoOriginalLP)
485 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
486 NestedLPtoOriginalLP.clear();
488 F.addFnAttr("wineh-parent", F.getName());
490 // Delete any blocks that were only used by handlers that were outlined above.
491 removeUnreachableBlocks(F);
493 BasicBlock *Entry = &F.getEntryBlock();
494 IRBuilder<> Builder(F.getParent()->getContext());
495 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
497 Function *FrameEscapeFn =
498 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
499 Function *RecoverFrameFn =
500 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
502 // Finally, replace all of the temporary allocas for frame variables used in
503 // the outlined handlers with calls to llvm.framerecover.
504 BasicBlock::iterator II = Entry->getFirstInsertionPt();
505 Instruction *AllocaInsertPt = II;
506 SmallVector<Value *, 8> AllocasToEscape;
507 for (auto &VarInfoEntry : FrameVarInfo) {
508 Value *ParentVal = VarInfoEntry.first;
509 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
511 // If the mapped value isn't already an alloca, we need to spill it if it
512 // is a computed value or copy it if it is an argument.
513 AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal);
515 if (auto *Arg = dyn_cast<Argument>(ParentVal)) {
516 // Lower this argument to a copy and then demote that to the stack.
517 // We can't just use the argument location because the handler needs
518 // it to be in the frame allocation block.
519 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
520 Value *TrueValue = ConstantInt::getTrue(Context);
521 Value *UndefValue = UndefValue::get(Arg->getType());
523 SelectInst::Create(TrueValue, Arg, UndefValue,
524 Arg->getName() + ".tmp", AllocaInsertPt);
525 Arg->replaceAllUsesWith(SI);
526 // Reset the select operand, because it was clobbered by the RAUW above.
527 SI->setOperand(1, Arg);
528 ParentAlloca = DemoteRegToStack(*SI, true, SI);
529 } else if (auto *PN = dyn_cast<PHINode>(ParentVal)) {
530 ParentAlloca = DemotePHIToStack(PN, AllocaInsertPt);
532 Instruction *ParentInst = cast<Instruction>(ParentVal);
533 // FIXME: This is a work-around to temporarily handle the case where an
534 // instruction that is only used in handlers is not sunk.
535 // Without uses, DemoteRegToStack would just eliminate the value.
536 // This will fail if ParentInst is an invoke.
537 if (ParentInst->getNumUses() == 0) {
538 BasicBlock::iterator InsertPt = ParentInst;
541 new AllocaInst(ParentInst->getType(), nullptr,
542 ParentInst->getName() + ".reg2mem",
544 new StoreInst(ParentInst, ParentAlloca, InsertPt);
546 ParentAlloca = DemoteRegToStack(*ParentInst, true, AllocaInsertPt);
551 // FIXME: We should try to sink unescaped allocas from the parent frame into
552 // the child frame. If the alloca is escaped, we have to use the lifetime
553 // markers to ensure that the alloca is only live within the child frame.
555 // Add this alloca to the list of things to escape.
556 AllocasToEscape.push_back(ParentAlloca);
558 // Next replace all outlined allocas that are mapped to it.
559 for (AllocaInst *TempAlloca : Allocas) {
560 if (TempAlloca == getCatchObjectSentinel())
561 continue; // Skip catch parameter sentinels.
562 Function *HandlerFn = TempAlloca->getParent()->getParent();
563 // FIXME: Sink this GEP into the blocks where it is used.
564 Builder.SetInsertPoint(TempAlloca);
565 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
566 Value *RecoverArgs[] = {
567 Builder.CreateBitCast(&F, Int8PtrType, ""),
568 &(HandlerFn->getArgumentList().back()),
569 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
570 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
571 // Add a pointer bitcast if the alloca wasn't an i8.
572 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
573 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
575 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
577 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
578 TempAlloca->removeFromParent();
579 RecoveredAlloca->takeName(TempAlloca);
582 } // End for each FrameVarInfo entry.
584 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
586 Builder.SetInsertPoint(&F.getEntryBlock().back());
587 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
589 // Clean up the handler action maps we created for this function
590 DeleteContainerSeconds(CatchHandlerMap);
591 CatchHandlerMap.clear();
592 DeleteContainerSeconds(CleanupHandlerMap);
593 CleanupHandlerMap.clear();
595 return HandlersOutlined;
598 void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
599 // If the return values of the landing pad instruction are extracted and
600 // stored to memory, we want to promote the store locations to reg values.
601 SmallVector<AllocaInst *, 2> EHAllocas;
603 // The landingpad instruction returns an aggregate value. Typically, its
604 // value will be passed to a pair of extract value instructions and the
605 // results of those extracts are often passed to store instructions.
606 // In unoptimized code the stored value will often be loaded and then stored
608 for (auto *U : LPad->users()) {
609 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
613 for (auto *EU : Extract->users()) {
614 if (auto *Store = dyn_cast<StoreInst>(EU)) {
615 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
616 EHAllocas.push_back(AV);
621 // We can't do this without a dominator tree.
624 if (!EHAllocas.empty()) {
625 PromoteMemToReg(EHAllocas, *DT);
629 // After promotion, some extracts may be trivially dead. Remove them.
630 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
631 for (auto *U : Users)
632 RecursivelyDeleteTriviallyDeadInstructions(U);
635 void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
636 LandingPadInst *OutlinedLPad,
637 const LandingPadInst *OriginalLPad,
638 FrameVarInfoMap &FrameVarInfo) {
639 // Get the nested block and erase the unreachable instruction that was
640 // temporarily inserted as its terminator.
641 LLVMContext &Context = ParentFn->getContext();
642 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
643 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
644 OutlinedBB->getTerminator()->eraseFromParent();
645 // That should leave OutlinedLPad as the last instruction in its block.
646 assert(&OutlinedBB->back() == OutlinedLPad);
648 // The original landing pad will have already had its action intrinsic
649 // built by the outlining loop. We need to clone that into the outlined
650 // location. It may also be necessary to add references to the exception
651 // variables to the outlined handler in which this landing pad is nested
652 // and remap return instructions in the nested handlers that should return
653 // to an address in the outlined handler.
654 Function *OutlinedHandlerFn = OutlinedBB->getParent();
655 BasicBlock::const_iterator II = OriginalLPad;
657 // The instruction after the landing pad should now be a call to eh.actions.
658 const Instruction *Recover = II;
659 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
660 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
662 // Remap the exception variables into the outlined function.
663 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
664 SmallVector<BlockAddress *, 4> ActionTargets;
665 SmallVector<ActionHandler *, 4> ActionList;
666 parseEHActions(EHActions, ActionList);
667 for (auto *Action : ActionList) {
668 auto *Catch = dyn_cast<CatchHandler>(Action);
671 // The dyn_cast to function here selects C++ catch handlers and skips
672 // SEH catch handlers.
673 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
676 // Visit all the return instructions, looking for places that return
677 // to a location within OutlinedHandlerFn.
678 for (BasicBlock &NestedHandlerBB : *Handler) {
679 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
683 // Handler functions must always return a block address.
684 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
685 // The original target will have been in the main parent function,
686 // but if it is the address of a block that has been outlined, it
687 // should be a block that was outlined into OutlinedHandlerFn.
688 assert(BA->getFunction() == ParentFn);
690 // Ignore targets that aren't part of OutlinedHandlerFn.
691 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
694 // If the return value is the address ofF a block that we
695 // previously outlined into the parent handler function, replace
696 // the return instruction and add the mapped target to the list
697 // of possible return addresses.
698 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
699 assert(MappedBB->getParent() == OutlinedHandlerFn);
700 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
701 Ret->eraseFromParent();
702 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
703 ActionTargets.push_back(NewBA);
706 DeleteContainerPointers(ActionList);
708 OutlinedBB->getInstList().push_back(EHActions);
710 // Insert an indirect branch into the outlined landing pad BB.
711 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
712 // Add the previously collected action targets.
713 for (auto *Target : ActionTargets)
714 IBr->addDestination(Target->getBasicBlock());
717 // This function examines a block to determine whether the block ends with a
718 // conditional branch to a catch handler based on a selector comparison.
719 // This function is used both by the WinEHPrepare::findSelectorComparison() and
720 // WinEHCleanupDirector::handleTypeIdFor().
721 static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
722 Constant *&Selector, BasicBlock *&NextBB) {
723 ICmpInst::Predicate Pred;
724 BasicBlock *TBB, *FBB;
727 if (!match(BB->getTerminator(),
728 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
732 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
733 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
736 if (Pred == CmpInst::ICMP_EQ) {
742 if (Pred == CmpInst::ICMP_NE) {
751 static BasicBlock *createStubLandingPad(Function *Handler,
752 Value *PersonalityFn) {
753 // FIXME: Finish this!
754 LLVMContext &Context = Handler->getContext();
755 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
756 Handler->getBasicBlockList().push_back(StubBB);
757 IRBuilder<> Builder(StubBB);
758 LandingPadInst *LPad = Builder.CreateLandingPad(
759 llvm::StructType::get(Type::getInt8PtrTy(Context),
760 Type::getInt32Ty(Context), nullptr),
762 LPad->setCleanup(true);
763 Builder.CreateUnreachable();
767 // Cycles through the blocks in an outlined handler function looking for an
768 // invoke instruction and inserts an invoke of llvm.donothing with an empty
769 // landing pad if none is found. The code that generates the .xdata tables for
770 // the handler needs at least one landing pad to identify the parent function's
772 void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
773 Value *PersonalityFn) {
774 ReturnInst *Ret = nullptr;
775 for (BasicBlock &BB : *Handler) {
776 TerminatorInst *Terminator = BB.getTerminator();
777 // If we find an invoke, there is nothing to be done.
778 auto *II = dyn_cast<InvokeInst>(Terminator);
781 // If we've already recorded a return instruction, keep looking for invokes.
784 // If we haven't recorded a return instruction yet, try this terminator.
785 Ret = dyn_cast<ReturnInst>(Terminator);
788 // If we got this far, the handler contains no invokes. We should have seen
789 // at least one return. We'll insert an invoke of llvm.donothing ahead of
792 BasicBlock *OldRetBB = Ret->getParent();
793 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Ret);
794 // SplitBlock adds an unconditional branch instruction at the end of the
795 // parent block. We want to replace that with an invoke call, so we can
797 OldRetBB->getTerminator()->eraseFromParent();
798 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
800 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
801 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
804 bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
805 LandingPadInst *LPad, BasicBlock *StartBB,
806 FrameVarInfoMap &VarInfo) {
807 Module *M = SrcFn->getParent();
808 LLVMContext &Context = M->getContext();
810 // Create a new function to receive the handler contents.
811 Type *Int8PtrType = Type::getInt8PtrTy(Context);
812 std::vector<Type *> ArgTys;
813 ArgTys.push_back(Int8PtrType);
814 ArgTys.push_back(Int8PtrType);
816 if (Action->getType() == Catch) {
817 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
818 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
819 SrcFn->getName() + ".catch", M);
821 FunctionType *FnType =
822 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
823 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
824 SrcFn->getName() + ".cleanup", M);
827 Handler->addFnAttr("wineh-parent", SrcFn->getName());
829 // Generate a standard prolog to setup the frame recovery structure.
830 IRBuilder<> Builder(Context);
831 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
832 Handler->getBasicBlockList().push_front(Entry);
833 Builder.SetInsertPoint(Entry);
834 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
836 std::unique_ptr<WinEHCloningDirectorBase> Director;
838 ValueToValueMapTy VMap;
840 LandingPadMap &LPadMap = LPadMaps[LPad];
841 if (!LPadMap.isInitialized())
842 LPadMap.mapLandingPad(LPad);
843 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
844 Constant *Sel = CatchAction->getSelector();
845 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
846 NestedLPtoOriginalLP));
847 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
848 ConstantInt::get(Type::getInt32Ty(Context), 1));
850 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
851 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
852 UndefValue::get(Type::getInt32Ty(Context)));
855 SmallVector<ReturnInst *, 8> Returns;
856 ClonedCodeInfo OutlinedFunctionInfo;
858 // If the start block contains PHI nodes, we need to map them.
859 BasicBlock::iterator II = StartBB->begin();
860 while (auto *PN = dyn_cast<PHINode>(II)) {
862 // Look for PHI values that we have already mapped (such as the selector).
863 for (Value *Val : PN->incoming_values()) {
864 if (VMap.count(Val)) {
865 VMap[PN] = VMap[Val];
869 // If we didn't find a match for this value, map it as an undef.
871 VMap[PN] = UndefValue::get(PN->getType());
876 // Skip over PHIs and, if applicable, landingpad instructions.
877 II = StartBB->getFirstInsertionPt();
879 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
880 /*ModuleLevelChanges=*/false, Returns, "",
881 &OutlinedFunctionInfo, Director.get());
883 // Move all the instructions in the first cloned block into our entry block.
884 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
885 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
886 FirstClonedBB->eraseFromParent();
888 // Make sure we can identify the handler's personality later.
889 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
891 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
892 WinEHCatchDirector *CatchDirector =
893 reinterpret_cast<WinEHCatchDirector *>(Director.get());
894 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
895 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
897 // Look for blocks that are not part of the landing pad that we just
898 // outlined but terminate with a call to llvm.eh.endcatch and a
899 // branch to a block that is in the handler we just outlined.
900 // These blocks will be part of a nested landing pad that intends to
901 // return to an address in this handler. This case is best handled
902 // after both landing pads have been outlined, so for now we'll just
903 // save the association of the blocks in LPadTargetBlocks. The
904 // return instructions which are created from these branches will be
905 // replaced after all landing pads have been outlined.
906 for (const auto MapEntry : VMap) {
907 // VMap maps all values and blocks that were just cloned, but dead
908 // blocks which were pruned will map to nullptr.
909 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
911 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
912 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
913 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
914 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
916 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
918 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
919 // This would indicate that a nested landing pad wants to return
920 // to a block that is outlined into two different handlers.
921 assert(!LPadTargetBlocks.count(MappedBB));
922 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
926 } // End if (CatchAction)
928 Action->setHandlerBlockOrFunc(Handler);
933 /// This BB must end in a selector dispatch. All we need to do is pass the
934 /// handler block to llvm.eh.actions and list it as a possible indirectbr
936 void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
937 BasicBlock *StartBB) {
938 BasicBlock *HandlerBB;
941 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
943 // If this was EH dispatch, this must be a conditional branch to the handler
945 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
946 // leading to crashes if some optimization hoists stuff here.
947 assert(CatchAction->getSelector() && HandlerBB &&
948 "expected catch EH dispatch");
950 // This must be a catch-all. Split the block after the landingpad.
951 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
953 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
955 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
956 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
957 CatchAction->setReturnTargets(Targets);
960 void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
961 // Each instance of this class should only ever be used to map a single
963 assert(OriginLPad == nullptr || OriginLPad == LPad);
965 // If the landing pad has already been mapped, there's nothing more to do.
966 if (OriginLPad == LPad)
971 // The landingpad instruction returns an aggregate value. Typically, its
972 // value will be passed to a pair of extract value instructions and the
973 // results of those extracts will have been promoted to reg values before
974 // this routine is called.
975 for (auto *U : LPad->users()) {
976 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
979 assert(Extract->getNumIndices() == 1 &&
980 "Unexpected operation: extracting both landing pad values");
981 unsigned int Idx = *(Extract->idx_begin());
982 assert((Idx == 0 || Idx == 1) &&
983 "Unexpected operation: extracting an unknown landing pad element");
985 ExtractedEHPtrs.push_back(Extract);
986 } else if (Idx == 1) {
987 ExtractedSelectors.push_back(Extract);
992 bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
993 return BB->getLandingPadInst() == OriginLPad;
996 bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
997 if (Inst == OriginLPad)
999 for (auto *Extract : ExtractedEHPtrs) {
1000 if (Inst == Extract)
1003 for (auto *Extract : ExtractedSelectors) {
1004 if (Inst == Extract)
1010 void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1011 Value *SelectorValue) const {
1012 // Remap all landing pad extract instructions to the specified values.
1013 for (auto *Extract : ExtractedEHPtrs)
1014 VMap[Extract] = EHPtrValue;
1015 for (auto *Extract : ExtractedSelectors)
1016 VMap[Extract] = SelectorValue;
1019 CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
1020 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1021 // If this is one of the boilerplate landing pad instructions, skip it.
1022 // The instruction will have already been remapped in VMap.
1023 if (LPadMap.isLandingPadSpecificInst(Inst))
1024 return CloningDirector::SkipInstruction;
1026 // Nested landing pads will be cloned as stubs, with just the
1027 // landingpad instruction and an unreachable instruction. When
1028 // all landingpads have been outlined, we'll replace this with the
1029 // llvm.eh.actions call and indirect branch created when the
1030 // landing pad was outlined.
1031 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1032 return handleLandingPad(VMap, LPad, NewBB);
1035 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1036 return handleInvoke(VMap, Invoke, NewBB);
1038 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1039 return handleResume(VMap, Resume, NewBB);
1041 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1042 return handleBeginCatch(VMap, Inst, NewBB);
1043 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1044 return handleEndCatch(VMap, Inst, NewBB);
1045 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1046 return handleTypeIdFor(VMap, Inst, NewBB);
1048 // Continue with the default cloning behavior.
1049 return CloningDirector::CloneInstruction;
1052 CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1053 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1054 Instruction *NewInst = LPad->clone();
1055 if (LPad->hasName())
1056 NewInst->setName(LPad->getName());
1057 // Save this correlation for later processing.
1058 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1059 VMap[LPad] = NewInst;
1060 BasicBlock::InstListType &InstList = NewBB->getInstList();
1061 InstList.push_back(NewInst);
1062 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1063 return CloningDirector::StopCloningBB;
1066 CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1067 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1068 // The argument to the call is some form of the first element of the
1069 // landingpad aggregate value, but that doesn't matter. It isn't used
1071 // The second argument is an outparameter where the exception object will be
1072 // stored. Typically the exception object is a scalar, but it can be an
1073 // aggregate when catching by value.
1074 // FIXME: Leave something behind to indicate where the exception object lives
1075 // for this handler. Should it be part of llvm.eh.actions?
1076 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1077 "llvm.eh.begincatch found while "
1078 "outlining catch handler.");
1079 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
1080 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1081 return CloningDirector::SkipInstruction;
1082 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1083 "catch parameter is not static alloca");
1084 Materializer.escapeCatchObject(ExceptionObjectVar);
1085 return CloningDirector::SkipInstruction;
1088 CloningDirector::CloningAction
1089 WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1090 const Instruction *Inst, BasicBlock *NewBB) {
1091 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1092 // It might be interesting to track whether or not we are inside a catch
1093 // function, but that might make the algorithm more brittle than it needs
1096 // The end catch call can occur in one of two places: either in a
1097 // landingpad block that is part of the catch handlers exception mechanism,
1098 // or at the end of the catch block. However, a catch-all handler may call
1099 // end catch from the original landing pad. If the call occurs in a nested
1100 // landing pad block, we must skip it and continue so that the landing pad
1102 auto *ParentBB = IntrinCall->getParent();
1103 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
1104 return CloningDirector::SkipInstruction;
1106 // If an end catch occurs anywhere else we want to terminate the handler
1107 // with a return to the code that follows the endcatch call. If the
1108 // next instruction is not an unconditional branch, we need to split the
1109 // block to provide a clear target for the return instruction.
1110 BasicBlock *ContinueBB;
1111 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1112 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1113 if (!Branch || !Branch->isUnconditional()) {
1114 // We're interrupting the cloning process at this location, so the
1115 // const_cast we're doing here will not cause a problem.
1116 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1117 const_cast<Instruction *>(cast<Instruction>(Next)));
1119 ContinueBB = Branch->getSuccessor(0);
1122 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1123 ReturnTargets.push_back(ContinueBB);
1125 // We just added a terminator to the cloned block.
1126 // Tell the caller to stop processing the current basic block so that
1127 // the branch instruction will be skipped.
1128 return CloningDirector::StopCloningBB;
1131 CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1132 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1133 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1134 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1135 // This causes a replacement that will collapse the landing pad CFG based
1136 // on the filter function we intend to match.
1137 if (Selector == CurrentSelector)
1138 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1140 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1141 // Tell the caller not to clone this instruction.
1142 return CloningDirector::SkipInstruction;
1145 CloningDirector::CloningAction
1146 WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1147 const InvokeInst *Invoke, BasicBlock *NewBB) {
1148 return CloningDirector::CloneInstruction;
1151 CloningDirector::CloningAction
1152 WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1153 const ResumeInst *Resume, BasicBlock *NewBB) {
1154 // Resume instructions shouldn't be reachable from catch handlers.
1155 // We still need to handle it, but it will be pruned.
1156 BasicBlock::InstListType &InstList = NewBB->getInstList();
1157 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1158 return CloningDirector::StopCloningBB;
1161 CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1162 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1163 // The MS runtime will terminate the process if an exception occurs in a
1164 // cleanup handler, so we shouldn't encounter landing pads in the actual
1165 // cleanup code, but they may appear in catch blocks. Depending on where
1166 // we started cloning we may see one, but it will get dropped during dead
1168 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1169 VMap[LPad] = NewInst;
1170 BasicBlock::InstListType &InstList = NewBB->getInstList();
1171 InstList.push_back(NewInst);
1172 return CloningDirector::StopCloningBB;
1175 CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1176 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1177 // Catch blocks within cleanup handlers will always be unreachable.
1178 // We'll insert an unreachable instruction now, but it will be pruned
1179 // before the cloning process is complete.
1180 BasicBlock::InstListType &InstList = NewBB->getInstList();
1181 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1182 return CloningDirector::StopCloningBB;
1185 CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1186 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1187 // Cleanup handlers nested within catch handlers may begin with a call to
1188 // eh.endcatch. We can just ignore that instruction.
1189 return CloningDirector::SkipInstruction;
1192 CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1193 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1194 // If we encounter a selector comparison while cloning a cleanup handler,
1195 // we want to stop cloning immediately. Anything after the dispatch
1196 // will be outlined into a different handler.
1197 BasicBlock *CatchHandler;
1200 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1201 CatchHandler, Selector, NextBB)) {
1202 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1203 return CloningDirector::StopCloningBB;
1205 // If eg.typeid.for is called for any other reason, it can be ignored.
1206 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1207 return CloningDirector::SkipInstruction;
1210 CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1211 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1212 // All invokes in cleanup handlers can be replaced with calls.
1213 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1214 // Insert a normal call instruction...
1216 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1217 Invoke->getName(), NewBB);
1218 NewCall->setCallingConv(Invoke->getCallingConv());
1219 NewCall->setAttributes(Invoke->getAttributes());
1220 NewCall->setDebugLoc(Invoke->getDebugLoc());
1221 VMap[Invoke] = NewCall;
1223 // Remap the operands.
1224 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1226 // Insert an unconditional branch to the normal destination.
1227 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1229 // The unwind destination won't be cloned into the new function, so
1230 // we don't need to clean up its phi nodes.
1232 // We just added a terminator to the cloned block.
1233 // Tell the caller to stop processing the current basic block.
1234 return CloningDirector::CloneSuccessors;
1237 CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1238 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1239 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1241 // We just added a terminator to the cloned block.
1242 // Tell the caller to stop processing the current basic block so that
1243 // the branch instruction will be skipped.
1244 return CloningDirector::StopCloningBB;
1247 WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1248 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1249 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
1250 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1251 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
1254 Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
1255 // If we're asked to materialize a value that is an instruction, we
1256 // temporarily create an alloca in the outlined function and add this
1257 // to the FrameVarInfo map. When all the outlining is complete, we'll
1258 // collect these into a structure, spilling non-alloca values in the
1259 // parent frame as necessary, and replace these temporary allocas with
1260 // GEPs referencing the frame allocation block.
1262 // If the value is an alloca, the mapping is direct.
1263 if (auto *AV = dyn_cast<AllocaInst>(V)) {
1264 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1265 Builder.Insert(NewAlloca, AV->getName());
1266 FrameVarInfo[AV].push_back(NewAlloca);
1270 // For other types of instructions or arguments, we need an alloca based on
1271 // the value's type and a load of the alloca. The alloca will be replaced
1272 // by a GEP, but the load will stay. In the parent function, the value will
1273 // be spilled to a location in the frame allocation block.
1274 if (isa<Instruction>(V) || isa<Argument>(V)) {
1275 AllocaInst *NewAlloca =
1276 Builder.CreateAlloca(V->getType(), nullptr, "eh.temp.alloca");
1277 FrameVarInfo[V].push_back(NewAlloca);
1278 LoadInst *NewLoad = Builder.CreateLoad(NewAlloca, V->getName() + ".reload");
1282 // Don't materialize other values.
1286 void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1287 // Catch parameter objects have to live in the parent frame. When we see a use
1288 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1289 // used from another handler. This will prevent us from trying to sink the
1290 // alloca into the handler and ensure that the catch parameter is present in
1291 // the call to llvm.frameescape.
1292 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1295 // This function maps the catch and cleanup handlers that are reachable from the
1296 // specified landing pad. The landing pad sequence will have this basic shape:
1298 // <cleanup handler>
1299 // <selector comparison>
1301 // <cleanup handler>
1302 // <selector comparison>
1304 // <cleanup handler>
1307 // Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1308 // any arbitrary control flow, but all paths through the cleanup code must
1309 // eventually reach the next selector comparison and no path can skip to a
1310 // different selector comparisons, though some paths may terminate abnormally.
1311 // Therefore, we will use a depth first search from the start of any given
1312 // cleanup block and stop searching when we find the next selector comparison.
1314 // If the landingpad instruction does not have a catch clause, we will assume
1315 // that any instructions other than selector comparisons and catch handlers can
1316 // be ignored. In practice, these will only be the boilerplate instructions.
1318 // The catch handlers may also have any control structure, but we are only
1319 // interested in the start of the catch handlers, so we don't need to actually
1320 // follow the flow of the catch handlers. The start of the catch handlers can
1321 // be located from the compare instructions, but they can be skipped in the
1322 // flow by following the contrary branch.
1323 void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1324 LandingPadActions &Actions) {
1325 unsigned int NumClauses = LPad->getNumClauses();
1326 unsigned int HandlersFound = 0;
1327 BasicBlock *BB = LPad->getParent();
1329 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1331 if (NumClauses == 0) {
1332 findCleanupHandlers(Actions, BB, nullptr);
1336 VisitedBlockSet VisitedBlocks;
1338 while (HandlersFound != NumClauses) {
1339 BasicBlock *NextBB = nullptr;
1341 // See if the clause we're looking for is a catch-all.
1342 // If so, the catch begins immediately.
1343 if (isa<ConstantPointerNull>(LPad->getClause(HandlersFound))) {
1344 // The catch all must occur last.
1345 assert(HandlersFound == NumClauses - 1);
1347 // For C++ EH, check if there is any interesting cleanup code before we
1348 // begin the catch. This is important because cleanups cannot rethrow
1349 // exceptions but code called from catches can. For SEH, it isn't
1350 // important if some finally code before a catch-all is executed out of
1351 // line or after recovering from the exception.
1352 if (Personality == EHPersonality::MSVC_CXX)
1353 findCleanupHandlers(Actions, BB, BB);
1355 // Add the catch handler to the action list.
1356 CatchHandler *Action =
1357 new CatchHandler(BB, LPad->getClause(HandlersFound), nullptr);
1358 CatchHandlerMap[BB] = Action;
1359 Actions.insertCatchHandler(Action);
1360 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1363 // Once we reach a catch-all, don't expect to hit a resume instruction.
1368 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
1369 // See if there is any interesting code executed before the dispatch.
1370 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
1372 assert(CatchAction);
1375 // Add the catch handler to the action list.
1376 Actions.insertCatchHandler(CatchAction);
1377 DEBUG(dbgs() << " Found catch dispatch in block "
1378 << CatchAction->getStartBlock()->getName() << "\n");
1380 // Move on to the block after the catch handler.
1384 // If we didn't wind up in a catch-all, see if there is any interesting code
1385 // executed before the resume.
1386 findCleanupHandlers(Actions, BB, BB);
1388 // It's possible that some optimization moved code into a landingpad that
1390 // previously being used for cleanup. If that happens, we need to execute
1392 // extra code from a cleanup handler.
1393 if (Actions.includesCleanup() && !LPad->isCleanup())
1394 LPad->setCleanup(true);
1397 // This function searches starting with the input block for the next
1398 // block that terminates with a branch whose condition is based on a selector
1399 // comparison. This may be the input block. See the mapLandingPadBlocks
1400 // comments for a discussion of control flow assumptions.
1402 CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1403 BasicBlock *&NextBB,
1404 VisitedBlockSet &VisitedBlocks) {
1405 // See if we've already found a catch handler use it.
1406 // Call count() first to avoid creating a null entry for blocks
1407 // we haven't seen before.
1408 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1409 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1410 NextBB = Action->getNextBB();
1414 // VisitedBlocks applies only to the current search. We still
1415 // need to consider blocks that we've visited while mapping other
1417 VisitedBlocks.insert(BB);
1419 BasicBlock *CatchBlock = nullptr;
1420 Constant *Selector = nullptr;
1422 // If this is the first time we've visited this block from any landing pad
1423 // look to see if it is a selector dispatch block.
1424 if (!CatchHandlerMap.count(BB)) {
1425 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1426 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1427 CatchHandlerMap[BB] = Action;
1432 // Visit each successor, looking for the dispatch.
1433 // FIXME: We expect to find the dispatch quickly, so this will probably
1434 // work better as a breadth first search.
1435 for (BasicBlock *Succ : successors(BB)) {
1436 if (VisitedBlocks.count(Succ))
1439 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1446 // These are helper functions to combine repeated code from findCleanupHandlers.
1447 static void createCleanupHandler(LandingPadActions &Actions,
1448 CleanupHandlerMapTy &CleanupHandlerMap,
1450 CleanupHandler *Action = new CleanupHandler(BB);
1451 CleanupHandlerMap[BB] = Action;
1452 Actions.insertCleanupHandler(Action);
1453 DEBUG(dbgs() << " Found cleanup code in block "
1454 << Action->getStartBlock()->getName() << "\n");
1457 static bool isFrameAddressCall(Value *V) {
1458 return match(V, m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1461 static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1462 Instruction *MaybeCall) {
1463 // Look for finally blocks that Clang has already outlined for us.
1464 // %fp = call i8* @llvm.frameaddress(i32 0)
1465 // call void @"fin$parent"(iN 1, i8* %fp)
1466 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1467 MaybeCall = MaybeCall->getNextNode();
1468 CallSite FinallyCall(MaybeCall);
1469 if (!FinallyCall || FinallyCall.arg_size() != 2)
1471 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1473 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1478 static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1479 // Skip single ubr blocks.
1480 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1481 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1482 if (Br && Br->isUnconditional())
1483 BB = Br->getSuccessor(0);
1490 // This function searches starting with the input block for the next block that
1491 // contains code that is not part of a catch handler and would not be eliminated
1492 // during handler outlining.
1494 void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1495 BasicBlock *StartBB, BasicBlock *EndBB) {
1496 // Here we will skip over the following:
1498 // landing pad prolog:
1500 // Unconditional branches
1502 // Selector dispatch
1506 // Anything else marks the start of an interesting block
1508 BasicBlock *BB = StartBB;
1509 // Anything other than an unconditional branch will kick us out of this loop
1510 // one way or another.
1512 BB = followSingleUnconditionalBranches(BB);
1513 // If we've already scanned this block, don't scan it again. If it is
1514 // a cleanup block, there will be an action in the CleanupHandlerMap.
1515 // If we've scanned it and it is not a cleanup block, there will be a
1516 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1517 // be no entry in the CleanupHandlerMap. We must call count() first to
1518 // avoid creating a null entry for blocks we haven't scanned.
1519 if (CleanupHandlerMap.count(BB)) {
1520 if (auto *Action = CleanupHandlerMap[BB]) {
1521 Actions.insertCleanupHandler(Action);
1522 DEBUG(dbgs() << " Found cleanup code in block "
1523 << Action->getStartBlock()->getName() << "\n");
1524 // FIXME: This cleanup might chain into another, and we need to discover
1528 // Here we handle the case where the cleanup handler map contains a
1529 // value for this block but the value is a nullptr. This means that
1530 // we have previously analyzed the block and determined that it did
1531 // not contain any cleanup code. Based on the earlier analysis, we
1532 // know the the block must end in either an unconditional branch, a
1533 // resume or a conditional branch that is predicated on a comparison
1534 // with a selector. Either the resume or the selector dispatch
1535 // would terminate the search for cleanup code, so the unconditional
1536 // branch is the only case for which we might need to continue
1538 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1539 if (SuccBB == BB || SuccBB == EndBB)
1546 // Create an entry in the cleanup handler map for this block. Initially
1547 // we create an entry that says this isn't a cleanup block. If we find
1548 // cleanup code, the caller will replace this entry.
1549 CleanupHandlerMap[BB] = nullptr;
1551 TerminatorInst *Terminator = BB->getTerminator();
1553 // Landing pad blocks have extra instructions we need to accept.
1554 LandingPadMap *LPadMap = nullptr;
1555 if (BB->isLandingPad()) {
1556 LandingPadInst *LPad = BB->getLandingPadInst();
1557 LPadMap = &LPadMaps[LPad];
1558 if (!LPadMap->isInitialized())
1559 LPadMap->mapLandingPad(LPad);
1562 // Look for the bare resume pattern:
1563 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1564 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
1565 // resume { i8*, i32 } %lpad.val2
1566 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1567 InsertValueInst *Insert1 = nullptr;
1568 InsertValueInst *Insert2 = nullptr;
1569 Value *ResumeVal = Resume->getOperand(0);
1570 // If the resume value isn't a phi or landingpad value, it should be a
1571 // series of insertions. Identify them so we can avoid them when scanning
1573 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
1574 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
1576 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1577 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1579 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1581 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1583 Instruction *Inst = II;
1584 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1586 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1588 if (!Inst->hasOneUse() ||
1589 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
1590 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1596 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
1597 if (Branch && Branch->isConditional()) {
1598 // Look for the selector dispatch.
1599 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1600 // %matches = icmp eq i32 %sel, %2
1601 // br i1 %matches, label %catch14, label %eh.resume
1602 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1603 if (!Compare || !Compare->isEquality())
1604 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1605 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1607 Instruction *Inst = II;
1608 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1610 if (Inst == Compare || Inst == Branch)
1612 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1614 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1616 // The selector dispatch block should always terminate our search.
1617 assert(BB == EndBB);
1621 if (isAsynchronousEHPersonality(Personality)) {
1622 // If this is a landingpad block, split the block at the first non-landing
1624 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1626 while (MaybeCall != BB->getTerminator() &&
1627 LPadMap->isLandingPadSpecificInst(MaybeCall))
1628 MaybeCall = MaybeCall->getNextNode();
1631 // Look for outlined finally calls.
1632 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
1633 Function *Fin = FinallyCall.getCalledFunction();
1634 assert(Fin && "outlined finally call should be direct");
1635 auto *Action = new CleanupHandler(BB);
1636 Action->setHandlerBlockOrFunc(Fin);
1637 Actions.insertCleanupHandler(Action);
1638 CleanupHandlerMap[BB] = Action;
1639 DEBUG(dbgs() << " Found frontend-outlined finally call to "
1640 << Fin->getName() << " in block "
1641 << Action->getStartBlock()->getName() << "\n");
1643 // Split the block if there were more interesting instructions and look
1644 // for finally calls in the normal successor block.
1645 BasicBlock *SuccBB = BB;
1646 if (FinallyCall.getInstruction() != BB->getTerminator() &&
1647 FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
1648 SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
1650 if (FinallyCall.isInvoke()) {
1651 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
1653 SuccBB = BB->getUniqueSuccessor();
1654 assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
1664 // Anything else is either a catch block or interesting cleanup code.
1665 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1667 Instruction *Inst = II;
1668 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1670 // Unconditional branches fall through to this loop.
1673 // If this is a catch block, there is no cleanup code to be found.
1674 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1676 // If this a nested landing pad, it may contain an endcatch call.
1677 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1679 // Anything else makes this interesting cleanup code.
1680 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
1683 // Only unconditional branches in empty blocks should get this far.
1684 assert(Branch && Branch->isUnconditional());
1687 BB = Branch->getSuccessor(0);
1691 // This is a public function, declared in WinEHFuncInfo.h and is also
1692 // referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
1693 void llvm::parseEHActions(const IntrinsicInst *II,
1694 SmallVectorImpl<ActionHandler *> &Actions) {
1695 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
1696 uint64_t ActionKind =
1697 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
1698 if (ActionKind == /*catch=*/1) {
1699 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
1700 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
1701 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
1702 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
1704 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
1705 CH->setHandlerBlockOrFunc(Handler);
1706 CH->setExceptionVarIndex(EHObjIndexVal);
1707 Actions.push_back(CH);
1708 } else if (ActionKind == 0) {
1709 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
1711 auto *CH = new CleanupHandler(/*BB=*/nullptr);
1712 CH->setHandlerBlockOrFunc(Handler);
1713 Actions.push_back(CH);
1715 llvm_unreachable("Expected either a catch or cleanup handler!");
1718 std::reverse(Actions.begin(), Actions.end());