blob: 0d26ed333ca7134928023f870ce50082299c389f [file] [log] [blame]
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass lowers LLVM IR exception handling into something closer to what the
Reid Kleckner0738a9c2015-05-05 17:44:16 +000011// backend wants for functions using a personality function from a runtime
12// provided by MSVC. Functions with other personality functions are left alone
13// and may be prepared by other passes. In particular, all supported MSVC
14// personality functions require cleanup code to be outlined, and the C++
15// personality requires catch handler code to be outlined.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/CodeGen/Passes.h"
20#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000021#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000022#include "llvm/ADT/SmallSet.h"
Reid Klecknerfd7df282015-04-22 21:05:21 +000023#include "llvm/ADT/SetVector.h"
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000024#include "llvm/ADT/Triple.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000025#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Analysis/LibCallSemantics.h"
Reid Klecknerf12c0302015-06-09 21:42:19 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000028#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000029#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/PatternMatch.h"
36#include "llvm/Pass.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000037#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000038#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000039#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000040#include "llvm/Transforms/Utils/Cloning.h"
41#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000042#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000043#include <memory>
44
45using namespace llvm;
46using namespace llvm::PatternMatch;
47
48#define DEBUG_TYPE "winehprepare"
49
50namespace {
51
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000052// This map is used to model frame variable usage during outlining, to
53// construct a structure type to hold the frame variables in a frame
54// allocation block, and to remap the frame variable allocas (including
55// spill locations as needed) to GEPs that get the variable from the
56// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000057typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000058
Reid Kleckner3567d272015-04-02 21:13:31 +000059// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
60// quite null.
61AllocaInst *getCatchObjectSentinel() {
62 return static_cast<AllocaInst *>(nullptr) + 1;
63}
64
Andrew Kaylor6b67d422015-03-11 23:22:06 +000065typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
66
Andrew Kaylor6b67d422015-03-11 23:22:06 +000067class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000068class LandingPadMap;
69
70typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
71typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
72
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000073class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000074public:
75 static char ID; // Pass identification, replacement for typeid.
76 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000077 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000078 if (TM)
Daniel Sanders110bf6d2015-06-24 13:25:57 +000079 TheTriple = TM->getTargetTriple();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000080 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000081
82 bool runOnFunction(Function &Fn) override;
83
84 bool doFinalization(Module &M) override;
85
86 void getAnalysisUsage(AnalysisUsage &AU) const override;
87
88 const char *getPassName() const override {
89 return "Windows exception handling preparation";
90 }
91
92private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000093 bool prepareExceptionHandlers(Function &F,
94 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylora6c5b962015-05-20 23:22:24 +000095 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000096 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000097 void demoteValuesLiveAcrossHandlers(Function &F,
98 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +000099 void findSEHEHReturnPoints(Function &F,
100 SetVector<BasicBlock *> &EHReturnBlocks);
101 void findCXXEHReturnPoints(Function &F,
102 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000103 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
104 SetVector<BasicBlock*> &Targets);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000105 void completeNestedLandingPad(Function *ParentFn,
106 LandingPadInst *OutlinedLPad,
107 const LandingPadInst *OriginalLPad,
108 FrameVarInfoMap &VarInfo);
Reid Kleckner6511c8b2015-07-01 20:59:25 +0000109 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
110 const Twine &Name, Module *M, Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000111 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
112 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000113 FrameVarInfoMap &VarInfo);
David Majnemer7fddecc2015-06-17 20:52:32 +0000114 void addStubInvokeToHandlerIfNeeded(Function *Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000115
116 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
117 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
118 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000119 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
120 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000121
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000122 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
123
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000124 Triple TheTriple;
125
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000126 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000127 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000128 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000129 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000130 CatchHandlerMapTy CatchHandlerMap;
131 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000132 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000133 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
134 SmallPtrSet<BasicBlock *, 4> EHBlocks;
135 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000136
137 // This maps landing pad instructions found in outlined handlers to
138 // the landing pad instruction in the parent function from which they
139 // were cloned. The cloned/nested landing pad is used as the key
140 // because the landing pad may be cloned into multiple handlers.
141 // This map will be used to add the llvm.eh.actions call to the nested
142 // landing pads after all handlers have been outlined.
143 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
144
145 // This maps blocks in the parent function which are destinations of
146 // catch handlers to cloned blocks in (other) outlined handlers. This
147 // handles the case where a nested landing pads has a catch handler that
148 // returns to a handler function rather than the parent function.
149 // The original block is used as the key here because there should only
150 // ever be one handler function from which the cloned block is not pruned.
151 // The original block will be pruned from the parent function after all
152 // handlers have been outlined. This map will be used to adjust the
153 // return instructions of handlers which return to the block that was
154 // outlined into a handler. This is done after all handlers have been
155 // outlined but before the outlined code is pruned from the parent function.
156 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000157
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000158 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000159 // 32-bit EH.
160 DenseMap<Function *, Value *> HandlerToParentFP;
161
Reid Kleckner582786b2015-04-30 18:17:12 +0000162 AllocaInst *SEHExceptionCodeSlot = nullptr;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000163};
164
165class WinEHFrameVariableMaterializer : public ValueMaterializer {
166public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000167 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000168 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000169 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000170
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000171 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000172
Reid Kleckner3567d272015-04-02 21:13:31 +0000173 void escapeCatchObject(Value *V);
174
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000175private:
176 FrameVarInfoMap &FrameVarInfo;
177 IRBuilder<> Builder;
178};
179
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000180class LandingPadMap {
181public:
182 LandingPadMap() : OriginLPad(nullptr) {}
183 void mapLandingPad(const LandingPadInst *LPad);
184
185 bool isInitialized() { return OriginLPad != nullptr; }
186
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000187 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000188 bool isLandingPadSpecificInst(const Instruction *Inst) const;
189
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000190 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
191 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000192
193private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000194 const LandingPadInst *OriginLPad;
195 // We will normally only see one of each of these instructions, but
196 // if more than one occurs for some reason we can handle that.
197 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
198 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000199};
200
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000201class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000202public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000203 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
204 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
205 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000206 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
207 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000208 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000209
210 CloningAction handleInstruction(ValueToValueMapTy &VMap,
211 const Instruction *Inst,
212 BasicBlock *NewBB) override;
213
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000214 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
215 const Instruction *Inst,
216 BasicBlock *NewBB) = 0;
217 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
218 const Instruction *Inst,
219 BasicBlock *NewBB) = 0;
220 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
221 const Instruction *Inst,
222 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000223 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
224 const IndirectBrInst *IBr,
225 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000226 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
227 const InvokeInst *Invoke,
228 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000229 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
230 const ResumeInst *Resume,
231 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000232 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
233 const CmpInst *Compare,
234 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000235 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
236 const LandingPadInst *LPad,
237 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000238
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000239 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
240
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000241protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000242 WinEHFrameVariableMaterializer Materializer;
243 Type *SelectorIDType;
244 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000245 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000246
247 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000248 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000249};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000250
251class WinEHCatchDirector : public WinEHCloningDirectorBase {
252public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000253 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000254 Function *CatchFn, Value *ParentFP, Value *Selector,
255 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000256 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
257 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000258 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000259 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000260 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
261 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000262
263 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
264 const Instruction *Inst,
265 BasicBlock *NewBB) override;
266 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
267 BasicBlock *NewBB) override;
268 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
269 const Instruction *Inst,
270 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000271 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
272 const IndirectBrInst *IBr,
273 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000274 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
275 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000276 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
277 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000278 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
279 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000280 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
281 const LandingPadInst *LPad,
282 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000283
Reid Kleckner3567d272015-04-02 21:13:31 +0000284 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000285 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
286
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000287private:
288 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000289
Reid Kleckner3567d272015-04-02 21:13:31 +0000290 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000291 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000292
293 // This will be a reference to the field of the same name in the WinEHPrepare
294 // object which instantiates this WinEHCatchDirector object.
295 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000296 DominatorTree *DT;
297 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000298};
299
300class WinEHCleanupDirector : public WinEHCloningDirectorBase {
301public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000302 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
303 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
304 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
305 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000306
307 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
308 const Instruction *Inst,
309 BasicBlock *NewBB) override;
310 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
311 BasicBlock *NewBB) override;
312 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
313 const Instruction *Inst,
314 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000315 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
316 const IndirectBrInst *IBr,
317 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000318 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
319 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000320 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
321 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000322 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
323 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000324 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
325 const LandingPadInst *LPad,
326 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000327};
328
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000329class LandingPadActions {
330public:
331 LandingPadActions() : HasCleanupHandlers(false) {}
332
333 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
334 void insertCleanupHandler(CleanupHandler *Action) {
335 Actions.push_back(Action);
336 HasCleanupHandlers = true;
337 }
338
339 bool includesCleanup() const { return HasCleanupHandlers; }
340
David Majnemercde33032015-03-30 22:58:10 +0000341 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000342 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
343 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
344
345private:
346 // Note that this class does not own the ActionHandler objects in this vector.
347 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
348 // in the WinEHPrepare class.
349 SmallVector<ActionHandler *, 4> Actions;
350 bool HasCleanupHandlers;
351};
352
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000353} // end anonymous namespace
354
355char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000356INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
357 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000358
359FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
360 return new WinEHPrepare(TM);
361}
362
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000363bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemere4abcef2015-08-06 21:07:55 +0000364 // No need to prepare outlined handlers.
365 if (Fn.hasFnAttribute("wineh-parent"))
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000366 return false;
367
David Majnemer09e1fdb2015-08-06 21:13:51 +0000368 SmallVector<LandingPadInst *, 4> LPads;
369 SmallVector<ResumeInst *, 4> Resumes;
370 for (BasicBlock &BB : Fn) {
371 if (auto *LP = BB.getLandingPadInst())
372 LPads.push_back(LP);
373 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
374 Resumes.push_back(Resume);
375 }
376
377 // No need to prepare functions that lack landing pads.
378 if (LPads.empty())
379 return false;
380
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000381 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000382 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000383
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000384 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000385 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000386 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000387
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000388 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000389 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000390
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000391 // If there were any landing pads, prepareExceptionHandlers will make changes.
392 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000393 return true;
394}
395
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000396bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000397
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000398void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
399 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000400 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000401}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000402
Reid Klecknerfd7df282015-04-22 21:05:21 +0000403static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
404 Constant *&Selector, BasicBlock *&NextBB);
405
406// Finds blocks reachable from the starting set Worklist. Does not follow unwind
407// edges or blocks listed in StopPoints.
408static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
409 SetVector<BasicBlock *> &Worklist,
410 const SetVector<BasicBlock *> *StopPoints) {
411 while (!Worklist.empty()) {
412 BasicBlock *BB = Worklist.pop_back_val();
413
414 // Don't cross blocks that we should stop at.
415 if (StopPoints && StopPoints->count(BB))
416 continue;
417
418 if (!ReachableBBs.insert(BB).second)
419 continue; // Already visited.
420
421 // Don't follow unwind edges of invokes.
422 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
423 Worklist.insert(II->getNormalDest());
424 continue;
425 }
426
427 // Otherwise, follow all successors.
428 Worklist.insert(succ_begin(BB), succ_end(BB));
429 }
430}
431
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000432// Attempt to find an instruction where a block can be split before
433// a call to llvm.eh.begincatch and its operands. If the block
434// begins with the begincatch call or one of its adjacent operands
435// the block will not be split.
436static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
437 IntrinsicInst *II) {
438 // If the begincatch call is already the first instruction in the block,
439 // don't split.
440 Instruction *FirstNonPHI = BB->getFirstNonPHI();
441 if (II == FirstNonPHI)
442 return nullptr;
443
444 // If either operand is in the same basic block as the instruction and
445 // isn't used by another instruction before the begincatch call, include it
446 // in the split block.
447 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
448 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
449
450 Instruction *I = II->getPrevNode();
451 Instruction *LastI = II;
452
453 while (I == Op0 || I == Op1) {
454 // If the block begins with one of the operands and there are no other
455 // instructions between the operand and the begincatch call, don't split.
456 if (I == FirstNonPHI)
457 return nullptr;
458
459 LastI = I;
460 I = I->getPrevNode();
461 }
462
463 // If there is at least one instruction in the block before the begincatch
464 // call and its operands, split the block at either the begincatch or
465 // its operand.
466 return LastI;
467}
468
Reid Klecknerfd7df282015-04-22 21:05:21 +0000469/// Find all points where exceptional control rejoins normal control flow via
470/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000471void WinEHPrepare::findCXXEHReturnPoints(
472 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000473 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
474 BasicBlock *BB = BBI;
475 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000476 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000477 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000478 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
479 if (SplitPt) {
480 // Split the block before the llvm.eh.begincatch call to allow
481 // cleanup and catch code to be distinguished later.
482 // Do not update BBI because we still need to process the
483 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000484 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000485 break;
486 }
487 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000488 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
489 // Split the block after the call to llvm.eh.endcatch if there is
490 // anything other than an unconditional branch, or if the successor
491 // starts with a phi.
492 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
493 if (!Br || !Br->isUnconditional() ||
494 isa<PHINode>(Br->getSuccessor(0)->begin())) {
495 DEBUG(dbgs() << "splitting block " << BB->getName()
496 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000497 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000498 }
499 // The next BB is normal control flow.
500 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
501 break;
502 }
503 }
504 }
505}
506
507static bool isCatchAllLandingPad(const BasicBlock *BB) {
508 const LandingPadInst *LP = BB->getLandingPadInst();
509 if (!LP)
510 return false;
511 unsigned N = LP->getNumClauses();
512 return (N > 0 && LP->isCatch(N - 1) &&
513 isa<ConstantPointerNull>(LP->getClause(N - 1)));
514}
515
516/// Find all points where exceptions control rejoins normal control flow via
517/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000518void WinEHPrepare::findSEHEHReturnPoints(
519 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000520 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
521 BasicBlock *BB = BBI;
522 // If the landingpad is a catch-all, treat the whole lpad as if it is
523 // reachable from normal control flow.
524 // FIXME: This is imprecise. We need a better way of identifying where a
525 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
526 // is no difference.
527 if (isCatchAllLandingPad(BB)) {
528 EHReturnBlocks.insert(BB);
529 continue;
530 }
531
532 BasicBlock *CatchHandler;
533 BasicBlock *NextBB;
534 Constant *Selector;
535 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000536 // Split the edge if there are multiple predecessors. This creates a place
537 // where we can insert EH recovery code.
538 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000539 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
540 << " to " << CatchHandler->getName() << '\n');
541 BBI = CatchHandler = SplitCriticalEdge(
542 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
543 }
544 EHReturnBlocks.insert(CatchHandler);
545 }
546 }
547}
548
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000549void WinEHPrepare::identifyEHBlocks(Function &F,
550 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000551 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
552 << F.getName() << '\n');
553
554 // Build a set of all non-exceptional blocks and exceptional blocks.
555 // - Non-exceptional blocks are blocks reachable from the entry block while
556 // not following invoke unwind edges.
557 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
558 // not follow llvm.eh.endcatch blocks, which mark a transition from
559 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000560
561 if (Personality == EHPersonality::MSVC_CXX)
562 findCXXEHReturnPoints(F, EHReturnBlocks);
563 else
564 findSEHEHReturnPoints(F, EHReturnBlocks);
565
566 DEBUG({
567 dbgs() << "identified the following blocks as EH return points:\n";
568 for (BasicBlock *BB : EHReturnBlocks)
569 dbgs() << " " << BB->getName() << '\n';
570 });
571
Andrew Kaylor91307432015-04-28 22:01:51 +0000572// Join points should not have phis at this point, unless they are a
573// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000574#ifndef NDEBUG
575 for (BasicBlock *BB : EHReturnBlocks)
576 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
577 "non-lpad EH return block has phi");
578#endif
579
580 // Normal blocks are the blocks reachable from the entry block and all EH
581 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000582 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000583 Worklist = EHReturnBlocks;
584 Worklist.insert(&F.getEntryBlock());
585 findReachableBlocks(NormalBlocks, Worklist, nullptr);
586 DEBUG({
587 dbgs() << "marked the following blocks as normal:\n";
588 for (BasicBlock *BB : NormalBlocks)
589 dbgs() << " " << BB->getName() << '\n';
590 });
591
592 // Exceptional blocks are the blocks reachable from landingpads that don't
593 // cross EH return points.
594 Worklist.clear();
595 for (auto *LPI : LPads)
596 Worklist.insert(LPI->getParent());
597 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
598 DEBUG({
599 dbgs() << "marked the following blocks as exceptional:\n";
600 for (BasicBlock *BB : EHBlocks)
601 dbgs() << " " << BB->getName() << '\n';
602 });
603
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000604}
605
606/// Ensure that all values live into and out of exception handlers are stored
607/// in memory.
608/// FIXME: This falls down when values are defined in one handler and live into
609/// another handler. For example, a cleanup defines a value used only by a
610/// catch handler.
611void WinEHPrepare::demoteValuesLiveAcrossHandlers(
612 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
613 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
614 << F.getName() << '\n');
615
616 // identifyEHBlocks() should have been called before this function.
617 assert(!NormalBlocks.empty());
618
Reid Kleckner7ea77082015-07-10 22:21:54 +0000619 // Try to avoid demoting EH pointer and selector values. They get in the way
620 // of our pattern matching.
621 SmallPtrSet<Instruction *, 10> EHVals;
622 for (BasicBlock &BB : F) {
623 LandingPadInst *LP = BB.getLandingPadInst();
624 if (!LP)
625 continue;
626 EHVals.insert(LP);
627 for (User *U : LP->users()) {
628 auto *EI = dyn_cast<ExtractValueInst>(U);
629 if (!EI)
630 continue;
631 EHVals.insert(EI);
632 for (User *U2 : EI->users()) {
633 if (auto *PN = dyn_cast<PHINode>(U2))
634 EHVals.insert(PN);
635 }
636 }
637 }
638
Reid Klecknerfd7df282015-04-22 21:05:21 +0000639 SetVector<Argument *> ArgsToDemote;
640 SetVector<Instruction *> InstrsToDemote;
641 for (BasicBlock &BB : F) {
642 bool IsNormalBB = NormalBlocks.count(&BB);
643 bool IsEHBB = EHBlocks.count(&BB);
644 if (!IsNormalBB && !IsEHBB)
645 continue; // Blocks that are neither normal nor EH are unreachable.
646 for (Instruction &I : BB) {
647 for (Value *Op : I.operands()) {
648 // Don't demote static allocas, constants, and labels.
649 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
650 continue;
651 auto *AI = dyn_cast<AllocaInst>(Op);
652 if (AI && AI->isStaticAlloca())
653 continue;
654
655 if (auto *Arg = dyn_cast<Argument>(Op)) {
656 if (IsEHBB) {
657 DEBUG(dbgs() << "Demoting argument " << *Arg
658 << " used by EH instr: " << I << "\n");
659 ArgsToDemote.insert(Arg);
660 }
661 continue;
662 }
663
Reid Kleckner7ea77082015-07-10 22:21:54 +0000664 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000665 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000666 if (EHVals.count(OpI))
667 continue;
668
Reid Klecknerfd7df282015-04-22 21:05:21 +0000669 BasicBlock *OpBB = OpI->getParent();
670 // If a value is produced and consumed in the same BB, we don't need to
671 // demote it.
672 if (OpBB == &BB)
673 continue;
674 bool IsOpNormalBB = NormalBlocks.count(OpBB);
675 bool IsOpEHBB = EHBlocks.count(OpBB);
676 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
677 DEBUG({
678 dbgs() << "Demoting instruction live in-out from EH:\n";
679 dbgs() << "Instr: " << *OpI << '\n';
680 dbgs() << "User: " << I << '\n';
681 });
682 InstrsToDemote.insert(OpI);
683 }
684 }
685 }
686 }
687
688 // Demote values live into and out of handlers.
689 // FIXME: This demotion is inefficient. We should insert spills at the point
690 // of definition, insert one reload in each handler that uses the value, and
691 // insert reloads in the BB used to rejoin normal control flow.
692 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
693 for (Instruction *I : InstrsToDemote)
694 DemoteRegToStack(*I, false, AllocaInsertPt);
695
696 // Demote arguments separately, and only for uses in EH blocks.
697 for (Argument *Arg : ArgsToDemote) {
698 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
699 Arg->getName() + ".reg2mem", AllocaInsertPt);
700 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
701 for (User *U : Users) {
702 auto *I = dyn_cast<Instruction>(U);
703 if (I && EHBlocks.count(I->getParent())) {
704 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
705 U->replaceUsesOfWith(Arg, Reload);
706 }
707 }
708 new StoreInst(Arg, Slot, AllocaInsertPt);
709 }
710
711 // Demote landingpad phis, as the landingpad will be removed from the machine
712 // CFG.
713 for (LandingPadInst *LPI : LPads) {
714 BasicBlock *BB = LPI->getParent();
715 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
716 DemotePHIToStack(Phi, AllocaInsertPt);
717 }
718
719 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
720 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
721}
722
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000723bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000724 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000725 // Don't run on functions that are already prepared.
726 for (LandingPadInst *LPad : LPads) {
727 BasicBlock *LPadBB = LPad->getParent();
728 for (Instruction &Inst : *LPadBB)
729 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
730 return false;
731 }
732
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000733 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000734 demoteValuesLiveAcrossHandlers(F, LPads);
735
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000736 // These containers are used to re-map frame variables that are used in
737 // outlined catch and cleanup handlers. They will be populated as the
738 // handlers are outlined.
739 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000740
741 bool HandlersOutlined = false;
742
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000743 Module *M = F.getParent();
744 LLVMContext &Context = M->getContext();
745
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000746 // Create a new function to receive the handler contents.
747 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
748 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000749 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000750
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000751 if (isAsynchronousEHPersonality(Personality)) {
752 // FIXME: Switch the ehptr type to i32 and then switch this.
753 SEHExceptionCodeSlot =
754 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
755 F.getEntryBlock().getFirstInsertionPt());
756 }
757
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000758 // In order to handle the case where one outlined catch handler returns
759 // to a block within another outlined catch handler that would otherwise
760 // be unreachable, we need to outline the nested landing pad before we
761 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000762 if (!isAsynchronousEHPersonality(Personality))
763 std::sort(LPads.begin(), LPads.end(),
764 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
765 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000766 });
767
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000768 // This container stores the llvm.eh.recover and IndirectBr instructions
769 // that make up the body of each landing pad after it has been outlined.
770 // We need to defer the population of the target list for the indirectbr
771 // until all landing pads have been outlined so that we can handle the
772 // case of blocks in the target that are reached only from nested
773 // landing pads.
774 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
775
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000776 for (LandingPadInst *LPad : LPads) {
777 // Look for evidence that this landingpad has already been processed.
778 bool LPadHasActionList = false;
779 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000780 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000781 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
782 LPadHasActionList = true;
783 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000784 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000785 }
786
787 // If we've already outlined the handlers for this landingpad,
788 // there's nothing more to do here.
789 if (LPadHasActionList)
790 continue;
791
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000792 // If either of the values in the aggregate returned by the landing pad is
793 // extracted and stored to memory, promote the stored value to a register.
794 promoteLandingPadValues(LPad);
795
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000796 LandingPadActions Actions;
797 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000798
Reid Kleckner9405ef02015-04-10 23:12:29 +0000799 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000800 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000801 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000802 continue;
803 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000804
805 // SEH doesn't do any outlining for catches. Instead, pass the handler
806 // basic block addr to llvm.eh.actions and list the block as a return
807 // target.
808 if (isAsynchronousEHPersonality(Personality)) {
809 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
810 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000811 continue;
812 }
813 }
814
Reid Kleckner9405ef02015-04-10 23:12:29 +0000815 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
816 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000817
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000818 // Split the block after the landingpad instruction so that it is just a
819 // call to llvm.eh.actions followed by indirectbr.
820 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000821 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000822 // Erase the branch inserted by the split so we can insert indirectbr.
823 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000824
Reid Klecknere3af86e2015-04-23 21:22:30 +0000825 // Replace all extracted values with undef and ultimately replace the
826 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000827 SmallVector<Instruction *, 4> SEHCodeUses;
828 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000829 for (User *U : LPad->users()) {
830 auto *E = dyn_cast<ExtractValueInst>(U);
831 if (!E)
832 continue;
833 assert(E->getNumIndices() == 1 &&
834 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000835 unsigned Idx = *E->idx_begin();
836 assert((Idx == 0 || Idx == 1) && "unexpected index");
837 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
838 SEHCodeUses.push_back(E);
839 else
840 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000841 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000842 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000843 E->replaceAllUsesWith(UndefValue::get(E->getType()));
844 E->eraseFromParent();
845 }
846 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000847
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000848 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000849 while (!SEHCodeUses.empty()) {
850 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000851 SmallVector<Use *, 4> Uses;
852 for (Use &U : E->uses())
853 Uses.push_back(&U);
854 for (Use *U : Uses) {
855 auto *I = cast<Instruction>(U->getUser());
856 if (isa<ResumeInst>(I))
857 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000858 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000859 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000860 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000861 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000862 }
863 E->replaceAllUsesWith(UndefValue::get(E->getType()));
864 E->eraseFromParent();
865 }
866
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000867 // Add a call to describe the actions for this landing pad.
868 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000869 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000870 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000871 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000872 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000873 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000874 // Find the frame escape index of the exception object alloca in the
875 // parent.
876 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000877 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000878 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
879 auto I = FrameVarInfo.find(EHObj);
880 assert(I != FrameVarInfo.end() &&
881 "failed to map llvm.eh.begincatch var");
882 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
883 }
884 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000885 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000886 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000887 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000888 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000889 }
890 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000891 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000892
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000893 SetVector<BasicBlock *> ReturnTargets;
894 for (ActionHandler *Action : Actions) {
895 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
896 const auto &CatchTargets = CatchAction->getReturnTargets();
897 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000898 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000899 }
900 IndirectBrInst *Branch =
901 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
902 for (BasicBlock *Target : ReturnTargets)
903 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000904
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000905 if (!isAsynchronousEHPersonality(Personality)) {
906 // C++ EH must repopulate the targets later to handle the case of
907 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000908 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000909 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000910
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000911 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000912
913 // If nothing got outlined, there is no more processing to be done.
914 if (!HandlersOutlined)
915 return false;
916
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000917 // Replace any nested landing pad stubs with the correct action handler.
918 // This must be done before we remove unreachable blocks because it
919 // cleans up references to outlined blocks that will be deleted.
920 for (auto &LPadPair : NestedLPtoOriginalLP)
921 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000922 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000923
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000924 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000925 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000926 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000927 for (auto &LPadImplPair : LPadImpls) {
928 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
929 IndirectBrInst *Branch = LPadImplPair.second;
930
931 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000932 parseEHActions(Recover, ActionList);
933
934 // Add an indirect branch listing possible successors of the catch handlers.
935 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000936 for (const auto &Action : ActionList) {
937 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000938 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
939 getPossibleReturnTargets(&F, Handler, ReturnTargets);
940 }
941 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000942 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000943 // Clear any targets we already knew about.
944 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
945 BasicBlock *KnownTarget = Branch->getDestination(I);
946 if (ReturnTargets.count(KnownTarget))
947 ReturnTargets.remove(KnownTarget);
948 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000949 for (BasicBlock *Target : ReturnTargets) {
950 Branch->addDestination(Target);
951 // The target may be a block that we excepted to get pruned.
952 // If it is, it may contain a call to llvm.eh.endcatch.
953 if (CheckedTargets.insert(Target)) {
954 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
955 // will be followed by an unconditional branch.
956 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
957 if (Br && Br->isUnconditional() &&
958 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
959 Instruction *Prev = Br->getPrevNode();
960 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
961 Prev->eraseFromParent();
962 }
963 }
964 }
965 }
966 LPadImpls.clear();
967
David Majnemercde33032015-03-30 22:58:10 +0000968 F.addFnAttr("wineh-parent", F.getName());
969
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000970 // Delete any blocks that were only used by handlers that were outlined above.
971 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000972
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000973 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000974 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000975 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000976
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000977 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +0000978 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000979 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +0000980 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +0000981 SmallVector<Value *, 8> AllocasToEscape;
982
Reid Kleckner60381792015-07-07 22:25:32 +0000983 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +0000984 // keep escaping those objects.
985 for (Instruction &I : F.front()) {
986 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +0000987 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +0000988 auto Args = II->arg_operands();
989 AllocasToEscape.append(Args.begin(), Args.end());
990 II->eraseFromParent();
991 break;
992 }
993 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000994
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000995 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +0000996 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000997 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000998 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000999 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001000 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001001
Reid Klecknerb4019412015-04-06 18:50:38 +00001002 // FIXME: We should try to sink unescaped allocas from the parent frame into
1003 // the child frame. If the alloca is escaped, we have to use the lifetime
1004 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001005
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001006 // Add this alloca to the list of things to escape.
1007 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001008
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001009 // Next replace all outlined allocas that are mapped to it.
1010 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001011 if (TempAlloca == getCatchObjectSentinel())
1012 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001013 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001014 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1015 assert(FP);
1016
Reid Kleckner60381792015-07-07 22:25:32 +00001017 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001018 Builder.SetInsertPoint(TempAlloca);
1019 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1020 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001021 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001022 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001023 Instruction *RecoveredAlloca =
1024 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1025
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001026 // Add a pointer bitcast if the alloca wasn't an i8.
1027 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1028 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001029 RecoveredAlloca = cast<Instruction>(
1030 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001031 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001032 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1033 TempAlloca->removeFromParent();
1034 RecoveredAlloca->takeName(TempAlloca);
1035 delete TempAlloca;
1036 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001037 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001038
Reid Kleckner60381792015-07-07 22:25:32 +00001039 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001040 // block.
1041 Builder.SetInsertPoint(&F.getEntryBlock().back());
1042 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1043
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001044 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001045 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1046 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1047 for (User *U : SEHExceptionCodeSlot->users()) {
1048 if (auto *Inst = dyn_cast<Instruction>(U))
1049 UserBlocks.insert(Inst->getParent());
1050 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001051 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001052 // After the promotion, kill off dead instructions.
1053 for (BasicBlock *BB : UserBlocks)
1054 SimplifyInstructionsInBlock(BB, LibInfo);
1055 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001056 }
1057
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001058 // Clean up the handler action maps we created for this function
1059 DeleteContainerSeconds(CatchHandlerMap);
1060 CatchHandlerMap.clear();
1061 DeleteContainerSeconds(CleanupHandlerMap);
1062 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001063 HandlerToParentFP.clear();
1064 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001065 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001066 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001067 EHBlocks.clear();
1068 NormalBlocks.clear();
1069 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001070
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001071 return HandlersOutlined;
1072}
1073
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001074void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1075 // If the return values of the landing pad instruction are extracted and
1076 // stored to memory, we want to promote the store locations to reg values.
1077 SmallVector<AllocaInst *, 2> EHAllocas;
1078
1079 // The landingpad instruction returns an aggregate value. Typically, its
1080 // value will be passed to a pair of extract value instructions and the
1081 // results of those extracts are often passed to store instructions.
1082 // In unoptimized code the stored value will often be loaded and then stored
1083 // again.
1084 for (auto *U : LPad->users()) {
1085 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1086 if (!Extract)
1087 continue;
1088
1089 for (auto *EU : Extract->users()) {
1090 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1091 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1092 EHAllocas.push_back(AV);
1093 }
1094 }
1095 }
1096
1097 // We can't do this without a dominator tree.
1098 assert(DT);
1099
1100 if (!EHAllocas.empty()) {
1101 PromoteMemToReg(EHAllocas, *DT);
1102 EHAllocas.clear();
1103 }
Reid Kleckner86762142015-04-16 00:02:04 +00001104
1105 // After promotion, some extracts may be trivially dead. Remove them.
1106 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1107 for (auto *U : Users)
1108 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001109}
1110
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001111void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1112 Function *HandlerF,
1113 SetVector<BasicBlock*> &Targets) {
1114 for (BasicBlock &BB : *HandlerF) {
1115 // If the handler contains landing pads, check for any
1116 // handlers that may return directly to a block in the
1117 // parent function.
1118 if (auto *LPI = BB.getLandingPadInst()) {
1119 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001120 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001121 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001122 for (const auto &Action : ActionList) {
1123 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001124 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1125 getPossibleReturnTargets(ParentF, NestedF, Targets);
1126 }
1127 }
1128 }
1129
1130 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1131 if (!Ret)
1132 continue;
1133
1134 // Handler functions must always return a block address.
1135 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1136
1137 // If this is the handler for a nested landing pad, the
1138 // return address may have been remapped to a block in the
1139 // parent handler. We're not interested in those.
1140 if (BA->getFunction() != ParentF)
1141 continue;
1142
1143 Targets.insert(BA->getBasicBlock());
1144 }
1145}
1146
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001147void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1148 LandingPadInst *OutlinedLPad,
1149 const LandingPadInst *OriginalLPad,
1150 FrameVarInfoMap &FrameVarInfo) {
1151 // Get the nested block and erase the unreachable instruction that was
1152 // temporarily inserted as its terminator.
1153 LLVMContext &Context = ParentFn->getContext();
1154 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001155 // If the nested landing pad was outlined before the landing pad that enclosed
1156 // it, it will already be in outlined form. In that case, we just need to see
1157 // if the returns and the enclosing branch instruction need to be updated.
1158 IndirectBrInst *Branch =
1159 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1160 if (!Branch) {
1161 // If the landing pad wasn't in outlined form, it should be a stub with
1162 // an unreachable terminator.
1163 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1164 OutlinedBB->getTerminator()->eraseFromParent();
1165 // That should leave OutlinedLPad as the last instruction in its block.
1166 assert(&OutlinedBB->back() == OutlinedLPad);
1167 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001168
1169 // The original landing pad will have already had its action intrinsic
1170 // built by the outlining loop. We need to clone that into the outlined
1171 // location. It may also be necessary to add references to the exception
1172 // variables to the outlined handler in which this landing pad is nested
1173 // and remap return instructions in the nested handlers that should return
1174 // to an address in the outlined handler.
1175 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001176 BasicBlock::const_iterator II = OriginalLPad;
1177 ++II;
1178 // The instruction after the landing pad should now be a call to eh.actions.
1179 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001180 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001181
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001182 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001183 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001184 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001185 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001186 for (const auto &Action : ActionList) {
1187 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001188 if (!Catch)
1189 continue;
1190 // The dyn_cast to function here selects C++ catch handlers and skips
1191 // SEH catch handlers.
1192 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1193 if (!Handler)
1194 continue;
1195 // Visit all the return instructions, looking for places that return
1196 // to a location within OutlinedHandlerFn.
1197 for (BasicBlock &NestedHandlerBB : *Handler) {
1198 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1199 if (!Ret)
1200 continue;
1201
1202 // Handler functions must always return a block address.
1203 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1204 // The original target will have been in the main parent function,
1205 // but if it is the address of a block that has been outlined, it
1206 // should be a block that was outlined into OutlinedHandlerFn.
1207 assert(BA->getFunction() == ParentFn);
1208
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001209 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001210 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1211 continue;
1212
1213 // If the return value is the address ofF a block that we
1214 // previously outlined into the parent handler function, replace
1215 // the return instruction and add the mapped target to the list
1216 // of possible return addresses.
1217 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1218 assert(MappedBB->getParent() == OutlinedHandlerFn);
1219 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1220 Ret->eraseFromParent();
1221 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1222 ActionTargets.push_back(NewBA);
1223 }
1224 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001225 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001226
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001227 if (Branch) {
1228 // If the landing pad was already in outlined form, just update its targets.
1229 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1230 Branch->removeDestination(I);
1231 // Add the previously collected action targets.
1232 for (auto *Target : ActionTargets)
1233 Branch->addDestination(Target->getBasicBlock());
1234 } else {
1235 // If the landing pad was previously stubbed out, fill in its outlined form.
1236 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1237 OutlinedBB->getInstList().push_back(NewEHActions);
1238
1239 // Insert an indirect branch into the outlined landing pad BB.
1240 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1241 // Add the previously collected action targets.
1242 for (auto *Target : ActionTargets)
1243 IBr->addDestination(Target->getBasicBlock());
1244 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001245}
1246
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001247// This function examines a block to determine whether the block ends with a
1248// conditional branch to a catch handler based on a selector comparison.
1249// This function is used both by the WinEHPrepare::findSelectorComparison() and
1250// WinEHCleanupDirector::handleTypeIdFor().
1251static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1252 Constant *&Selector, BasicBlock *&NextBB) {
1253 ICmpInst::Predicate Pred;
1254 BasicBlock *TBB, *FBB;
1255 Value *LHS, *RHS;
1256
1257 if (!match(BB->getTerminator(),
1258 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1259 return false;
1260
1261 if (!match(LHS,
1262 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1263 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1264 return false;
1265
1266 if (Pred == CmpInst::ICMP_EQ) {
1267 CatchHandler = TBB;
1268 NextBB = FBB;
1269 return true;
1270 }
1271
1272 if (Pred == CmpInst::ICMP_NE) {
1273 CatchHandler = FBB;
1274 NextBB = TBB;
1275 return true;
1276 }
1277
1278 return false;
1279}
1280
Andrew Kaylor41758512015-04-20 22:04:09 +00001281static bool isCatchBlock(BasicBlock *BB) {
1282 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1283 II != IE; ++II) {
1284 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1285 return true;
1286 }
1287 return false;
1288}
1289
David Majnemer7fddecc2015-06-17 20:52:32 +00001290static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001291 // FIXME: Finish this!
1292 LLVMContext &Context = Handler->getContext();
1293 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1294 Handler->getBasicBlockList().push_back(StubBB);
1295 IRBuilder<> Builder(StubBB);
1296 LandingPadInst *LPad = Builder.CreateLandingPad(
1297 llvm::StructType::get(Type::getInt8PtrTy(Context),
1298 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001299 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001300 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001301 Function *ActionIntrin =
1302 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001303 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001304 LPad->setCleanup(true);
1305 Builder.CreateUnreachable();
1306 return StubBB;
1307}
1308
1309// Cycles through the blocks in an outlined handler function looking for an
1310// invoke instruction and inserts an invoke of llvm.donothing with an empty
1311// landing pad if none is found. The code that generates the .xdata tables for
1312// the handler needs at least one landing pad to identify the parent function's
1313// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001314void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001315 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001316 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001317 for (BasicBlock &BB : *Handler) {
1318 TerminatorInst *Terminator = BB.getTerminator();
1319 // If we find an invoke, there is nothing to be done.
1320 auto *II = dyn_cast<InvokeInst>(Terminator);
1321 if (II)
1322 return;
1323 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001324 if (!Ret)
1325 Ret = dyn_cast<ReturnInst>(Terminator);
1326 // If we haven't recorded an unreachable instruction, try this terminator.
1327 if (!Unreached)
1328 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001329 }
1330
1331 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001332 // at least one return or unreachable instruction. We'll insert an invoke of
1333 // llvm.donothing ahead of that instruction.
1334 assert(Ret || Unreached);
1335 TerminatorInst *Term;
1336 if (Ret)
1337 Term = Ret;
1338 else
1339 Term = Unreached;
1340 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001341 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001342 // SplitBlock adds an unconditional branch instruction at the end of the
1343 // parent block. We want to replace that with an invoke call, so we can
1344 // erase it now.
1345 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001346 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001347 Function *F =
1348 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1349 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1350}
1351
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001352// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1353// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001354Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1355 const Twine &Name, Module *M,
1356 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001357 // x64 uses a two-argument prototype where the parent FP is the second
1358 // argument. x86 uses no arguments, just the incoming EBP value.
1359 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001360 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001361 FunctionType *FnType;
1362 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001363 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1364 FnType = FunctionType::get(RetTy, ArgTys, false);
1365 } else {
1366 FnType = FunctionType::get(RetTy, None, false);
1367 }
1368
1369 Function *Handler =
1370 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1371 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1372 Handler->getBasicBlockList().push_front(Entry);
1373 if (TheTriple.getArch() == Triple::x86_64) {
1374 ParentFP = &(Handler->getArgumentList().back());
1375 } else {
1376 assert(M);
1377 Function *FrameAddressFn =
1378 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001379 Function *RecoverFPFn =
1380 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1381 IRBuilder<> Builder(&Handler->getEntryBlock());
1382 Value *EBP =
1383 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1384 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1385 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001386 }
1387 return Handler;
1388}
1389
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001390bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1391 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001392 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001393 Module *M = SrcFn->getParent();
1394 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001395 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001396
1397 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001398 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001399 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001400 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001401 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001402 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001403 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001404 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001405 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001406 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001407 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001408 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001409 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001410 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001411
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001412 // Generate a standard prolog to setup the frame recovery structure.
1413 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001414 Builder.SetInsertPoint(Entry);
1415 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1416
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001417 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001418
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001419 ValueToValueMapTy VMap;
1420
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001421 LandingPadMap &LPadMap = LPadMaps[LPad];
1422 if (!LPadMap.isInitialized())
1423 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001424 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1425 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001426 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1427 LPadMap, NestedLPtoOriginalLP, DT,
1428 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001429 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1430 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001431 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001432 Director.reset(
1433 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001434 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1435 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001436 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001437
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001438 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001439 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001440
Andrew Kaylor3170e562015-03-20 21:42:54 +00001441 // If the start block contains PHI nodes, we need to map them.
1442 BasicBlock::iterator II = StartBB->begin();
1443 while (auto *PN = dyn_cast<PHINode>(II)) {
1444 bool Mapped = false;
1445 // Look for PHI values that we have already mapped (such as the selector).
1446 for (Value *Val : PN->incoming_values()) {
1447 if (VMap.count(Val)) {
1448 VMap[PN] = VMap[Val];
1449 Mapped = true;
1450 }
1451 }
1452 // If we didn't find a match for this value, map it as an undef.
1453 if (!Mapped) {
1454 VMap[PN] = UndefValue::get(PN->getType());
1455 }
1456 ++II;
1457 }
1458
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001459 // The landing pad value may be used by PHI nodes. It will ultimately be
1460 // eliminated, but we need it in the map for intermediate handling.
1461 VMap[LPad] = UndefValue::get(LPad->getType());
1462
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001463 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001464 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001465
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001466 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001467 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001468 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001469
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001470 // Move all the instructions in the cloned "entry" block into our entry block.
1471 // Depending on how the parent function was laid out, the block that will
1472 // correspond to the outlined entry block may not be the first block in the
1473 // list. We can recognize it, however, as the cloned block which has no
1474 // predecessors. Any other block wouldn't have been cloned if it didn't
1475 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001476 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001477 while (!pred_empty(ClonedIt))
1478 ++ClonedIt;
1479 BasicBlock *ClonedEntryBB = ClonedIt;
1480 assert(ClonedEntryBB);
1481 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1482 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001483
Andrew Kaylorbb111322015-04-07 21:30:23 +00001484 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001485 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001486
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001487 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1488 WinEHCatchDirector *CatchDirector =
1489 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1490 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1491 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001492
1493 // Look for blocks that are not part of the landing pad that we just
1494 // outlined but terminate with a call to llvm.eh.endcatch and a
1495 // branch to a block that is in the handler we just outlined.
1496 // These blocks will be part of a nested landing pad that intends to
1497 // return to an address in this handler. This case is best handled
1498 // after both landing pads have been outlined, so for now we'll just
1499 // save the association of the blocks in LPadTargetBlocks. The
1500 // return instructions which are created from these branches will be
1501 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001502 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001503 // VMap maps all values and blocks that were just cloned, but dead
1504 // blocks which were pruned will map to nullptr.
1505 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1506 continue;
1507 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1508 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1509 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1510 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1511 continue;
1512 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1513 --II;
1514 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1515 // This would indicate that a nested landing pad wants to return
1516 // to a block that is outlined into two different handlers.
1517 assert(!LPadTargetBlocks.count(MappedBB));
1518 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1519 }
1520 }
1521 }
1522 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001523
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001524 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001525
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001526 return true;
1527}
1528
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001529/// This BB must end in a selector dispatch. All we need to do is pass the
1530/// handler block to llvm.eh.actions and list it as a possible indirectbr
1531/// target.
1532void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1533 BasicBlock *StartBB) {
1534 BasicBlock *HandlerBB;
1535 BasicBlock *NextBB;
1536 Constant *Selector;
1537 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1538 if (Res) {
1539 // If this was EH dispatch, this must be a conditional branch to the handler
1540 // block.
1541 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1542 // leading to crashes if some optimization hoists stuff here.
1543 assert(CatchAction->getSelector() && HandlerBB &&
1544 "expected catch EH dispatch");
1545 } else {
1546 // This must be a catch-all. Split the block after the landingpad.
1547 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001548 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001549 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001550 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1551 Function *EHCodeFn = Intrinsic::getDeclaration(
1552 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001553 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001554 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1555 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001556 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1557 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1558 CatchAction->setReturnTargets(Targets);
1559}
1560
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001561void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1562 // Each instance of this class should only ever be used to map a single
1563 // landing pad.
1564 assert(OriginLPad == nullptr || OriginLPad == LPad);
1565
1566 // If the landing pad has already been mapped, there's nothing more to do.
1567 if (OriginLPad == LPad)
1568 return;
1569
1570 OriginLPad = LPad;
1571
1572 // The landingpad instruction returns an aggregate value. Typically, its
1573 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001574 // results of those extracts will have been promoted to reg values before
1575 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001576 for (auto *U : LPad->users()) {
1577 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1578 if (!Extract)
1579 continue;
1580 assert(Extract->getNumIndices() == 1 &&
1581 "Unexpected operation: extracting both landing pad values");
1582 unsigned int Idx = *(Extract->idx_begin());
1583 assert((Idx == 0 || Idx == 1) &&
1584 "Unexpected operation: extracting an unknown landing pad element");
1585 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001586 ExtractedEHPtrs.push_back(Extract);
1587 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001588 ExtractedSelectors.push_back(Extract);
1589 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001590 }
1591}
1592
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001593bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1594 return BB->getLandingPadInst() == OriginLPad;
1595}
1596
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001597bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1598 if (Inst == OriginLPad)
1599 return true;
1600 for (auto *Extract : ExtractedEHPtrs) {
1601 if (Inst == Extract)
1602 return true;
1603 }
1604 for (auto *Extract : ExtractedSelectors) {
1605 if (Inst == Extract)
1606 return true;
1607 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001608 return false;
1609}
1610
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001611void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1612 Value *SelectorValue) const {
1613 // Remap all landing pad extract instructions to the specified values.
1614 for (auto *Extract : ExtractedEHPtrs)
1615 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001616 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001617 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001618}
1619
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001620static bool isLocalAddressCall(const Value *V) {
1621 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001622}
1623
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001624CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001625 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001626 // If this is one of the boilerplate landing pad instructions, skip it.
1627 // The instruction will have already been remapped in VMap.
1628 if (LPadMap.isLandingPadSpecificInst(Inst))
1629 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001630
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001631 // Nested landing pads that have not already been outlined will be cloned as
1632 // stubs, with just the landingpad instruction and an unreachable instruction.
1633 // When all landingpads have been outlined, we'll replace this with the
1634 // llvm.eh.actions call and indirect branch created when the landing pad was
1635 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001636 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1637 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001638 }
1639
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001640 // Nested landing pads that have already been outlined will be cloned in their
1641 // outlined form, but we need to intercept the ibr instruction to filter out
1642 // targets that do not return to the handler we are outlining.
1643 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1644 return handleIndirectBr(VMap, IBr, NewBB);
1645 }
1646
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001647 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1648 return handleInvoke(VMap, Invoke, NewBB);
1649
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001650 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1651 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001652
Andrew Kaylorea8df612015-04-17 23:05:43 +00001653 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1654 return handleCompare(VMap, Cmp, NewBB);
1655
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001656 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1657 return handleBeginCatch(VMap, Inst, NewBB);
1658 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1659 return handleEndCatch(VMap, Inst, NewBB);
1660 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1661 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001662
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001663 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001664 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001665 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001666 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001667 return CloningDirector::SkipInstruction;
1668 }
1669
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001670 // Continue with the default cloning behavior.
1671 return CloningDirector::CloneInstruction;
1672}
1673
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001674CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1675 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001676 // If the instruction after the landing pad is a call to llvm.eh.actions
1677 // the landing pad has already been outlined. In this case, we should
1678 // clone it because it may return to a block in the handler we are
1679 // outlining now that would otherwise be unreachable. The landing pads
1680 // are sorted before outlining begins to enable this case to work
1681 // properly.
1682 const Instruction *NextI = LPad->getNextNode();
1683 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1684 return CloningDirector::CloneInstruction;
1685
1686 // If the landing pad hasn't been outlined yet, the landing pad we are
1687 // outlining now does not dominate it and so it cannot return to a block
1688 // in this handler. In that case, we can just insert a stub landing
1689 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001690 Instruction *NewInst = LPad->clone();
1691 if (LPad->hasName())
1692 NewInst->setName(LPad->getName());
1693 // Save this correlation for later processing.
1694 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1695 VMap[LPad] = NewInst;
1696 BasicBlock::InstListType &InstList = NewBB->getInstList();
1697 InstList.push_back(NewInst);
1698 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1699 return CloningDirector::StopCloningBB;
1700}
1701
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001702CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1703 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1704 // The argument to the call is some form of the first element of the
1705 // landingpad aggregate value, but that doesn't matter. It isn't used
1706 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001707 // The second argument is an outparameter where the exception object will be
1708 // stored. Typically the exception object is a scalar, but it can be an
1709 // aggregate when catching by value.
1710 // FIXME: Leave something behind to indicate where the exception object lives
1711 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001712 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1713 "llvm.eh.begincatch found while "
1714 "outlining catch handler.");
1715 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001716 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1717 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001718 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1719 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001720 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001721 return CloningDirector::SkipInstruction;
1722}
1723
1724CloningDirector::CloningAction
1725WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1726 const Instruction *Inst, BasicBlock *NewBB) {
1727 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1728 // It might be interesting to track whether or not we are inside a catch
1729 // function, but that might make the algorithm more brittle than it needs
1730 // to be.
1731
1732 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001733 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001734 // or at the end of the catch block. However, a catch-all handler may call
1735 // end catch from the original landing pad. If the call occurs in a nested
1736 // landing pad block, we must skip it and continue so that the landing pad
1737 // gets cloned.
1738 auto *ParentBB = IntrinCall->getParent();
1739 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001740 return CloningDirector::SkipInstruction;
1741
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001742 // If an end catch occurs anywhere else we want to terminate the handler
1743 // with a return to the code that follows the endcatch call. If the
1744 // next instruction is not an unconditional branch, we need to split the
1745 // block to provide a clear target for the return instruction.
1746 BasicBlock *ContinueBB;
1747 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1748 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1749 if (!Branch || !Branch->isUnconditional()) {
1750 // We're interrupting the cloning process at this location, so the
1751 // const_cast we're doing here will not cause a problem.
1752 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1753 const_cast<Instruction *>(cast<Instruction>(Next)));
1754 } else {
1755 ContinueBB = Branch->getSuccessor(0);
1756 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001757
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001758 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1759 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001760
1761 // We just added a terminator to the cloned block.
1762 // Tell the caller to stop processing the current basic block so that
1763 // the branch instruction will be skipped.
1764 return CloningDirector::StopCloningBB;
1765}
1766
1767CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1768 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1769 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1770 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1771 // This causes a replacement that will collapse the landing pad CFG based
1772 // on the filter function we intend to match.
1773 if (Selector == CurrentSelector)
1774 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1775 else
1776 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1777 // Tell the caller not to clone this instruction.
1778 return CloningDirector::SkipInstruction;
1779}
1780
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001781CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1782 ValueToValueMapTy &VMap,
1783 const IndirectBrInst *IBr,
1784 BasicBlock *NewBB) {
1785 // If this indirect branch is not part of a landing pad block, just clone it.
1786 const BasicBlock *ParentBB = IBr->getParent();
1787 if (!ParentBB->isLandingPad())
1788 return CloningDirector::CloneInstruction;
1789
1790 // If it is part of a landing pad, we want to filter out target blocks
1791 // that are not part of the handler we are outlining.
1792 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1793
1794 // Save this correlation for later processing.
1795 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1796
1797 // We should only get here for landing pads that have already been outlined.
1798 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1799
1800 // Copy the indirectbr, but only include targets that were previously
1801 // identified as EH blocks and are dominated by the nested landing pad.
1802 SetVector<const BasicBlock *> ReturnTargets;
1803 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1804 auto *TargetBB = IBr->getDestination(I);
1805 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1806 DT->dominates(ParentBB, TargetBB)) {
1807 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1808 ReturnTargets.insert(TargetBB);
1809 }
1810 }
1811 IndirectBrInst *NewBranch =
1812 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1813 ReturnTargets.size(), NewBB);
1814 for (auto *Target : ReturnTargets)
1815 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1816
1817 // The operands and targets of the branch instruction are remapped later
1818 // because it is a terminator. Tell the cloning code to clone the
1819 // blocks we just added to the target list.
1820 return CloningDirector::CloneSuccessors;
1821}
1822
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001823CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001824WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1825 const InvokeInst *Invoke, BasicBlock *NewBB) {
1826 return CloningDirector::CloneInstruction;
1827}
1828
1829CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001830WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1831 const ResumeInst *Resume, BasicBlock *NewBB) {
1832 // Resume instructions shouldn't be reachable from catch handlers.
1833 // We still need to handle it, but it will be pruned.
1834 BasicBlock::InstListType &InstList = NewBB->getInstList();
1835 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1836 return CloningDirector::StopCloningBB;
1837}
1838
Andrew Kaylorea8df612015-04-17 23:05:43 +00001839CloningDirector::CloningAction
1840WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1841 const CmpInst *Compare, BasicBlock *NewBB) {
1842 const IntrinsicInst *IntrinCall = nullptr;
1843 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1844 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001845 } else if (match(Compare->getOperand(1),
1846 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001847 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1848 }
1849 if (IntrinCall) {
1850 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1851 // This causes a replacement that will collapse the landing pad CFG based
1852 // on the filter function we intend to match.
1853 if (Selector == CurrentSelector->stripPointerCasts()) {
1854 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001855 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001856 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1857 }
1858 return CloningDirector::SkipInstruction;
1859 }
1860 return CloningDirector::CloneInstruction;
1861}
1862
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001863CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1864 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1865 // The MS runtime will terminate the process if an exception occurs in a
1866 // cleanup handler, so we shouldn't encounter landing pads in the actual
1867 // cleanup code, but they may appear in catch blocks. Depending on where
1868 // we started cloning we may see one, but it will get dropped during dead
1869 // block pruning.
1870 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1871 VMap[LPad] = NewInst;
1872 BasicBlock::InstListType &InstList = NewBB->getInstList();
1873 InstList.push_back(NewInst);
1874 return CloningDirector::StopCloningBB;
1875}
1876
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001877CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1878 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001879 // Cleanup code may flow into catch blocks or the catch block may be part
1880 // of a branch that will be optimized away. We'll insert a return
1881 // instruction now, but it may be pruned before the cloning process is
1882 // complete.
1883 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001884 return CloningDirector::StopCloningBB;
1885}
1886
1887CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1888 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001889 // Cleanup handlers nested within catch handlers may begin with a call to
1890 // eh.endcatch. We can just ignore that instruction.
1891 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001892}
1893
1894CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1895 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001896 // If we encounter a selector comparison while cloning a cleanup handler,
1897 // we want to stop cloning immediately. Anything after the dispatch
1898 // will be outlined into a different handler.
1899 BasicBlock *CatchHandler;
1900 Constant *Selector;
1901 BasicBlock *NextBB;
1902 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1903 CatchHandler, Selector, NextBB)) {
1904 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1905 return CloningDirector::StopCloningBB;
1906 }
1907 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001908 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001909 return CloningDirector::SkipInstruction;
1910}
1911
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001912CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1913 ValueToValueMapTy &VMap,
1914 const IndirectBrInst *IBr,
1915 BasicBlock *NewBB) {
1916 // No special handling is required for cleanup cloning.
1917 return CloningDirector::CloneInstruction;
1918}
1919
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001920CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1921 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1922 // All invokes in cleanup handlers can be replaced with calls.
1923 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1924 // Insert a normal call instruction...
1925 CallInst *NewCall =
1926 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1927 Invoke->getName(), NewBB);
1928 NewCall->setCallingConv(Invoke->getCallingConv());
1929 NewCall->setAttributes(Invoke->getAttributes());
1930 NewCall->setDebugLoc(Invoke->getDebugLoc());
1931 VMap[Invoke] = NewCall;
1932
Reid Kleckner6e48a822015-04-10 16:26:42 +00001933 // Remap the operands.
1934 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1935
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001936 // Insert an unconditional branch to the normal destination.
1937 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1938
1939 // The unwind destination won't be cloned into the new function, so
1940 // we don't need to clean up its phi nodes.
1941
1942 // We just added a terminator to the cloned block.
1943 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001944 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001945}
1946
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001947CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1948 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1949 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1950
1951 // We just added a terminator to the cloned block.
1952 // Tell the caller to stop processing the current basic block so that
1953 // the branch instruction will be skipped.
1954 return CloningDirector::StopCloningBB;
1955}
1956
Andrew Kaylorea8df612015-04-17 23:05:43 +00001957CloningDirector::CloningAction
1958WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1959 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001960 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1961 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1962 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1963 return CloningDirector::SkipInstruction;
1964 }
1965 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001966}
1967
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001968WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001969 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001970 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001971 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001972
1973 // New allocas should be inserted in the entry block, but after the parent FP
1974 // is established if it is an instruction.
1975 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1976 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1977 InsertPoint = FPInst->getNextNode();
1978 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001979}
1980
1981Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001982 // If we're asked to materialize a static alloca, we temporarily create an
1983 // alloca in the outlined function and add this to the FrameVarInfo map. When
1984 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00001985 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001986 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001987 assert(AV->isStaticAlloca() &&
1988 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00001989 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1990 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001991 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001992 return NewAlloca;
1993 }
1994
Andrew Kaylor72029c62015-03-03 00:41:03 +00001995 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00001996 Function *Parent = isa<Instruction>(V)
1997 ? cast<Instruction>(V)->getParent()->getParent()
1998 : cast<Argument>(V)->getParent();
1999 errs()
2000 << "Failed to demote instruction used in exception handler of function "
2001 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002002 errs() << " " << *V << '\n';
2003 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002004 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002005
Andrew Kaylor72029c62015-03-03 00:41:03 +00002006 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002007 return nullptr;
2008}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002009
Reid Kleckner3567d272015-04-02 21:13:31 +00002010void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2011 // Catch parameter objects have to live in the parent frame. When we see a use
2012 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2013 // used from another handler. This will prevent us from trying to sink the
2014 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002015 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002016 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2017}
2018
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002019// This function maps the catch and cleanup handlers that are reachable from the
2020// specified landing pad. The landing pad sequence will have this basic shape:
2021//
2022// <cleanup handler>
2023// <selector comparison>
2024// <catch handler>
2025// <cleanup handler>
2026// <selector comparison>
2027// <catch handler>
2028// <cleanup handler>
2029// ...
2030//
2031// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2032// any arbitrary control flow, but all paths through the cleanup code must
2033// eventually reach the next selector comparison and no path can skip to a
2034// different selector comparisons, though some paths may terminate abnormally.
2035// Therefore, we will use a depth first search from the start of any given
2036// cleanup block and stop searching when we find the next selector comparison.
2037//
2038// If the landingpad instruction does not have a catch clause, we will assume
2039// that any instructions other than selector comparisons and catch handlers can
2040// be ignored. In practice, these will only be the boilerplate instructions.
2041//
2042// The catch handlers may also have any control structure, but we are only
2043// interested in the start of the catch handlers, so we don't need to actually
2044// follow the flow of the catch handlers. The start of the catch handlers can
2045// be located from the compare instructions, but they can be skipped in the
2046// flow by following the contrary branch.
2047void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2048 LandingPadActions &Actions) {
2049 unsigned int NumClauses = LPad->getNumClauses();
2050 unsigned int HandlersFound = 0;
2051 BasicBlock *BB = LPad->getParent();
2052
2053 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2054
2055 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002056 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002057 return;
2058 }
2059
2060 VisitedBlockSet VisitedBlocks;
2061
2062 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002063 BasicBlock *NextBB = nullptr;
2064
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002065 // Skip over filter clauses.
2066 if (LPad->isFilter(HandlersFound)) {
2067 ++HandlersFound;
2068 continue;
2069 }
2070
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002071 // See if the clause we're looking for is a catch-all.
2072 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002073 Constant *ExpectedSelector =
2074 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002075 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002076 // The catch all must occur last.
2077 assert(HandlersFound == NumClauses - 1);
2078
Andrew Kaylorea8df612015-04-17 23:05:43 +00002079 // There can be additional selector dispatches in the call chain that we
2080 // need to ignore.
2081 BasicBlock *CatchBlock = nullptr;
2082 Constant *Selector;
2083 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2084 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002085 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002086 BB = NextBB;
2087 }
2088
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002089 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002090 CatchHandler *Action = nullptr;
2091 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2092 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2093 Action = CatchHandlerMap[BB];
2094 assert(Action->getSelector() == ExpectedSelector);
2095 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002096 // We don't expect a selector dispatch, but there may be a call to
2097 // llvm.eh.begincatch, which separates catch handling code from
2098 // cleanup code in the same control flow. This call looks for the
2099 // begincatch intrinsic.
2100 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2101 if (Action) {
2102 // For C++ EH, check if there is any interesting cleanup code before
2103 // we begin the catch. This is important because cleanups cannot
2104 // rethrow exceptions but code called from catches can. For SEH, it
2105 // isn't important if some finally code before a catch-all is executed
2106 // out of line or after recovering from the exception.
2107 if (Personality == EHPersonality::MSVC_CXX)
2108 findCleanupHandlers(Actions, BB, BB);
2109 } else {
2110 // If an action was not found, it means that the control flows
2111 // directly into the catch-all handler and there is no cleanup code.
2112 // That's an expected situation and we must create a catch action.
2113 // Since this is a catch-all handler, the selector won't actually
2114 // appear in the code anywhere. ExpectedSelector here is the constant
2115 // null ptr that we got from the landing pad instruction.
2116 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2117 CatchHandlerMap[BB] = Action;
2118 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002119 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002120 Actions.insertCatchHandler(Action);
2121 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2122 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002123
2124 // Once we reach a catch-all, don't expect to hit a resume instruction.
2125 BB = nullptr;
2126 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002127 }
2128
2129 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002130 assert(CatchAction);
2131
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002132 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002133 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002134
Andrew Kaylorea8df612015-04-17 23:05:43 +00002135 // When the source program contains multiple nested try blocks the catch
2136 // handlers can get strung together in such a way that we can encounter
2137 // a dispatch for a selector that we've already had a handler for.
2138 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2139 ++HandlersFound;
2140
2141 // Add the catch handler to the action list.
2142 DEBUG(dbgs() << " Found catch dispatch in block "
2143 << CatchAction->getStartBlock()->getName() << "\n");
2144 Actions.insertCatchHandler(CatchAction);
2145 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002146 // Under some circumstances optimized IR will flow unconditionally into a
2147 // handler block without checking the selector. This can only happen if
2148 // the landing pad has a catch-all handler and the handler for the
2149 // preceeding catch clause is identical to the catch-call handler
2150 // (typically an empty catch). In this case, the handler must be shared
2151 // by all remaining clauses.
2152 if (isa<ConstantPointerNull>(
2153 CatchAction->getSelector()->stripPointerCasts())) {
2154 DEBUG(dbgs() << " Applying early catch-all handler in block "
2155 << CatchAction->getStartBlock()->getName()
2156 << " to all remaining clauses.\n");
2157 Actions.insertCatchHandler(CatchAction);
2158 return;
2159 }
2160
Andrew Kaylorea8df612015-04-17 23:05:43 +00002161 DEBUG(dbgs() << " Found extra catch dispatch in block "
2162 << CatchAction->getStartBlock()->getName() << "\n");
2163 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002164
2165 // Move on to the block after the catch handler.
2166 BB = NextBB;
2167 }
2168
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002169 // If we didn't wind up in a catch-all, see if there is any interesting code
2170 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002171 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002172
2173 // It's possible that some optimization moved code into a landingpad that
2174 // wasn't
2175 // previously being used for cleanup. If that happens, we need to execute
2176 // that
2177 // extra code from a cleanup handler.
2178 if (Actions.includesCleanup() && !LPad->isCleanup())
2179 LPad->setCleanup(true);
2180}
2181
2182// This function searches starting with the input block for the next
2183// block that terminates with a branch whose condition is based on a selector
2184// comparison. This may be the input block. See the mapLandingPadBlocks
2185// comments for a discussion of control flow assumptions.
2186//
2187CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2188 BasicBlock *&NextBB,
2189 VisitedBlockSet &VisitedBlocks) {
2190 // See if we've already found a catch handler use it.
2191 // Call count() first to avoid creating a null entry for blocks
2192 // we haven't seen before.
2193 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2194 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2195 NextBB = Action->getNextBB();
2196 return Action;
2197 }
2198
2199 // VisitedBlocks applies only to the current search. We still
2200 // need to consider blocks that we've visited while mapping other
2201 // landing pads.
2202 VisitedBlocks.insert(BB);
2203
2204 BasicBlock *CatchBlock = nullptr;
2205 Constant *Selector = nullptr;
2206
2207 // If this is the first time we've visited this block from any landing pad
2208 // look to see if it is a selector dispatch block.
2209 if (!CatchHandlerMap.count(BB)) {
2210 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2211 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2212 CatchHandlerMap[BB] = Action;
2213 return Action;
2214 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002215 // If we encounter a block containing an llvm.eh.begincatch before we
2216 // find a selector dispatch block, the handler is assumed to be
2217 // reached unconditionally. This happens for catch-all blocks, but
2218 // it can also happen for other catch handlers that have been combined
2219 // with the catch-all handler during optimization.
2220 if (isCatchBlock(BB)) {
2221 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2222 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2223 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2224 CatchHandlerMap[BB] = Action;
2225 return Action;
2226 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002227 }
2228
2229 // Visit each successor, looking for the dispatch.
2230 // FIXME: We expect to find the dispatch quickly, so this will probably
2231 // work better as a breadth first search.
2232 for (BasicBlock *Succ : successors(BB)) {
2233 if (VisitedBlocks.count(Succ))
2234 continue;
2235
2236 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2237 if (Action)
2238 return Action;
2239 }
2240 return nullptr;
2241}
2242
Reid Kleckner9405ef02015-04-10 23:12:29 +00002243// These are helper functions to combine repeated code from findCleanupHandlers.
2244static void createCleanupHandler(LandingPadActions &Actions,
2245 CleanupHandlerMapTy &CleanupHandlerMap,
2246 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002247 CleanupHandler *Action = new CleanupHandler(BB);
2248 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002249 Actions.insertCleanupHandler(Action);
2250 DEBUG(dbgs() << " Found cleanup code in block "
2251 << Action->getStartBlock()->getName() << "\n");
2252}
2253
Reid Kleckner9405ef02015-04-10 23:12:29 +00002254static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2255 Instruction *MaybeCall) {
2256 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002257 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002258 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002259 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002260 MaybeCall = MaybeCall->getNextNode();
2261 CallSite FinallyCall(MaybeCall);
2262 if (!FinallyCall || FinallyCall.arg_size() != 2)
2263 return CallSite();
2264 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2265 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002266 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002267 return CallSite();
2268 return FinallyCall;
2269}
2270
2271static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2272 // Skip single ubr blocks.
2273 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2274 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2275 if (Br && Br->isUnconditional())
2276 BB = Br->getSuccessor(0);
2277 else
2278 return BB;
2279 }
2280 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002281}
2282
2283// This function searches starting with the input block for the next block that
2284// contains code that is not part of a catch handler and would not be eliminated
2285// during handler outlining.
2286//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002287void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2288 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002289 // Here we will skip over the following:
2290 //
2291 // landing pad prolog:
2292 //
2293 // Unconditional branches
2294 //
2295 // Selector dispatch
2296 //
2297 // Resume pattern
2298 //
2299 // Anything else marks the start of an interesting block
2300
2301 BasicBlock *BB = StartBB;
2302 // Anything other than an unconditional branch will kick us out of this loop
2303 // one way or another.
2304 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002305 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002306 // If we've already scanned this block, don't scan it again. If it is
2307 // a cleanup block, there will be an action in the CleanupHandlerMap.
2308 // If we've scanned it and it is not a cleanup block, there will be a
2309 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2310 // be no entry in the CleanupHandlerMap. We must call count() first to
2311 // avoid creating a null entry for blocks we haven't scanned.
2312 if (CleanupHandlerMap.count(BB)) {
2313 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002314 Actions.insertCleanupHandler(Action);
2315 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002316 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002317 // FIXME: This cleanup might chain into another, and we need to discover
2318 // that.
2319 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002320 } else {
2321 // Here we handle the case where the cleanup handler map contains a
2322 // value for this block but the value is a nullptr. This means that
2323 // we have previously analyzed the block and determined that it did
2324 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002325 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002326 // resume or a conditional branch that is predicated on a comparison
2327 // with a selector. Either the resume or the selector dispatch
2328 // would terminate the search for cleanup code, so the unconditional
2329 // branch is the only case for which we might need to continue
2330 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002331 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2332 if (SuccBB == BB || SuccBB == EndBB)
2333 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002334 BB = SuccBB;
2335 continue;
2336 }
2337 }
2338
2339 // Create an entry in the cleanup handler map for this block. Initially
2340 // we create an entry that says this isn't a cleanup block. If we find
2341 // cleanup code, the caller will replace this entry.
2342 CleanupHandlerMap[BB] = nullptr;
2343
2344 TerminatorInst *Terminator = BB->getTerminator();
2345
2346 // Landing pad blocks have extra instructions we need to accept.
2347 LandingPadMap *LPadMap = nullptr;
2348 if (BB->isLandingPad()) {
2349 LandingPadInst *LPad = BB->getLandingPadInst();
2350 LPadMap = &LPadMaps[LPad];
2351 if (!LPadMap->isInitialized())
2352 LPadMap->mapLandingPad(LPad);
2353 }
2354
2355 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002356 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2357 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002358 // resume { i8*, i32 } %lpad.val2
2359 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2360 InsertValueInst *Insert1 = nullptr;
2361 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002362 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002363 // If the resume value isn't a phi or landingpad value, it should be a
2364 // series of insertions. Identify them so we can avoid them when scanning
2365 // for cleanups.
2366 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002367 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002368 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002369 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002370 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2371 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002372 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002373 }
2374 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2375 II != IE; ++II) {
2376 Instruction *Inst = II;
2377 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2378 continue;
2379 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2380 continue;
2381 if (!Inst->hasOneUse() ||
2382 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002383 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002384 }
2385 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002386 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002387 }
2388
2389 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002390 if (Branch && Branch->isConditional()) {
2391 // Look for the selector dispatch.
2392 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2393 // %matches = icmp eq i32 %sel, %2
2394 // br i1 %matches, label %catch14, label %eh.resume
2395 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2396 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002397 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002398 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2399 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002400 Instruction *Inst = II;
2401 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2402 continue;
2403 if (Inst == Compare || Inst == Branch)
2404 continue;
2405 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2406 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002407 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002408 }
2409 // The selector dispatch block should always terminate our search.
2410 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002411 return;
2412 }
2413
2414 if (isAsynchronousEHPersonality(Personality)) {
2415 // If this is a landingpad block, split the block at the first non-landing
2416 // pad instruction.
2417 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2418 if (LPadMap) {
2419 while (MaybeCall != BB->getTerminator() &&
2420 LPadMap->isLandingPadSpecificInst(MaybeCall))
2421 MaybeCall = MaybeCall->getNextNode();
2422 }
2423
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002424 // Look for outlined finally calls on x64, since those happen to match the
2425 // prototype provided by the runtime.
2426 if (TheTriple.getArch() == Triple::x86_64) {
2427 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2428 Function *Fin = FinallyCall.getCalledFunction();
2429 assert(Fin && "outlined finally call should be direct");
2430 auto *Action = new CleanupHandler(BB);
2431 Action->setHandlerBlockOrFunc(Fin);
2432 Actions.insertCleanupHandler(Action);
2433 CleanupHandlerMap[BB] = Action;
2434 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2435 << Fin->getName() << " in block "
2436 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002437
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002438 // Split the block if there were more interesting instructions and
2439 // look for finally calls in the normal successor block.
2440 BasicBlock *SuccBB = BB;
2441 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2442 FinallyCall.getInstruction()->getNextNode() !=
2443 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002444 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002445 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002446 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002447 if (FinallyCall.isInvoke()) {
2448 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2449 ->getNormalDest();
2450 } else {
2451 SuccBB = BB->getUniqueSuccessor();
2452 assert(SuccBB &&
2453 "splitOutlinedFinallyCalls didn't insert a branch");
2454 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002455 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002456 BB = SuccBB;
2457 if (BB == EndBB)
2458 return;
2459 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002460 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002461 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002462 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002463
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002464 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002465 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2466 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002467 Instruction *Inst = II;
2468 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2469 continue;
2470 // Unconditional branches fall through to this loop.
2471 if (Inst == Branch)
2472 continue;
2473 // If this is a catch block, there is no cleanup code to be found.
2474 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002475 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002476 // If this a nested landing pad, it may contain an endcatch call.
2477 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002478 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002479 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002480 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002481 }
2482
2483 // Only unconditional branches in empty blocks should get this far.
2484 assert(Branch && Branch->isUnconditional());
2485 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002486 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002487 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002488 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002489}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002490
2491// This is a public function, declared in WinEHFuncInfo.h and is also
2492// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002493void llvm::parseEHActions(
2494 const IntrinsicInst *II,
2495 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002496 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2497 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002498 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2499 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002500 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002501 if (ActionKind == /*catch=*/1) {
2502 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2503 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2504 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2505 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2506 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002507 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2508 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002509 CH->setHandlerBlockOrFunc(Handler);
2510 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002511 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002512 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002513 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2514 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002515 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002516 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002517 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002518 } else {
2519 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002520 }
2521 }
2522 std::reverse(Actions.begin(), Actions.end());
2523}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002524
2525namespace {
2526struct WinEHNumbering {
2527 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2528 CurrentBaseState(-1), NextState(0) {}
2529
2530 WinEHFuncInfo &FuncInfo;
2531 int CurrentBaseState;
2532 int NextState;
2533
2534 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2535 SmallPtrSet<const Function *, 4> VisitedHandlers;
2536
2537 int currentEHNumber() const {
2538 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2539 }
2540
2541 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2542 void createTryBlockMapEntry(int TryLow, int TryHigh,
2543 ArrayRef<CatchHandler *> Handlers);
2544 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2545 ImmutableCallSite CS);
2546 void popUnmatchedActions(int FirstMismatch);
2547 void calculateStateNumbers(const Function &F);
2548 void findActionRootLPads(const Function &F);
2549};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002550}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002551
2552void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2553 WinEHUnwindMapEntry UME;
2554 UME.ToState = ToState;
2555 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2556 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
2557 else
2558 UME.Cleanup = nullptr;
2559 FuncInfo.UnwindMap.push_back(UME);
2560}
2561
2562void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2563 ArrayRef<CatchHandler *> Handlers) {
2564 // See if we already have an entry for this set of handlers.
2565 // This is using iterators rather than a range-based for loop because
2566 // if we find the entry we're looking for we'll need the iterator to erase it.
2567 int NumHandlers = Handlers.size();
2568 auto I = FuncInfo.TryBlockMap.begin();
2569 auto E = FuncInfo.TryBlockMap.end();
2570 for ( ; I != E; ++I) {
2571 auto &Entry = *I;
2572 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2573 continue;
2574 int N;
2575 for (N = 0; N < NumHandlers; ++N) {
2576 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2577 break; // breaks out of inner loop
2578 }
2579 // If all the handlers match, this is what we were looking for.
2580 if (N == NumHandlers) {
2581 break;
2582 }
2583 }
2584
2585 // If we found an existing entry for this set of handlers, extend the range
2586 // but move the entry to the end of the map vector. The order of entries
2587 // in the map is critical to the way that the runtime finds handlers.
2588 // FIXME: Depending on what has happened with block ordering, this may
2589 // incorrectly combine entries that should remain separate.
2590 if (I != E) {
2591 // Copy the existing entry.
2592 WinEHTryBlockMapEntry Entry = *I;
2593 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2594 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2595 assert(Entry.TryLow <= Entry.TryHigh);
2596 // Erase the old entry and add this one to the back.
2597 FuncInfo.TryBlockMap.erase(I);
2598 FuncInfo.TryBlockMap.push_back(Entry);
2599 return;
2600 }
2601
2602 // If we didn't find an entry, create a new one.
2603 WinEHTryBlockMapEntry TBME;
2604 TBME.TryLow = TryLow;
2605 TBME.TryHigh = TryHigh;
2606 assert(TBME.TryLow <= TBME.TryHigh);
2607 for (CatchHandler *CH : Handlers) {
2608 WinEHHandlerType HT;
2609 if (CH->getSelector()->isNullValue()) {
2610 HT.Adjectives = 0x40;
2611 HT.TypeDescriptor = nullptr;
2612 } else {
2613 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2614 // Selectors are always pointers to GlobalVariables with 'struct' type.
2615 // The struct has two fields, adjectives and a type descriptor.
2616 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2617 HT.Adjectives =
2618 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2619 HT.TypeDescriptor =
2620 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2621 }
2622 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2623 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2624 TBME.HandlerArray.push_back(HT);
2625 }
2626 FuncInfo.TryBlockMap.push_back(TBME);
2627}
2628
2629static void print_name(const Value *V) {
2630#ifndef NDEBUG
2631 if (!V) {
2632 DEBUG(dbgs() << "null");
2633 return;
2634 }
2635
2636 if (const auto *F = dyn_cast<Function>(V))
2637 DEBUG(dbgs() << F->getName());
2638 else
2639 DEBUG(V->dump());
2640#endif
2641}
2642
2643void WinEHNumbering::processCallSite(
2644 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2645 ImmutableCallSite CS) {
2646 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2647 << ") for: ");
2648 print_name(CS ? CS.getCalledValue() : nullptr);
2649 DEBUG(dbgs() << '\n');
2650
2651 DEBUG(dbgs() << "HandlerStack: \n");
2652 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2653 DEBUG(dbgs() << " ");
2654 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2655 DEBUG(dbgs() << '\n');
2656 }
2657 DEBUG(dbgs() << "Actions: \n");
2658 for (int I = 0, E = Actions.size(); I < E; ++I) {
2659 DEBUG(dbgs() << " ");
2660 print_name(Actions[I]->getHandlerBlockOrFunc());
2661 DEBUG(dbgs() << '\n');
2662 }
2663 int FirstMismatch = 0;
2664 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2665 ++FirstMismatch) {
2666 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2667 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2668 break;
2669 }
2670
2671 // Remove unmatched actions from the stack and process their EH states.
2672 popUnmatchedActions(FirstMismatch);
2673
2674 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2675 print_name(CS ? CS.getCalledValue() : nullptr);
2676 DEBUG(dbgs() << '\n');
2677
2678 bool LastActionWasCatch = false;
2679 const LandingPadInst *LastRootLPad = nullptr;
2680 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2681 // We can reuse eh states when pushing two catches for the same invoke.
2682 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2683 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2684 // Various conditions can lead to a handler being popped from the
2685 // stack and re-pushed later. That shouldn't create a new state.
2686 // FIXME: Can code optimization lead to re-used handlers?
2687 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2688 // If we already assigned the state enclosed by this handler re-use it.
2689 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2690 continue;
2691 }
2692 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2693 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2694 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2695 Actions[I]->setEHState(currentEHNumber());
2696 } else {
2697 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2698 print_name(Actions[I]->getHandlerBlockOrFunc());
2699 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2700 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2701 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2702 Actions[I]->setEHState(NextState);
2703 NextState++;
2704 }
2705 HandlerStack.push_back(std::move(Actions[I]));
2706 LastActionWasCatch = CurrActionIsCatch;
2707 LastRootLPad = RootLPad;
2708 }
2709
2710 // This is used to defer numbering states for a handler until after the
2711 // last time it appears in an invoke action list.
2712 if (CS.isInvoke()) {
2713 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2714 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2715 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2716 continue;
2717 FuncInfo.LastInvokeVisited[Handler] = true;
2718 DEBUG(dbgs() << "Last invoke of ");
2719 print_name(Handler);
2720 DEBUG(dbgs() << " has been visited.\n");
2721 }
2722 }
2723
2724 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2725 print_name(CS ? CS.getCalledValue() : nullptr);
2726 DEBUG(dbgs() << '\n');
2727}
2728
2729void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2730 // Don't recurse while we are looping over the handler stack. Instead, defer
2731 // the numbering of the catch handlers until we are done popping.
2732 SmallVector<CatchHandler *, 4> PoppedCatches;
2733 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2734 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2735 if (isa<CatchHandler>(Handler.get()))
2736 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2737 }
2738
2739 int TryHigh = NextState - 1;
2740 int LastTryLowIdx = 0;
2741 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2742 CatchHandler *CH = PoppedCatches[I];
2743 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2744 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2745 int TryLow = CH->getEHState();
2746 auto Handlers =
2747 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2748 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2749 for (size_t J = 0; J < Handlers.size(); ++J) {
2750 DEBUG(dbgs() << ", ");
2751 print_name(Handlers[J]->getHandlerBlockOrFunc());
2752 }
2753 DEBUG(dbgs() << ")\n");
2754 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2755 LastTryLowIdx = I + 1;
2756 }
2757 }
2758
2759 for (CatchHandler *CH : PoppedCatches) {
2760 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2761 if (FuncInfo.LastInvokeVisited[F]) {
2762 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2763 print_name(F);
2764 DEBUG(dbgs() << '\n');
2765 FuncInfo.HandlerBaseState[F] = NextState;
2766 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2767 << ", null)\n");
2768 createUnwindMapEntry(currentEHNumber(), nullptr);
2769 ++NextState;
2770 calculateStateNumbers(*F);
2771 }
2772 else {
2773 DEBUG(dbgs() << "Deferring handling of ");
2774 print_name(F);
2775 DEBUG(dbgs() << " until last invoke visited.\n");
2776 }
2777 }
2778 delete CH;
2779 }
2780}
2781
2782void WinEHNumbering::calculateStateNumbers(const Function &F) {
2783 auto I = VisitedHandlers.insert(&F);
2784 if (!I.second)
2785 return; // We've already visited this handler, don't renumber it.
2786
2787 int OldBaseState = CurrentBaseState;
2788 if (FuncInfo.HandlerBaseState.count(&F)) {
2789 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2790 }
2791
2792 size_t SavedHandlerStackSize = HandlerStack.size();
2793
2794 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2795 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2796 for (const BasicBlock &BB : F) {
2797 for (const Instruction &I : BB) {
2798 const auto *CI = dyn_cast<CallInst>(&I);
2799 if (!CI || CI->doesNotThrow())
2800 continue;
2801 processCallSite(None, CI);
2802 }
2803 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2804 if (!II)
2805 continue;
2806 const LandingPadInst *LPI = II->getLandingPadInst();
2807 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2808 if (!ActionsCall)
2809 continue;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002810 parseEHActions(ActionsCall, ActionList);
2811 if (ActionList.empty())
2812 continue;
2813 processCallSite(ActionList, II);
2814 ActionList.clear();
2815 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
2816 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2817 << " to landing pad at " << LPI->getParent()->getName()
2818 << '\n');
2819 }
2820
2821 // Pop any actions that were pushed on the stack for this function.
2822 popUnmatchedActions(SavedHandlerStackSize);
2823
2824 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2825 << " to " << F.getName() << '\n');
2826 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2827
2828 CurrentBaseState = OldBaseState;
2829}
2830
2831// This function follows the same basic traversal as calculateStateNumbers
2832// but it is necessary to identify the root landing pad associated
2833// with each action before we start assigning state numbers.
2834void WinEHNumbering::findActionRootLPads(const Function &F) {
2835 auto I = VisitedHandlers.insert(&F);
2836 if (!I.second)
2837 return; // We've already visited this handler, don't revisit it.
2838
2839 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2840 for (const BasicBlock &BB : F) {
2841 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2842 if (!II)
2843 continue;
2844 const LandingPadInst *LPI = II->getLandingPadInst();
2845 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2846 if (!ActionsCall)
2847 continue;
2848
2849 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2850 parseEHActions(ActionsCall, ActionList);
2851 if (ActionList.empty())
2852 continue;
2853 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2854 if (auto *Handler
2855 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2856 FuncInfo.LastInvoke[Handler] = II;
2857 // Don't replace the root landing pad if we previously saw this
2858 // handler in a different function.
2859 if (FuncInfo.RootLPad.count(Handler) &&
2860 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2861 continue;
2862 DEBUG(dbgs() << "Setting root lpad for ");
2863 print_name(Handler);
2864 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2865 FuncInfo.RootLPad[Handler] = LPI;
2866 }
2867 }
2868 // Walk the actions again and look for nested handlers. This has to
2869 // happen after all of the actions have been processed in the current
2870 // function.
2871 for (int I = 0, E = ActionList.size(); I < E; ++I)
2872 if (auto *Handler
2873 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2874 findActionRootLPads(*Handler);
2875 ActionList.clear();
2876 }
2877}
2878
2879void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
2880 WinEHFuncInfo &FuncInfo) {
2881 // Return if it's already been done.
2882 if (!FuncInfo.LandingPadStateMap.empty())
2883 return;
2884
2885 WinEHNumbering Num(FuncInfo);
2886 Num.findActionRootLPads(*ParentFn);
2887 // The VisitedHandlers list is used by both findActionRootLPads and
2888 // calculateStateNumbers, but both functions need to visit all handlers.
2889 Num.VisitedHandlers.clear();
2890 Num.calculateStateNumbers(*ParentFn);
2891 // Pop everything on the handler stack.
2892 // It may be necessary to call this more than once because a handler can
2893 // be pushed on the stack as a result of clearing the stack.
2894 while (!Num.HandlerStack.empty())
2895 Num.processCallSite(None, ImmutableCallSite());
2896}