Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1 | //===-- WinEHPrepare - Prepare exception handling for code generation ---===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass lowers LLVM IR exception handling into something closer to what the |
Reid Kleckner | 0738a9c | 2015-05-05 17:44:16 +0000 | [diff] [blame] | 11 | // backend wants for functions using a personality function from a runtime |
| 12 | // provided by MSVC. Functions with other personality functions are left alone |
| 13 | // and may be prepared by other passes. In particular, all supported MSVC |
| 14 | // personality functions require cleanup code to be outlined, and the C++ |
| 15 | // personality requires catch handler code to be outlined. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 16 | // |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
| 19 | #include "llvm/CodeGen/Passes.h" |
| 20 | #include "llvm/ADT/MapVector.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/STLExtras.h" |
Benjamin Kramer | a8d61b1 | 2015-03-23 18:57:17 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/SmallSet.h" |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 23 | #include "llvm/ADT/SetVector.h" |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/Triple.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/TinyPtrVector.h" |
| 26 | #include "llvm/Analysis/LibCallSemantics.h" |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 27 | #include "llvm/CodeGen/WinEHFuncInfo.h" |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Dominators.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Function.h" |
| 30 | #include "llvm/IR/IRBuilder.h" |
| 31 | #include "llvm/IR/Instructions.h" |
| 32 | #include "llvm/IR/IntrinsicInst.h" |
| 33 | #include "llvm/IR/Module.h" |
| 34 | #include "llvm/IR/PatternMatch.h" |
| 35 | #include "llvm/Pass.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 36 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | a8d61b1 | 2015-03-23 18:57:17 +0000 | [diff] [blame] | 37 | #include "llvm/Support/raw_ostream.h" |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 38 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 39 | #include "llvm/Transforms/Utils/Cloning.h" |
| 40 | #include "llvm/Transforms/Utils/Local.h" |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 41 | #include "llvm/Transforms/Utils/PromoteMemToReg.h" |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 42 | #include <memory> |
| 43 | |
| 44 | using namespace llvm; |
| 45 | using namespace llvm::PatternMatch; |
| 46 | |
| 47 | #define DEBUG_TYPE "winehprepare" |
| 48 | |
| 49 | namespace { |
| 50 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 51 | // This map is used to model frame variable usage during outlining, to |
| 52 | // construct a structure type to hold the frame variables in a frame |
| 53 | // allocation block, and to remap the frame variable allocas (including |
| 54 | // spill locations as needed) to GEPs that get the variable from the |
| 55 | // frame allocation structure. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 56 | typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 57 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 58 | // TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't |
| 59 | // quite null. |
| 60 | AllocaInst *getCatchObjectSentinel() { |
| 61 | return static_cast<AllocaInst *>(nullptr) + 1; |
| 62 | } |
| 63 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 64 | typedef SmallSet<BasicBlock *, 4> VisitedBlockSet; |
| 65 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 66 | class LandingPadActions; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 67 | class LandingPadMap; |
| 68 | |
| 69 | typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy; |
| 70 | typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy; |
| 71 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 72 | class WinEHPrepare : public FunctionPass { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 73 | public: |
| 74 | static char ID; // Pass identification, replacement for typeid. |
| 75 | WinEHPrepare(const TargetMachine *TM = nullptr) |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 76 | : FunctionPass(ID) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 77 | if (TM) |
| 78 | TheTriple = Triple(TM->getTargetTriple()); |
| 79 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 80 | |
| 81 | bool runOnFunction(Function &Fn) override; |
| 82 | |
| 83 | bool doFinalization(Module &M) override; |
| 84 | |
| 85 | void getAnalysisUsage(AnalysisUsage &AU) const override; |
| 86 | |
| 87 | const char *getPassName() const override { |
| 88 | return "Windows exception handling preparation"; |
| 89 | } |
| 90 | |
| 91 | private: |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 92 | bool prepareExceptionHandlers(Function &F, |
| 93 | SmallVectorImpl<LandingPadInst *> &LPads); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 94 | void promoteLandingPadValues(LandingPadInst *LPad); |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 95 | void demoteValuesLiveAcrossHandlers(Function &F, |
| 96 | SmallVectorImpl<LandingPadInst *> &LPads); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 97 | void findSEHEHReturnPoints(Function &F, |
| 98 | SetVector<BasicBlock *> &EHReturnBlocks); |
| 99 | void findCXXEHReturnPoints(Function &F, |
| 100 | SetVector<BasicBlock *> &EHReturnBlocks); |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 101 | void getPossibleReturnTargets(Function *ParentF, Function *HandlerF, |
| 102 | SetVector<BasicBlock*> &Targets); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 103 | void completeNestedLandingPad(Function *ParentFn, |
| 104 | LandingPadInst *OutlinedLPad, |
| 105 | const LandingPadInst *OriginalLPad, |
| 106 | FrameVarInfoMap &VarInfo); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 107 | Function *createHandlerFunc(Type *RetTy, const Twine &Name, Module *M, |
| 108 | Value *&ParentFP); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 109 | bool outlineHandler(ActionHandler *Action, Function *SrcFn, |
| 110 | LandingPadInst *LPad, BasicBlock *StartBB, |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 111 | FrameVarInfoMap &VarInfo); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 112 | void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 113 | |
| 114 | void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions); |
| 115 | CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB, |
| 116 | VisitedBlockSet &VisitedBlocks); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 117 | void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB, |
| 118 | BasicBlock *EndBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 119 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 120 | void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB); |
| 121 | |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 122 | Triple TheTriple; |
| 123 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 124 | // All fields are reset by runOnFunction. |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 125 | DominatorTree *DT = nullptr; |
| 126 | EHPersonality Personality = EHPersonality::Unknown; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 127 | CatchHandlerMapTy CatchHandlerMap; |
| 128 | CleanupHandlerMapTy CleanupHandlerMap; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 129 | DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 130 | |
| 131 | // This maps landing pad instructions found in outlined handlers to |
| 132 | // the landing pad instruction in the parent function from which they |
| 133 | // were cloned. The cloned/nested landing pad is used as the key |
| 134 | // because the landing pad may be cloned into multiple handlers. |
| 135 | // This map will be used to add the llvm.eh.actions call to the nested |
| 136 | // landing pads after all handlers have been outlined. |
| 137 | DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP; |
| 138 | |
| 139 | // This maps blocks in the parent function which are destinations of |
| 140 | // catch handlers to cloned blocks in (other) outlined handlers. This |
| 141 | // handles the case where a nested landing pads has a catch handler that |
| 142 | // returns to a handler function rather than the parent function. |
| 143 | // The original block is used as the key here because there should only |
| 144 | // ever be one handler function from which the cloned block is not pruned. |
| 145 | // The original block will be pruned from the parent function after all |
| 146 | // handlers have been outlined. This map will be used to adjust the |
| 147 | // return instructions of handlers which return to the block that was |
| 148 | // outlined into a handler. This is done after all handlers have been |
| 149 | // outlined but before the outlined code is pruned from the parent function. |
| 150 | DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks; |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 151 | |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 152 | // Map from outlined handler to call to llvm.frameaddress(1). Only used for |
| 153 | // 32-bit EH. |
| 154 | DenseMap<Function *, Value *> HandlerToParentFP; |
| 155 | |
Reid Kleckner | 582786b | 2015-04-30 18:17:12 +0000 | [diff] [blame] | 156 | AllocaInst *SEHExceptionCodeSlot = nullptr; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 157 | }; |
| 158 | |
| 159 | class WinEHFrameVariableMaterializer : public ValueMaterializer { |
| 160 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 161 | WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP, |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 162 | FrameVarInfoMap &FrameVarInfo); |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 163 | ~WinEHFrameVariableMaterializer() override {} |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 164 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 165 | Value *materializeValueFor(Value *V) override; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 166 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 167 | void escapeCatchObject(Value *V); |
| 168 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 169 | private: |
| 170 | FrameVarInfoMap &FrameVarInfo; |
| 171 | IRBuilder<> Builder; |
| 172 | }; |
| 173 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 174 | class LandingPadMap { |
| 175 | public: |
| 176 | LandingPadMap() : OriginLPad(nullptr) {} |
| 177 | void mapLandingPad(const LandingPadInst *LPad); |
| 178 | |
| 179 | bool isInitialized() { return OriginLPad != nullptr; } |
| 180 | |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 181 | bool isOriginLandingPadBlock(const BasicBlock *BB) const; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 182 | bool isLandingPadSpecificInst(const Instruction *Inst) const; |
| 183 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 184 | void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, |
| 185 | Value *SelectorValue) const; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 186 | |
| 187 | private: |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 188 | const LandingPadInst *OriginLPad; |
| 189 | // We will normally only see one of each of these instructions, but |
| 190 | // if more than one occurs for some reason we can handle that. |
| 191 | TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs; |
| 192 | TinyPtrVector<const ExtractValueInst *> ExtractedSelectors; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 193 | }; |
| 194 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 195 | class WinEHCloningDirectorBase : public CloningDirector { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 196 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 197 | WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP, |
| 198 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) |
| 199 | : Materializer(HandlerFn, ParentFP, VarInfo), |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 200 | SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())), |
| 201 | Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())), |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 202 | LPadMap(LPadMap), ParentFP(ParentFP) {} |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 203 | |
| 204 | CloningAction handleInstruction(ValueToValueMapTy &VMap, |
| 205 | const Instruction *Inst, |
| 206 | BasicBlock *NewBB) override; |
| 207 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 208 | virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 209 | const Instruction *Inst, |
| 210 | BasicBlock *NewBB) = 0; |
| 211 | virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap, |
| 212 | const Instruction *Inst, |
| 213 | BasicBlock *NewBB) = 0; |
| 214 | virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 215 | const Instruction *Inst, |
| 216 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 217 | virtual CloningAction handleInvoke(ValueToValueMapTy &VMap, |
| 218 | const InvokeInst *Invoke, |
| 219 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 220 | virtual CloningAction handleResume(ValueToValueMapTy &VMap, |
| 221 | const ResumeInst *Resume, |
| 222 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 223 | virtual CloningAction handleCompare(ValueToValueMapTy &VMap, |
| 224 | const CmpInst *Compare, |
| 225 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 226 | virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 227 | const LandingPadInst *LPad, |
| 228 | BasicBlock *NewBB) = 0; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 229 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 230 | ValueMaterializer *getValueMaterializer() override { return &Materializer; } |
| 231 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 232 | protected: |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 233 | WinEHFrameVariableMaterializer Materializer; |
| 234 | Type *SelectorIDType; |
| 235 | Type *Int8PtrType; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 236 | LandingPadMap &LPadMap; |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 237 | |
| 238 | /// The value representing the parent frame pointer. |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 239 | Value *ParentFP; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 240 | }; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 241 | |
| 242 | class WinEHCatchDirector : public WinEHCloningDirectorBase { |
| 243 | public: |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 244 | WinEHCatchDirector( |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 245 | Function *CatchFn, Value *ParentFP, Value *Selector, |
| 246 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap, |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 247 | DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads) |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 248 | : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap), |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 249 | CurrentSelector(Selector->stripPointerCasts()), |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 250 | ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {} |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 251 | |
| 252 | CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 253 | const Instruction *Inst, |
| 254 | BasicBlock *NewBB) override; |
| 255 | CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, |
| 256 | BasicBlock *NewBB) override; |
| 257 | CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 258 | const Instruction *Inst, |
| 259 | BasicBlock *NewBB) override; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 260 | CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, |
| 261 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 262 | CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, |
| 263 | BasicBlock *NewBB) override; |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 264 | CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, |
| 265 | BasicBlock *NewBB) override; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 266 | CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 267 | const LandingPadInst *LPad, |
| 268 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 269 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 270 | Value *getExceptionVar() { return ExceptionObjectVar; } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 271 | TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; } |
| 272 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 273 | private: |
| 274 | Value *CurrentSelector; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 275 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 276 | Value *ExceptionObjectVar; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 277 | TinyPtrVector<BasicBlock *> ReturnTargets; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 278 | |
| 279 | // This will be a reference to the field of the same name in the WinEHPrepare |
| 280 | // object which instantiates this WinEHCatchDirector object. |
| 281 | DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 282 | }; |
| 283 | |
| 284 | class WinEHCleanupDirector : public WinEHCloningDirectorBase { |
| 285 | public: |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 286 | WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP, |
| 287 | FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap) |
| 288 | : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo, |
| 289 | LPadMap) {} |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 290 | |
| 291 | CloningAction handleBeginCatch(ValueToValueMapTy &VMap, |
| 292 | const Instruction *Inst, |
| 293 | BasicBlock *NewBB) override; |
| 294 | CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst, |
| 295 | BasicBlock *NewBB) override; |
| 296 | CloningAction handleTypeIdFor(ValueToValueMapTy &VMap, |
| 297 | const Instruction *Inst, |
| 298 | BasicBlock *NewBB) override; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 299 | CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke, |
| 300 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 301 | CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume, |
| 302 | BasicBlock *NewBB) override; |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 303 | CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare, |
| 304 | BasicBlock *NewBB) override; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 305 | CloningAction handleLandingPad(ValueToValueMapTy &VMap, |
| 306 | const LandingPadInst *LPad, |
| 307 | BasicBlock *NewBB) override; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 308 | }; |
| 309 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 310 | class LandingPadActions { |
| 311 | public: |
| 312 | LandingPadActions() : HasCleanupHandlers(false) {} |
| 313 | |
| 314 | void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); } |
| 315 | void insertCleanupHandler(CleanupHandler *Action) { |
| 316 | Actions.push_back(Action); |
| 317 | HasCleanupHandlers = true; |
| 318 | } |
| 319 | |
| 320 | bool includesCleanup() const { return HasCleanupHandlers; } |
| 321 | |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 322 | SmallVectorImpl<ActionHandler *> &actions() { return Actions; } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 323 | SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); } |
| 324 | SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); } |
| 325 | |
| 326 | private: |
| 327 | // Note that this class does not own the ActionHandler objects in this vector. |
| 328 | // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap |
| 329 | // in the WinEHPrepare class. |
| 330 | SmallVector<ActionHandler *, 4> Actions; |
| 331 | bool HasCleanupHandlers; |
| 332 | }; |
| 333 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 334 | } // end anonymous namespace |
| 335 | |
| 336 | char WinEHPrepare::ID = 0; |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 337 | INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions", |
| 338 | false, false) |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 339 | |
| 340 | FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) { |
| 341 | return new WinEHPrepare(TM); |
| 342 | } |
| 343 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 344 | bool WinEHPrepare::runOnFunction(Function &Fn) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 345 | // No need to prepare outlined handlers. |
| 346 | if (Fn.hasFnAttribute("wineh-parent")) |
| 347 | return false; |
| 348 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 349 | SmallVector<LandingPadInst *, 4> LPads; |
| 350 | SmallVector<ResumeInst *, 4> Resumes; |
| 351 | for (BasicBlock &BB : Fn) { |
| 352 | if (auto *LP = BB.getLandingPadInst()) |
| 353 | LPads.push_back(LP); |
| 354 | if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator())) |
| 355 | Resumes.push_back(Resume); |
| 356 | } |
| 357 | |
| 358 | // No need to prepare functions that lack landing pads. |
| 359 | if (LPads.empty()) |
| 360 | return false; |
| 361 | |
| 362 | // Classify the personality to see what kind of preparation we need. |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 363 | Personality = classifyEHPersonality(LPads.back()->getPersonalityFn()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 364 | |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 365 | // Do nothing if this is not an MSVC personality. |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 366 | if (!isMSVCEHPersonality(Personality)) |
Reid Kleckner | 47c8e7a | 2015-03-12 00:36:20 +0000 | [diff] [blame] | 367 | return false; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 368 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 369 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 370 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 371 | // If there were any landing pads, prepareExceptionHandlers will make changes. |
| 372 | prepareExceptionHandlers(Fn, LPads); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 373 | return true; |
| 374 | } |
| 375 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 376 | bool WinEHPrepare::doFinalization(Module &M) { return false; } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 377 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 378 | void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const { |
| 379 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 380 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 381 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 382 | static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, |
| 383 | Constant *&Selector, BasicBlock *&NextBB); |
| 384 | |
| 385 | // Finds blocks reachable from the starting set Worklist. Does not follow unwind |
| 386 | // edges or blocks listed in StopPoints. |
| 387 | static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs, |
| 388 | SetVector<BasicBlock *> &Worklist, |
| 389 | const SetVector<BasicBlock *> *StopPoints) { |
| 390 | while (!Worklist.empty()) { |
| 391 | BasicBlock *BB = Worklist.pop_back_val(); |
| 392 | |
| 393 | // Don't cross blocks that we should stop at. |
| 394 | if (StopPoints && StopPoints->count(BB)) |
| 395 | continue; |
| 396 | |
| 397 | if (!ReachableBBs.insert(BB).second) |
| 398 | continue; // Already visited. |
| 399 | |
| 400 | // Don't follow unwind edges of invokes. |
| 401 | if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) { |
| 402 | Worklist.insert(II->getNormalDest()); |
| 403 | continue; |
| 404 | } |
| 405 | |
| 406 | // Otherwise, follow all successors. |
| 407 | Worklist.insert(succ_begin(BB), succ_end(BB)); |
| 408 | } |
| 409 | } |
| 410 | |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 411 | // Attempt to find an instruction where a block can be split before |
| 412 | // a call to llvm.eh.begincatch and its operands. If the block |
| 413 | // begins with the begincatch call or one of its adjacent operands |
| 414 | // the block will not be split. |
| 415 | static Instruction *findBeginCatchSplitPoint(BasicBlock *BB, |
| 416 | IntrinsicInst *II) { |
| 417 | // If the begincatch call is already the first instruction in the block, |
| 418 | // don't split. |
| 419 | Instruction *FirstNonPHI = BB->getFirstNonPHI(); |
| 420 | if (II == FirstNonPHI) |
| 421 | return nullptr; |
| 422 | |
| 423 | // If either operand is in the same basic block as the instruction and |
| 424 | // isn't used by another instruction before the begincatch call, include it |
| 425 | // in the split block. |
| 426 | auto *Op0 = dyn_cast<Instruction>(II->getOperand(0)); |
| 427 | auto *Op1 = dyn_cast<Instruction>(II->getOperand(1)); |
| 428 | |
| 429 | Instruction *I = II->getPrevNode(); |
| 430 | Instruction *LastI = II; |
| 431 | |
| 432 | while (I == Op0 || I == Op1) { |
| 433 | // If the block begins with one of the operands and there are no other |
| 434 | // instructions between the operand and the begincatch call, don't split. |
| 435 | if (I == FirstNonPHI) |
| 436 | return nullptr; |
| 437 | |
| 438 | LastI = I; |
| 439 | I = I->getPrevNode(); |
| 440 | } |
| 441 | |
| 442 | // If there is at least one instruction in the block before the begincatch |
| 443 | // call and its operands, split the block at either the begincatch or |
| 444 | // its operand. |
| 445 | return LastI; |
| 446 | } |
| 447 | |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 448 | /// Find all points where exceptional control rejoins normal control flow via |
| 449 | /// llvm.eh.endcatch. Add them to the normal bb reachability worklist. |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 450 | void WinEHPrepare::findCXXEHReturnPoints( |
| 451 | Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 452 | for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { |
| 453 | BasicBlock *BB = BBI; |
| 454 | for (Instruction &I : *BB) { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 455 | if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) { |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 456 | Instruction *SplitPt = |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 457 | findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I)); |
| 458 | if (SplitPt) { |
| 459 | // Split the block before the llvm.eh.begincatch call to allow |
| 460 | // cleanup and catch code to be distinguished later. |
| 461 | // Do not update BBI because we still need to process the |
| 462 | // portion of the block that we are splitting off. |
Andrew Kaylor | a33f159 | 2015-04-29 17:21:26 +0000 | [diff] [blame] | 463 | SplitBlock(BB, SplitPt, DT); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 464 | break; |
| 465 | } |
| 466 | } |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 467 | if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) { |
| 468 | // Split the block after the call to llvm.eh.endcatch if there is |
| 469 | // anything other than an unconditional branch, or if the successor |
| 470 | // starts with a phi. |
| 471 | auto *Br = dyn_cast<BranchInst>(I.getNextNode()); |
| 472 | if (!Br || !Br->isUnconditional() || |
| 473 | isa<PHINode>(Br->getSuccessor(0)->begin())) { |
| 474 | DEBUG(dbgs() << "splitting block " << BB->getName() |
| 475 | << " with llvm.eh.endcatch\n"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 476 | BBI = SplitBlock(BB, I.getNextNode(), DT); |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 477 | } |
| 478 | // The next BB is normal control flow. |
| 479 | EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0)); |
| 480 | break; |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | static bool isCatchAllLandingPad(const BasicBlock *BB) { |
| 487 | const LandingPadInst *LP = BB->getLandingPadInst(); |
| 488 | if (!LP) |
| 489 | return false; |
| 490 | unsigned N = LP->getNumClauses(); |
| 491 | return (N > 0 && LP->isCatch(N - 1) && |
| 492 | isa<ConstantPointerNull>(LP->getClause(N - 1))); |
| 493 | } |
| 494 | |
| 495 | /// Find all points where exceptions control rejoins normal control flow via |
| 496 | /// selector dispatch. |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 497 | void WinEHPrepare::findSEHEHReturnPoints( |
| 498 | Function &F, SetVector<BasicBlock *> &EHReturnBlocks) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 499 | for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { |
| 500 | BasicBlock *BB = BBI; |
| 501 | // If the landingpad is a catch-all, treat the whole lpad as if it is |
| 502 | // reachable from normal control flow. |
| 503 | // FIXME: This is imprecise. We need a better way of identifying where a |
| 504 | // catch-all starts and cleanups stop. As far as LLVM is concerned, there |
| 505 | // is no difference. |
| 506 | if (isCatchAllLandingPad(BB)) { |
| 507 | EHReturnBlocks.insert(BB); |
| 508 | continue; |
| 509 | } |
| 510 | |
| 511 | BasicBlock *CatchHandler; |
| 512 | BasicBlock *NextBB; |
| 513 | Constant *Selector; |
| 514 | if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) { |
| 515 | // Split the edge if there is a phi node. Returning from EH to a phi node |
| 516 | // is just as impossible as having a phi after an indirectbr. |
| 517 | if (isa<PHINode>(CatchHandler->begin())) { |
| 518 | DEBUG(dbgs() << "splitting EH return edge from " << BB->getName() |
| 519 | << " to " << CatchHandler->getName() << '\n'); |
| 520 | BBI = CatchHandler = SplitCriticalEdge( |
| 521 | BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler)); |
| 522 | } |
| 523 | EHReturnBlocks.insert(CatchHandler); |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// Ensure that all values live into and out of exception handlers are stored |
| 529 | /// in memory. |
| 530 | /// FIXME: This falls down when values are defined in one handler and live into |
| 531 | /// another handler. For example, a cleanup defines a value used only by a |
| 532 | /// catch handler. |
| 533 | void WinEHPrepare::demoteValuesLiveAcrossHandlers( |
| 534 | Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { |
| 535 | DEBUG(dbgs() << "Demoting values live across exception handlers in function " |
| 536 | << F.getName() << '\n'); |
| 537 | |
| 538 | // Build a set of all non-exceptional blocks and exceptional blocks. |
| 539 | // - Non-exceptional blocks are blocks reachable from the entry block while |
| 540 | // not following invoke unwind edges. |
| 541 | // - Exceptional blocks are blocks reachable from landingpads. Analysis does |
| 542 | // not follow llvm.eh.endcatch blocks, which mark a transition from |
| 543 | // exceptional to normal control. |
| 544 | SmallPtrSet<BasicBlock *, 4> NormalBlocks; |
| 545 | SmallPtrSet<BasicBlock *, 4> EHBlocks; |
| 546 | SetVector<BasicBlock *> EHReturnBlocks; |
| 547 | SetVector<BasicBlock *> Worklist; |
| 548 | |
| 549 | if (Personality == EHPersonality::MSVC_CXX) |
| 550 | findCXXEHReturnPoints(F, EHReturnBlocks); |
| 551 | else |
| 552 | findSEHEHReturnPoints(F, EHReturnBlocks); |
| 553 | |
| 554 | DEBUG({ |
| 555 | dbgs() << "identified the following blocks as EH return points:\n"; |
| 556 | for (BasicBlock *BB : EHReturnBlocks) |
| 557 | dbgs() << " " << BB->getName() << '\n'; |
| 558 | }); |
| 559 | |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 560 | // Join points should not have phis at this point, unless they are a |
| 561 | // landingpad, in which case we will demote their phis later. |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 562 | #ifndef NDEBUG |
| 563 | for (BasicBlock *BB : EHReturnBlocks) |
| 564 | assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) && |
| 565 | "non-lpad EH return block has phi"); |
| 566 | #endif |
| 567 | |
| 568 | // Normal blocks are the blocks reachable from the entry block and all EH |
| 569 | // return points. |
| 570 | Worklist = EHReturnBlocks; |
| 571 | Worklist.insert(&F.getEntryBlock()); |
| 572 | findReachableBlocks(NormalBlocks, Worklist, nullptr); |
| 573 | DEBUG({ |
| 574 | dbgs() << "marked the following blocks as normal:\n"; |
| 575 | for (BasicBlock *BB : NormalBlocks) |
| 576 | dbgs() << " " << BB->getName() << '\n'; |
| 577 | }); |
| 578 | |
| 579 | // Exceptional blocks are the blocks reachable from landingpads that don't |
| 580 | // cross EH return points. |
| 581 | Worklist.clear(); |
| 582 | for (auto *LPI : LPads) |
| 583 | Worklist.insert(LPI->getParent()); |
| 584 | findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks); |
| 585 | DEBUG({ |
| 586 | dbgs() << "marked the following blocks as exceptional:\n"; |
| 587 | for (BasicBlock *BB : EHBlocks) |
| 588 | dbgs() << " " << BB->getName() << '\n'; |
| 589 | }); |
| 590 | |
| 591 | SetVector<Argument *> ArgsToDemote; |
| 592 | SetVector<Instruction *> InstrsToDemote; |
| 593 | for (BasicBlock &BB : F) { |
| 594 | bool IsNormalBB = NormalBlocks.count(&BB); |
| 595 | bool IsEHBB = EHBlocks.count(&BB); |
| 596 | if (!IsNormalBB && !IsEHBB) |
| 597 | continue; // Blocks that are neither normal nor EH are unreachable. |
| 598 | for (Instruction &I : BB) { |
| 599 | for (Value *Op : I.operands()) { |
| 600 | // Don't demote static allocas, constants, and labels. |
| 601 | if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op)) |
| 602 | continue; |
| 603 | auto *AI = dyn_cast<AllocaInst>(Op); |
| 604 | if (AI && AI->isStaticAlloca()) |
| 605 | continue; |
| 606 | |
| 607 | if (auto *Arg = dyn_cast<Argument>(Op)) { |
| 608 | if (IsEHBB) { |
| 609 | DEBUG(dbgs() << "Demoting argument " << *Arg |
| 610 | << " used by EH instr: " << I << "\n"); |
| 611 | ArgsToDemote.insert(Arg); |
| 612 | } |
| 613 | continue; |
| 614 | } |
| 615 | |
| 616 | auto *OpI = cast<Instruction>(Op); |
| 617 | BasicBlock *OpBB = OpI->getParent(); |
| 618 | // If a value is produced and consumed in the same BB, we don't need to |
| 619 | // demote it. |
| 620 | if (OpBB == &BB) |
| 621 | continue; |
| 622 | bool IsOpNormalBB = NormalBlocks.count(OpBB); |
| 623 | bool IsOpEHBB = EHBlocks.count(OpBB); |
| 624 | if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) { |
| 625 | DEBUG({ |
| 626 | dbgs() << "Demoting instruction live in-out from EH:\n"; |
| 627 | dbgs() << "Instr: " << *OpI << '\n'; |
| 628 | dbgs() << "User: " << I << '\n'; |
| 629 | }); |
| 630 | InstrsToDemote.insert(OpI); |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | // Demote values live into and out of handlers. |
| 637 | // FIXME: This demotion is inefficient. We should insert spills at the point |
| 638 | // of definition, insert one reload in each handler that uses the value, and |
| 639 | // insert reloads in the BB used to rejoin normal control flow. |
| 640 | Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt(); |
| 641 | for (Instruction *I : InstrsToDemote) |
| 642 | DemoteRegToStack(*I, false, AllocaInsertPt); |
| 643 | |
| 644 | // Demote arguments separately, and only for uses in EH blocks. |
| 645 | for (Argument *Arg : ArgsToDemote) { |
| 646 | auto *Slot = new AllocaInst(Arg->getType(), nullptr, |
| 647 | Arg->getName() + ".reg2mem", AllocaInsertPt); |
| 648 | SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end()); |
| 649 | for (User *U : Users) { |
| 650 | auto *I = dyn_cast<Instruction>(U); |
| 651 | if (I && EHBlocks.count(I->getParent())) { |
| 652 | auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I); |
| 653 | U->replaceUsesOfWith(Arg, Reload); |
| 654 | } |
| 655 | } |
| 656 | new StoreInst(Arg, Slot, AllocaInsertPt); |
| 657 | } |
| 658 | |
| 659 | // Demote landingpad phis, as the landingpad will be removed from the machine |
| 660 | // CFG. |
| 661 | for (LandingPadInst *LPI : LPads) { |
| 662 | BasicBlock *BB = LPI->getParent(); |
| 663 | while (auto *Phi = dyn_cast<PHINode>(BB->begin())) |
| 664 | DemotePHIToStack(Phi, AllocaInsertPt); |
| 665 | } |
| 666 | |
| 667 | DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and " |
| 668 | << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n"); |
| 669 | } |
| 670 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 671 | bool WinEHPrepare::prepareExceptionHandlers( |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 672 | Function &F, SmallVectorImpl<LandingPadInst *> &LPads) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 673 | // Don't run on functions that are already prepared. |
| 674 | for (LandingPadInst *LPad : LPads) { |
| 675 | BasicBlock *LPadBB = LPad->getParent(); |
| 676 | for (Instruction &Inst : *LPadBB) |
| 677 | if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) |
| 678 | return false; |
| 679 | } |
| 680 | |
| 681 | demoteValuesLiveAcrossHandlers(F, LPads); |
| 682 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 683 | // These containers are used to re-map frame variables that are used in |
| 684 | // outlined catch and cleanup handlers. They will be populated as the |
| 685 | // handlers are outlined. |
| 686 | FrameVarInfoMap FrameVarInfo; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 687 | |
| 688 | bool HandlersOutlined = false; |
| 689 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 690 | Module *M = F.getParent(); |
| 691 | LLVMContext &Context = M->getContext(); |
| 692 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 693 | // Create a new function to receive the handler contents. |
| 694 | PointerType *Int8PtrType = Type::getInt8PtrTy(Context); |
| 695 | Type *Int32Type = Type::getInt32Ty(Context); |
Reid Kleckner | 52b0779 | 2015-03-12 01:45:37 +0000 | [diff] [blame] | 696 | Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 697 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 698 | if (isAsynchronousEHPersonality(Personality)) { |
| 699 | // FIXME: Switch the ehptr type to i32 and then switch this. |
| 700 | SEHExceptionCodeSlot = |
| 701 | new AllocaInst(Int8PtrType, nullptr, "seh_exception_code", |
| 702 | F.getEntryBlock().getFirstInsertionPt()); |
| 703 | } |
| 704 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 705 | // This container stores the llvm.eh.recover and IndirectBr instructions |
| 706 | // that make up the body of each landing pad after it has been outlined. |
| 707 | // We need to defer the population of the target list for the indirectbr |
| 708 | // until all landing pads have been outlined so that we can handle the |
| 709 | // case of blocks in the target that are reached only from nested |
| 710 | // landing pads. |
| 711 | SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls; |
| 712 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 713 | for (LandingPadInst *LPad : LPads) { |
| 714 | // Look for evidence that this landingpad has already been processed. |
| 715 | bool LPadHasActionList = false; |
| 716 | BasicBlock *LPadBB = LPad->getParent(); |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 717 | for (Instruction &Inst : *LPadBB) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 718 | if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) { |
| 719 | LPadHasActionList = true; |
| 720 | break; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 721 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 722 | } |
| 723 | |
| 724 | // If we've already outlined the handlers for this landingpad, |
| 725 | // there's nothing more to do here. |
| 726 | if (LPadHasActionList) |
| 727 | continue; |
| 728 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 729 | // If either of the values in the aggregate returned by the landing pad is |
| 730 | // extracted and stored to memory, promote the stored value to a register. |
| 731 | promoteLandingPadValues(LPad); |
| 732 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 733 | LandingPadActions Actions; |
| 734 | mapLandingPadBlocks(LPad, Actions); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 735 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 736 | HandlersOutlined |= !Actions.actions().empty(); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 737 | for (ActionHandler *Action : Actions) { |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 738 | if (Action->hasBeenProcessed()) |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 739 | continue; |
| 740 | BasicBlock *StartBB = Action->getStartBlock(); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 741 | |
| 742 | // SEH doesn't do any outlining for catches. Instead, pass the handler |
| 743 | // basic block addr to llvm.eh.actions and list the block as a return |
| 744 | // target. |
| 745 | if (isAsynchronousEHPersonality(Personality)) { |
| 746 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 747 | processSEHCatchHandler(CatchAction, StartBB); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 748 | continue; |
| 749 | } |
| 750 | } |
| 751 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 752 | outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo); |
| 753 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 754 | |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 755 | // Split the block after the landingpad instruction so that it is just a |
| 756 | // call to llvm.eh.actions followed by indirectbr. |
| 757 | assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 758 | SplitBlock(LPadBB, LPad->getNextNode(), DT); |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 759 | // Erase the branch inserted by the split so we can insert indirectbr. |
| 760 | LPadBB->getTerminator()->eraseFromParent(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 761 | |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 762 | // Replace all extracted values with undef and ultimately replace the |
| 763 | // landingpad with undef. |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 764 | SmallVector<Instruction *, 4> SEHCodeUses; |
| 765 | SmallVector<Instruction *, 4> EHUndefs; |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 766 | for (User *U : LPad->users()) { |
| 767 | auto *E = dyn_cast<ExtractValueInst>(U); |
| 768 | if (!E) |
| 769 | continue; |
| 770 | assert(E->getNumIndices() == 1 && |
| 771 | "Unexpected operation: extracting both landing pad values"); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 772 | unsigned Idx = *E->idx_begin(); |
| 773 | assert((Idx == 0 || Idx == 1) && "unexpected index"); |
| 774 | if (Idx == 0 && isAsynchronousEHPersonality(Personality)) |
| 775 | SEHCodeUses.push_back(E); |
| 776 | else |
| 777 | EHUndefs.push_back(E); |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 778 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 779 | for (Instruction *E : EHUndefs) { |
Reid Kleckner | e3af86e | 2015-04-23 21:22:30 +0000 | [diff] [blame] | 780 | E->replaceAllUsesWith(UndefValue::get(E->getType())); |
| 781 | E->eraseFromParent(); |
| 782 | } |
| 783 | LPad->replaceAllUsesWith(UndefValue::get(LPad->getType())); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 784 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 785 | // Rewrite uses of the exception pointer to loads of an alloca. |
| 786 | for (Instruction *E : SEHCodeUses) { |
| 787 | SmallVector<Use *, 4> Uses; |
| 788 | for (Use &U : E->uses()) |
| 789 | Uses.push_back(&U); |
| 790 | for (Use *U : Uses) { |
| 791 | auto *I = cast<Instruction>(U->getUser()); |
| 792 | if (isa<ResumeInst>(I)) |
| 793 | continue; |
| 794 | LoadInst *LI; |
| 795 | if (auto *Phi = dyn_cast<PHINode>(I)) |
| 796 | LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, |
| 797 | Phi->getIncomingBlock(*U)); |
| 798 | else |
| 799 | LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I); |
| 800 | U->set(LI); |
| 801 | } |
| 802 | E->replaceAllUsesWith(UndefValue::get(E->getType())); |
| 803 | E->eraseFromParent(); |
| 804 | } |
| 805 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 806 | // Add a call to describe the actions for this landing pad. |
| 807 | std::vector<Value *> ActionArgs; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 808 | for (ActionHandler *Action : Actions) { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 809 | // Action codes from docs are: 0 cleanup, 1 catch. |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 810 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 811 | ActionArgs.push_back(ConstantInt::get(Int32Type, 1)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 812 | ActionArgs.push_back(CatchAction->getSelector()); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 813 | // Find the frame escape index of the exception object alloca in the |
| 814 | // parent. |
| 815 | int FrameEscapeIdx = -1; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 816 | Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar()); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 817 | if (EHObj && !isa<ConstantPointerNull>(EHObj)) { |
| 818 | auto I = FrameVarInfo.find(EHObj); |
| 819 | assert(I != FrameVarInfo.end() && |
| 820 | "failed to map llvm.eh.begincatch var"); |
| 821 | FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I); |
| 822 | } |
| 823 | ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 824 | } else { |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 825 | ActionArgs.push_back(ConstantInt::get(Int32Type, 0)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 826 | } |
Reid Kleckner | c759fe9 | 2015-03-19 22:31:02 +0000 | [diff] [blame] | 827 | ActionArgs.push_back(Action->getHandlerBlockOrFunc()); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 828 | } |
| 829 | CallInst *Recover = |
Reid Kleckner | 2c3ccaa | 2015-04-24 16:22:19 +0000 | [diff] [blame] | 830 | CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 831 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 832 | if (isAsynchronousEHPersonality(Personality)) { |
| 833 | // SEH can create the target list directly, since catch handlers |
| 834 | // are not outlined. |
| 835 | SetVector<BasicBlock *> ReturnTargets; |
| 836 | for (ActionHandler *Action : Actions) { |
| 837 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 838 | const auto &CatchTargets = CatchAction->getReturnTargets(); |
| 839 | ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end()); |
| 840 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 841 | } |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 842 | IndirectBrInst *Branch = |
| 843 | IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB); |
| 844 | for (BasicBlock *Target : ReturnTargets) |
| 845 | Branch->addDestination(Target); |
| 846 | } else { |
| 847 | // C++ EH must defer populating the targets to handle the case of |
| 848 | // targets that are reached indirectly through nested landing pads. |
| 849 | IndirectBrInst *Branch = |
| 850 | IndirectBrInst::Create(Recover, 0, LPadBB); |
| 851 | |
| 852 | LPadImpls.push_back(std::make_pair(Recover, Branch)); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 853 | } |
| 854 | } // End for each landingpad |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 855 | |
| 856 | // If nothing got outlined, there is no more processing to be done. |
| 857 | if (!HandlersOutlined) |
| 858 | return false; |
| 859 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 860 | // Replace any nested landing pad stubs with the correct action handler. |
| 861 | // This must be done before we remove unreachable blocks because it |
| 862 | // cleans up references to outlined blocks that will be deleted. |
| 863 | for (auto &LPadPair : NestedLPtoOriginalLP) |
| 864 | completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo); |
Andrew Kaylor | 67d3c03 | 2015-04-08 20:57:22 +0000 | [diff] [blame] | 865 | NestedLPtoOriginalLP.clear(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 866 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 867 | // Populate the indirectbr instructions' target lists if we deferred |
| 868 | // doing so above. |
| 869 | SetVector<BasicBlock*> CheckedTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 870 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 871 | for (auto &LPadImplPair : LPadImpls) { |
| 872 | IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first); |
| 873 | IndirectBrInst *Branch = LPadImplPair.second; |
| 874 | |
| 875 | // Get a list of handlers called by |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 876 | parseEHActions(Recover, ActionList); |
| 877 | |
| 878 | // Add an indirect branch listing possible successors of the catch handlers. |
| 879 | SetVector<BasicBlock *> ReturnTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 880 | for (const auto &Action : ActionList) { |
| 881 | if (auto *CA = dyn_cast<CatchHandler>(Action.get())) { |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 882 | Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc()); |
| 883 | getPossibleReturnTargets(&F, Handler, ReturnTargets); |
| 884 | } |
| 885 | } |
Andrew Kaylor | 0ddaf2b | 2015-05-12 00:13:51 +0000 | [diff] [blame] | 886 | ActionList.clear(); |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 887 | for (BasicBlock *Target : ReturnTargets) { |
| 888 | Branch->addDestination(Target); |
| 889 | // The target may be a block that we excepted to get pruned. |
| 890 | // If it is, it may contain a call to llvm.eh.endcatch. |
| 891 | if (CheckedTargets.insert(Target)) { |
| 892 | // Earlier preparations guarantee that all calls to llvm.eh.endcatch |
| 893 | // will be followed by an unconditional branch. |
| 894 | auto *Br = dyn_cast<BranchInst>(Target->getTerminator()); |
| 895 | if (Br && Br->isUnconditional() && |
| 896 | Br != Target->getFirstNonPHIOrDbgOrLifetime()) { |
| 897 | Instruction *Prev = Br->getPrevNode(); |
| 898 | if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>())) |
| 899 | Prev->eraseFromParent(); |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | } |
| 904 | LPadImpls.clear(); |
| 905 | |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 906 | F.addFnAttr("wineh-parent", F.getName()); |
| 907 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 908 | // Delete any blocks that were only used by handlers that were outlined above. |
| 909 | removeUnreachableBlocks(F); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 910 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 911 | BasicBlock *Entry = &F.getEntryBlock(); |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 912 | IRBuilder<> Builder(F.getParent()->getContext()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 913 | Builder.SetInsertPoint(Entry->getFirstInsertionPt()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 914 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 915 | Function *FrameEscapeFn = |
| 916 | Intrinsic::getDeclaration(M, Intrinsic::frameescape); |
| 917 | Function *RecoverFrameFn = |
| 918 | Intrinsic::getDeclaration(M, Intrinsic::framerecover); |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 919 | SmallVector<Value *, 8> AllocasToEscape; |
| 920 | |
| 921 | // Scan the entry block for an existing call to llvm.frameescape. We need to |
| 922 | // keep escaping those objects. |
| 923 | for (Instruction &I : F.front()) { |
| 924 | auto *II = dyn_cast<IntrinsicInst>(&I); |
| 925 | if (II && II->getIntrinsicID() == Intrinsic::frameescape) { |
| 926 | auto Args = II->arg_operands(); |
| 927 | AllocasToEscape.append(Args.begin(), Args.end()); |
| 928 | II->eraseFromParent(); |
| 929 | break; |
| 930 | } |
| 931 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 932 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 933 | // Finally, replace all of the temporary allocas for frame variables used in |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 934 | // the outlined handlers with calls to llvm.framerecover. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 935 | for (auto &VarInfoEntry : FrameVarInfo) { |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 936 | Value *ParentVal = VarInfoEntry.first; |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 937 | TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second; |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 938 | AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal); |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 939 | |
Reid Kleckner | b401941 | 2015-04-06 18:50:38 +0000 | [diff] [blame] | 940 | // FIXME: We should try to sink unescaped allocas from the parent frame into |
| 941 | // the child frame. If the alloca is escaped, we have to use the lifetime |
| 942 | // markers to ensure that the alloca is only live within the child frame. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 943 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 944 | // Add this alloca to the list of things to escape. |
| 945 | AllocasToEscape.push_back(ParentAlloca); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 946 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 947 | // Next replace all outlined allocas that are mapped to it. |
| 948 | for (AllocaInst *TempAlloca : Allocas) { |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 949 | if (TempAlloca == getCatchObjectSentinel()) |
| 950 | continue; // Skip catch parameter sentinels. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 951 | Function *HandlerFn = TempAlloca->getParent()->getParent(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 952 | llvm::Value *FP = HandlerToParentFP[HandlerFn]; |
| 953 | assert(FP); |
| 954 | |
| 955 | // FIXME: Sink this framerecover into the blocks where it is used. |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 956 | Builder.SetInsertPoint(TempAlloca); |
| 957 | Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc()); |
| 958 | Value *RecoverArgs[] = { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 959 | Builder.CreateBitCast(&F, Int8PtrType, ""), FP, |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 960 | llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)}; |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 961 | Instruction *RecoveredAlloca = |
| 962 | Builder.CreateCall(RecoverFrameFn, RecoverArgs); |
| 963 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 964 | // Add a pointer bitcast if the alloca wasn't an i8. |
| 965 | if (RecoveredAlloca->getType() != TempAlloca->getType()) { |
| 966 | RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8"); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 967 | RecoveredAlloca = cast<Instruction>( |
| 968 | Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType())); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 969 | } |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 970 | TempAlloca->replaceAllUsesWith(RecoveredAlloca); |
| 971 | TempAlloca->removeFromParent(); |
| 972 | RecoveredAlloca->takeName(TempAlloca); |
| 973 | delete TempAlloca; |
| 974 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 975 | } // End for each FrameVarInfo entry. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 976 | |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 977 | // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry |
| 978 | // block. |
| 979 | Builder.SetInsertPoint(&F.getEntryBlock().back()); |
| 980 | Builder.CreateCall(FrameEscapeFn, AllocasToEscape); |
| 981 | |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 982 | if (SEHExceptionCodeSlot) { |
| 983 | if (SEHExceptionCodeSlot->hasNUses(0)) |
| 984 | SEHExceptionCodeSlot->eraseFromParent(); |
Reid Kleckner | 0738a9c | 2015-05-05 17:44:16 +0000 | [diff] [blame] | 985 | else if (isAllocaPromotable(SEHExceptionCodeSlot)) |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 986 | PromoteMemToReg(SEHExceptionCodeSlot, *DT); |
| 987 | } |
| 988 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 989 | // Clean up the handler action maps we created for this function |
| 990 | DeleteContainerSeconds(CatchHandlerMap); |
| 991 | CatchHandlerMap.clear(); |
| 992 | DeleteContainerSeconds(CleanupHandlerMap); |
| 993 | CleanupHandlerMap.clear(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 994 | HandlerToParentFP.clear(); |
| 995 | DT = nullptr; |
Ahmed Bougacha | ed363c5 | 2015-05-06 01:28:58 +0000 | [diff] [blame] | 996 | SEHExceptionCodeSlot = nullptr; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 997 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 998 | return HandlersOutlined; |
| 999 | } |
| 1000 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1001 | void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) { |
| 1002 | // If the return values of the landing pad instruction are extracted and |
| 1003 | // stored to memory, we want to promote the store locations to reg values. |
| 1004 | SmallVector<AllocaInst *, 2> EHAllocas; |
| 1005 | |
| 1006 | // The landingpad instruction returns an aggregate value. Typically, its |
| 1007 | // value will be passed to a pair of extract value instructions and the |
| 1008 | // results of those extracts are often passed to store instructions. |
| 1009 | // In unoptimized code the stored value will often be loaded and then stored |
| 1010 | // again. |
| 1011 | for (auto *U : LPad->users()) { |
| 1012 | ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); |
| 1013 | if (!Extract) |
| 1014 | continue; |
| 1015 | |
| 1016 | for (auto *EU : Extract->users()) { |
| 1017 | if (auto *Store = dyn_cast<StoreInst>(EU)) { |
| 1018 | auto *AV = cast<AllocaInst>(Store->getPointerOperand()); |
| 1019 | EHAllocas.push_back(AV); |
| 1020 | } |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | // We can't do this without a dominator tree. |
| 1025 | assert(DT); |
| 1026 | |
| 1027 | if (!EHAllocas.empty()) { |
| 1028 | PromoteMemToReg(EHAllocas, *DT); |
| 1029 | EHAllocas.clear(); |
| 1030 | } |
Reid Kleckner | 8676214 | 2015-04-16 00:02:04 +0000 | [diff] [blame] | 1031 | |
| 1032 | // After promotion, some extracts may be trivially dead. Remove them. |
| 1033 | SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end()); |
| 1034 | for (auto *U : Users) |
| 1035 | RecursivelyDeleteTriviallyDeadInstructions(U); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1036 | } |
| 1037 | |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1038 | void WinEHPrepare::getPossibleReturnTargets(Function *ParentF, |
| 1039 | Function *HandlerF, |
| 1040 | SetVector<BasicBlock*> &Targets) { |
| 1041 | for (BasicBlock &BB : *HandlerF) { |
| 1042 | // If the handler contains landing pads, check for any |
| 1043 | // handlers that may return directly to a block in the |
| 1044 | // parent function. |
| 1045 | if (auto *LPI = BB.getLandingPadInst()) { |
| 1046 | IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode()); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1047 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1048 | parseEHActions(Recover, ActionList); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1049 | for (const auto &Action : ActionList) { |
| 1050 | if (auto *CH = dyn_cast<CatchHandler>(Action.get())) { |
Andrew Kaylor | cc14f38 | 2015-05-11 23:06:02 +0000 | [diff] [blame] | 1051 | Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc()); |
| 1052 | getPossibleReturnTargets(ParentF, NestedF, Targets); |
| 1053 | } |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()); |
| 1058 | if (!Ret) |
| 1059 | continue; |
| 1060 | |
| 1061 | // Handler functions must always return a block address. |
| 1062 | BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); |
| 1063 | |
| 1064 | // If this is the handler for a nested landing pad, the |
| 1065 | // return address may have been remapped to a block in the |
| 1066 | // parent handler. We're not interested in those. |
| 1067 | if (BA->getFunction() != ParentF) |
| 1068 | continue; |
| 1069 | |
| 1070 | Targets.insert(BA->getBasicBlock()); |
| 1071 | } |
| 1072 | } |
| 1073 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1074 | void WinEHPrepare::completeNestedLandingPad(Function *ParentFn, |
| 1075 | LandingPadInst *OutlinedLPad, |
| 1076 | const LandingPadInst *OriginalLPad, |
| 1077 | FrameVarInfoMap &FrameVarInfo) { |
| 1078 | // Get the nested block and erase the unreachable instruction that was |
| 1079 | // temporarily inserted as its terminator. |
| 1080 | LLVMContext &Context = ParentFn->getContext(); |
| 1081 | BasicBlock *OutlinedBB = OutlinedLPad->getParent(); |
| 1082 | assert(isa<UnreachableInst>(OutlinedBB->getTerminator())); |
| 1083 | OutlinedBB->getTerminator()->eraseFromParent(); |
| 1084 | // That should leave OutlinedLPad as the last instruction in its block. |
| 1085 | assert(&OutlinedBB->back() == OutlinedLPad); |
| 1086 | |
| 1087 | // The original landing pad will have already had its action intrinsic |
| 1088 | // built by the outlining loop. We need to clone that into the outlined |
| 1089 | // location. It may also be necessary to add references to the exception |
| 1090 | // variables to the outlined handler in which this landing pad is nested |
| 1091 | // and remap return instructions in the nested handlers that should return |
| 1092 | // to an address in the outlined handler. |
| 1093 | Function *OutlinedHandlerFn = OutlinedBB->getParent(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1094 | BasicBlock::const_iterator II = OriginalLPad; |
| 1095 | ++II; |
| 1096 | // The instruction after the landing pad should now be a call to eh.actions. |
| 1097 | const Instruction *Recover = II; |
| 1098 | assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>())); |
| 1099 | IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone()); |
| 1100 | |
| 1101 | // Remap the exception variables into the outlined function. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1102 | SmallVector<BlockAddress *, 4> ActionTargets; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1103 | SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1104 | parseEHActions(EHActions, ActionList); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 1105 | for (const auto &Action : ActionList) { |
| 1106 | auto *Catch = dyn_cast<CatchHandler>(Action.get()); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1107 | if (!Catch) |
| 1108 | continue; |
| 1109 | // The dyn_cast to function here selects C++ catch handlers and skips |
| 1110 | // SEH catch handlers. |
| 1111 | auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc()); |
| 1112 | if (!Handler) |
| 1113 | continue; |
| 1114 | // Visit all the return instructions, looking for places that return |
| 1115 | // to a location within OutlinedHandlerFn. |
| 1116 | for (BasicBlock &NestedHandlerBB : *Handler) { |
| 1117 | auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator()); |
| 1118 | if (!Ret) |
| 1119 | continue; |
| 1120 | |
| 1121 | // Handler functions must always return a block address. |
| 1122 | BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue()); |
| 1123 | // The original target will have been in the main parent function, |
| 1124 | // but if it is the address of a block that has been outlined, it |
| 1125 | // should be a block that was outlined into OutlinedHandlerFn. |
| 1126 | assert(BA->getFunction() == ParentFn); |
| 1127 | |
| 1128 | // Ignore targets that aren't part of OutlinedHandlerFn. |
| 1129 | if (!LPadTargetBlocks.count(BA->getBasicBlock())) |
| 1130 | continue; |
| 1131 | |
| 1132 | // If the return value is the address ofF a block that we |
| 1133 | // previously outlined into the parent handler function, replace |
| 1134 | // the return instruction and add the mapped target to the list |
| 1135 | // of possible return addresses. |
| 1136 | BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()]; |
| 1137 | assert(MappedBB->getParent() == OutlinedHandlerFn); |
| 1138 | BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB); |
| 1139 | Ret->eraseFromParent(); |
| 1140 | ReturnInst::Create(Context, NewBA, &NestedHandlerBB); |
| 1141 | ActionTargets.push_back(NewBA); |
| 1142 | } |
| 1143 | } |
Andrew Kaylor | 7a0cec3 | 2015-04-03 21:44:17 +0000 | [diff] [blame] | 1144 | ActionList.clear(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1145 | OutlinedBB->getInstList().push_back(EHActions); |
| 1146 | |
| 1147 | // Insert an indirect branch into the outlined landing pad BB. |
| 1148 | IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB); |
| 1149 | // Add the previously collected action targets. |
| 1150 | for (auto *Target : ActionTargets) |
| 1151 | IBr->addDestination(Target->getBasicBlock()); |
| 1152 | } |
| 1153 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1154 | // This function examines a block to determine whether the block ends with a |
| 1155 | // conditional branch to a catch handler based on a selector comparison. |
| 1156 | // This function is used both by the WinEHPrepare::findSelectorComparison() and |
| 1157 | // WinEHCleanupDirector::handleTypeIdFor(). |
| 1158 | static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler, |
| 1159 | Constant *&Selector, BasicBlock *&NextBB) { |
| 1160 | ICmpInst::Predicate Pred; |
| 1161 | BasicBlock *TBB, *FBB; |
| 1162 | Value *LHS, *RHS; |
| 1163 | |
| 1164 | if (!match(BB->getTerminator(), |
| 1165 | m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB))) |
| 1166 | return false; |
| 1167 | |
| 1168 | if (!match(LHS, |
| 1169 | m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) && |
| 1170 | !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector)))) |
| 1171 | return false; |
| 1172 | |
| 1173 | if (Pred == CmpInst::ICMP_EQ) { |
| 1174 | CatchHandler = TBB; |
| 1175 | NextBB = FBB; |
| 1176 | return true; |
| 1177 | } |
| 1178 | |
| 1179 | if (Pred == CmpInst::ICMP_NE) { |
| 1180 | CatchHandler = FBB; |
| 1181 | NextBB = TBB; |
| 1182 | return true; |
| 1183 | } |
| 1184 | |
| 1185 | return false; |
| 1186 | } |
| 1187 | |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 1188 | static bool isCatchBlock(BasicBlock *BB) { |
| 1189 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 1190 | II != IE; ++II) { |
| 1191 | if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>())) |
| 1192 | return true; |
| 1193 | } |
| 1194 | return false; |
| 1195 | } |
| 1196 | |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1197 | static BasicBlock *createStubLandingPad(Function *Handler, |
| 1198 | Value *PersonalityFn) { |
| 1199 | // FIXME: Finish this! |
| 1200 | LLVMContext &Context = Handler->getContext(); |
| 1201 | BasicBlock *StubBB = BasicBlock::Create(Context, "stub"); |
| 1202 | Handler->getBasicBlockList().push_back(StubBB); |
| 1203 | IRBuilder<> Builder(StubBB); |
| 1204 | LandingPadInst *LPad = Builder.CreateLandingPad( |
| 1205 | llvm::StructType::get(Type::getInt8PtrTy(Context), |
| 1206 | Type::getInt32Ty(Context), nullptr), |
| 1207 | PersonalityFn, 0); |
Andrew Kaylor | 43e1d76 | 2015-04-23 00:20:44 +0000 | [diff] [blame] | 1208 | // Insert a call to llvm.eh.actions so that we don't try to outline this lpad. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1209 | Function *ActionIntrin = |
| 1210 | Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame^] | 1211 | Builder.CreateCall(ActionIntrin, {}, "recover"); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1212 | LPad->setCleanup(true); |
| 1213 | Builder.CreateUnreachable(); |
| 1214 | return StubBB; |
| 1215 | } |
| 1216 | |
| 1217 | // Cycles through the blocks in an outlined handler function looking for an |
| 1218 | // invoke instruction and inserts an invoke of llvm.donothing with an empty |
| 1219 | // landing pad if none is found. The code that generates the .xdata tables for |
| 1220 | // the handler needs at least one landing pad to identify the parent function's |
| 1221 | // personality. |
| 1222 | void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler, |
| 1223 | Value *PersonalityFn) { |
| 1224 | ReturnInst *Ret = nullptr; |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1225 | UnreachableInst *Unreached = nullptr; |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1226 | for (BasicBlock &BB : *Handler) { |
| 1227 | TerminatorInst *Terminator = BB.getTerminator(); |
| 1228 | // If we find an invoke, there is nothing to be done. |
| 1229 | auto *II = dyn_cast<InvokeInst>(Terminator); |
| 1230 | if (II) |
| 1231 | return; |
| 1232 | // If we've already recorded a return instruction, keep looking for invokes. |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1233 | if (!Ret) |
| 1234 | Ret = dyn_cast<ReturnInst>(Terminator); |
| 1235 | // If we haven't recorded an unreachable instruction, try this terminator. |
| 1236 | if (!Unreached) |
| 1237 | Unreached = dyn_cast<UnreachableInst>(Terminator); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1238 | } |
| 1239 | |
| 1240 | // If we got this far, the handler contains no invokes. We should have seen |
Andrew Kaylor | 5f71552 | 2015-04-23 18:37:39 +0000 | [diff] [blame] | 1241 | // at least one return or unreachable instruction. We'll insert an invoke of |
| 1242 | // llvm.donothing ahead of that instruction. |
| 1243 | assert(Ret || Unreached); |
| 1244 | TerminatorInst *Term; |
| 1245 | if (Ret) |
| 1246 | Term = Ret; |
| 1247 | else |
| 1248 | Term = Unreached; |
| 1249 | BasicBlock *OldRetBB = Term->getParent(); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 1250 | BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1251 | // SplitBlock adds an unconditional branch instruction at the end of the |
| 1252 | // parent block. We want to replace that with an invoke call, so we can |
| 1253 | // erase it now. |
| 1254 | OldRetBB->getTerminator()->eraseFromParent(); |
| 1255 | BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn); |
| 1256 | Function *F = |
| 1257 | Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing); |
| 1258 | InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB); |
| 1259 | } |
| 1260 | |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1261 | // FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering |
| 1262 | // usually doesn't build LLVM IR, so that's probably the wrong place. |
| 1263 | Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name, |
| 1264 | Module *M, Value *&ParentFP) { |
| 1265 | // x64 uses a two-argument prototype where the parent FP is the second |
| 1266 | // argument. x86 uses no arguments, just the incoming EBP value. |
| 1267 | LLVMContext &Context = M->getContext(); |
| 1268 | FunctionType *FnType; |
| 1269 | if (TheTriple.getArch() == Triple::x86_64) { |
| 1270 | Type *Int8PtrType = Type::getInt8PtrTy(Context); |
| 1271 | Type *ArgTys[2] = {Int8PtrType, Int8PtrType}; |
| 1272 | FnType = FunctionType::get(RetTy, ArgTys, false); |
| 1273 | } else { |
| 1274 | FnType = FunctionType::get(RetTy, None, false); |
| 1275 | } |
| 1276 | |
| 1277 | Function *Handler = |
| 1278 | Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M); |
| 1279 | BasicBlock *Entry = BasicBlock::Create(Context, "entry"); |
| 1280 | Handler->getBasicBlockList().push_front(Entry); |
| 1281 | if (TheTriple.getArch() == Triple::x86_64) { |
| 1282 | ParentFP = &(Handler->getArgumentList().back()); |
| 1283 | } else { |
| 1284 | assert(M); |
| 1285 | Function *FrameAddressFn = |
| 1286 | Intrinsic::getDeclaration(M, Intrinsic::frameaddress); |
| 1287 | Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)}; |
| 1288 | ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp", |
| 1289 | &Handler->getEntryBlock()); |
| 1290 | } |
| 1291 | return Handler; |
| 1292 | } |
| 1293 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1294 | bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn, |
| 1295 | LandingPadInst *LPad, BasicBlock *StartBB, |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1296 | FrameVarInfoMap &VarInfo) { |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1297 | Module *M = SrcFn->getParent(); |
| 1298 | LLVMContext &Context = M->getContext(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1299 | Type *Int8PtrType = Type::getInt8PtrTy(Context); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1300 | |
| 1301 | // Create a new function to receive the handler contents. |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1302 | Value *ParentFP; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1303 | Function *Handler; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1304 | if (Action->getType() == Catch) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1305 | Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M, |
| 1306 | ParentFP); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1307 | } else { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1308 | Handler = createHandlerFunc(Type::getVoidTy(Context), |
| 1309 | SrcFn->getName() + ".cleanup", M, ParentFP); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1310 | } |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1311 | HandlerToParentFP[Handler] = ParentFP; |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 1312 | Handler->addFnAttr("wineh-parent", SrcFn->getName()); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1313 | BasicBlock *Entry = &Handler->getEntryBlock(); |
David Majnemer | cde3303 | 2015-03-30 22:58:10 +0000 | [diff] [blame] | 1314 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1315 | // Generate a standard prolog to setup the frame recovery structure. |
| 1316 | IRBuilder<> Builder(Context); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1317 | Builder.SetInsertPoint(Entry); |
| 1318 | Builder.SetCurrentDebugLocation(LPad->getDebugLoc()); |
| 1319 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1320 | std::unique_ptr<WinEHCloningDirectorBase> Director; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1321 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1322 | ValueToValueMapTy VMap; |
| 1323 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1324 | LandingPadMap &LPadMap = LPadMaps[LPad]; |
| 1325 | if (!LPadMap.isInitialized()) |
| 1326 | LPadMap.mapLandingPad(LPad); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1327 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 1328 | Constant *Sel = CatchAction->getSelector(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1329 | Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, |
| 1330 | VarInfo, LPadMap, |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1331 | NestedLPtoOriginalLP)); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1332 | LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), |
| 1333 | ConstantInt::get(Type::getInt32Ty(Context), 1)); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1334 | } else { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1335 | Director.reset( |
| 1336 | new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap)); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1337 | LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType), |
| 1338 | UndefValue::get(Type::getInt32Ty(Context))); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1339 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1340 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1341 | SmallVector<ReturnInst *, 8> Returns; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1342 | ClonedCodeInfo OutlinedFunctionInfo; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1343 | |
Andrew Kaylor | 3170e56 | 2015-03-20 21:42:54 +0000 | [diff] [blame] | 1344 | // If the start block contains PHI nodes, we need to map them. |
| 1345 | BasicBlock::iterator II = StartBB->begin(); |
| 1346 | while (auto *PN = dyn_cast<PHINode>(II)) { |
| 1347 | bool Mapped = false; |
| 1348 | // Look for PHI values that we have already mapped (such as the selector). |
| 1349 | for (Value *Val : PN->incoming_values()) { |
| 1350 | if (VMap.count(Val)) { |
| 1351 | VMap[PN] = VMap[Val]; |
| 1352 | Mapped = true; |
| 1353 | } |
| 1354 | } |
| 1355 | // If we didn't find a match for this value, map it as an undef. |
| 1356 | if (!Mapped) { |
| 1357 | VMap[PN] = UndefValue::get(PN->getType()); |
| 1358 | } |
| 1359 | ++II; |
| 1360 | } |
| 1361 | |
Andrew Kaylor | 00e5d9e | 2015-04-20 22:53:42 +0000 | [diff] [blame] | 1362 | // The landing pad value may be used by PHI nodes. It will ultimately be |
| 1363 | // eliminated, but we need it in the map for intermediate handling. |
| 1364 | VMap[LPad] = UndefValue::get(LPad->getType()); |
| 1365 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1366 | // Skip over PHIs and, if applicable, landingpad instructions. |
Andrew Kaylor | 3170e56 | 2015-03-20 21:42:54 +0000 | [diff] [blame] | 1367 | II = StartBB->getFirstInsertionPt(); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1368 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1369 | CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1370 | /*ModuleLevelChanges=*/false, Returns, "", |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1371 | &OutlinedFunctionInfo, Director.get()); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1372 | |
Andrew Kaylor | 5dacfd8 | 2015-04-24 23:10:38 +0000 | [diff] [blame] | 1373 | // Move all the instructions in the cloned "entry" block into our entry block. |
| 1374 | // Depending on how the parent function was laid out, the block that will |
| 1375 | // correspond to the outlined entry block may not be the first block in the |
| 1376 | // list. We can recognize it, however, as the cloned block which has no |
| 1377 | // predecessors. Any other block wouldn't have been cloned if it didn't |
| 1378 | // have a predecessor which was also cloned. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1379 | Function::iterator ClonedIt = std::next(Function::iterator(Entry)); |
Andrew Kaylor | 5dacfd8 | 2015-04-24 23:10:38 +0000 | [diff] [blame] | 1380 | while (!pred_empty(ClonedIt)) |
| 1381 | ++ClonedIt; |
| 1382 | BasicBlock *ClonedEntryBB = ClonedIt; |
| 1383 | assert(ClonedEntryBB); |
| 1384 | Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList()); |
| 1385 | ClonedEntryBB->eraseFromParent(); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1386 | |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1387 | // Make sure we can identify the handler's personality later. |
| 1388 | addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn()); |
| 1389 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1390 | if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) { |
| 1391 | WinEHCatchDirector *CatchDirector = |
| 1392 | reinterpret_cast<WinEHCatchDirector *>(Director.get()); |
| 1393 | CatchAction->setExceptionVar(CatchDirector->getExceptionVar()); |
| 1394 | CatchAction->setReturnTargets(CatchDirector->getReturnTargets()); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1395 | |
| 1396 | // Look for blocks that are not part of the landing pad that we just |
| 1397 | // outlined but terminate with a call to llvm.eh.endcatch and a |
| 1398 | // branch to a block that is in the handler we just outlined. |
| 1399 | // These blocks will be part of a nested landing pad that intends to |
| 1400 | // return to an address in this handler. This case is best handled |
| 1401 | // after both landing pads have been outlined, so for now we'll just |
| 1402 | // save the association of the blocks in LPadTargetBlocks. The |
| 1403 | // return instructions which are created from these branches will be |
| 1404 | // replaced after all landing pads have been outlined. |
Richard Trieu | 6b1aa5f | 2015-04-15 01:21:15 +0000 | [diff] [blame] | 1405 | for (const auto MapEntry : VMap) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1406 | // VMap maps all values and blocks that were just cloned, but dead |
| 1407 | // blocks which were pruned will map to nullptr. |
| 1408 | if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr) |
| 1409 | continue; |
| 1410 | const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first); |
| 1411 | for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) { |
| 1412 | auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator()); |
| 1413 | if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1) |
| 1414 | continue; |
| 1415 | BasicBlock::iterator II = const_cast<BranchInst *>(Branch); |
| 1416 | --II; |
| 1417 | if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) { |
| 1418 | // This would indicate that a nested landing pad wants to return |
| 1419 | // to a block that is outlined into two different handlers. |
| 1420 | assert(!LPadTargetBlocks.count(MappedBB)); |
| 1421 | LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second); |
| 1422 | } |
| 1423 | } |
| 1424 | } |
| 1425 | } // End if (CatchAction) |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1426 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1427 | Action->setHandlerBlockOrFunc(Handler); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1428 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1429 | return true; |
| 1430 | } |
| 1431 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1432 | /// This BB must end in a selector dispatch. All we need to do is pass the |
| 1433 | /// handler block to llvm.eh.actions and list it as a possible indirectbr |
| 1434 | /// target. |
| 1435 | void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction, |
| 1436 | BasicBlock *StartBB) { |
| 1437 | BasicBlock *HandlerBB; |
| 1438 | BasicBlock *NextBB; |
| 1439 | Constant *Selector; |
| 1440 | bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB); |
| 1441 | if (Res) { |
| 1442 | // If this was EH dispatch, this must be a conditional branch to the handler |
| 1443 | // block. |
| 1444 | // FIXME: Handle instructions in the dispatch block. Currently we drop them, |
| 1445 | // leading to crashes if some optimization hoists stuff here. |
| 1446 | assert(CatchAction->getSelector() && HandlerBB && |
| 1447 | "expected catch EH dispatch"); |
| 1448 | } else { |
| 1449 | // This must be a catch-all. Split the block after the landingpad. |
| 1450 | assert(CatchAction->getSelector()->isNullValue() && "expected catch-all"); |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 1451 | HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1452 | } |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1453 | IRBuilder<> Builder(HandlerBB->getFirstInsertionPt()); |
| 1454 | Function *EHCodeFn = Intrinsic::getDeclaration( |
| 1455 | StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode); |
David Blaikie | ff6409d | 2015-05-18 22:13:54 +0000 | [diff] [blame^] | 1456 | Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode"); |
Reid Kleckner | cfbfe6f | 2015-04-24 20:25:05 +0000 | [diff] [blame] | 1457 | Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType()); |
| 1458 | Builder.CreateStore(Code, SEHExceptionCodeSlot); |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1459 | CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB)); |
| 1460 | TinyPtrVector<BasicBlock *> Targets(HandlerBB); |
| 1461 | CatchAction->setReturnTargets(Targets); |
| 1462 | } |
| 1463 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1464 | void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) { |
| 1465 | // Each instance of this class should only ever be used to map a single |
| 1466 | // landing pad. |
| 1467 | assert(OriginLPad == nullptr || OriginLPad == LPad); |
| 1468 | |
| 1469 | // If the landing pad has already been mapped, there's nothing more to do. |
| 1470 | if (OriginLPad == LPad) |
| 1471 | return; |
| 1472 | |
| 1473 | OriginLPad = LPad; |
| 1474 | |
| 1475 | // The landingpad instruction returns an aggregate value. Typically, its |
| 1476 | // value will be passed to a pair of extract value instructions and the |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1477 | // results of those extracts will have been promoted to reg values before |
| 1478 | // this routine is called. |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1479 | for (auto *U : LPad->users()) { |
| 1480 | const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U); |
| 1481 | if (!Extract) |
| 1482 | continue; |
| 1483 | assert(Extract->getNumIndices() == 1 && |
| 1484 | "Unexpected operation: extracting both landing pad values"); |
| 1485 | unsigned int Idx = *(Extract->idx_begin()); |
| 1486 | assert((Idx == 0 || Idx == 1) && |
| 1487 | "Unexpected operation: extracting an unknown landing pad element"); |
| 1488 | if (Idx == 0) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1489 | ExtractedEHPtrs.push_back(Extract); |
| 1490 | } else if (Idx == 1) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1491 | ExtractedSelectors.push_back(Extract); |
| 1492 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1493 | } |
| 1494 | } |
| 1495 | |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 1496 | bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const { |
| 1497 | return BB->getLandingPadInst() == OriginLPad; |
| 1498 | } |
| 1499 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1500 | bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const { |
| 1501 | if (Inst == OriginLPad) |
| 1502 | return true; |
| 1503 | for (auto *Extract : ExtractedEHPtrs) { |
| 1504 | if (Inst == Extract) |
| 1505 | return true; |
| 1506 | } |
| 1507 | for (auto *Extract : ExtractedSelectors) { |
| 1508 | if (Inst == Extract) |
| 1509 | return true; |
| 1510 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1511 | return false; |
| 1512 | } |
| 1513 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1514 | void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue, |
| 1515 | Value *SelectorValue) const { |
| 1516 | // Remap all landing pad extract instructions to the specified values. |
| 1517 | for (auto *Extract : ExtractedEHPtrs) |
| 1518 | VMap[Extract] = EHPtrValue; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1519 | for (auto *Extract : ExtractedSelectors) |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1520 | VMap[Extract] = SelectorValue; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1521 | } |
| 1522 | |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1523 | static bool isFrameAddressCall(const Value *V) { |
| 1524 | return match(const_cast<Value *>(V), |
| 1525 | m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0))); |
| 1526 | } |
| 1527 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1528 | CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction( |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1529 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1530 | // If this is one of the boilerplate landing pad instructions, skip it. |
| 1531 | // The instruction will have already been remapped in VMap. |
| 1532 | if (LPadMap.isLandingPadSpecificInst(Inst)) |
| 1533 | return CloningDirector::SkipInstruction; |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1534 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1535 | // Nested landing pads will be cloned as stubs, with just the |
| 1536 | // landingpad instruction and an unreachable instruction. When |
| 1537 | // all landingpads have been outlined, we'll replace this with the |
| 1538 | // llvm.eh.actions call and indirect branch created when the |
| 1539 | // landing pad was outlined. |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1540 | if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) { |
| 1541 | return handleLandingPad(VMap, LPad, NewBB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1542 | } |
| 1543 | |
| 1544 | if (auto *Invoke = dyn_cast<InvokeInst>(Inst)) |
| 1545 | return handleInvoke(VMap, Invoke, NewBB); |
| 1546 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1547 | if (auto *Resume = dyn_cast<ResumeInst>(Inst)) |
| 1548 | return handleResume(VMap, Resume, NewBB); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1549 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1550 | if (auto *Cmp = dyn_cast<CmpInst>(Inst)) |
| 1551 | return handleCompare(VMap, Cmp, NewBB); |
| 1552 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1553 | if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) |
| 1554 | return handleBeginCatch(VMap, Inst, NewBB); |
| 1555 | if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) |
| 1556 | return handleEndCatch(VMap, Inst, NewBB); |
| 1557 | if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) |
| 1558 | return handleTypeIdFor(VMap, Inst, NewBB); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1559 | |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1560 | // When outlining llvm.frameaddress(i32 0), remap that to the second argument, |
| 1561 | // which is the FP of the parent. |
| 1562 | if (isFrameAddressCall(Inst)) { |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1563 | VMap[Inst] = ParentFP; |
Reid Kleckner | f14787d | 2015-04-22 00:07:52 +0000 | [diff] [blame] | 1564 | return CloningDirector::SkipInstruction; |
| 1565 | } |
| 1566 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1567 | // Continue with the default cloning behavior. |
| 1568 | return CloningDirector::CloneInstruction; |
| 1569 | } |
| 1570 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1571 | CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad( |
| 1572 | ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { |
| 1573 | Instruction *NewInst = LPad->clone(); |
| 1574 | if (LPad->hasName()) |
| 1575 | NewInst->setName(LPad->getName()); |
| 1576 | // Save this correlation for later processing. |
| 1577 | NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad; |
| 1578 | VMap[LPad] = NewInst; |
| 1579 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1580 | InstList.push_back(NewInst); |
| 1581 | InstList.push_back(new UnreachableInst(NewBB->getContext())); |
| 1582 | return CloningDirector::StopCloningBB; |
| 1583 | } |
| 1584 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1585 | CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch( |
| 1586 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
| 1587 | // The argument to the call is some form of the first element of the |
| 1588 | // landingpad aggregate value, but that doesn't matter. It isn't used |
| 1589 | // here. |
Reid Kleckner | 4236653 | 2015-03-03 23:20:30 +0000 | [diff] [blame] | 1590 | // The second argument is an outparameter where the exception object will be |
| 1591 | // stored. Typically the exception object is a scalar, but it can be an |
| 1592 | // aggregate when catching by value. |
| 1593 | // FIXME: Leave something behind to indicate where the exception object lives |
| 1594 | // for this handler. Should it be part of llvm.eh.actions? |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1595 | assert(ExceptionObjectVar == nullptr && "Multiple calls to " |
| 1596 | "llvm.eh.begincatch found while " |
| 1597 | "outlining catch handler."); |
| 1598 | ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts(); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1599 | if (isa<ConstantPointerNull>(ExceptionObjectVar)) |
| 1600 | return CloningDirector::SkipInstruction; |
Reid Kleckner | aab30e1 | 2015-04-03 18:18:06 +0000 | [diff] [blame] | 1601 | assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() && |
| 1602 | "catch parameter is not static alloca"); |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1603 | Materializer.escapeCatchObject(ExceptionObjectVar); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1604 | return CloningDirector::SkipInstruction; |
| 1605 | } |
| 1606 | |
| 1607 | CloningDirector::CloningAction |
| 1608 | WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap, |
| 1609 | const Instruction *Inst, BasicBlock *NewBB) { |
| 1610 | auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); |
| 1611 | // It might be interesting to track whether or not we are inside a catch |
| 1612 | // function, but that might make the algorithm more brittle than it needs |
| 1613 | // to be. |
| 1614 | |
| 1615 | // The end catch call can occur in one of two places: either in a |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1616 | // landingpad block that is part of the catch handlers exception mechanism, |
Andrew Kaylor | f7118ae | 2015-03-27 22:31:12 +0000 | [diff] [blame] | 1617 | // or at the end of the catch block. However, a catch-all handler may call |
| 1618 | // end catch from the original landing pad. If the call occurs in a nested |
| 1619 | // landing pad block, we must skip it and continue so that the landing pad |
| 1620 | // gets cloned. |
| 1621 | auto *ParentBB = IntrinCall->getParent(); |
| 1622 | if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB)) |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1623 | return CloningDirector::SkipInstruction; |
| 1624 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1625 | // If an end catch occurs anywhere else we want to terminate the handler |
| 1626 | // with a return to the code that follows the endcatch call. If the |
| 1627 | // next instruction is not an unconditional branch, we need to split the |
| 1628 | // block to provide a clear target for the return instruction. |
| 1629 | BasicBlock *ContinueBB; |
| 1630 | auto Next = std::next(BasicBlock::const_iterator(IntrinCall)); |
| 1631 | const BranchInst *Branch = dyn_cast<BranchInst>(Next); |
| 1632 | if (!Branch || !Branch->isUnconditional()) { |
| 1633 | // We're interrupting the cloning process at this location, so the |
| 1634 | // const_cast we're doing here will not cause a problem. |
| 1635 | ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB), |
| 1636 | const_cast<Instruction *>(cast<Instruction>(Next))); |
| 1637 | } else { |
| 1638 | ContinueBB = Branch->getSuccessor(0); |
| 1639 | } |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1640 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 1641 | ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB); |
| 1642 | ReturnTargets.push_back(ContinueBB); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1643 | |
| 1644 | // We just added a terminator to the cloned block. |
| 1645 | // Tell the caller to stop processing the current basic block so that |
| 1646 | // the branch instruction will be skipped. |
| 1647 | return CloningDirector::StopCloningBB; |
| 1648 | } |
| 1649 | |
| 1650 | CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor( |
| 1651 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
| 1652 | auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst); |
| 1653 | Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); |
| 1654 | // This causes a replacement that will collapse the landing pad CFG based |
| 1655 | // on the filter function we intend to match. |
| 1656 | if (Selector == CurrentSelector) |
| 1657 | VMap[Inst] = ConstantInt::get(SelectorIDType, 1); |
| 1658 | else |
| 1659 | VMap[Inst] = ConstantInt::get(SelectorIDType, 0); |
| 1660 | // Tell the caller not to clone this instruction. |
| 1661 | return CloningDirector::SkipInstruction; |
| 1662 | } |
| 1663 | |
| 1664 | CloningDirector::CloningAction |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1665 | WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap, |
| 1666 | const InvokeInst *Invoke, BasicBlock *NewBB) { |
| 1667 | return CloningDirector::CloneInstruction; |
| 1668 | } |
| 1669 | |
| 1670 | CloningDirector::CloningAction |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1671 | WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap, |
| 1672 | const ResumeInst *Resume, BasicBlock *NewBB) { |
| 1673 | // Resume instructions shouldn't be reachable from catch handlers. |
| 1674 | // We still need to handle it, but it will be pruned. |
| 1675 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1676 | InstList.push_back(new UnreachableInst(NewBB->getContext())); |
| 1677 | return CloningDirector::StopCloningBB; |
| 1678 | } |
| 1679 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1680 | CloningDirector::CloningAction |
| 1681 | WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap, |
| 1682 | const CmpInst *Compare, BasicBlock *NewBB) { |
| 1683 | const IntrinsicInst *IntrinCall = nullptr; |
| 1684 | if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
| 1685 | IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0)); |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1686 | } else if (match(Compare->getOperand(1), |
| 1687 | m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1688 | IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1)); |
| 1689 | } |
| 1690 | if (IntrinCall) { |
| 1691 | Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts(); |
| 1692 | // This causes a replacement that will collapse the landing pad CFG based |
| 1693 | // on the filter function we intend to match. |
| 1694 | if (Selector == CurrentSelector->stripPointerCasts()) { |
| 1695 | VMap[Compare] = ConstantInt::get(SelectorIDType, 1); |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1696 | } else { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1697 | VMap[Compare] = ConstantInt::get(SelectorIDType, 0); |
| 1698 | } |
| 1699 | return CloningDirector::SkipInstruction; |
| 1700 | } |
| 1701 | return CloningDirector::CloneInstruction; |
| 1702 | } |
| 1703 | |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1704 | CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad( |
| 1705 | ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) { |
| 1706 | // The MS runtime will terminate the process if an exception occurs in a |
| 1707 | // cleanup handler, so we shouldn't encounter landing pads in the actual |
| 1708 | // cleanup code, but they may appear in catch blocks. Depending on where |
| 1709 | // we started cloning we may see one, but it will get dropped during dead |
| 1710 | // block pruning. |
| 1711 | Instruction *NewInst = new UnreachableInst(NewBB->getContext()); |
| 1712 | VMap[LPad] = NewInst; |
| 1713 | BasicBlock::InstListType &InstList = NewBB->getInstList(); |
| 1714 | InstList.push_back(NewInst); |
| 1715 | return CloningDirector::StopCloningBB; |
| 1716 | } |
| 1717 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1718 | CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch( |
| 1719 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1720 | // Cleanup code may flow into catch blocks or the catch block may be part |
| 1721 | // of a branch that will be optimized away. We'll insert a return |
| 1722 | // instruction now, but it may be pruned before the cloning process is |
| 1723 | // complete. |
| 1724 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1725 | return CloningDirector::StopCloningBB; |
| 1726 | } |
| 1727 | |
| 1728 | CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch( |
| 1729 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 1730 | // Cleanup handlers nested within catch handlers may begin with a call to |
| 1731 | // eh.endcatch. We can just ignore that instruction. |
| 1732 | return CloningDirector::SkipInstruction; |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1733 | } |
| 1734 | |
| 1735 | CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor( |
| 1736 | ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1737 | // If we encounter a selector comparison while cloning a cleanup handler, |
| 1738 | // we want to stop cloning immediately. Anything after the dispatch |
| 1739 | // will be outlined into a different handler. |
| 1740 | BasicBlock *CatchHandler; |
| 1741 | Constant *Selector; |
| 1742 | BasicBlock *NextBB; |
| 1743 | if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()), |
| 1744 | CatchHandler, Selector, NextBB)) { |
| 1745 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
| 1746 | return CloningDirector::StopCloningBB; |
| 1747 | } |
| 1748 | // If eg.typeid.for is called for any other reason, it can be ignored. |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1749 | VMap[Inst] = ConstantInt::get(SelectorIDType, 0); |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1750 | return CloningDirector::SkipInstruction; |
| 1751 | } |
| 1752 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1753 | CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke( |
| 1754 | ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) { |
| 1755 | // All invokes in cleanup handlers can be replaced with calls. |
| 1756 | SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3); |
| 1757 | // Insert a normal call instruction... |
| 1758 | CallInst *NewCall = |
| 1759 | CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs, |
| 1760 | Invoke->getName(), NewBB); |
| 1761 | NewCall->setCallingConv(Invoke->getCallingConv()); |
| 1762 | NewCall->setAttributes(Invoke->getAttributes()); |
| 1763 | NewCall->setDebugLoc(Invoke->getDebugLoc()); |
| 1764 | VMap[Invoke] = NewCall; |
| 1765 | |
Reid Kleckner | 6e48a82 | 2015-04-10 16:26:42 +0000 | [diff] [blame] | 1766 | // Remap the operands. |
| 1767 | llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer); |
| 1768 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1769 | // Insert an unconditional branch to the normal destination. |
| 1770 | BranchInst::Create(Invoke->getNormalDest(), NewBB); |
| 1771 | |
| 1772 | // The unwind destination won't be cloned into the new function, so |
| 1773 | // we don't need to clean up its phi nodes. |
| 1774 | |
| 1775 | // We just added a terminator to the cloned block. |
| 1776 | // Tell the caller to stop processing the current basic block. |
Reid Kleckner | 6e48a82 | 2015-04-10 16:26:42 +0000 | [diff] [blame] | 1777 | return CloningDirector::CloneSuccessors; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1778 | } |
| 1779 | |
Andrew Kaylor | f0f5e46 | 2015-03-03 20:00:16 +0000 | [diff] [blame] | 1780 | CloningDirector::CloningAction WinEHCleanupDirector::handleResume( |
| 1781 | ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) { |
| 1782 | ReturnInst::Create(NewBB->getContext(), nullptr, NewBB); |
| 1783 | |
| 1784 | // We just added a terminator to the cloned block. |
| 1785 | // Tell the caller to stop processing the current basic block so that |
| 1786 | // the branch instruction will be skipped. |
| 1787 | return CloningDirector::StopCloningBB; |
| 1788 | } |
| 1789 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1790 | CloningDirector::CloningAction |
| 1791 | WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap, |
| 1792 | const CmpInst *Compare, BasicBlock *NewBB) { |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1793 | if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) || |
| 1794 | match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) { |
| 1795 | VMap[Compare] = ConstantInt::get(SelectorIDType, 1); |
| 1796 | return CloningDirector::SkipInstruction; |
| 1797 | } |
| 1798 | return CloningDirector::CloneInstruction; |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1799 | } |
| 1800 | |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1801 | WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer( |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1802 | Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo) |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1803 | : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 1804 | BasicBlock *EntryBB = &OutlinedFn->getEntryBlock(); |
Reid Kleckner | bcda1cd | 2015-04-29 22:49:54 +0000 | [diff] [blame] | 1805 | |
| 1806 | // New allocas should be inserted in the entry block, but after the parent FP |
| 1807 | // is established if it is an instruction. |
| 1808 | Instruction *InsertPoint = EntryBB->getFirstInsertionPt(); |
| 1809 | if (auto *FPInst = dyn_cast<Instruction>(ParentFP)) |
| 1810 | InsertPoint = FPInst->getNextNode(); |
| 1811 | Builder.SetInsertPoint(EntryBB, InsertPoint); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1812 | } |
| 1813 | |
| 1814 | Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 1815 | // If we're asked to materialize a static alloca, we temporarily create an |
| 1816 | // alloca in the outlined function and add this to the FrameVarInfo map. When |
| 1817 | // all the outlining is complete, we'll replace these temporary allocas with |
| 1818 | // calls to llvm.framerecover. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1819 | if (auto *AV = dyn_cast<AllocaInst>(V)) { |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 1820 | assert(AV->isStaticAlloca() && |
| 1821 | "cannot materialize un-demoted dynamic alloca"); |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 1822 | AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone()); |
| 1823 | Builder.Insert(NewAlloca, AV->getName()); |
Reid Kleckner | cfb9ce5 | 2015-03-05 18:26:34 +0000 | [diff] [blame] | 1824 | FrameVarInfo[AV].push_back(NewAlloca); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1825 | return NewAlloca; |
| 1826 | } |
| 1827 | |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 1828 | if (isa<Instruction>(V) || isa<Argument>(V)) { |
Reid Kleckner | d1b38c4 | 2015-05-06 18:45:24 +0000 | [diff] [blame] | 1829 | Function *Parent = isa<Instruction>(V) |
| 1830 | ? cast<Instruction>(V)->getParent()->getParent() |
| 1831 | : cast<Argument>(V)->getParent(); |
| 1832 | errs() |
| 1833 | << "Failed to demote instruction used in exception handler of function " |
| 1834 | << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n"; |
Reid Kleckner | fd7df28 | 2015-04-22 21:05:21 +0000 | [diff] [blame] | 1835 | errs() << " " << *V << '\n'; |
| 1836 | report_fatal_error("WinEHPrepare failed to demote instruction"); |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1837 | } |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1838 | |
Andrew Kaylor | 72029c6 | 2015-03-03 00:41:03 +0000 | [diff] [blame] | 1839 | // Don't materialize other values. |
Andrew Kaylor | 1476e6d | 2015-02-24 20:49:35 +0000 | [diff] [blame] | 1840 | return nullptr; |
| 1841 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1842 | |
Reid Kleckner | 3567d27 | 2015-04-02 21:13:31 +0000 | [diff] [blame] | 1843 | void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) { |
| 1844 | // Catch parameter objects have to live in the parent frame. When we see a use |
| 1845 | // of a catch parameter, add a sentinel to the multimap to indicate that it's |
| 1846 | // used from another handler. This will prevent us from trying to sink the |
| 1847 | // alloca into the handler and ensure that the catch parameter is present in |
| 1848 | // the call to llvm.frameescape. |
| 1849 | FrameVarInfo[V].push_back(getCatchObjectSentinel()); |
| 1850 | } |
| 1851 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1852 | // This function maps the catch and cleanup handlers that are reachable from the |
| 1853 | // specified landing pad. The landing pad sequence will have this basic shape: |
| 1854 | // |
| 1855 | // <cleanup handler> |
| 1856 | // <selector comparison> |
| 1857 | // <catch handler> |
| 1858 | // <cleanup handler> |
| 1859 | // <selector comparison> |
| 1860 | // <catch handler> |
| 1861 | // <cleanup handler> |
| 1862 | // ... |
| 1863 | // |
| 1864 | // Any of the cleanup slots may be absent. The cleanup slots may be occupied by |
| 1865 | // any arbitrary control flow, but all paths through the cleanup code must |
| 1866 | // eventually reach the next selector comparison and no path can skip to a |
| 1867 | // different selector comparisons, though some paths may terminate abnormally. |
| 1868 | // Therefore, we will use a depth first search from the start of any given |
| 1869 | // cleanup block and stop searching when we find the next selector comparison. |
| 1870 | // |
| 1871 | // If the landingpad instruction does not have a catch clause, we will assume |
| 1872 | // that any instructions other than selector comparisons and catch handlers can |
| 1873 | // be ignored. In practice, these will only be the boilerplate instructions. |
| 1874 | // |
| 1875 | // The catch handlers may also have any control structure, but we are only |
| 1876 | // interested in the start of the catch handlers, so we don't need to actually |
| 1877 | // follow the flow of the catch handlers. The start of the catch handlers can |
| 1878 | // be located from the compare instructions, but they can be skipped in the |
| 1879 | // flow by following the contrary branch. |
| 1880 | void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad, |
| 1881 | LandingPadActions &Actions) { |
| 1882 | unsigned int NumClauses = LPad->getNumClauses(); |
| 1883 | unsigned int HandlersFound = 0; |
| 1884 | BasicBlock *BB = LPad->getParent(); |
| 1885 | |
| 1886 | DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n"); |
| 1887 | |
| 1888 | if (NumClauses == 0) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 1889 | findCleanupHandlers(Actions, BB, nullptr); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1890 | return; |
| 1891 | } |
| 1892 | |
| 1893 | VisitedBlockSet VisitedBlocks; |
| 1894 | |
| 1895 | while (HandlersFound != NumClauses) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1896 | BasicBlock *NextBB = nullptr; |
| 1897 | |
Andrew Kaylor | 20ae2a3 | 2015-04-23 22:38:36 +0000 | [diff] [blame] | 1898 | // Skip over filter clauses. |
| 1899 | if (LPad->isFilter(HandlersFound)) { |
| 1900 | ++HandlersFound; |
| 1901 | continue; |
| 1902 | } |
| 1903 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1904 | // See if the clause we're looking for is a catch-all. |
| 1905 | // If so, the catch begins immediately. |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1906 | Constant *ExpectedSelector = |
| 1907 | LPad->getClause(HandlersFound)->stripPointerCasts(); |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1908 | if (isa<ConstantPointerNull>(ExpectedSelector)) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1909 | // The catch all must occur last. |
| 1910 | assert(HandlersFound == NumClauses - 1); |
| 1911 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1912 | // There can be additional selector dispatches in the call chain that we |
| 1913 | // need to ignore. |
| 1914 | BasicBlock *CatchBlock = nullptr; |
| 1915 | Constant *Selector; |
| 1916 | while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { |
| 1917 | DEBUG(dbgs() << " Found extra catch dispatch in block " |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 1918 | << CatchBlock->getName() << "\n"); |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1919 | BB = NextBB; |
| 1920 | } |
| 1921 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1922 | // Add the catch handler to the action list. |
Andrew Kaylor | f18771b | 2015-04-20 18:48:45 +0000 | [diff] [blame] | 1923 | CatchHandler *Action = nullptr; |
| 1924 | if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { |
| 1925 | // If the CatchHandlerMap already has an entry for this BB, re-use it. |
| 1926 | Action = CatchHandlerMap[BB]; |
| 1927 | assert(Action->getSelector() == ExpectedSelector); |
| 1928 | } else { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 1929 | // We don't expect a selector dispatch, but there may be a call to |
| 1930 | // llvm.eh.begincatch, which separates catch handling code from |
| 1931 | // cleanup code in the same control flow. This call looks for the |
| 1932 | // begincatch intrinsic. |
| 1933 | Action = findCatchHandler(BB, NextBB, VisitedBlocks); |
| 1934 | if (Action) { |
| 1935 | // For C++ EH, check if there is any interesting cleanup code before |
| 1936 | // we begin the catch. This is important because cleanups cannot |
| 1937 | // rethrow exceptions but code called from catches can. For SEH, it |
| 1938 | // isn't important if some finally code before a catch-all is executed |
| 1939 | // out of line or after recovering from the exception. |
| 1940 | if (Personality == EHPersonality::MSVC_CXX) |
| 1941 | findCleanupHandlers(Actions, BB, BB); |
| 1942 | } else { |
| 1943 | // If an action was not found, it means that the control flows |
| 1944 | // directly into the catch-all handler and there is no cleanup code. |
| 1945 | // That's an expected situation and we must create a catch action. |
| 1946 | // Since this is a catch-all handler, the selector won't actually |
| 1947 | // appear in the code anywhere. ExpectedSelector here is the constant |
| 1948 | // null ptr that we got from the landing pad instruction. |
| 1949 | Action = new CatchHandler(BB, ExpectedSelector, nullptr); |
| 1950 | CatchHandlerMap[BB] = Action; |
| 1951 | } |
Andrew Kaylor | f18771b | 2015-04-20 18:48:45 +0000 | [diff] [blame] | 1952 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1953 | Actions.insertCatchHandler(Action); |
| 1954 | DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n"); |
| 1955 | ++HandlersFound; |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 1956 | |
| 1957 | // Once we reach a catch-all, don't expect to hit a resume instruction. |
| 1958 | BB = nullptr; |
| 1959 | break; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1960 | } |
| 1961 | |
| 1962 | CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks); |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 1963 | assert(CatchAction); |
| 1964 | |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1965 | // See if there is any interesting code executed before the dispatch. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 1966 | findCleanupHandlers(Actions, BB, CatchAction->getStartBlock()); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1967 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1968 | // When the source program contains multiple nested try blocks the catch |
| 1969 | // handlers can get strung together in such a way that we can encounter |
| 1970 | // a dispatch for a selector that we've already had a handler for. |
| 1971 | if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) { |
| 1972 | ++HandlersFound; |
| 1973 | |
| 1974 | // Add the catch handler to the action list. |
| 1975 | DEBUG(dbgs() << " Found catch dispatch in block " |
| 1976 | << CatchAction->getStartBlock()->getName() << "\n"); |
| 1977 | Actions.insertCatchHandler(CatchAction); |
| 1978 | } else { |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 1979 | // Under some circumstances optimized IR will flow unconditionally into a |
| 1980 | // handler block without checking the selector. This can only happen if |
| 1981 | // the landing pad has a catch-all handler and the handler for the |
| 1982 | // preceeding catch clause is identical to the catch-call handler |
| 1983 | // (typically an empty catch). In this case, the handler must be shared |
| 1984 | // by all remaining clauses. |
| 1985 | if (isa<ConstantPointerNull>( |
| 1986 | CatchAction->getSelector()->stripPointerCasts())) { |
| 1987 | DEBUG(dbgs() << " Applying early catch-all handler in block " |
| 1988 | << CatchAction->getStartBlock()->getName() |
| 1989 | << " to all remaining clauses.\n"); |
| 1990 | Actions.insertCatchHandler(CatchAction); |
| 1991 | return; |
| 1992 | } |
| 1993 | |
Andrew Kaylor | ea8df61 | 2015-04-17 23:05:43 +0000 | [diff] [blame] | 1994 | DEBUG(dbgs() << " Found extra catch dispatch in block " |
| 1995 | << CatchAction->getStartBlock()->getName() << "\n"); |
| 1996 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 1997 | |
| 1998 | // Move on to the block after the catch handler. |
| 1999 | BB = NextBB; |
| 2000 | } |
| 2001 | |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2002 | // If we didn't wind up in a catch-all, see if there is any interesting code |
| 2003 | // executed before the resume. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2004 | findCleanupHandlers(Actions, BB, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2005 | |
| 2006 | // It's possible that some optimization moved code into a landingpad that |
| 2007 | // wasn't |
| 2008 | // previously being used for cleanup. If that happens, we need to execute |
| 2009 | // that |
| 2010 | // extra code from a cleanup handler. |
| 2011 | if (Actions.includesCleanup() && !LPad->isCleanup()) |
| 2012 | LPad->setCleanup(true); |
| 2013 | } |
| 2014 | |
| 2015 | // This function searches starting with the input block for the next |
| 2016 | // block that terminates with a branch whose condition is based on a selector |
| 2017 | // comparison. This may be the input block. See the mapLandingPadBlocks |
| 2018 | // comments for a discussion of control flow assumptions. |
| 2019 | // |
| 2020 | CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB, |
| 2021 | BasicBlock *&NextBB, |
| 2022 | VisitedBlockSet &VisitedBlocks) { |
| 2023 | // See if we've already found a catch handler use it. |
| 2024 | // Call count() first to avoid creating a null entry for blocks |
| 2025 | // we haven't seen before. |
| 2026 | if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) { |
| 2027 | CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]); |
| 2028 | NextBB = Action->getNextBB(); |
| 2029 | return Action; |
| 2030 | } |
| 2031 | |
| 2032 | // VisitedBlocks applies only to the current search. We still |
| 2033 | // need to consider blocks that we've visited while mapping other |
| 2034 | // landing pads. |
| 2035 | VisitedBlocks.insert(BB); |
| 2036 | |
| 2037 | BasicBlock *CatchBlock = nullptr; |
| 2038 | Constant *Selector = nullptr; |
| 2039 | |
| 2040 | // If this is the first time we've visited this block from any landing pad |
| 2041 | // look to see if it is a selector dispatch block. |
| 2042 | if (!CatchHandlerMap.count(BB)) { |
| 2043 | if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) { |
| 2044 | CatchHandler *Action = new CatchHandler(BB, Selector, NextBB); |
| 2045 | CatchHandlerMap[BB] = Action; |
| 2046 | return Action; |
| 2047 | } |
Andrew Kaylor | 4175851 | 2015-04-20 22:04:09 +0000 | [diff] [blame] | 2048 | // If we encounter a block containing an llvm.eh.begincatch before we |
| 2049 | // find a selector dispatch block, the handler is assumed to be |
| 2050 | // reached unconditionally. This happens for catch-all blocks, but |
| 2051 | // it can also happen for other catch handlers that have been combined |
| 2052 | // with the catch-all handler during optimization. |
| 2053 | if (isCatchBlock(BB)) { |
| 2054 | PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext()); |
| 2055 | Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy); |
| 2056 | CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr); |
| 2057 | CatchHandlerMap[BB] = Action; |
| 2058 | return Action; |
| 2059 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2060 | } |
| 2061 | |
| 2062 | // Visit each successor, looking for the dispatch. |
| 2063 | // FIXME: We expect to find the dispatch quickly, so this will probably |
| 2064 | // work better as a breadth first search. |
| 2065 | for (BasicBlock *Succ : successors(BB)) { |
| 2066 | if (VisitedBlocks.count(Succ)) |
| 2067 | continue; |
| 2068 | |
| 2069 | CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks); |
| 2070 | if (Action) |
| 2071 | return Action; |
| 2072 | } |
| 2073 | return nullptr; |
| 2074 | } |
| 2075 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2076 | // These are helper functions to combine repeated code from findCleanupHandlers. |
| 2077 | static void createCleanupHandler(LandingPadActions &Actions, |
| 2078 | CleanupHandlerMapTy &CleanupHandlerMap, |
| 2079 | BasicBlock *BB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2080 | CleanupHandler *Action = new CleanupHandler(BB); |
| 2081 | CleanupHandlerMap[BB] = Action; |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2082 | Actions.insertCleanupHandler(Action); |
| 2083 | DEBUG(dbgs() << " Found cleanup code in block " |
| 2084 | << Action->getStartBlock()->getName() << "\n"); |
| 2085 | } |
| 2086 | |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2087 | static CallSite matchOutlinedFinallyCall(BasicBlock *BB, |
| 2088 | Instruction *MaybeCall) { |
| 2089 | // Look for finally blocks that Clang has already outlined for us. |
| 2090 | // %fp = call i8* @llvm.frameaddress(i32 0) |
| 2091 | // call void @"fin$parent"(iN 1, i8* %fp) |
| 2092 | if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator()) |
| 2093 | MaybeCall = MaybeCall->getNextNode(); |
| 2094 | CallSite FinallyCall(MaybeCall); |
| 2095 | if (!FinallyCall || FinallyCall.arg_size() != 2) |
| 2096 | return CallSite(); |
| 2097 | if (!match(FinallyCall.getArgument(0), m_SpecificInt(1))) |
| 2098 | return CallSite(); |
| 2099 | if (!isFrameAddressCall(FinallyCall.getArgument(1))) |
| 2100 | return CallSite(); |
| 2101 | return FinallyCall; |
| 2102 | } |
| 2103 | |
| 2104 | static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) { |
| 2105 | // Skip single ubr blocks. |
| 2106 | while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) { |
| 2107 | auto *Br = dyn_cast<BranchInst>(BB->getTerminator()); |
| 2108 | if (Br && Br->isUnconditional()) |
| 2109 | BB = Br->getSuccessor(0); |
| 2110 | else |
| 2111 | return BB; |
| 2112 | } |
| 2113 | return BB; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2114 | } |
| 2115 | |
| 2116 | // This function searches starting with the input block for the next block that |
| 2117 | // contains code that is not part of a catch handler and would not be eliminated |
| 2118 | // during handler outlining. |
| 2119 | // |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2120 | void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions, |
| 2121 | BasicBlock *StartBB, BasicBlock *EndBB) { |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2122 | // Here we will skip over the following: |
| 2123 | // |
| 2124 | // landing pad prolog: |
| 2125 | // |
| 2126 | // Unconditional branches |
| 2127 | // |
| 2128 | // Selector dispatch |
| 2129 | // |
| 2130 | // Resume pattern |
| 2131 | // |
| 2132 | // Anything else marks the start of an interesting block |
| 2133 | |
| 2134 | BasicBlock *BB = StartBB; |
| 2135 | // Anything other than an unconditional branch will kick us out of this loop |
| 2136 | // one way or another. |
| 2137 | while (BB) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2138 | BB = followSingleUnconditionalBranches(BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2139 | // If we've already scanned this block, don't scan it again. If it is |
| 2140 | // a cleanup block, there will be an action in the CleanupHandlerMap. |
| 2141 | // If we've scanned it and it is not a cleanup block, there will be a |
| 2142 | // nullptr in the CleanupHandlerMap. If we have not scanned it, there will |
| 2143 | // be no entry in the CleanupHandlerMap. We must call count() first to |
| 2144 | // avoid creating a null entry for blocks we haven't scanned. |
| 2145 | if (CleanupHandlerMap.count(BB)) { |
| 2146 | if (auto *Action = CleanupHandlerMap[BB]) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2147 | Actions.insertCleanupHandler(Action); |
| 2148 | DEBUG(dbgs() << " Found cleanup code in block " |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 2149 | << Action->getStartBlock()->getName() << "\n"); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2150 | // FIXME: This cleanup might chain into another, and we need to discover |
| 2151 | // that. |
| 2152 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2153 | } else { |
| 2154 | // Here we handle the case where the cleanup handler map contains a |
| 2155 | // value for this block but the value is a nullptr. This means that |
| 2156 | // we have previously analyzed the block and determined that it did |
| 2157 | // not contain any cleanup code. Based on the earlier analysis, we |
| 2158 | // know the the block must end in either an unconditional branch, a |
| 2159 | // resume or a conditional branch that is predicated on a comparison |
| 2160 | // with a selector. Either the resume or the selector dispatch |
| 2161 | // would terminate the search for cleanup code, so the unconditional |
| 2162 | // branch is the only case for which we might need to continue |
| 2163 | // searching. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2164 | BasicBlock *SuccBB = followSingleUnconditionalBranches(BB); |
| 2165 | if (SuccBB == BB || SuccBB == EndBB) |
| 2166 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2167 | BB = SuccBB; |
| 2168 | continue; |
| 2169 | } |
| 2170 | } |
| 2171 | |
| 2172 | // Create an entry in the cleanup handler map for this block. Initially |
| 2173 | // we create an entry that says this isn't a cleanup block. If we find |
| 2174 | // cleanup code, the caller will replace this entry. |
| 2175 | CleanupHandlerMap[BB] = nullptr; |
| 2176 | |
| 2177 | TerminatorInst *Terminator = BB->getTerminator(); |
| 2178 | |
| 2179 | // Landing pad blocks have extra instructions we need to accept. |
| 2180 | LandingPadMap *LPadMap = nullptr; |
| 2181 | if (BB->isLandingPad()) { |
| 2182 | LandingPadInst *LPad = BB->getLandingPadInst(); |
| 2183 | LPadMap = &LPadMaps[LPad]; |
| 2184 | if (!LPadMap->isInitialized()) |
| 2185 | LPadMap->mapLandingPad(LPad); |
| 2186 | } |
| 2187 | |
| 2188 | // Look for the bare resume pattern: |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2189 | // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0 |
| 2190 | // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1 |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2191 | // resume { i8*, i32 } %lpad.val2 |
| 2192 | if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) { |
| 2193 | InsertValueInst *Insert1 = nullptr; |
| 2194 | InsertValueInst *Insert2 = nullptr; |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2195 | Value *ResumeVal = Resume->getOperand(0); |
Reid Kleckner | 1c130bb | 2015-04-16 17:02:23 +0000 | [diff] [blame] | 2196 | // If the resume value isn't a phi or landingpad value, it should be a |
| 2197 | // series of insertions. Identify them so we can avoid them when scanning |
| 2198 | // for cleanups. |
| 2199 | if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) { |
Reid Kleckner | 0f9e27a | 2015-03-18 20:26:53 +0000 | [diff] [blame] | 2200 | Insert2 = dyn_cast<InsertValueInst>(ResumeVal); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2201 | if (!Insert2) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2202 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2203 | Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand()); |
| 2204 | if (!Insert1) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2205 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2206 | } |
| 2207 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2208 | II != IE; ++II) { |
| 2209 | Instruction *Inst = II; |
| 2210 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2211 | continue; |
| 2212 | if (Inst == Insert1 || Inst == Insert2 || Inst == Resume) |
| 2213 | continue; |
| 2214 | if (!Inst->hasOneUse() || |
| 2215 | (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) { |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2216 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2217 | } |
| 2218 | } |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2219 | return; |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2220 | } |
| 2221 | |
| 2222 | BranchInst *Branch = dyn_cast<BranchInst>(Terminator); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2223 | if (Branch && Branch->isConditional()) { |
| 2224 | // Look for the selector dispatch. |
| 2225 | // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*)) |
| 2226 | // %matches = icmp eq i32 %sel, %2 |
| 2227 | // br i1 %matches, label %catch14, label %eh.resume |
| 2228 | CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition()); |
| 2229 | if (!Compare || !Compare->isEquality()) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2230 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2231 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2232 | II != IE; ++II) { |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2233 | Instruction *Inst = II; |
| 2234 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2235 | continue; |
| 2236 | if (Inst == Compare || Inst == Branch) |
| 2237 | continue; |
| 2238 | if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>())) |
| 2239 | continue; |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2240 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2241 | } |
| 2242 | // The selector dispatch block should always terminate our search. |
| 2243 | assert(BB == EndBB); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2244 | return; |
| 2245 | } |
| 2246 | |
| 2247 | if (isAsynchronousEHPersonality(Personality)) { |
| 2248 | // If this is a landingpad block, split the block at the first non-landing |
| 2249 | // pad instruction. |
| 2250 | Instruction *MaybeCall = BB->getFirstNonPHIOrDbg(); |
| 2251 | if (LPadMap) { |
| 2252 | while (MaybeCall != BB->getTerminator() && |
| 2253 | LPadMap->isLandingPadSpecificInst(MaybeCall)) |
| 2254 | MaybeCall = MaybeCall->getNextNode(); |
| 2255 | } |
| 2256 | |
| 2257 | // Look for outlined finally calls. |
| 2258 | if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) { |
| 2259 | Function *Fin = FinallyCall.getCalledFunction(); |
| 2260 | assert(Fin && "outlined finally call should be direct"); |
| 2261 | auto *Action = new CleanupHandler(BB); |
| 2262 | Action->setHandlerBlockOrFunc(Fin); |
| 2263 | Actions.insertCleanupHandler(Action); |
| 2264 | CleanupHandlerMap[BB] = Action; |
| 2265 | DEBUG(dbgs() << " Found frontend-outlined finally call to " |
| 2266 | << Fin->getName() << " in block " |
| 2267 | << Action->getStartBlock()->getName() << "\n"); |
| 2268 | |
| 2269 | // Split the block if there were more interesting instructions and look |
| 2270 | // for finally calls in the normal successor block. |
| 2271 | BasicBlock *SuccBB = BB; |
| 2272 | if (FinallyCall.getInstruction() != BB->getTerminator() && |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 2273 | FinallyCall.getInstruction()->getNextNode() != |
| 2274 | BB->getTerminator()) { |
| 2275 | SuccBB = |
| 2276 | SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2277 | } else { |
| 2278 | if (FinallyCall.isInvoke()) { |
Andrew Kaylor | 046f7b4 | 2015-04-28 21:54:14 +0000 | [diff] [blame] | 2279 | SuccBB = |
| 2280 | cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest(); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2281 | } else { |
| 2282 | SuccBB = BB->getUniqueSuccessor(); |
Andrew Kaylor | 9130743 | 2015-04-28 22:01:51 +0000 | [diff] [blame] | 2283 | assert(SuccBB && |
| 2284 | "splitOutlinedFinallyCalls didn't insert a branch"); |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2285 | } |
| 2286 | } |
| 2287 | BB = SuccBB; |
| 2288 | if (BB == EndBB) |
| 2289 | return; |
| 2290 | continue; |
| 2291 | } |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2292 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2293 | |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2294 | // Anything else is either a catch block or interesting cleanup code. |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2295 | for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end(); |
| 2296 | II != IE; ++II) { |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2297 | Instruction *Inst = II; |
| 2298 | if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst)) |
| 2299 | continue; |
| 2300 | // Unconditional branches fall through to this loop. |
| 2301 | if (Inst == Branch) |
| 2302 | continue; |
| 2303 | // If this is a catch block, there is no cleanup code to be found. |
| 2304 | if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>())) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2305 | return; |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2306 | // If this a nested landing pad, it may contain an endcatch call. |
| 2307 | if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>())) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2308 | return; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2309 | // Anything else makes this interesting cleanup code. |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2310 | return createCleanupHandler(Actions, CleanupHandlerMap, BB); |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2311 | } |
| 2312 | |
| 2313 | // Only unconditional branches in empty blocks should get this far. |
| 2314 | assert(Branch && Branch->isUnconditional()); |
| 2315 | if (BB == EndBB) |
Reid Kleckner | 9405ef0 | 2015-04-10 23:12:29 +0000 | [diff] [blame] | 2316 | return; |
Andrew Kaylor | 64622aa | 2015-04-01 17:21:25 +0000 | [diff] [blame] | 2317 | BB = Branch->getSuccessor(0); |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2318 | } |
Andrew Kaylor | 6b67d42 | 2015-03-11 23:22:06 +0000 | [diff] [blame] | 2319 | } |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2320 | |
| 2321 | // This is a public function, declared in WinEHFuncInfo.h and is also |
| 2322 | // referenced by WinEHNumbering in FunctionLoweringInfo.cpp. |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2323 | void llvm::parseEHActions( |
| 2324 | const IntrinsicInst *II, |
| 2325 | SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2326 | for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) { |
| 2327 | uint64_t ActionKind = |
Andrew Kaylor | bb11132 | 2015-04-07 21:30:23 +0000 | [diff] [blame] | 2328 | cast<ConstantInt>(II->getArgOperand(I))->getZExtValue(); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2329 | if (ActionKind == /*catch=*/1) { |
| 2330 | auto *Selector = cast<Constant>(II->getArgOperand(I + 1)); |
| 2331 | ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2)); |
| 2332 | int64_t EHObjIndexVal = EHObjIndex->getSExtValue(); |
| 2333 | Constant *Handler = cast<Constant>(II->getArgOperand(I + 3)); |
| 2334 | I += 4; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2335 | auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector, |
| 2336 | /*NextBB=*/nullptr); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2337 | CH->setHandlerBlockOrFunc(Handler); |
| 2338 | CH->setExceptionVarIndex(EHObjIndexVal); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2339 | Actions.push_back(std::move(CH)); |
David Majnemer | 69132a7 | 2015-04-03 22:49:05 +0000 | [diff] [blame] | 2340 | } else if (ActionKind == 0) { |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2341 | Constant *Handler = cast<Constant>(II->getArgOperand(I + 1)); |
| 2342 | I += 2; |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2343 | auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2344 | CH->setHandlerBlockOrFunc(Handler); |
Benjamin Kramer | a48e065 | 2015-05-16 15:40:03 +0000 | [diff] [blame] | 2345 | Actions.push_back(std::move(CH)); |
David Majnemer | 69132a7 | 2015-04-03 22:49:05 +0000 | [diff] [blame] | 2346 | } else { |
| 2347 | llvm_unreachable("Expected either a catch or cleanup handler!"); |
Andrew Kaylor | aa92ab0 | 2015-04-03 19:37:50 +0000 | [diff] [blame] | 2348 | } |
| 2349 | } |
| 2350 | std::reverse(Actions.begin(), Actions.end()); |
| 2351 | } |