blob: 03f53cda831fd9cbb779171ffb25878bd58a1e6e [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
11// backend wants. It snifs the personality function to see which kind of
12// preparation is necessary. If the personality function uses the Itanium LSDA,
13// this pass delegates to the DWARF EH preparation pass.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/CodeGen/Passes.h"
18#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000019#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000020#include "llvm/ADT/SmallSet.h"
Reid Klecknerfd7df282015-04-22 21:05:21 +000021#include "llvm/ADT/SetVector.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000022#include "llvm/ADT/TinyPtrVector.h"
23#include "llvm/Analysis/LibCallSemantics.h"
David Majnemercde33032015-03-30 22:58:10 +000024#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000025#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/PatternMatch.h"
32#include "llvm/Pass.h"
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000033#include "llvm/Support/CommandLine.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000034#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000035#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000037#include "llvm/Transforms/Utils/Cloning.h"
38#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000039#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000040#include <memory>
41
42using namespace llvm;
43using namespace llvm::PatternMatch;
44
45#define DEBUG_TYPE "winehprepare"
46
47namespace {
48
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000049// This map is used to model frame variable usage during outlining, to
50// construct a structure type to hold the frame variables in a frame
51// allocation block, and to remap the frame variable allocas (including
52// spill locations as needed) to GEPs that get the variable from the
53// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000054typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000055
Reid Kleckner3567d272015-04-02 21:13:31 +000056// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
57// quite null.
58AllocaInst *getCatchObjectSentinel() {
59 return static_cast<AllocaInst *>(nullptr) + 1;
60}
61
Andrew Kaylor6b67d422015-03-11 23:22:06 +000062typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
63
Andrew Kaylor6b67d422015-03-11 23:22:06 +000064class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000065class LandingPadMap;
66
67typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
68typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
69
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000070class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000071public:
72 static char ID; // Pass identification, replacement for typeid.
73 WinEHPrepare(const TargetMachine *TM = nullptr)
Andrew Kaylor64622aa2015-04-01 17:21:25 +000074 : FunctionPass(ID), DT(nullptr) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000075
76 bool runOnFunction(Function &Fn) override;
77
78 bool doFinalization(Module &M) override;
79
80 void getAnalysisUsage(AnalysisUsage &AU) const override;
81
82 const char *getPassName() const override {
83 return "Windows exception handling preparation";
84 }
85
86private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000087 bool prepareExceptionHandlers(Function &F,
88 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000089 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000090 void demoteValuesLiveAcrossHandlers(Function &F,
91 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kayloraa92ab02015-04-03 19:37:50 +000092 void completeNestedLandingPad(Function *ParentFn,
93 LandingPadInst *OutlinedLPad,
94 const LandingPadInst *OriginalLPad,
95 FrameVarInfoMap &VarInfo);
Andrew Kaylor6b67d422015-03-11 23:22:06 +000096 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
97 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +000098 FrameVarInfoMap &VarInfo);
Andrew Kaylorbb111322015-04-07 21:30:23 +000099 void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000100
101 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
102 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
103 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000104 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
105 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000106
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000107 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
108
109 // All fields are reset by runOnFunction.
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000110 DominatorTree *DT;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000111 EHPersonality Personality;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000112 CatchHandlerMapTy CatchHandlerMap;
113 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000114 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000115
116 // This maps landing pad instructions found in outlined handlers to
117 // the landing pad instruction in the parent function from which they
118 // were cloned. The cloned/nested landing pad is used as the key
119 // because the landing pad may be cloned into multiple handlers.
120 // This map will be used to add the llvm.eh.actions call to the nested
121 // landing pads after all handlers have been outlined.
122 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
123
124 // This maps blocks in the parent function which are destinations of
125 // catch handlers to cloned blocks in (other) outlined handlers. This
126 // handles the case where a nested landing pads has a catch handler that
127 // returns to a handler function rather than the parent function.
128 // The original block is used as the key here because there should only
129 // ever be one handler function from which the cloned block is not pruned.
130 // The original block will be pruned from the parent function after all
131 // handlers have been outlined. This map will be used to adjust the
132 // return instructions of handlers which return to the block that was
133 // outlined into a handler. This is done after all handlers have been
134 // outlined but before the outlined code is pruned from the parent function.
135 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000136};
137
138class WinEHFrameVariableMaterializer : public ValueMaterializer {
139public:
140 WinEHFrameVariableMaterializer(Function *OutlinedFn,
141 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000142 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000143
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000144 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000145
Reid Kleckner3567d272015-04-02 21:13:31 +0000146 void escapeCatchObject(Value *V);
147
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000148private:
149 FrameVarInfoMap &FrameVarInfo;
150 IRBuilder<> Builder;
151};
152
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000153class LandingPadMap {
154public:
155 LandingPadMap() : OriginLPad(nullptr) {}
156 void mapLandingPad(const LandingPadInst *LPad);
157
158 bool isInitialized() { return OriginLPad != nullptr; }
159
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000160 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000161 bool isLandingPadSpecificInst(const Instruction *Inst) const;
162
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000163 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
164 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000165
166private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000167 const LandingPadInst *OriginLPad;
168 // We will normally only see one of each of these instructions, but
169 // if more than one occurs for some reason we can handle that.
170 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
171 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000172};
173
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000174class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000175public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000176 WinEHCloningDirectorBase(Function *HandlerFn, FrameVarInfoMap &VarInfo,
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000177 LandingPadMap &LPadMap)
178 : Materializer(HandlerFn, VarInfo),
179 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
180 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerf14787d2015-04-22 00:07:52 +0000181 LPadMap(LPadMap) {
182 auto AI = HandlerFn->getArgumentList().begin();
183 ++AI;
184 EstablisherFrame = AI;
185 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000186
187 CloningAction handleInstruction(ValueToValueMapTy &VMap,
188 const Instruction *Inst,
189 BasicBlock *NewBB) override;
190
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000191 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
192 const Instruction *Inst,
193 BasicBlock *NewBB) = 0;
194 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
195 const Instruction *Inst,
196 BasicBlock *NewBB) = 0;
197 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
198 const Instruction *Inst,
199 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000200 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
201 const InvokeInst *Invoke,
202 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000203 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
204 const ResumeInst *Resume,
205 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000206 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
207 const CmpInst *Compare,
208 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000209 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
210 const LandingPadInst *LPad,
211 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000212
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000213 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
214
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000215protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000216 WinEHFrameVariableMaterializer Materializer;
217 Type *SelectorIDType;
218 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000219 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000220
221 /// The value representing the parent frame pointer.
222 Value *EstablisherFrame;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000223};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000224
225class WinEHCatchDirector : public WinEHCloningDirectorBase {
226public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000227 WinEHCatchDirector(
228 Function *CatchFn, Value *Selector, FrameVarInfoMap &VarInfo,
229 LandingPadMap &LPadMap,
230 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000231 : WinEHCloningDirectorBase(CatchFn, VarInfo, LPadMap),
232 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000233 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000234
235 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
236 const Instruction *Inst,
237 BasicBlock *NewBB) override;
238 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
239 BasicBlock *NewBB) override;
240 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
241 const Instruction *Inst,
242 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000243 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
244 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000245 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
246 BasicBlock *NewBB) override;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000247 CloningAction handleCompare(ValueToValueMapTy &VMap,
248 const CmpInst *Compare, BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000249 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
250 const LandingPadInst *LPad,
251 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000252
Reid Kleckner3567d272015-04-02 21:13:31 +0000253 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000254 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
255
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000256private:
257 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000258
Reid Kleckner3567d272015-04-02 21:13:31 +0000259 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000260 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000261
262 // This will be a reference to the field of the same name in the WinEHPrepare
263 // object which instantiates this WinEHCatchDirector object.
264 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000265};
266
267class WinEHCleanupDirector : public WinEHCloningDirectorBase {
268public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000269 WinEHCleanupDirector(Function *CleanupFn, FrameVarInfoMap &VarInfo,
270 LandingPadMap &LPadMap)
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000271 : WinEHCloningDirectorBase(CleanupFn, VarInfo, LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000272
273 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
274 const Instruction *Inst,
275 BasicBlock *NewBB) override;
276 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
277 BasicBlock *NewBB) override;
278 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
279 const Instruction *Inst,
280 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000281 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
282 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000283 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
284 BasicBlock *NewBB) override;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000285 CloningAction handleCompare(ValueToValueMapTy &VMap,
286 const CmpInst *Compare, BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000287 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288 const LandingPadInst *LPad,
289 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000290};
291
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000292class LandingPadActions {
293public:
294 LandingPadActions() : HasCleanupHandlers(false) {}
295
296 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
297 void insertCleanupHandler(CleanupHandler *Action) {
298 Actions.push_back(Action);
299 HasCleanupHandlers = true;
300 }
301
302 bool includesCleanup() const { return HasCleanupHandlers; }
303
David Majnemercde33032015-03-30 22:58:10 +0000304 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000305 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
306 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
307
308private:
309 // Note that this class does not own the ActionHandler objects in this vector.
310 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
311 // in the WinEHPrepare class.
312 SmallVector<ActionHandler *, 4> Actions;
313 bool HasCleanupHandlers;
314};
315
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000316} // end anonymous namespace
317
318char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000319INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
320 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000321
322FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
323 return new WinEHPrepare(TM);
324}
325
Reid Kleckner909ea7e2015-04-23 18:34:01 +0000326// FIXME: Remove this once the backend can handle the prepared IR.
327static cl::opt<bool>
328 SEHPrepare("sehprepare", cl::Hidden,
329 cl::desc("Prepare functions with SEH personalities"));
330
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000331bool WinEHPrepare::runOnFunction(Function &Fn) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000332 // No need to prepare outlined handlers.
333 if (Fn.hasFnAttribute("wineh-parent"))
334 return false;
335
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000336 SmallVector<LandingPadInst *, 4> LPads;
337 SmallVector<ResumeInst *, 4> Resumes;
338 for (BasicBlock &BB : Fn) {
339 if (auto *LP = BB.getLandingPadInst())
340 LPads.push_back(LP);
341 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
342 Resumes.push_back(Resume);
343 }
344
345 // No need to prepare functions that lack landing pads.
346 if (LPads.empty())
347 return false;
348
349 // Classify the personality to see what kind of preparation we need.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000350 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000351
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000352 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000353 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000354 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000355
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000356 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
357
Reid Kleckner909ea7e2015-04-23 18:34:01 +0000358 if (isAsynchronousEHPersonality(Personality) && !SEHPrepare) {
359 // Replace all resume instructions with unreachable.
360 // FIXME: Remove this once the backend can handle the prepared IR.
361 for (ResumeInst *Resume : Resumes) {
362 IRBuilder<>(Resume).CreateUnreachable();
363 Resume->eraseFromParent();
364 }
365 return true;
366 }
367
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000368 // If there were any landing pads, prepareExceptionHandlers will make changes.
369 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370 return true;
371}
372
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000373bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000374
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000375void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
376 AU.addRequired<DominatorTreeWrapperPass>();
377}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000378
Reid Klecknerfd7df282015-04-22 21:05:21 +0000379static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
380 Constant *&Selector, BasicBlock *&NextBB);
381
382// Finds blocks reachable from the starting set Worklist. Does not follow unwind
383// edges or blocks listed in StopPoints.
384static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
385 SetVector<BasicBlock *> &Worklist,
386 const SetVector<BasicBlock *> *StopPoints) {
387 while (!Worklist.empty()) {
388 BasicBlock *BB = Worklist.pop_back_val();
389
390 // Don't cross blocks that we should stop at.
391 if (StopPoints && StopPoints->count(BB))
392 continue;
393
394 if (!ReachableBBs.insert(BB).second)
395 continue; // Already visited.
396
397 // Don't follow unwind edges of invokes.
398 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
399 Worklist.insert(II->getNormalDest());
400 continue;
401 }
402
403 // Otherwise, follow all successors.
404 Worklist.insert(succ_begin(BB), succ_end(BB));
405 }
406}
407
408/// Find all points where exceptional control rejoins normal control flow via
409/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
410static void findCXXEHReturnPoints(Function &F,
411 SetVector<BasicBlock *> &EHReturnBlocks) {
412 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
413 BasicBlock *BB = BBI;
414 for (Instruction &I : *BB) {
415 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
416 // Split the block after the call to llvm.eh.endcatch if there is
417 // anything other than an unconditional branch, or if the successor
418 // starts with a phi.
419 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
420 if (!Br || !Br->isUnconditional() ||
421 isa<PHINode>(Br->getSuccessor(0)->begin())) {
422 DEBUG(dbgs() << "splitting block " << BB->getName()
423 << " with llvm.eh.endcatch\n");
424 BBI = BB->splitBasicBlock(I.getNextNode(), "ehreturn");
425 }
426 // The next BB is normal control flow.
427 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
428 break;
429 }
430 }
431 }
432}
433
434static bool isCatchAllLandingPad(const BasicBlock *BB) {
435 const LandingPadInst *LP = BB->getLandingPadInst();
436 if (!LP)
437 return false;
438 unsigned N = LP->getNumClauses();
439 return (N > 0 && LP->isCatch(N - 1) &&
440 isa<ConstantPointerNull>(LP->getClause(N - 1)));
441}
442
443/// Find all points where exceptions control rejoins normal control flow via
444/// selector dispatch.
445static void findSEHEHReturnPoints(Function &F,
446 SetVector<BasicBlock *> &EHReturnBlocks) {
447 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
448 BasicBlock *BB = BBI;
449 // If the landingpad is a catch-all, treat the whole lpad as if it is
450 // reachable from normal control flow.
451 // FIXME: This is imprecise. We need a better way of identifying where a
452 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
453 // is no difference.
454 if (isCatchAllLandingPad(BB)) {
455 EHReturnBlocks.insert(BB);
456 continue;
457 }
458
459 BasicBlock *CatchHandler;
460 BasicBlock *NextBB;
461 Constant *Selector;
462 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
463 // Split the edge if there is a phi node. Returning from EH to a phi node
464 // is just as impossible as having a phi after an indirectbr.
465 if (isa<PHINode>(CatchHandler->begin())) {
466 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
467 << " to " << CatchHandler->getName() << '\n');
468 BBI = CatchHandler = SplitCriticalEdge(
469 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
470 }
471 EHReturnBlocks.insert(CatchHandler);
472 }
473 }
474}
475
476/// Ensure that all values live into and out of exception handlers are stored
477/// in memory.
478/// FIXME: This falls down when values are defined in one handler and live into
479/// another handler. For example, a cleanup defines a value used only by a
480/// catch handler.
481void WinEHPrepare::demoteValuesLiveAcrossHandlers(
482 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
483 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
484 << F.getName() << '\n');
485
486 // Build a set of all non-exceptional blocks and exceptional blocks.
487 // - Non-exceptional blocks are blocks reachable from the entry block while
488 // not following invoke unwind edges.
489 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
490 // not follow llvm.eh.endcatch blocks, which mark a transition from
491 // exceptional to normal control.
492 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
493 SmallPtrSet<BasicBlock *, 4> EHBlocks;
494 SetVector<BasicBlock *> EHReturnBlocks;
495 SetVector<BasicBlock *> Worklist;
496
497 if (Personality == EHPersonality::MSVC_CXX)
498 findCXXEHReturnPoints(F, EHReturnBlocks);
499 else
500 findSEHEHReturnPoints(F, EHReturnBlocks);
501
502 DEBUG({
503 dbgs() << "identified the following blocks as EH return points:\n";
504 for (BasicBlock *BB : EHReturnBlocks)
505 dbgs() << " " << BB->getName() << '\n';
506 });
507
508 // Join points should not have phis at this point, unless they are a
509 // landingpad, in which case we will demote their phis later.
510#ifndef NDEBUG
511 for (BasicBlock *BB : EHReturnBlocks)
512 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
513 "non-lpad EH return block has phi");
514#endif
515
516 // Normal blocks are the blocks reachable from the entry block and all EH
517 // return points.
518 Worklist = EHReturnBlocks;
519 Worklist.insert(&F.getEntryBlock());
520 findReachableBlocks(NormalBlocks, Worklist, nullptr);
521 DEBUG({
522 dbgs() << "marked the following blocks as normal:\n";
523 for (BasicBlock *BB : NormalBlocks)
524 dbgs() << " " << BB->getName() << '\n';
525 });
526
527 // Exceptional blocks are the blocks reachable from landingpads that don't
528 // cross EH return points.
529 Worklist.clear();
530 for (auto *LPI : LPads)
531 Worklist.insert(LPI->getParent());
532 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
533 DEBUG({
534 dbgs() << "marked the following blocks as exceptional:\n";
535 for (BasicBlock *BB : EHBlocks)
536 dbgs() << " " << BB->getName() << '\n';
537 });
538
539 SetVector<Argument *> ArgsToDemote;
540 SetVector<Instruction *> InstrsToDemote;
541 for (BasicBlock &BB : F) {
542 bool IsNormalBB = NormalBlocks.count(&BB);
543 bool IsEHBB = EHBlocks.count(&BB);
544 if (!IsNormalBB && !IsEHBB)
545 continue; // Blocks that are neither normal nor EH are unreachable.
546 for (Instruction &I : BB) {
547 for (Value *Op : I.operands()) {
548 // Don't demote static allocas, constants, and labels.
549 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
550 continue;
551 auto *AI = dyn_cast<AllocaInst>(Op);
552 if (AI && AI->isStaticAlloca())
553 continue;
554
555 if (auto *Arg = dyn_cast<Argument>(Op)) {
556 if (IsEHBB) {
557 DEBUG(dbgs() << "Demoting argument " << *Arg
558 << " used by EH instr: " << I << "\n");
559 ArgsToDemote.insert(Arg);
560 }
561 continue;
562 }
563
564 auto *OpI = cast<Instruction>(Op);
565 BasicBlock *OpBB = OpI->getParent();
566 // If a value is produced and consumed in the same BB, we don't need to
567 // demote it.
568 if (OpBB == &BB)
569 continue;
570 bool IsOpNormalBB = NormalBlocks.count(OpBB);
571 bool IsOpEHBB = EHBlocks.count(OpBB);
572 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
573 DEBUG({
574 dbgs() << "Demoting instruction live in-out from EH:\n";
575 dbgs() << "Instr: " << *OpI << '\n';
576 dbgs() << "User: " << I << '\n';
577 });
578 InstrsToDemote.insert(OpI);
579 }
580 }
581 }
582 }
583
584 // Demote values live into and out of handlers.
585 // FIXME: This demotion is inefficient. We should insert spills at the point
586 // of definition, insert one reload in each handler that uses the value, and
587 // insert reloads in the BB used to rejoin normal control flow.
588 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
589 for (Instruction *I : InstrsToDemote)
590 DemoteRegToStack(*I, false, AllocaInsertPt);
591
592 // Demote arguments separately, and only for uses in EH blocks.
593 for (Argument *Arg : ArgsToDemote) {
594 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
595 Arg->getName() + ".reg2mem", AllocaInsertPt);
596 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
597 for (User *U : Users) {
598 auto *I = dyn_cast<Instruction>(U);
599 if (I && EHBlocks.count(I->getParent())) {
600 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
601 U->replaceUsesOfWith(Arg, Reload);
602 }
603 }
604 new StoreInst(Arg, Slot, AllocaInsertPt);
605 }
606
607 // Demote landingpad phis, as the landingpad will be removed from the machine
608 // CFG.
609 for (LandingPadInst *LPI : LPads) {
610 BasicBlock *BB = LPI->getParent();
611 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
612 DemotePHIToStack(Phi, AllocaInsertPt);
613 }
614
615 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
616 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
617}
618
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000619bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000620 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000621 // Don't run on functions that are already prepared.
622 for (LandingPadInst *LPad : LPads) {
623 BasicBlock *LPadBB = LPad->getParent();
624 for (Instruction &Inst : *LPadBB)
625 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
626 return false;
627 }
628
629 demoteValuesLiveAcrossHandlers(F, LPads);
630
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000631 // These containers are used to re-map frame variables that are used in
632 // outlined catch and cleanup handlers. They will be populated as the
633 // handlers are outlined.
634 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000635
636 bool HandlersOutlined = false;
637
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000638 Module *M = F.getParent();
639 LLVMContext &Context = M->getContext();
640
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000641 // Create a new function to receive the handler contents.
642 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
643 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000644 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000645
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000646 for (LandingPadInst *LPad : LPads) {
647 // Look for evidence that this landingpad has already been processed.
648 bool LPadHasActionList = false;
649 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000650 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000651 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
652 LPadHasActionList = true;
653 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000654 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000655 }
656
657 // If we've already outlined the handlers for this landingpad,
658 // there's nothing more to do here.
659 if (LPadHasActionList)
660 continue;
661
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000662 // If either of the values in the aggregate returned by the landing pad is
663 // extracted and stored to memory, promote the stored value to a register.
664 promoteLandingPadValues(LPad);
665
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000666 LandingPadActions Actions;
667 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000668
Reid Kleckner9405ef02015-04-10 23:12:29 +0000669 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000670 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000671 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000672 continue;
673 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000674
675 // SEH doesn't do any outlining for catches. Instead, pass the handler
676 // basic block addr to llvm.eh.actions and list the block as a return
677 // target.
678 if (isAsynchronousEHPersonality(Personality)) {
679 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
680 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000681 continue;
682 }
683 }
684
Reid Kleckner9405ef02015-04-10 23:12:29 +0000685 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
686 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000687
688 // Replace the landing pad with a new llvm.eh.action based landing pad.
689 BasicBlock *NewLPadBB = BasicBlock::Create(Context, "lpad", &F, LPadBB);
690 assert(!isa<PHINode>(LPadBB->begin()));
David Majnemercde33032015-03-30 22:58:10 +0000691 auto *NewLPad = cast<LandingPadInst>(LPad->clone());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000692 NewLPadBB->getInstList().push_back(NewLPad);
693 while (!pred_empty(LPadBB)) {
694 auto *pred = *pred_begin(LPadBB);
695 InvokeInst *Invoke = cast<InvokeInst>(pred->getTerminator());
696 Invoke->setUnwindDest(NewLPadBB);
697 }
698
Reid Kleckner86762142015-04-16 00:02:04 +0000699 // If anyone is still using the old landingpad value, just give them undef
700 // instead. The eh pointer and selector values are not real.
701 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
702
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000703 // Replace the mapping of any nested landing pad that previously mapped
704 // to this landing pad with a referenced to the cloned version.
705 for (auto &LPadPair : NestedLPtoOriginalLP) {
706 const LandingPadInst *OriginalLPad = LPadPair.second;
707 if (OriginalLPad == LPad) {
708 LPadPair.second = NewLPad;
709 }
710 }
711
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000712 // Replace uses of the old lpad in phis with this block and delete the old
713 // block.
714 LPadBB->replaceSuccessorsPhiUsesWith(NewLPadBB);
715 LPadBB->getTerminator()->eraseFromParent();
716 new UnreachableInst(LPadBB->getContext(), LPadBB);
717
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000718 // Add a call to describe the actions for this landing pad.
719 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000720 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000721 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000722 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000723 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000724 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000725 // Find the frame escape index of the exception object alloca in the
726 // parent.
727 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000728 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000729 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
730 auto I = FrameVarInfo.find(EHObj);
731 assert(I != FrameVarInfo.end() &&
732 "failed to map llvm.eh.begincatch var");
733 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
734 }
735 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000736 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000737 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000738 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000739 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000740 }
741 CallInst *Recover =
742 CallInst::Create(ActionIntrin, ActionArgs, "recover", NewLPadBB);
743
744 // Add an indirect branch listing possible successors of the catch handlers.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000745 SetVector<BasicBlock *> ReturnTargets;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000746 for (ActionHandler *Action : Actions) {
747 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000748 const auto &CatchTargets = CatchAction->getReturnTargets();
749 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000750 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000751 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000752 IndirectBrInst *Branch =
753 IndirectBrInst::Create(Recover, ReturnTargets.size(), NewLPadBB);
754 for (BasicBlock *Target : ReturnTargets)
755 Branch->addDestination(Target);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000756 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000757
758 // If nothing got outlined, there is no more processing to be done.
759 if (!HandlersOutlined)
760 return false;
761
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000762 // Replace any nested landing pad stubs with the correct action handler.
763 // This must be done before we remove unreachable blocks because it
764 // cleans up references to outlined blocks that will be deleted.
765 for (auto &LPadPair : NestedLPtoOriginalLP)
766 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000767 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000768
David Majnemercde33032015-03-30 22:58:10 +0000769 F.addFnAttr("wineh-parent", F.getName());
770
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000771 // Delete any blocks that were only used by handlers that were outlined above.
772 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000773
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000774 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000775 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000776 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000777
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000778 Function *FrameEscapeFn =
779 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
780 Function *RecoverFrameFn =
781 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +0000782 SmallVector<Value *, 8> AllocasToEscape;
783
784 // Scan the entry block for an existing call to llvm.frameescape. We need to
785 // keep escaping those objects.
786 for (Instruction &I : F.front()) {
787 auto *II = dyn_cast<IntrinsicInst>(&I);
788 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
789 auto Args = II->arg_operands();
790 AllocasToEscape.append(Args.begin(), Args.end());
791 II->eraseFromParent();
792 break;
793 }
794 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000795
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000796 // Finally, replace all of the temporary allocas for frame variables used in
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000797 // the outlined handlers with calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000798 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000799 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000800 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000801 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +0000802
Reid Klecknerb4019412015-04-06 18:50:38 +0000803 // FIXME: We should try to sink unescaped allocas from the parent frame into
804 // the child frame. If the alloca is escaped, we have to use the lifetime
805 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000806
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000807 // Add this alloca to the list of things to escape.
808 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000809
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000810 // Next replace all outlined allocas that are mapped to it.
811 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +0000812 if (TempAlloca == getCatchObjectSentinel())
813 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000814 Function *HandlerFn = TempAlloca->getParent()->getParent();
815 // FIXME: Sink this GEP into the blocks where it is used.
816 Builder.SetInsertPoint(TempAlloca);
817 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
818 Value *RecoverArgs[] = {
819 Builder.CreateBitCast(&F, Int8PtrType, ""),
820 &(HandlerFn->getArgumentList().back()),
821 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000822 Value *RecoveredAlloca = Builder.CreateCall(RecoverFrameFn, RecoverArgs);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000823 // Add a pointer bitcast if the alloca wasn't an i8.
824 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
825 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
826 RecoveredAlloca =
827 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000828 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000829 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
830 TempAlloca->removeFromParent();
831 RecoveredAlloca->takeName(TempAlloca);
832 delete TempAlloca;
833 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000834 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000835
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000836 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
837 // block.
838 Builder.SetInsertPoint(&F.getEntryBlock().back());
839 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
840
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000841 // Clean up the handler action maps we created for this function
842 DeleteContainerSeconds(CatchHandlerMap);
843 CatchHandlerMap.clear();
844 DeleteContainerSeconds(CleanupHandlerMap);
845 CleanupHandlerMap.clear();
846
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000847 return HandlersOutlined;
848}
849
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000850void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
851 // If the return values of the landing pad instruction are extracted and
852 // stored to memory, we want to promote the store locations to reg values.
853 SmallVector<AllocaInst *, 2> EHAllocas;
854
855 // The landingpad instruction returns an aggregate value. Typically, its
856 // value will be passed to a pair of extract value instructions and the
857 // results of those extracts are often passed to store instructions.
858 // In unoptimized code the stored value will often be loaded and then stored
859 // again.
860 for (auto *U : LPad->users()) {
861 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
862 if (!Extract)
863 continue;
864
865 for (auto *EU : Extract->users()) {
866 if (auto *Store = dyn_cast<StoreInst>(EU)) {
867 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
868 EHAllocas.push_back(AV);
869 }
870 }
871 }
872
873 // We can't do this without a dominator tree.
874 assert(DT);
875
876 if (!EHAllocas.empty()) {
877 PromoteMemToReg(EHAllocas, *DT);
878 EHAllocas.clear();
879 }
Reid Kleckner86762142015-04-16 00:02:04 +0000880
881 // After promotion, some extracts may be trivially dead. Remove them.
882 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
883 for (auto *U : Users)
884 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000885}
886
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000887void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
888 LandingPadInst *OutlinedLPad,
889 const LandingPadInst *OriginalLPad,
890 FrameVarInfoMap &FrameVarInfo) {
891 // Get the nested block and erase the unreachable instruction that was
892 // temporarily inserted as its terminator.
893 LLVMContext &Context = ParentFn->getContext();
894 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
895 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
896 OutlinedBB->getTerminator()->eraseFromParent();
897 // That should leave OutlinedLPad as the last instruction in its block.
898 assert(&OutlinedBB->back() == OutlinedLPad);
899
900 // The original landing pad will have already had its action intrinsic
901 // built by the outlining loop. We need to clone that into the outlined
902 // location. It may also be necessary to add references to the exception
903 // variables to the outlined handler in which this landing pad is nested
904 // and remap return instructions in the nested handlers that should return
905 // to an address in the outlined handler.
906 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000907 BasicBlock::const_iterator II = OriginalLPad;
908 ++II;
909 // The instruction after the landing pad should now be a call to eh.actions.
910 const Instruction *Recover = II;
911 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
912 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
913
914 // Remap the exception variables into the outlined function.
915 WinEHFrameVariableMaterializer Materializer(OutlinedHandlerFn, FrameVarInfo);
916 SmallVector<BlockAddress *, 4> ActionTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000917 SmallVector<ActionHandler *, 4> ActionList;
918 parseEHActions(EHActions, ActionList);
919 for (auto *Action : ActionList) {
920 auto *Catch = dyn_cast<CatchHandler>(Action);
921 if (!Catch)
922 continue;
923 // The dyn_cast to function here selects C++ catch handlers and skips
924 // SEH catch handlers.
925 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
926 if (!Handler)
927 continue;
928 // Visit all the return instructions, looking for places that return
929 // to a location within OutlinedHandlerFn.
930 for (BasicBlock &NestedHandlerBB : *Handler) {
931 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
932 if (!Ret)
933 continue;
934
935 // Handler functions must always return a block address.
936 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
937 // The original target will have been in the main parent function,
938 // but if it is the address of a block that has been outlined, it
939 // should be a block that was outlined into OutlinedHandlerFn.
940 assert(BA->getFunction() == ParentFn);
941
942 // Ignore targets that aren't part of OutlinedHandlerFn.
943 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
944 continue;
945
946 // If the return value is the address ofF a block that we
947 // previously outlined into the parent handler function, replace
948 // the return instruction and add the mapped target to the list
949 // of possible return addresses.
950 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
951 assert(MappedBB->getParent() == OutlinedHandlerFn);
952 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
953 Ret->eraseFromParent();
954 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
955 ActionTargets.push_back(NewBA);
956 }
957 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +0000958 DeleteContainerPointers(ActionList);
959 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000960 OutlinedBB->getInstList().push_back(EHActions);
961
962 // Insert an indirect branch into the outlined landing pad BB.
963 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
964 // Add the previously collected action targets.
965 for (auto *Target : ActionTargets)
966 IBr->addDestination(Target->getBasicBlock());
967}
968
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000969// This function examines a block to determine whether the block ends with a
970// conditional branch to a catch handler based on a selector comparison.
971// This function is used both by the WinEHPrepare::findSelectorComparison() and
972// WinEHCleanupDirector::handleTypeIdFor().
973static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
974 Constant *&Selector, BasicBlock *&NextBB) {
975 ICmpInst::Predicate Pred;
976 BasicBlock *TBB, *FBB;
977 Value *LHS, *RHS;
978
979 if (!match(BB->getTerminator(),
980 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
981 return false;
982
983 if (!match(LHS,
984 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
985 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
986 return false;
987
988 if (Pred == CmpInst::ICMP_EQ) {
989 CatchHandler = TBB;
990 NextBB = FBB;
991 return true;
992 }
993
994 if (Pred == CmpInst::ICMP_NE) {
995 CatchHandler = FBB;
996 NextBB = TBB;
997 return true;
998 }
999
1000 return false;
1001}
1002
Andrew Kaylor41758512015-04-20 22:04:09 +00001003static bool isCatchBlock(BasicBlock *BB) {
1004 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1005 II != IE; ++II) {
1006 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1007 return true;
1008 }
1009 return false;
1010}
1011
Andrew Kaylorbb111322015-04-07 21:30:23 +00001012static BasicBlock *createStubLandingPad(Function *Handler,
1013 Value *PersonalityFn) {
1014 // FIXME: Finish this!
1015 LLVMContext &Context = Handler->getContext();
1016 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1017 Handler->getBasicBlockList().push_back(StubBB);
1018 IRBuilder<> Builder(StubBB);
1019 LandingPadInst *LPad = Builder.CreateLandingPad(
1020 llvm::StructType::get(Type::getInt8PtrTy(Context),
1021 Type::getInt32Ty(Context), nullptr),
1022 PersonalityFn, 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001023 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
1024 Function *ActionIntrin = Intrinsic::getDeclaration(Handler->getParent(),
1025 Intrinsic::eh_actions);
1026 Builder.CreateCall(ActionIntrin, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001027 LPad->setCleanup(true);
1028 Builder.CreateUnreachable();
1029 return StubBB;
1030}
1031
1032// Cycles through the blocks in an outlined handler function looking for an
1033// invoke instruction and inserts an invoke of llvm.donothing with an empty
1034// landing pad if none is found. The code that generates the .xdata tables for
1035// the handler needs at least one landing pad to identify the parent function's
1036// personality.
1037void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1038 Value *PersonalityFn) {
1039 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001040 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001041 for (BasicBlock &BB : *Handler) {
1042 TerminatorInst *Terminator = BB.getTerminator();
1043 // If we find an invoke, there is nothing to be done.
1044 auto *II = dyn_cast<InvokeInst>(Terminator);
1045 if (II)
1046 return;
1047 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001048 if (!Ret)
1049 Ret = dyn_cast<ReturnInst>(Terminator);
1050 // If we haven't recorded an unreachable instruction, try this terminator.
1051 if (!Unreached)
1052 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001053 }
1054
1055 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001056 // at least one return or unreachable instruction. We'll insert an invoke of
1057 // llvm.donothing ahead of that instruction.
1058 assert(Ret || Unreached);
1059 TerminatorInst *Term;
1060 if (Ret)
1061 Term = Ret;
1062 else
1063 Term = Unreached;
1064 BasicBlock *OldRetBB = Term->getParent();
1065 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001066 // SplitBlock adds an unconditional branch instruction at the end of the
1067 // parent block. We want to replace that with an invoke call, so we can
1068 // erase it now.
1069 OldRetBB->getTerminator()->eraseFromParent();
1070 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1071 Function *F =
1072 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1073 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1074}
1075
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001076bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1077 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001078 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001079 Module *M = SrcFn->getParent();
1080 LLVMContext &Context = M->getContext();
1081
1082 // Create a new function to receive the handler contents.
1083 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1084 std::vector<Type *> ArgTys;
1085 ArgTys.push_back(Int8PtrType);
1086 ArgTys.push_back(Int8PtrType);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001087 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001088 if (Action->getType() == Catch) {
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001089 FunctionType *FnType = FunctionType::get(Int8PtrType, ArgTys, false);
1090 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1091 SrcFn->getName() + ".catch", M);
1092 } else {
1093 FunctionType *FnType =
1094 FunctionType::get(Type::getVoidTy(Context), ArgTys, false);
1095 Handler = Function::Create(FnType, GlobalVariable::InternalLinkage,
1096 SrcFn->getName() + ".cleanup", M);
1097 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001098
David Majnemercde33032015-03-30 22:58:10 +00001099 Handler->addFnAttr("wineh-parent", SrcFn->getName());
1100
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001101 // Generate a standard prolog to setup the frame recovery structure.
1102 IRBuilder<> Builder(Context);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001103 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1104 Handler->getBasicBlockList().push_front(Entry);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001105 Builder.SetInsertPoint(Entry);
1106 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1107
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001108 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001109
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001110 ValueToValueMapTy VMap;
1111
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001112 LandingPadMap &LPadMap = LPadMaps[LPad];
1113 if (!LPadMap.isInitialized())
1114 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001115 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1116 Constant *Sel = CatchAction->getSelector();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001117 Director.reset(new WinEHCatchDirector(Handler, Sel, VarInfo, LPadMap,
1118 NestedLPtoOriginalLP));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001119 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1120 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001121 } else {
1122 Director.reset(new WinEHCleanupDirector(Handler, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001123 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1124 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001125 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001126
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001127 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001128 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001129
Andrew Kaylor3170e562015-03-20 21:42:54 +00001130 // If the start block contains PHI nodes, we need to map them.
1131 BasicBlock::iterator II = StartBB->begin();
1132 while (auto *PN = dyn_cast<PHINode>(II)) {
1133 bool Mapped = false;
1134 // Look for PHI values that we have already mapped (such as the selector).
1135 for (Value *Val : PN->incoming_values()) {
1136 if (VMap.count(Val)) {
1137 VMap[PN] = VMap[Val];
1138 Mapped = true;
1139 }
1140 }
1141 // If we didn't find a match for this value, map it as an undef.
1142 if (!Mapped) {
1143 VMap[PN] = UndefValue::get(PN->getType());
1144 }
1145 ++II;
1146 }
1147
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001148 // The landing pad value may be used by PHI nodes. It will ultimately be
1149 // eliminated, but we need it in the map for intermediate handling.
1150 VMap[LPad] = UndefValue::get(LPad->getType());
1151
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001152 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001153 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001154
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001155 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001157 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001158
1159 // Move all the instructions in the first cloned block into our entry block.
1160 BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));
1161 Entry->getInstList().splice(Entry->end(), FirstClonedBB->getInstList());
1162 FirstClonedBB->eraseFromParent();
1163
Andrew Kaylorbb111322015-04-07 21:30:23 +00001164 // Make sure we can identify the handler's personality later.
1165 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1166
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001167 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1168 WinEHCatchDirector *CatchDirector =
1169 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1170 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1171 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001172
1173 // Look for blocks that are not part of the landing pad that we just
1174 // outlined but terminate with a call to llvm.eh.endcatch and a
1175 // branch to a block that is in the handler we just outlined.
1176 // These blocks will be part of a nested landing pad that intends to
1177 // return to an address in this handler. This case is best handled
1178 // after both landing pads have been outlined, so for now we'll just
1179 // save the association of the blocks in LPadTargetBlocks. The
1180 // return instructions which are created from these branches will be
1181 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001182 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001183 // VMap maps all values and blocks that were just cloned, but dead
1184 // blocks which were pruned will map to nullptr.
1185 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1186 continue;
1187 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1188 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1189 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1190 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1191 continue;
1192 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1193 --II;
1194 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1195 // This would indicate that a nested landing pad wants to return
1196 // to a block that is outlined into two different handlers.
1197 assert(!LPadTargetBlocks.count(MappedBB));
1198 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1199 }
1200 }
1201 }
1202 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001203
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001204 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001205
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001206 return true;
1207}
1208
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001209/// This BB must end in a selector dispatch. All we need to do is pass the
1210/// handler block to llvm.eh.actions and list it as a possible indirectbr
1211/// target.
1212void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1213 BasicBlock *StartBB) {
1214 BasicBlock *HandlerBB;
1215 BasicBlock *NextBB;
1216 Constant *Selector;
1217 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1218 if (Res) {
1219 // If this was EH dispatch, this must be a conditional branch to the handler
1220 // block.
1221 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1222 // leading to crashes if some optimization hoists stuff here.
1223 assert(CatchAction->getSelector() && HandlerBB &&
1224 "expected catch EH dispatch");
1225 } else {
1226 // This must be a catch-all. Split the block after the landingpad.
1227 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
1228 HandlerBB =
1229 StartBB->splitBasicBlock(StartBB->getFirstInsertionPt(), "catch.all");
1230 }
1231 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1232 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1233 CatchAction->setReturnTargets(Targets);
1234}
1235
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001236void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1237 // Each instance of this class should only ever be used to map a single
1238 // landing pad.
1239 assert(OriginLPad == nullptr || OriginLPad == LPad);
1240
1241 // If the landing pad has already been mapped, there's nothing more to do.
1242 if (OriginLPad == LPad)
1243 return;
1244
1245 OriginLPad = LPad;
1246
1247 // The landingpad instruction returns an aggregate value. Typically, its
1248 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001249 // results of those extracts will have been promoted to reg values before
1250 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001251 for (auto *U : LPad->users()) {
1252 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1253 if (!Extract)
1254 continue;
1255 assert(Extract->getNumIndices() == 1 &&
1256 "Unexpected operation: extracting both landing pad values");
1257 unsigned int Idx = *(Extract->idx_begin());
1258 assert((Idx == 0 || Idx == 1) &&
1259 "Unexpected operation: extracting an unknown landing pad element");
1260 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001261 ExtractedEHPtrs.push_back(Extract);
1262 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001263 ExtractedSelectors.push_back(Extract);
1264 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001265 }
1266}
1267
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001268bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1269 return BB->getLandingPadInst() == OriginLPad;
1270}
1271
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001272bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1273 if (Inst == OriginLPad)
1274 return true;
1275 for (auto *Extract : ExtractedEHPtrs) {
1276 if (Inst == Extract)
1277 return true;
1278 }
1279 for (auto *Extract : ExtractedSelectors) {
1280 if (Inst == Extract)
1281 return true;
1282 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001283 return false;
1284}
1285
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001286void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1287 Value *SelectorValue) const {
1288 // Remap all landing pad extract instructions to the specified values.
1289 for (auto *Extract : ExtractedEHPtrs)
1290 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001291 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001292 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001293}
1294
Reid Klecknerf14787d2015-04-22 00:07:52 +00001295static bool isFrameAddressCall(const Value *V) {
1296 return match(const_cast<Value *>(V),
1297 m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1298}
1299
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001300CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001301 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001302 // If this is one of the boilerplate landing pad instructions, skip it.
1303 // The instruction will have already been remapped in VMap.
1304 if (LPadMap.isLandingPadSpecificInst(Inst))
1305 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001306
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001307 // Nested landing pads will be cloned as stubs, with just the
1308 // landingpad instruction and an unreachable instruction. When
1309 // all landingpads have been outlined, we'll replace this with the
1310 // llvm.eh.actions call and indirect branch created when the
1311 // landing pad was outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001312 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1313 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001314 }
1315
1316 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1317 return handleInvoke(VMap, Invoke, NewBB);
1318
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001319 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1320 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001321
Andrew Kaylorea8df612015-04-17 23:05:43 +00001322 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1323 return handleCompare(VMap, Cmp, NewBB);
1324
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001325 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1326 return handleBeginCatch(VMap, Inst, NewBB);
1327 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1328 return handleEndCatch(VMap, Inst, NewBB);
1329 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1330 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001331
Reid Klecknerf14787d2015-04-22 00:07:52 +00001332 // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1333 // which is the FP of the parent.
1334 if (isFrameAddressCall(Inst)) {
1335 VMap[Inst] = EstablisherFrame;
1336 return CloningDirector::SkipInstruction;
1337 }
1338
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001339 // Continue with the default cloning behavior.
1340 return CloningDirector::CloneInstruction;
1341}
1342
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001343CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1344 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1345 Instruction *NewInst = LPad->clone();
1346 if (LPad->hasName())
1347 NewInst->setName(LPad->getName());
1348 // Save this correlation for later processing.
1349 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1350 VMap[LPad] = NewInst;
1351 BasicBlock::InstListType &InstList = NewBB->getInstList();
1352 InstList.push_back(NewInst);
1353 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1354 return CloningDirector::StopCloningBB;
1355}
1356
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001357CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1358 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1359 // The argument to the call is some form of the first element of the
1360 // landingpad aggregate value, but that doesn't matter. It isn't used
1361 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001362 // The second argument is an outparameter where the exception object will be
1363 // stored. Typically the exception object is a scalar, but it can be an
1364 // aggregate when catching by value.
1365 // FIXME: Leave something behind to indicate where the exception object lives
1366 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001367 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1368 "llvm.eh.begincatch found while "
1369 "outlining catch handler.");
1370 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001371 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1372 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001373 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1374 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001375 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001376 return CloningDirector::SkipInstruction;
1377}
1378
1379CloningDirector::CloningAction
1380WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1381 const Instruction *Inst, BasicBlock *NewBB) {
1382 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1383 // It might be interesting to track whether or not we are inside a catch
1384 // function, but that might make the algorithm more brittle than it needs
1385 // to be.
1386
1387 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001388 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001389 // or at the end of the catch block. However, a catch-all handler may call
1390 // end catch from the original landing pad. If the call occurs in a nested
1391 // landing pad block, we must skip it and continue so that the landing pad
1392 // gets cloned.
1393 auto *ParentBB = IntrinCall->getParent();
1394 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001395 return CloningDirector::SkipInstruction;
1396
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001397 // If an end catch occurs anywhere else we want to terminate the handler
1398 // with a return to the code that follows the endcatch call. If the
1399 // next instruction is not an unconditional branch, we need to split the
1400 // block to provide a clear target for the return instruction.
1401 BasicBlock *ContinueBB;
1402 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1403 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1404 if (!Branch || !Branch->isUnconditional()) {
1405 // We're interrupting the cloning process at this location, so the
1406 // const_cast we're doing here will not cause a problem.
1407 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1408 const_cast<Instruction *>(cast<Instruction>(Next)));
1409 } else {
1410 ContinueBB = Branch->getSuccessor(0);
1411 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001412
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001413 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1414 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001415
1416 // We just added a terminator to the cloned block.
1417 // Tell the caller to stop processing the current basic block so that
1418 // the branch instruction will be skipped.
1419 return CloningDirector::StopCloningBB;
1420}
1421
1422CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1423 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1424 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1425 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1426 // This causes a replacement that will collapse the landing pad CFG based
1427 // on the filter function we intend to match.
1428 if (Selector == CurrentSelector)
1429 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1430 else
1431 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1432 // Tell the caller not to clone this instruction.
1433 return CloningDirector::SkipInstruction;
1434}
1435
1436CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001437WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1438 const InvokeInst *Invoke, BasicBlock *NewBB) {
1439 return CloningDirector::CloneInstruction;
1440}
1441
1442CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001443WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1444 const ResumeInst *Resume, BasicBlock *NewBB) {
1445 // Resume instructions shouldn't be reachable from catch handlers.
1446 // We still need to handle it, but it will be pruned.
1447 BasicBlock::InstListType &InstList = NewBB->getInstList();
1448 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1449 return CloningDirector::StopCloningBB;
1450}
1451
Andrew Kaylorea8df612015-04-17 23:05:43 +00001452CloningDirector::CloningAction
1453WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1454 const CmpInst *Compare, BasicBlock *NewBB) {
1455 const IntrinsicInst *IntrinCall = nullptr;
1456 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1457 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
1458 } else if (match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1459 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1460 }
1461 if (IntrinCall) {
1462 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1463 // This causes a replacement that will collapse the landing pad CFG based
1464 // on the filter function we intend to match.
1465 if (Selector == CurrentSelector->stripPointerCasts()) {
1466 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1467 }
1468 else {
1469 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1470 }
1471 return CloningDirector::SkipInstruction;
1472 }
1473 return CloningDirector::CloneInstruction;
1474}
1475
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001476CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1477 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1478 // The MS runtime will terminate the process if an exception occurs in a
1479 // cleanup handler, so we shouldn't encounter landing pads in the actual
1480 // cleanup code, but they may appear in catch blocks. Depending on where
1481 // we started cloning we may see one, but it will get dropped during dead
1482 // block pruning.
1483 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1484 VMap[LPad] = NewInst;
1485 BasicBlock::InstListType &InstList = NewBB->getInstList();
1486 InstList.push_back(NewInst);
1487 return CloningDirector::StopCloningBB;
1488}
1489
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001490CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1491 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001492 // Cleanup code may flow into catch blocks or the catch block may be part
1493 // of a branch that will be optimized away. We'll insert a return
1494 // instruction now, but it may be pruned before the cloning process is
1495 // complete.
1496 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001497 return CloningDirector::StopCloningBB;
1498}
1499
1500CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1501 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001502 // Cleanup handlers nested within catch handlers may begin with a call to
1503 // eh.endcatch. We can just ignore that instruction.
1504 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001505}
1506
1507CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1508 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001509 // If we encounter a selector comparison while cloning a cleanup handler,
1510 // we want to stop cloning immediately. Anything after the dispatch
1511 // will be outlined into a different handler.
1512 BasicBlock *CatchHandler;
1513 Constant *Selector;
1514 BasicBlock *NextBB;
1515 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1516 CatchHandler, Selector, NextBB)) {
1517 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1518 return CloningDirector::StopCloningBB;
1519 }
1520 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001521 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001522 return CloningDirector::SkipInstruction;
1523}
1524
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001525CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1526 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1527 // All invokes in cleanup handlers can be replaced with calls.
1528 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1529 // Insert a normal call instruction...
1530 CallInst *NewCall =
1531 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1532 Invoke->getName(), NewBB);
1533 NewCall->setCallingConv(Invoke->getCallingConv());
1534 NewCall->setAttributes(Invoke->getAttributes());
1535 NewCall->setDebugLoc(Invoke->getDebugLoc());
1536 VMap[Invoke] = NewCall;
1537
Reid Kleckner6e48a822015-04-10 16:26:42 +00001538 // Remap the operands.
1539 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1540
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001541 // Insert an unconditional branch to the normal destination.
1542 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1543
1544 // The unwind destination won't be cloned into the new function, so
1545 // we don't need to clean up its phi nodes.
1546
1547 // We just added a terminator to the cloned block.
1548 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001549 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001550}
1551
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001552CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1553 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1554 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1555
1556 // We just added a terminator to the cloned block.
1557 // Tell the caller to stop processing the current basic block so that
1558 // the branch instruction will be skipped.
1559 return CloningDirector::StopCloningBB;
1560}
1561
Andrew Kaylorea8df612015-04-17 23:05:43 +00001562CloningDirector::CloningAction
1563WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1564 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001565 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1566 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1567 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1568 return CloningDirector::SkipInstruction;
1569 }
1570 return CloningDirector::CloneInstruction;
1571
1572}
1573
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001574WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
1575 Function *OutlinedFn, FrameVarInfoMap &FrameVarInfo)
1576 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001577 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
1578 Builder.SetInsertPoint(EntryBB, EntryBB->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001579}
1580
1581Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001582 // If we're asked to materialize a static alloca, we temporarily create an
1583 // alloca in the outlined function and add this to the FrameVarInfo map. When
1584 // all the outlining is complete, we'll replace these temporary allocas with
1585 // calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001586 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001587 assert(AV->isStaticAlloca() &&
1588 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00001589 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1590 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001591 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001592 return NewAlloca;
1593 }
1594
Andrew Kaylor72029c62015-03-03 00:41:03 +00001595 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001596 errs() << "Failed to demote instruction used in exception handler:\n";
1597 errs() << " " << *V << '\n';
1598 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001599 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001600
Andrew Kaylor72029c62015-03-03 00:41:03 +00001601 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001602 return nullptr;
1603}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001604
Reid Kleckner3567d272015-04-02 21:13:31 +00001605void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1606 // Catch parameter objects have to live in the parent frame. When we see a use
1607 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1608 // used from another handler. This will prevent us from trying to sink the
1609 // alloca into the handler and ensure that the catch parameter is present in
1610 // the call to llvm.frameescape.
1611 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1612}
1613
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001614// This function maps the catch and cleanup handlers that are reachable from the
1615// specified landing pad. The landing pad sequence will have this basic shape:
1616//
1617// <cleanup handler>
1618// <selector comparison>
1619// <catch handler>
1620// <cleanup handler>
1621// <selector comparison>
1622// <catch handler>
1623// <cleanup handler>
1624// ...
1625//
1626// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1627// any arbitrary control flow, but all paths through the cleanup code must
1628// eventually reach the next selector comparison and no path can skip to a
1629// different selector comparisons, though some paths may terminate abnormally.
1630// Therefore, we will use a depth first search from the start of any given
1631// cleanup block and stop searching when we find the next selector comparison.
1632//
1633// If the landingpad instruction does not have a catch clause, we will assume
1634// that any instructions other than selector comparisons and catch handlers can
1635// be ignored. In practice, these will only be the boilerplate instructions.
1636//
1637// The catch handlers may also have any control structure, but we are only
1638// interested in the start of the catch handlers, so we don't need to actually
1639// follow the flow of the catch handlers. The start of the catch handlers can
1640// be located from the compare instructions, but they can be skipped in the
1641// flow by following the contrary branch.
1642void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1643 LandingPadActions &Actions) {
1644 unsigned int NumClauses = LPad->getNumClauses();
1645 unsigned int HandlersFound = 0;
1646 BasicBlock *BB = LPad->getParent();
1647
1648 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1649
1650 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001651 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001652 return;
1653 }
1654
1655 VisitedBlockSet VisitedBlocks;
1656
1657 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001658 BasicBlock *NextBB = nullptr;
1659
1660 // See if the clause we're looking for is a catch-all.
1661 // If so, the catch begins immediately.
Andrew Kaylorea8df612015-04-17 23:05:43 +00001662 Constant *ExpectedSelector = LPad->getClause(HandlersFound)->stripPointerCasts();
1663 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001664 // The catch all must occur last.
1665 assert(HandlersFound == NumClauses - 1);
1666
Andrew Kaylorea8df612015-04-17 23:05:43 +00001667 // There can be additional selector dispatches in the call chain that we
1668 // need to ignore.
1669 BasicBlock *CatchBlock = nullptr;
1670 Constant *Selector;
1671 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1672 DEBUG(dbgs() << " Found extra catch dispatch in block "
1673 << CatchBlock->getName() << "\n");
1674 BB = NextBB;
1675 }
1676
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001677 // For C++ EH, check if there is any interesting cleanup code before we
1678 // begin the catch. This is important because cleanups cannot rethrow
1679 // exceptions but code called from catches can. For SEH, it isn't
1680 // important if some finally code before a catch-all is executed out of
1681 // line or after recovering from the exception.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001682 if (Personality == EHPersonality::MSVC_CXX)
1683 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001684
1685 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00001686 CatchHandler *Action = nullptr;
1687 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1688 // If the CatchHandlerMap already has an entry for this BB, re-use it.
1689 Action = CatchHandlerMap[BB];
1690 assert(Action->getSelector() == ExpectedSelector);
1691 } else {
1692 // Since this is a catch-all handler, the selector won't actually appear
1693 // in the code anywhere. ExpectedSelector here is the constant null ptr
1694 // that we got from the landing pad instruction.
1695 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1696 CatchHandlerMap[BB] = Action;
1697 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001698 Actions.insertCatchHandler(Action);
1699 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1700 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001701
1702 // Once we reach a catch-all, don't expect to hit a resume instruction.
1703 BB = nullptr;
1704 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001705 }
1706
1707 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00001708 assert(CatchAction);
1709
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001710 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001711 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001712
Andrew Kaylorea8df612015-04-17 23:05:43 +00001713 // When the source program contains multiple nested try blocks the catch
1714 // handlers can get strung together in such a way that we can encounter
1715 // a dispatch for a selector that we've already had a handler for.
1716 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1717 ++HandlersFound;
1718
1719 // Add the catch handler to the action list.
1720 DEBUG(dbgs() << " Found catch dispatch in block "
1721 << CatchAction->getStartBlock()->getName() << "\n");
1722 Actions.insertCatchHandler(CatchAction);
1723 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00001724 // Under some circumstances optimized IR will flow unconditionally into a
1725 // handler block without checking the selector. This can only happen if
1726 // the landing pad has a catch-all handler and the handler for the
1727 // preceeding catch clause is identical to the catch-call handler
1728 // (typically an empty catch). In this case, the handler must be shared
1729 // by all remaining clauses.
1730 if (isa<ConstantPointerNull>(
1731 CatchAction->getSelector()->stripPointerCasts())) {
1732 DEBUG(dbgs() << " Applying early catch-all handler in block "
1733 << CatchAction->getStartBlock()->getName()
1734 << " to all remaining clauses.\n");
1735 Actions.insertCatchHandler(CatchAction);
1736 return;
1737 }
1738
Andrew Kaylorea8df612015-04-17 23:05:43 +00001739 DEBUG(dbgs() << " Found extra catch dispatch in block "
1740 << CatchAction->getStartBlock()->getName() << "\n");
1741 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001742
1743 // Move on to the block after the catch handler.
1744 BB = NextBB;
1745 }
1746
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001747 // If we didn't wind up in a catch-all, see if there is any interesting code
1748 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001749 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001750
1751 // It's possible that some optimization moved code into a landingpad that
1752 // wasn't
1753 // previously being used for cleanup. If that happens, we need to execute
1754 // that
1755 // extra code from a cleanup handler.
1756 if (Actions.includesCleanup() && !LPad->isCleanup())
1757 LPad->setCleanup(true);
1758}
1759
1760// This function searches starting with the input block for the next
1761// block that terminates with a branch whose condition is based on a selector
1762// comparison. This may be the input block. See the mapLandingPadBlocks
1763// comments for a discussion of control flow assumptions.
1764//
1765CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
1766 BasicBlock *&NextBB,
1767 VisitedBlockSet &VisitedBlocks) {
1768 // See if we've already found a catch handler use it.
1769 // Call count() first to avoid creating a null entry for blocks
1770 // we haven't seen before.
1771 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1772 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
1773 NextBB = Action->getNextBB();
1774 return Action;
1775 }
1776
1777 // VisitedBlocks applies only to the current search. We still
1778 // need to consider blocks that we've visited while mapping other
1779 // landing pads.
1780 VisitedBlocks.insert(BB);
1781
1782 BasicBlock *CatchBlock = nullptr;
1783 Constant *Selector = nullptr;
1784
1785 // If this is the first time we've visited this block from any landing pad
1786 // look to see if it is a selector dispatch block.
1787 if (!CatchHandlerMap.count(BB)) {
1788 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1789 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
1790 CatchHandlerMap[BB] = Action;
1791 return Action;
1792 }
Andrew Kaylor41758512015-04-20 22:04:09 +00001793 // If we encounter a block containing an llvm.eh.begincatch before we
1794 // find a selector dispatch block, the handler is assumed to be
1795 // reached unconditionally. This happens for catch-all blocks, but
1796 // it can also happen for other catch handlers that have been combined
1797 // with the catch-all handler during optimization.
1798 if (isCatchBlock(BB)) {
1799 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
1800 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
1801 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
1802 CatchHandlerMap[BB] = Action;
1803 return Action;
1804 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001805 }
1806
1807 // Visit each successor, looking for the dispatch.
1808 // FIXME: We expect to find the dispatch quickly, so this will probably
1809 // work better as a breadth first search.
1810 for (BasicBlock *Succ : successors(BB)) {
1811 if (VisitedBlocks.count(Succ))
1812 continue;
1813
1814 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
1815 if (Action)
1816 return Action;
1817 }
1818 return nullptr;
1819}
1820
Reid Kleckner9405ef02015-04-10 23:12:29 +00001821// These are helper functions to combine repeated code from findCleanupHandlers.
1822static void createCleanupHandler(LandingPadActions &Actions,
1823 CleanupHandlerMapTy &CleanupHandlerMap,
1824 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001825 CleanupHandler *Action = new CleanupHandler(BB);
1826 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00001827 Actions.insertCleanupHandler(Action);
1828 DEBUG(dbgs() << " Found cleanup code in block "
1829 << Action->getStartBlock()->getName() << "\n");
1830}
1831
Reid Kleckner9405ef02015-04-10 23:12:29 +00001832static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
1833 Instruction *MaybeCall) {
1834 // Look for finally blocks that Clang has already outlined for us.
1835 // %fp = call i8* @llvm.frameaddress(i32 0)
1836 // call void @"fin$parent"(iN 1, i8* %fp)
1837 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
1838 MaybeCall = MaybeCall->getNextNode();
1839 CallSite FinallyCall(MaybeCall);
1840 if (!FinallyCall || FinallyCall.arg_size() != 2)
1841 return CallSite();
1842 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
1843 return CallSite();
1844 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
1845 return CallSite();
1846 return FinallyCall;
1847}
1848
1849static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
1850 // Skip single ubr blocks.
1851 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
1852 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
1853 if (Br && Br->isUnconditional())
1854 BB = Br->getSuccessor(0);
1855 else
1856 return BB;
1857 }
1858 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001859}
1860
1861// This function searches starting with the input block for the next block that
1862// contains code that is not part of a catch handler and would not be eliminated
1863// during handler outlining.
1864//
Reid Kleckner9405ef02015-04-10 23:12:29 +00001865void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
1866 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001867 // Here we will skip over the following:
1868 //
1869 // landing pad prolog:
1870 //
1871 // Unconditional branches
1872 //
1873 // Selector dispatch
1874 //
1875 // Resume pattern
1876 //
1877 // Anything else marks the start of an interesting block
1878
1879 BasicBlock *BB = StartBB;
1880 // Anything other than an unconditional branch will kick us out of this loop
1881 // one way or another.
1882 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001883 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001884 // If we've already scanned this block, don't scan it again. If it is
1885 // a cleanup block, there will be an action in the CleanupHandlerMap.
1886 // If we've scanned it and it is not a cleanup block, there will be a
1887 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
1888 // be no entry in the CleanupHandlerMap. We must call count() first to
1889 // avoid creating a null entry for blocks we haven't scanned.
1890 if (CleanupHandlerMap.count(BB)) {
1891 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001892 Actions.insertCleanupHandler(Action);
1893 DEBUG(dbgs() << " Found cleanup code in block "
1894 << Action->getStartBlock()->getName() << "\n");
1895 // FIXME: This cleanup might chain into another, and we need to discover
1896 // that.
1897 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001898 } else {
1899 // Here we handle the case where the cleanup handler map contains a
1900 // value for this block but the value is a nullptr. This means that
1901 // we have previously analyzed the block and determined that it did
1902 // not contain any cleanup code. Based on the earlier analysis, we
1903 // know the the block must end in either an unconditional branch, a
1904 // resume or a conditional branch that is predicated on a comparison
1905 // with a selector. Either the resume or the selector dispatch
1906 // would terminate the search for cleanup code, so the unconditional
1907 // branch is the only case for which we might need to continue
1908 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001909 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
1910 if (SuccBB == BB || SuccBB == EndBB)
1911 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001912 BB = SuccBB;
1913 continue;
1914 }
1915 }
1916
1917 // Create an entry in the cleanup handler map for this block. Initially
1918 // we create an entry that says this isn't a cleanup block. If we find
1919 // cleanup code, the caller will replace this entry.
1920 CleanupHandlerMap[BB] = nullptr;
1921
1922 TerminatorInst *Terminator = BB->getTerminator();
1923
1924 // Landing pad blocks have extra instructions we need to accept.
1925 LandingPadMap *LPadMap = nullptr;
1926 if (BB->isLandingPad()) {
1927 LandingPadInst *LPad = BB->getLandingPadInst();
1928 LPadMap = &LPadMaps[LPad];
1929 if (!LPadMap->isInitialized())
1930 LPadMap->mapLandingPad(LPad);
1931 }
1932
1933 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001934 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
1935 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001936 // resume { i8*, i32 } %lpad.val2
1937 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
1938 InsertValueInst *Insert1 = nullptr;
1939 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001940 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00001941 // If the resume value isn't a phi or landingpad value, it should be a
1942 // series of insertions. Identify them so we can avoid them when scanning
1943 // for cleanups.
1944 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001945 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001946 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00001947 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001948 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
1949 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00001950 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001951 }
1952 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1953 II != IE; ++II) {
1954 Instruction *Inst = II;
1955 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1956 continue;
1957 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
1958 continue;
1959 if (!Inst->hasOneUse() ||
1960 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001961 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001962 }
1963 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00001964 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001965 }
1966
1967 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001968 if (Branch && Branch->isConditional()) {
1969 // Look for the selector dispatch.
1970 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
1971 // %matches = icmp eq i32 %sel, %2
1972 // br i1 %matches, label %catch14, label %eh.resume
1973 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
1974 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00001975 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001976 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1977 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001978 Instruction *Inst = II;
1979 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
1980 continue;
1981 if (Inst == Compare || Inst == Branch)
1982 continue;
1983 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1984 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00001985 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001986 }
1987 // The selector dispatch block should always terminate our search.
1988 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00001989 return;
1990 }
1991
1992 if (isAsynchronousEHPersonality(Personality)) {
1993 // If this is a landingpad block, split the block at the first non-landing
1994 // pad instruction.
1995 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
1996 if (LPadMap) {
1997 while (MaybeCall != BB->getTerminator() &&
1998 LPadMap->isLandingPadSpecificInst(MaybeCall))
1999 MaybeCall = MaybeCall->getNextNode();
2000 }
2001
2002 // Look for outlined finally calls.
2003 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2004 Function *Fin = FinallyCall.getCalledFunction();
2005 assert(Fin && "outlined finally call should be direct");
2006 auto *Action = new CleanupHandler(BB);
2007 Action->setHandlerBlockOrFunc(Fin);
2008 Actions.insertCleanupHandler(Action);
2009 CleanupHandlerMap[BB] = Action;
2010 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2011 << Fin->getName() << " in block "
2012 << Action->getStartBlock()->getName() << "\n");
2013
2014 // Split the block if there were more interesting instructions and look
2015 // for finally calls in the normal successor block.
2016 BasicBlock *SuccBB = BB;
2017 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2018 FinallyCall.getInstruction()->getNextNode() != BB->getTerminator()) {
2019 SuccBB = BB->splitBasicBlock(FinallyCall.getInstruction()->getNextNode());
2020 } else {
2021 if (FinallyCall.isInvoke()) {
2022 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
2023 } else {
2024 SuccBB = BB->getUniqueSuccessor();
2025 assert(SuccBB && "splitOutlinedFinallyCalls didn't insert a branch");
2026 }
2027 }
2028 BB = SuccBB;
2029 if (BB == EndBB)
2030 return;
2031 continue;
2032 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002033 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002034
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002035 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002036 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2037 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002038 Instruction *Inst = II;
2039 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2040 continue;
2041 // Unconditional branches fall through to this loop.
2042 if (Inst == Branch)
2043 continue;
2044 // If this is a catch block, there is no cleanup code to be found.
2045 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002046 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002047 // If this a nested landing pad, it may contain an endcatch call.
2048 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002049 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002050 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002051 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002052 }
2053
2054 // Only unconditional branches in empty blocks should get this far.
2055 assert(Branch && Branch->isUnconditional());
2056 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002057 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002058 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002059 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002060}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002061
2062// This is a public function, declared in WinEHFuncInfo.h and is also
2063// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
2064void llvm::parseEHActions(const IntrinsicInst *II,
David Majnemer69132a72015-04-03 22:49:05 +00002065 SmallVectorImpl<ActionHandler *> &Actions) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002066 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2067 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002068 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002069 if (ActionKind == /*catch=*/1) {
2070 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2071 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2072 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2073 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2074 I += 4;
2075 auto *CH = new CatchHandler(/*BB=*/nullptr, Selector, /*NextBB=*/nullptr);
2076 CH->setHandlerBlockOrFunc(Handler);
2077 CH->setExceptionVarIndex(EHObjIndexVal);
2078 Actions.push_back(CH);
David Majnemer69132a72015-04-03 22:49:05 +00002079 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002080 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2081 I += 2;
2082 auto *CH = new CleanupHandler(/*BB=*/nullptr);
2083 CH->setHandlerBlockOrFunc(Handler);
2084 Actions.push_back(CH);
David Majnemer69132a72015-04-03 22:49:05 +00002085 } else {
2086 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002087 }
2088 }
2089 std::reverse(Actions.begin(), Actions.end());
2090}