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