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