blob: e4e63fddebb883ae7fd4c407b156859b4e882d97 [file] [log] [blame]
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass lowers LLVM IR exception handling into something closer to what the
Reid Kleckner0738a9c2015-05-05 17:44:16 +000011// backend wants for functions using a personality function from a runtime
12// provided by MSVC. Functions with other personality functions are left alone
13// and may be prepared by other passes. In particular, all supported MSVC
14// personality functions require cleanup code to be outlined, and the C++
15// personality requires catch handler code to be outlined.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/CodeGen/Passes.h"
20#include "llvm/ADT/MapVector.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000021#include "llvm/ADT/STLExtras.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000022#include "llvm/ADT/SmallSet.h"
Reid Klecknerfd7df282015-04-22 21:05:21 +000023#include "llvm/ADT/SetVector.h"
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000024#include "llvm/ADT/Triple.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000025#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Analysis/LibCallSemantics.h"
David Majnemercde33032015-03-30 22:58:10 +000027#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000028#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/PatternMatch.h"
35#include "llvm/Pass.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000036#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000037#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000039#include "llvm/Transforms/Utils/Cloning.h"
40#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000041#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000042#include <memory>
43
44using namespace llvm;
45using namespace llvm::PatternMatch;
46
47#define DEBUG_TYPE "winehprepare"
48
49namespace {
50
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000051// This map is used to model frame variable usage during outlining, to
52// construct a structure type to hold the frame variables in a frame
53// allocation block, and to remap the frame variable allocas (including
54// spill locations as needed) to GEPs that get the variable from the
55// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000056typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000057
Reid Kleckner3567d272015-04-02 21:13:31 +000058// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
59// quite null.
60AllocaInst *getCatchObjectSentinel() {
61 return static_cast<AllocaInst *>(nullptr) + 1;
62}
63
Andrew Kaylor6b67d422015-03-11 23:22:06 +000064typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
65
Andrew Kaylor6b67d422015-03-11 23:22:06 +000066class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000067class LandingPadMap;
68
69typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
70typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
71
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000072class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000073public:
74 static char ID; // Pass identification, replacement for typeid.
75 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000076 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000077 if (TM)
78 TheTriple = Triple(TM->getTargetTriple());
79 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000080
81 bool runOnFunction(Function &Fn) override;
82
83 bool doFinalization(Module &M) override;
84
85 void getAnalysisUsage(AnalysisUsage &AU) const override;
86
87 const char *getPassName() const override {
88 return "Windows exception handling preparation";
89 }
90
91private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000092 bool prepareExceptionHandlers(Function &F,
93 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000094 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000095 void demoteValuesLiveAcrossHandlers(Function &F,
96 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +000097 void findSEHEHReturnPoints(Function &F,
98 SetVector<BasicBlock *> &EHReturnBlocks);
99 void findCXXEHReturnPoints(Function &F,
100 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000101 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
102 SetVector<BasicBlock*> &Targets);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000103 void completeNestedLandingPad(Function *ParentFn,
104 LandingPadInst *OutlinedLPad,
105 const LandingPadInst *OriginalLPad,
106 FrameVarInfoMap &VarInfo);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000107 Function *createHandlerFunc(Type *RetTy, const Twine &Name, Module *M,
108 Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000109 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
110 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000111 FrameVarInfoMap &VarInfo);
Andrew Kaylorbb111322015-04-07 21:30:23 +0000112 void addStubInvokeToHandlerIfNeeded(Function *Handler, Value *PersonalityFn);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000113
114 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
115 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
116 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000117 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
118 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000119
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000120 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
121
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000122 Triple TheTriple;
123
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000124 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000125 DominatorTree *DT = nullptr;
126 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000127 CatchHandlerMapTy CatchHandlerMap;
128 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000129 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000130
131 // This maps landing pad instructions found in outlined handlers to
132 // the landing pad instruction in the parent function from which they
133 // were cloned. The cloned/nested landing pad is used as the key
134 // because the landing pad may be cloned into multiple handlers.
135 // This map will be used to add the llvm.eh.actions call to the nested
136 // landing pads after all handlers have been outlined.
137 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
138
139 // This maps blocks in the parent function which are destinations of
140 // catch handlers to cloned blocks in (other) outlined handlers. This
141 // handles the case where a nested landing pads has a catch handler that
142 // returns to a handler function rather than the parent function.
143 // The original block is used as the key here because there should only
144 // ever be one handler function from which the cloned block is not pruned.
145 // The original block will be pruned from the parent function after all
146 // handlers have been outlined. This map will be used to adjust the
147 // return instructions of handlers which return to the block that was
148 // outlined into a handler. This is done after all handlers have been
149 // outlined but before the outlined code is pruned from the parent function.
150 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000151
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000152 // Map from outlined handler to call to llvm.frameaddress(1). Only used for
153 // 32-bit EH.
154 DenseMap<Function *, Value *> HandlerToParentFP;
155
Reid Kleckner582786b2015-04-30 18:17:12 +0000156 AllocaInst *SEHExceptionCodeSlot = nullptr;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000157};
158
159class WinEHFrameVariableMaterializer : public ValueMaterializer {
160public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000161 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000162 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000163 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000164
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000165 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000166
Reid Kleckner3567d272015-04-02 21:13:31 +0000167 void escapeCatchObject(Value *V);
168
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000169private:
170 FrameVarInfoMap &FrameVarInfo;
171 IRBuilder<> Builder;
172};
173
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000174class LandingPadMap {
175public:
176 LandingPadMap() : OriginLPad(nullptr) {}
177 void mapLandingPad(const LandingPadInst *LPad);
178
179 bool isInitialized() { return OriginLPad != nullptr; }
180
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000181 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000182 bool isLandingPadSpecificInst(const Instruction *Inst) const;
183
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000184 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
185 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000186
187private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000188 const LandingPadInst *OriginLPad;
189 // We will normally only see one of each of these instructions, but
190 // if more than one occurs for some reason we can handle that.
191 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
192 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000193};
194
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000195class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000196public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000197 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
198 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
199 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000200 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
201 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000202 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000203
204 CloningAction handleInstruction(ValueToValueMapTy &VMap,
205 const Instruction *Inst,
206 BasicBlock *NewBB) override;
207
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000208 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
209 const Instruction *Inst,
210 BasicBlock *NewBB) = 0;
211 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
212 const Instruction *Inst,
213 BasicBlock *NewBB) = 0;
214 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
215 const Instruction *Inst,
216 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000217 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
218 const InvokeInst *Invoke,
219 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000220 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
221 const ResumeInst *Resume,
222 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000223 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
224 const CmpInst *Compare,
225 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000226 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
227 const LandingPadInst *LPad,
228 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000229
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000230 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
231
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000232protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000233 WinEHFrameVariableMaterializer Materializer;
234 Type *SelectorIDType;
235 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000236 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000237
238 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000239 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000240};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000241
242class WinEHCatchDirector : public WinEHCloningDirectorBase {
243public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000244 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000245 Function *CatchFn, Value *ParentFP, Value *Selector,
246 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000247 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000248 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000249 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000250 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000251
252 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
253 const Instruction *Inst,
254 BasicBlock *NewBB) override;
255 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
256 BasicBlock *NewBB) override;
257 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
258 const Instruction *Inst,
259 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000260 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
261 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000262 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
263 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000264 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
265 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000266 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
267 const LandingPadInst *LPad,
268 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000269
Reid Kleckner3567d272015-04-02 21:13:31 +0000270 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000271 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
272
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000273private:
274 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000275
Reid Kleckner3567d272015-04-02 21:13:31 +0000276 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000277 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000278
279 // This will be a reference to the field of the same name in the WinEHPrepare
280 // object which instantiates this WinEHCatchDirector object.
281 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000282};
283
284class WinEHCleanupDirector : public WinEHCloningDirectorBase {
285public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000286 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
287 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
288 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
289 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000290
291 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
292 const Instruction *Inst,
293 BasicBlock *NewBB) override;
294 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
295 BasicBlock *NewBB) override;
296 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
297 const Instruction *Inst,
298 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000299 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
300 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000301 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
302 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000303 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
304 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000305 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
306 const LandingPadInst *LPad,
307 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000308};
309
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000310class LandingPadActions {
311public:
312 LandingPadActions() : HasCleanupHandlers(false) {}
313
314 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
315 void insertCleanupHandler(CleanupHandler *Action) {
316 Actions.push_back(Action);
317 HasCleanupHandlers = true;
318 }
319
320 bool includesCleanup() const { return HasCleanupHandlers; }
321
David Majnemercde33032015-03-30 22:58:10 +0000322 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000323 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
324 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
325
326private:
327 // Note that this class does not own the ActionHandler objects in this vector.
328 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
329 // in the WinEHPrepare class.
330 SmallVector<ActionHandler *, 4> Actions;
331 bool HasCleanupHandlers;
332};
333
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000334} // end anonymous namespace
335
336char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000337INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
338 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000339
340FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
341 return new WinEHPrepare(TM);
342}
343
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000344bool WinEHPrepare::runOnFunction(Function &Fn) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000345 // No need to prepare outlined handlers.
346 if (Fn.hasFnAttribute("wineh-parent"))
347 return false;
348
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000349 SmallVector<LandingPadInst *, 4> LPads;
350 SmallVector<ResumeInst *, 4> Resumes;
351 for (BasicBlock &BB : Fn) {
352 if (auto *LP = BB.getLandingPadInst())
353 LPads.push_back(LP);
354 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
355 Resumes.push_back(Resume);
356 }
357
358 // No need to prepare functions that lack landing pads.
359 if (LPads.empty())
360 return false;
361
362 // Classify the personality to see what kind of preparation we need.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000363 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000364
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000365 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000366 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000367 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000368
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000369 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
370
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000371 // If there were any landing pads, prepareExceptionHandlers will make changes.
372 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000373 return true;
374}
375
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000376bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000377
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000378void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
379 AU.addRequired<DominatorTreeWrapperPass>();
380}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000381
Reid Klecknerfd7df282015-04-22 21:05:21 +0000382static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
383 Constant *&Selector, BasicBlock *&NextBB);
384
385// Finds blocks reachable from the starting set Worklist. Does not follow unwind
386// edges or blocks listed in StopPoints.
387static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
388 SetVector<BasicBlock *> &Worklist,
389 const SetVector<BasicBlock *> *StopPoints) {
390 while (!Worklist.empty()) {
391 BasicBlock *BB = Worklist.pop_back_val();
392
393 // Don't cross blocks that we should stop at.
394 if (StopPoints && StopPoints->count(BB))
395 continue;
396
397 if (!ReachableBBs.insert(BB).second)
398 continue; // Already visited.
399
400 // Don't follow unwind edges of invokes.
401 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
402 Worklist.insert(II->getNormalDest());
403 continue;
404 }
405
406 // Otherwise, follow all successors.
407 Worklist.insert(succ_begin(BB), succ_end(BB));
408 }
409}
410
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000411// Attempt to find an instruction where a block can be split before
412// a call to llvm.eh.begincatch and its operands. If the block
413// begins with the begincatch call or one of its adjacent operands
414// the block will not be split.
415static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
416 IntrinsicInst *II) {
417 // If the begincatch call is already the first instruction in the block,
418 // don't split.
419 Instruction *FirstNonPHI = BB->getFirstNonPHI();
420 if (II == FirstNonPHI)
421 return nullptr;
422
423 // If either operand is in the same basic block as the instruction and
424 // isn't used by another instruction before the begincatch call, include it
425 // in the split block.
426 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
427 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
428
429 Instruction *I = II->getPrevNode();
430 Instruction *LastI = II;
431
432 while (I == Op0 || I == Op1) {
433 // If the block begins with one of the operands and there are no other
434 // instructions between the operand and the begincatch call, don't split.
435 if (I == FirstNonPHI)
436 return nullptr;
437
438 LastI = I;
439 I = I->getPrevNode();
440 }
441
442 // If there is at least one instruction in the block before the begincatch
443 // call and its operands, split the block at either the begincatch or
444 // its operand.
445 return LastI;
446}
447
Reid Klecknerfd7df282015-04-22 21:05:21 +0000448/// Find all points where exceptional control rejoins normal control flow via
449/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000450void WinEHPrepare::findCXXEHReturnPoints(
451 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000452 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
453 BasicBlock *BB = BBI;
454 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000455 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000456 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000457 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
458 if (SplitPt) {
459 // Split the block before the llvm.eh.begincatch call to allow
460 // cleanup and catch code to be distinguished later.
461 // Do not update BBI because we still need to process the
462 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000463 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000464 break;
465 }
466 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000467 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
468 // Split the block after the call to llvm.eh.endcatch if there is
469 // anything other than an unconditional branch, or if the successor
470 // starts with a phi.
471 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
472 if (!Br || !Br->isUnconditional() ||
473 isa<PHINode>(Br->getSuccessor(0)->begin())) {
474 DEBUG(dbgs() << "splitting block " << BB->getName()
475 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000476 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000477 }
478 // The next BB is normal control flow.
479 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
480 break;
481 }
482 }
483 }
484}
485
486static bool isCatchAllLandingPad(const BasicBlock *BB) {
487 const LandingPadInst *LP = BB->getLandingPadInst();
488 if (!LP)
489 return false;
490 unsigned N = LP->getNumClauses();
491 return (N > 0 && LP->isCatch(N - 1) &&
492 isa<ConstantPointerNull>(LP->getClause(N - 1)));
493}
494
495/// Find all points where exceptions control rejoins normal control flow via
496/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000497void WinEHPrepare::findSEHEHReturnPoints(
498 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000499 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
500 BasicBlock *BB = BBI;
501 // If the landingpad is a catch-all, treat the whole lpad as if it is
502 // reachable from normal control flow.
503 // FIXME: This is imprecise. We need a better way of identifying where a
504 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
505 // is no difference.
506 if (isCatchAllLandingPad(BB)) {
507 EHReturnBlocks.insert(BB);
508 continue;
509 }
510
511 BasicBlock *CatchHandler;
512 BasicBlock *NextBB;
513 Constant *Selector;
514 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
515 // Split the edge if there is a phi node. Returning from EH to a phi node
516 // is just as impossible as having a phi after an indirectbr.
517 if (isa<PHINode>(CatchHandler->begin())) {
518 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
519 << " to " << CatchHandler->getName() << '\n');
520 BBI = CatchHandler = SplitCriticalEdge(
521 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
522 }
523 EHReturnBlocks.insert(CatchHandler);
524 }
525 }
526}
527
528/// Ensure that all values live into and out of exception handlers are stored
529/// in memory.
530/// FIXME: This falls down when values are defined in one handler and live into
531/// another handler. For example, a cleanup defines a value used only by a
532/// catch handler.
533void WinEHPrepare::demoteValuesLiveAcrossHandlers(
534 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
535 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
536 << F.getName() << '\n');
537
538 // Build a set of all non-exceptional blocks and exceptional blocks.
539 // - Non-exceptional blocks are blocks reachable from the entry block while
540 // not following invoke unwind edges.
541 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
542 // not follow llvm.eh.endcatch blocks, which mark a transition from
543 // exceptional to normal control.
544 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
545 SmallPtrSet<BasicBlock *, 4> EHBlocks;
546 SetVector<BasicBlock *> EHReturnBlocks;
547 SetVector<BasicBlock *> Worklist;
548
549 if (Personality == EHPersonality::MSVC_CXX)
550 findCXXEHReturnPoints(F, EHReturnBlocks);
551 else
552 findSEHEHReturnPoints(F, EHReturnBlocks);
553
554 DEBUG({
555 dbgs() << "identified the following blocks as EH return points:\n";
556 for (BasicBlock *BB : EHReturnBlocks)
557 dbgs() << " " << BB->getName() << '\n';
558 });
559
Andrew Kaylor91307432015-04-28 22:01:51 +0000560// Join points should not have phis at this point, unless they are a
561// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000562#ifndef NDEBUG
563 for (BasicBlock *BB : EHReturnBlocks)
564 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
565 "non-lpad EH return block has phi");
566#endif
567
568 // Normal blocks are the blocks reachable from the entry block and all EH
569 // return points.
570 Worklist = EHReturnBlocks;
571 Worklist.insert(&F.getEntryBlock());
572 findReachableBlocks(NormalBlocks, Worklist, nullptr);
573 DEBUG({
574 dbgs() << "marked the following blocks as normal:\n";
575 for (BasicBlock *BB : NormalBlocks)
576 dbgs() << " " << BB->getName() << '\n';
577 });
578
579 // Exceptional blocks are the blocks reachable from landingpads that don't
580 // cross EH return points.
581 Worklist.clear();
582 for (auto *LPI : LPads)
583 Worklist.insert(LPI->getParent());
584 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
585 DEBUG({
586 dbgs() << "marked the following blocks as exceptional:\n";
587 for (BasicBlock *BB : EHBlocks)
588 dbgs() << " " << BB->getName() << '\n';
589 });
590
591 SetVector<Argument *> ArgsToDemote;
592 SetVector<Instruction *> InstrsToDemote;
593 for (BasicBlock &BB : F) {
594 bool IsNormalBB = NormalBlocks.count(&BB);
595 bool IsEHBB = EHBlocks.count(&BB);
596 if (!IsNormalBB && !IsEHBB)
597 continue; // Blocks that are neither normal nor EH are unreachable.
598 for (Instruction &I : BB) {
599 for (Value *Op : I.operands()) {
600 // Don't demote static allocas, constants, and labels.
601 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
602 continue;
603 auto *AI = dyn_cast<AllocaInst>(Op);
604 if (AI && AI->isStaticAlloca())
605 continue;
606
607 if (auto *Arg = dyn_cast<Argument>(Op)) {
608 if (IsEHBB) {
609 DEBUG(dbgs() << "Demoting argument " << *Arg
610 << " used by EH instr: " << I << "\n");
611 ArgsToDemote.insert(Arg);
612 }
613 continue;
614 }
615
616 auto *OpI = cast<Instruction>(Op);
617 BasicBlock *OpBB = OpI->getParent();
618 // If a value is produced and consumed in the same BB, we don't need to
619 // demote it.
620 if (OpBB == &BB)
621 continue;
622 bool IsOpNormalBB = NormalBlocks.count(OpBB);
623 bool IsOpEHBB = EHBlocks.count(OpBB);
624 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
625 DEBUG({
626 dbgs() << "Demoting instruction live in-out from EH:\n";
627 dbgs() << "Instr: " << *OpI << '\n';
628 dbgs() << "User: " << I << '\n';
629 });
630 InstrsToDemote.insert(OpI);
631 }
632 }
633 }
634 }
635
636 // Demote values live into and out of handlers.
637 // FIXME: This demotion is inefficient. We should insert spills at the point
638 // of definition, insert one reload in each handler that uses the value, and
639 // insert reloads in the BB used to rejoin normal control flow.
640 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
641 for (Instruction *I : InstrsToDemote)
642 DemoteRegToStack(*I, false, AllocaInsertPt);
643
644 // Demote arguments separately, and only for uses in EH blocks.
645 for (Argument *Arg : ArgsToDemote) {
646 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
647 Arg->getName() + ".reg2mem", AllocaInsertPt);
648 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
649 for (User *U : Users) {
650 auto *I = dyn_cast<Instruction>(U);
651 if (I && EHBlocks.count(I->getParent())) {
652 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
653 U->replaceUsesOfWith(Arg, Reload);
654 }
655 }
656 new StoreInst(Arg, Slot, AllocaInsertPt);
657 }
658
659 // Demote landingpad phis, as the landingpad will be removed from the machine
660 // CFG.
661 for (LandingPadInst *LPI : LPads) {
662 BasicBlock *BB = LPI->getParent();
663 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
664 DemotePHIToStack(Phi, AllocaInsertPt);
665 }
666
667 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
668 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
669}
670
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000671bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000672 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000673 // Don't run on functions that are already prepared.
674 for (LandingPadInst *LPad : LPads) {
675 BasicBlock *LPadBB = LPad->getParent();
676 for (Instruction &Inst : *LPadBB)
677 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
678 return false;
679 }
680
681 demoteValuesLiveAcrossHandlers(F, LPads);
682
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000683 // These containers are used to re-map frame variables that are used in
684 // outlined catch and cleanup handlers. They will be populated as the
685 // handlers are outlined.
686 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000687
688 bool HandlersOutlined = false;
689
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000690 Module *M = F.getParent();
691 LLVMContext &Context = M->getContext();
692
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000693 // Create a new function to receive the handler contents.
694 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
695 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000696 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000697
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000698 if (isAsynchronousEHPersonality(Personality)) {
699 // FIXME: Switch the ehptr type to i32 and then switch this.
700 SEHExceptionCodeSlot =
701 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
702 F.getEntryBlock().getFirstInsertionPt());
703 }
704
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000705 // This container stores the llvm.eh.recover and IndirectBr instructions
706 // that make up the body of each landing pad after it has been outlined.
707 // We need to defer the population of the target list for the indirectbr
708 // until all landing pads have been outlined so that we can handle the
709 // case of blocks in the target that are reached only from nested
710 // landing pads.
711 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
712
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000713 for (LandingPadInst *LPad : LPads) {
714 // Look for evidence that this landingpad has already been processed.
715 bool LPadHasActionList = false;
716 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000717 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000718 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
719 LPadHasActionList = true;
720 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000721 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000722 }
723
724 // If we've already outlined the handlers for this landingpad,
725 // there's nothing more to do here.
726 if (LPadHasActionList)
727 continue;
728
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000729 // If either of the values in the aggregate returned by the landing pad is
730 // extracted and stored to memory, promote the stored value to a register.
731 promoteLandingPadValues(LPad);
732
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000733 LandingPadActions Actions;
734 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000735
Reid Kleckner9405ef02015-04-10 23:12:29 +0000736 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000737 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000738 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000739 continue;
740 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000741
742 // SEH doesn't do any outlining for catches. Instead, pass the handler
743 // basic block addr to llvm.eh.actions and list the block as a return
744 // target.
745 if (isAsynchronousEHPersonality(Personality)) {
746 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
747 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000748 continue;
749 }
750 }
751
Reid Kleckner9405ef02015-04-10 23:12:29 +0000752 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
753 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000754
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000755 // Split the block after the landingpad instruction so that it is just a
756 // call to llvm.eh.actions followed by indirectbr.
757 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000758 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000759 // Erase the branch inserted by the split so we can insert indirectbr.
760 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000761
Reid Klecknere3af86e2015-04-23 21:22:30 +0000762 // Replace all extracted values with undef and ultimately replace the
763 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000764 SmallVector<Instruction *, 4> SEHCodeUses;
765 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000766 for (User *U : LPad->users()) {
767 auto *E = dyn_cast<ExtractValueInst>(U);
768 if (!E)
769 continue;
770 assert(E->getNumIndices() == 1 &&
771 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000772 unsigned Idx = *E->idx_begin();
773 assert((Idx == 0 || Idx == 1) && "unexpected index");
774 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
775 SEHCodeUses.push_back(E);
776 else
777 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000778 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000779 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000780 E->replaceAllUsesWith(UndefValue::get(E->getType()));
781 E->eraseFromParent();
782 }
783 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000784
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000785 // Rewrite uses of the exception pointer to loads of an alloca.
786 for (Instruction *E : SEHCodeUses) {
787 SmallVector<Use *, 4> Uses;
788 for (Use &U : E->uses())
789 Uses.push_back(&U);
790 for (Use *U : Uses) {
791 auto *I = cast<Instruction>(U->getUser());
792 if (isa<ResumeInst>(I))
793 continue;
794 LoadInst *LI;
795 if (auto *Phi = dyn_cast<PHINode>(I))
796 LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false,
797 Phi->getIncomingBlock(*U));
798 else
799 LI = new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I);
800 U->set(LI);
801 }
802 E->replaceAllUsesWith(UndefValue::get(E->getType()));
803 E->eraseFromParent();
804 }
805
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000806 // Add a call to describe the actions for this landing pad.
807 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000808 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000809 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000810 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000811 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000812 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000813 // Find the frame escape index of the exception object alloca in the
814 // parent.
815 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000816 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000817 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
818 auto I = FrameVarInfo.find(EHObj);
819 assert(I != FrameVarInfo.end() &&
820 "failed to map llvm.eh.begincatch var");
821 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
822 }
823 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000824 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000825 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000826 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000827 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000828 }
829 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000830 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000831
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000832 if (isAsynchronousEHPersonality(Personality)) {
833 // SEH can create the target list directly, since catch handlers
834 // are not outlined.
835 SetVector<BasicBlock *> ReturnTargets;
836 for (ActionHandler *Action : Actions) {
837 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
838 const auto &CatchTargets = CatchAction->getReturnTargets();
839 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
840 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000841 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000842 IndirectBrInst *Branch =
843 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
844 for (BasicBlock *Target : ReturnTargets)
845 Branch->addDestination(Target);
846 } else {
847 // C++ EH must defer populating the targets to handle the case of
848 // targets that are reached indirectly through nested landing pads.
849 IndirectBrInst *Branch =
850 IndirectBrInst::Create(Recover, 0, LPadBB);
851
852 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000853 }
854 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000855
856 // If nothing got outlined, there is no more processing to be done.
857 if (!HandlersOutlined)
858 return false;
859
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000860 // Replace any nested landing pad stubs with the correct action handler.
861 // This must be done before we remove unreachable blocks because it
862 // cleans up references to outlined blocks that will be deleted.
863 for (auto &LPadPair : NestedLPtoOriginalLP)
864 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000865 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000866
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000867 // Populate the indirectbr instructions' target lists if we deferred
868 // doing so above.
869 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000870 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000871 for (auto &LPadImplPair : LPadImpls) {
872 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
873 IndirectBrInst *Branch = LPadImplPair.second;
874
875 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000876 parseEHActions(Recover, ActionList);
877
878 // Add an indirect branch listing possible successors of the catch handlers.
879 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000880 for (const auto &Action : ActionList) {
881 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000882 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
883 getPossibleReturnTargets(&F, Handler, ReturnTargets);
884 }
885 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000886 ActionList.clear();
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000887 for (BasicBlock *Target : ReturnTargets) {
888 Branch->addDestination(Target);
889 // The target may be a block that we excepted to get pruned.
890 // If it is, it may contain a call to llvm.eh.endcatch.
891 if (CheckedTargets.insert(Target)) {
892 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
893 // will be followed by an unconditional branch.
894 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
895 if (Br && Br->isUnconditional() &&
896 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
897 Instruction *Prev = Br->getPrevNode();
898 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
899 Prev->eraseFromParent();
900 }
901 }
902 }
903 }
904 LPadImpls.clear();
905
David Majnemercde33032015-03-30 22:58:10 +0000906 F.addFnAttr("wineh-parent", F.getName());
907
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000908 // Delete any blocks that were only used by handlers that were outlined above.
909 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000910
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000911 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000912 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000913 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000914
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000915 Function *FrameEscapeFn =
916 Intrinsic::getDeclaration(M, Intrinsic::frameescape);
917 Function *RecoverFrameFn =
918 Intrinsic::getDeclaration(M, Intrinsic::framerecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +0000919 SmallVector<Value *, 8> AllocasToEscape;
920
921 // Scan the entry block for an existing call to llvm.frameescape. We need to
922 // keep escaping those objects.
923 for (Instruction &I : F.front()) {
924 auto *II = dyn_cast<IntrinsicInst>(&I);
925 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
926 auto Args = II->arg_operands();
927 AllocasToEscape.append(Args.begin(), Args.end());
928 II->eraseFromParent();
929 break;
930 }
931 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000932
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000933 // Finally, replace all of the temporary allocas for frame variables used in
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000934 // the outlined handlers with calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000935 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +0000936 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000937 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000938 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +0000939
Reid Klecknerb4019412015-04-06 18:50:38 +0000940 // FIXME: We should try to sink unescaped allocas from the parent frame into
941 // the child frame. If the alloca is escaped, we have to use the lifetime
942 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000943
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000944 // Add this alloca to the list of things to escape.
945 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000946
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000947 // Next replace all outlined allocas that are mapped to it.
948 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +0000949 if (TempAlloca == getCatchObjectSentinel())
950 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000951 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000952 llvm::Value *FP = HandlerToParentFP[HandlerFn];
953 assert(FP);
954
955 // FIXME: Sink this framerecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000956 Builder.SetInsertPoint(TempAlloca);
957 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
958 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000959 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000960 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000961 Instruction *RecoveredAlloca =
962 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
963
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000964 // Add a pointer bitcast if the alloca wasn't an i8.
965 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
966 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000967 RecoveredAlloca = cast<Instruction>(
968 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000969 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000970 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
971 TempAlloca->removeFromParent();
972 RecoveredAlloca->takeName(TempAlloca);
973 delete TempAlloca;
974 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000975 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000976
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000977 // Insert 'call void (...)* @llvm.frameescape(...)' at the end of the entry
978 // block.
979 Builder.SetInsertPoint(&F.getEntryBlock().back());
980 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
981
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000982 if (SEHExceptionCodeSlot) {
983 if (SEHExceptionCodeSlot->hasNUses(0))
984 SEHExceptionCodeSlot->eraseFromParent();
Reid Kleckner0738a9c2015-05-05 17:44:16 +0000985 else if (isAllocaPromotable(SEHExceptionCodeSlot))
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000986 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
987 }
988
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000989 // Clean up the handler action maps we created for this function
990 DeleteContainerSeconds(CatchHandlerMap);
991 CatchHandlerMap.clear();
992 DeleteContainerSeconds(CleanupHandlerMap);
993 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000994 HandlerToParentFP.clear();
995 DT = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +0000996 SEHExceptionCodeSlot = nullptr;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000997
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000998 return HandlersOutlined;
999}
1000
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001001void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1002 // If the return values of the landing pad instruction are extracted and
1003 // stored to memory, we want to promote the store locations to reg values.
1004 SmallVector<AllocaInst *, 2> EHAllocas;
1005
1006 // The landingpad instruction returns an aggregate value. Typically, its
1007 // value will be passed to a pair of extract value instructions and the
1008 // results of those extracts are often passed to store instructions.
1009 // In unoptimized code the stored value will often be loaded and then stored
1010 // again.
1011 for (auto *U : LPad->users()) {
1012 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1013 if (!Extract)
1014 continue;
1015
1016 for (auto *EU : Extract->users()) {
1017 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1018 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1019 EHAllocas.push_back(AV);
1020 }
1021 }
1022 }
1023
1024 // We can't do this without a dominator tree.
1025 assert(DT);
1026
1027 if (!EHAllocas.empty()) {
1028 PromoteMemToReg(EHAllocas, *DT);
1029 EHAllocas.clear();
1030 }
Reid Kleckner86762142015-04-16 00:02:04 +00001031
1032 // After promotion, some extracts may be trivially dead. Remove them.
1033 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1034 for (auto *U : Users)
1035 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001036}
1037
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001038void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1039 Function *HandlerF,
1040 SetVector<BasicBlock*> &Targets) {
1041 for (BasicBlock &BB : *HandlerF) {
1042 // If the handler contains landing pads, check for any
1043 // handlers that may return directly to a block in the
1044 // parent function.
1045 if (auto *LPI = BB.getLandingPadInst()) {
1046 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001047 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001048 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001049 for (const auto &Action : ActionList) {
1050 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001051 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1052 getPossibleReturnTargets(ParentF, NestedF, Targets);
1053 }
1054 }
1055 }
1056
1057 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1058 if (!Ret)
1059 continue;
1060
1061 // Handler functions must always return a block address.
1062 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1063
1064 // If this is the handler for a nested landing pad, the
1065 // return address may have been remapped to a block in the
1066 // parent handler. We're not interested in those.
1067 if (BA->getFunction() != ParentF)
1068 continue;
1069
1070 Targets.insert(BA->getBasicBlock());
1071 }
1072}
1073
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001074void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1075 LandingPadInst *OutlinedLPad,
1076 const LandingPadInst *OriginalLPad,
1077 FrameVarInfoMap &FrameVarInfo) {
1078 // Get the nested block and erase the unreachable instruction that was
1079 // temporarily inserted as its terminator.
1080 LLVMContext &Context = ParentFn->getContext();
1081 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
1082 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1083 OutlinedBB->getTerminator()->eraseFromParent();
1084 // That should leave OutlinedLPad as the last instruction in its block.
1085 assert(&OutlinedBB->back() == OutlinedLPad);
1086
1087 // The original landing pad will have already had its action intrinsic
1088 // built by the outlining loop. We need to clone that into the outlined
1089 // location. It may also be necessary to add references to the exception
1090 // variables to the outlined handler in which this landing pad is nested
1091 // and remap return instructions in the nested handlers that should return
1092 // to an address in the outlined handler.
1093 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001094 BasicBlock::const_iterator II = OriginalLPad;
1095 ++II;
1096 // The instruction after the landing pad should now be a call to eh.actions.
1097 const Instruction *Recover = II;
1098 assert(match(Recover, m_Intrinsic<Intrinsic::eh_actions>()));
1099 IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover->clone());
1100
1101 // Remap the exception variables into the outlined function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001102 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001103 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001104 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001105 for (const auto &Action : ActionList) {
1106 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001107 if (!Catch)
1108 continue;
1109 // The dyn_cast to function here selects C++ catch handlers and skips
1110 // SEH catch handlers.
1111 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1112 if (!Handler)
1113 continue;
1114 // Visit all the return instructions, looking for places that return
1115 // to a location within OutlinedHandlerFn.
1116 for (BasicBlock &NestedHandlerBB : *Handler) {
1117 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1118 if (!Ret)
1119 continue;
1120
1121 // Handler functions must always return a block address.
1122 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1123 // The original target will have been in the main parent function,
1124 // but if it is the address of a block that has been outlined, it
1125 // should be a block that was outlined into OutlinedHandlerFn.
1126 assert(BA->getFunction() == ParentFn);
1127
1128 // Ignore targets that aren't part of OutlinedHandlerFn.
1129 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1130 continue;
1131
1132 // If the return value is the address ofF a block that we
1133 // previously outlined into the parent handler function, replace
1134 // the return instruction and add the mapped target to the list
1135 // of possible return addresses.
1136 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1137 assert(MappedBB->getParent() == OutlinedHandlerFn);
1138 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1139 Ret->eraseFromParent();
1140 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1141 ActionTargets.push_back(NewBA);
1142 }
1143 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001144 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001145 OutlinedBB->getInstList().push_back(EHActions);
1146
1147 // Insert an indirect branch into the outlined landing pad BB.
1148 IndirectBrInst *IBr = IndirectBrInst::Create(EHActions, 0, OutlinedBB);
1149 // Add the previously collected action targets.
1150 for (auto *Target : ActionTargets)
1151 IBr->addDestination(Target->getBasicBlock());
1152}
1153
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001154// This function examines a block to determine whether the block ends with a
1155// conditional branch to a catch handler based on a selector comparison.
1156// This function is used both by the WinEHPrepare::findSelectorComparison() and
1157// WinEHCleanupDirector::handleTypeIdFor().
1158static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1159 Constant *&Selector, BasicBlock *&NextBB) {
1160 ICmpInst::Predicate Pred;
1161 BasicBlock *TBB, *FBB;
1162 Value *LHS, *RHS;
1163
1164 if (!match(BB->getTerminator(),
1165 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1166 return false;
1167
1168 if (!match(LHS,
1169 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1170 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1171 return false;
1172
1173 if (Pred == CmpInst::ICMP_EQ) {
1174 CatchHandler = TBB;
1175 NextBB = FBB;
1176 return true;
1177 }
1178
1179 if (Pred == CmpInst::ICMP_NE) {
1180 CatchHandler = FBB;
1181 NextBB = TBB;
1182 return true;
1183 }
1184
1185 return false;
1186}
1187
Andrew Kaylor41758512015-04-20 22:04:09 +00001188static bool isCatchBlock(BasicBlock *BB) {
1189 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1190 II != IE; ++II) {
1191 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1192 return true;
1193 }
1194 return false;
1195}
1196
Andrew Kaylorbb111322015-04-07 21:30:23 +00001197static BasicBlock *createStubLandingPad(Function *Handler,
1198 Value *PersonalityFn) {
1199 // FIXME: Finish this!
1200 LLVMContext &Context = Handler->getContext();
1201 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1202 Handler->getBasicBlockList().push_back(StubBB);
1203 IRBuilder<> Builder(StubBB);
1204 LandingPadInst *LPad = Builder.CreateLandingPad(
1205 llvm::StructType::get(Type::getInt8PtrTy(Context),
1206 Type::getInt32Ty(Context), nullptr),
1207 PersonalityFn, 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001208 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001209 Function *ActionIntrin =
1210 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001211 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001212 LPad->setCleanup(true);
1213 Builder.CreateUnreachable();
1214 return StubBB;
1215}
1216
1217// Cycles through the blocks in an outlined handler function looking for an
1218// invoke instruction and inserts an invoke of llvm.donothing with an empty
1219// landing pad if none is found. The code that generates the .xdata tables for
1220// the handler needs at least one landing pad to identify the parent function's
1221// personality.
1222void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler,
1223 Value *PersonalityFn) {
1224 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001225 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001226 for (BasicBlock &BB : *Handler) {
1227 TerminatorInst *Terminator = BB.getTerminator();
1228 // If we find an invoke, there is nothing to be done.
1229 auto *II = dyn_cast<InvokeInst>(Terminator);
1230 if (II)
1231 return;
1232 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001233 if (!Ret)
1234 Ret = dyn_cast<ReturnInst>(Terminator);
1235 // If we haven't recorded an unreachable instruction, try this terminator.
1236 if (!Unreached)
1237 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001238 }
1239
1240 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001241 // at least one return or unreachable instruction. We'll insert an invoke of
1242 // llvm.donothing ahead of that instruction.
1243 assert(Ret || Unreached);
1244 TerminatorInst *Term;
1245 if (Ret)
1246 Term = Ret;
1247 else
1248 Term = Unreached;
1249 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001250 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001251 // SplitBlock adds an unconditional branch instruction at the end of the
1252 // parent block. We want to replace that with an invoke call, so we can
1253 // erase it now.
1254 OldRetBB->getTerminator()->eraseFromParent();
1255 BasicBlock *StubLandingPad = createStubLandingPad(Handler, PersonalityFn);
1256 Function *F =
1257 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1258 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1259}
1260
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001261// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1262// usually doesn't build LLVM IR, so that's probably the wrong place.
1263Function *WinEHPrepare::createHandlerFunc(Type *RetTy, const Twine &Name,
1264 Module *M, Value *&ParentFP) {
1265 // x64 uses a two-argument prototype where the parent FP is the second
1266 // argument. x86 uses no arguments, just the incoming EBP value.
1267 LLVMContext &Context = M->getContext();
1268 FunctionType *FnType;
1269 if (TheTriple.getArch() == Triple::x86_64) {
1270 Type *Int8PtrType = Type::getInt8PtrTy(Context);
1271 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1272 FnType = FunctionType::get(RetTy, ArgTys, false);
1273 } else {
1274 FnType = FunctionType::get(RetTy, None, false);
1275 }
1276
1277 Function *Handler =
1278 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1279 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1280 Handler->getBasicBlockList().push_front(Entry);
1281 if (TheTriple.getArch() == Triple::x86_64) {
1282 ParentFP = &(Handler->getArgumentList().back());
1283 } else {
1284 assert(M);
1285 Function *FrameAddressFn =
1286 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
1287 Value *Args[1] = {ConstantInt::get(Type::getInt32Ty(Context), 1)};
1288 ParentFP = CallInst::Create(FrameAddressFn, Args, "parent_fp",
1289 &Handler->getEntryBlock());
1290 }
1291 return Handler;
1292}
1293
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001294bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1295 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001296 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001297 Module *M = SrcFn->getParent();
1298 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001299 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001300
1301 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001302 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001303 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001304 if (Action->getType() == Catch) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001305 Handler = createHandlerFunc(Int8PtrType, SrcFn->getName() + ".catch", M,
1306 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001307 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001308 Handler = createHandlerFunc(Type::getVoidTy(Context),
1309 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001310 }
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001311 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001312 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001313 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001314
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001315 // Generate a standard prolog to setup the frame recovery structure.
1316 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001317 Builder.SetInsertPoint(Entry);
1318 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1319
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001320 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001321
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001322 ValueToValueMapTy VMap;
1323
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001324 LandingPadMap &LPadMap = LPadMaps[LPad];
1325 if (!LPadMap.isInitialized())
1326 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001327 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1328 Constant *Sel = CatchAction->getSelector();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001329 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel,
1330 VarInfo, LPadMap,
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001331 NestedLPtoOriginalLP));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001332 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1333 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001334 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001335 Director.reset(
1336 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001337 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1338 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001339 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001340
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001341 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001342 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001343
Andrew Kaylor3170e562015-03-20 21:42:54 +00001344 // If the start block contains PHI nodes, we need to map them.
1345 BasicBlock::iterator II = StartBB->begin();
1346 while (auto *PN = dyn_cast<PHINode>(II)) {
1347 bool Mapped = false;
1348 // Look for PHI values that we have already mapped (such as the selector).
1349 for (Value *Val : PN->incoming_values()) {
1350 if (VMap.count(Val)) {
1351 VMap[PN] = VMap[Val];
1352 Mapped = true;
1353 }
1354 }
1355 // If we didn't find a match for this value, map it as an undef.
1356 if (!Mapped) {
1357 VMap[PN] = UndefValue::get(PN->getType());
1358 }
1359 ++II;
1360 }
1361
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001362 // The landing pad value may be used by PHI nodes. It will ultimately be
1363 // eliminated, but we need it in the map for intermediate handling.
1364 VMap[LPad] = UndefValue::get(LPad->getType());
1365
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001366 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001367 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001368
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001369 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001370 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001371 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001372
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001373 // Move all the instructions in the cloned "entry" block into our entry block.
1374 // Depending on how the parent function was laid out, the block that will
1375 // correspond to the outlined entry block may not be the first block in the
1376 // list. We can recognize it, however, as the cloned block which has no
1377 // predecessors. Any other block wouldn't have been cloned if it didn't
1378 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001379 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001380 while (!pred_empty(ClonedIt))
1381 ++ClonedIt;
1382 BasicBlock *ClonedEntryBB = ClonedIt;
1383 assert(ClonedEntryBB);
1384 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1385 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001386
Andrew Kaylorbb111322015-04-07 21:30:23 +00001387 // Make sure we can identify the handler's personality later.
1388 addStubInvokeToHandlerIfNeeded(Handler, LPad->getPersonalityFn());
1389
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001390 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1391 WinEHCatchDirector *CatchDirector =
1392 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1393 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1394 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001395
1396 // Look for blocks that are not part of the landing pad that we just
1397 // outlined but terminate with a call to llvm.eh.endcatch and a
1398 // branch to a block that is in the handler we just outlined.
1399 // These blocks will be part of a nested landing pad that intends to
1400 // return to an address in this handler. This case is best handled
1401 // after both landing pads have been outlined, so for now we'll just
1402 // save the association of the blocks in LPadTargetBlocks. The
1403 // return instructions which are created from these branches will be
1404 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001405 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001406 // VMap maps all values and blocks that were just cloned, but dead
1407 // blocks which were pruned will map to nullptr.
1408 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1409 continue;
1410 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1411 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1412 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1413 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1414 continue;
1415 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1416 --II;
1417 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1418 // This would indicate that a nested landing pad wants to return
1419 // to a block that is outlined into two different handlers.
1420 assert(!LPadTargetBlocks.count(MappedBB));
1421 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1422 }
1423 }
1424 }
1425 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001426
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001427 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001428
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001429 return true;
1430}
1431
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001432/// This BB must end in a selector dispatch. All we need to do is pass the
1433/// handler block to llvm.eh.actions and list it as a possible indirectbr
1434/// target.
1435void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1436 BasicBlock *StartBB) {
1437 BasicBlock *HandlerBB;
1438 BasicBlock *NextBB;
1439 Constant *Selector;
1440 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1441 if (Res) {
1442 // If this was EH dispatch, this must be a conditional branch to the handler
1443 // block.
1444 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1445 // leading to crashes if some optimization hoists stuff here.
1446 assert(CatchAction->getSelector() && HandlerBB &&
1447 "expected catch EH dispatch");
1448 } else {
1449 // This must be a catch-all. Split the block after the landingpad.
1450 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001451 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001452 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001453 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1454 Function *EHCodeFn = Intrinsic::getDeclaration(
1455 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001456 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001457 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1458 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001459 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1460 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1461 CatchAction->setReturnTargets(Targets);
1462}
1463
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001464void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1465 // Each instance of this class should only ever be used to map a single
1466 // landing pad.
1467 assert(OriginLPad == nullptr || OriginLPad == LPad);
1468
1469 // If the landing pad has already been mapped, there's nothing more to do.
1470 if (OriginLPad == LPad)
1471 return;
1472
1473 OriginLPad = LPad;
1474
1475 // The landingpad instruction returns an aggregate value. Typically, its
1476 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001477 // results of those extracts will have been promoted to reg values before
1478 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001479 for (auto *U : LPad->users()) {
1480 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1481 if (!Extract)
1482 continue;
1483 assert(Extract->getNumIndices() == 1 &&
1484 "Unexpected operation: extracting both landing pad values");
1485 unsigned int Idx = *(Extract->idx_begin());
1486 assert((Idx == 0 || Idx == 1) &&
1487 "Unexpected operation: extracting an unknown landing pad element");
1488 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001489 ExtractedEHPtrs.push_back(Extract);
1490 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001491 ExtractedSelectors.push_back(Extract);
1492 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001493 }
1494}
1495
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001496bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1497 return BB->getLandingPadInst() == OriginLPad;
1498}
1499
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001500bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1501 if (Inst == OriginLPad)
1502 return true;
1503 for (auto *Extract : ExtractedEHPtrs) {
1504 if (Inst == Extract)
1505 return true;
1506 }
1507 for (auto *Extract : ExtractedSelectors) {
1508 if (Inst == Extract)
1509 return true;
1510 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001511 return false;
1512}
1513
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001514void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1515 Value *SelectorValue) const {
1516 // Remap all landing pad extract instructions to the specified values.
1517 for (auto *Extract : ExtractedEHPtrs)
1518 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001519 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001520 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001521}
1522
Reid Klecknerf14787d2015-04-22 00:07:52 +00001523static bool isFrameAddressCall(const Value *V) {
1524 return match(const_cast<Value *>(V),
1525 m_Intrinsic<Intrinsic::frameaddress>(m_SpecificInt(0)));
1526}
1527
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001528CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001529 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001530 // If this is one of the boilerplate landing pad instructions, skip it.
1531 // The instruction will have already been remapped in VMap.
1532 if (LPadMap.isLandingPadSpecificInst(Inst))
1533 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001534
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001535 // Nested landing pads will be cloned as stubs, with just the
1536 // landingpad instruction and an unreachable instruction. When
1537 // all landingpads have been outlined, we'll replace this with the
1538 // llvm.eh.actions call and indirect branch created when the
1539 // landing pad was outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001540 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1541 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001542 }
1543
1544 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1545 return handleInvoke(VMap, Invoke, NewBB);
1546
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001547 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1548 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001549
Andrew Kaylorea8df612015-04-17 23:05:43 +00001550 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1551 return handleCompare(VMap, Cmp, NewBB);
1552
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001553 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1554 return handleBeginCatch(VMap, Inst, NewBB);
1555 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1556 return handleEndCatch(VMap, Inst, NewBB);
1557 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1558 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001559
Reid Klecknerf14787d2015-04-22 00:07:52 +00001560 // When outlining llvm.frameaddress(i32 0), remap that to the second argument,
1561 // which is the FP of the parent.
1562 if (isFrameAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001563 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001564 return CloningDirector::SkipInstruction;
1565 }
1566
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001567 // Continue with the default cloning behavior.
1568 return CloningDirector::CloneInstruction;
1569}
1570
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001571CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1572 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1573 Instruction *NewInst = LPad->clone();
1574 if (LPad->hasName())
1575 NewInst->setName(LPad->getName());
1576 // Save this correlation for later processing.
1577 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1578 VMap[LPad] = NewInst;
1579 BasicBlock::InstListType &InstList = NewBB->getInstList();
1580 InstList.push_back(NewInst);
1581 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1582 return CloningDirector::StopCloningBB;
1583}
1584
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001585CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1586 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1587 // The argument to the call is some form of the first element of the
1588 // landingpad aggregate value, but that doesn't matter. It isn't used
1589 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001590 // The second argument is an outparameter where the exception object will be
1591 // stored. Typically the exception object is a scalar, but it can be an
1592 // aggregate when catching by value.
1593 // FIXME: Leave something behind to indicate where the exception object lives
1594 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001595 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1596 "llvm.eh.begincatch found while "
1597 "outlining catch handler.");
1598 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001599 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1600 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001601 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1602 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001603 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001604 return CloningDirector::SkipInstruction;
1605}
1606
1607CloningDirector::CloningAction
1608WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1609 const Instruction *Inst, BasicBlock *NewBB) {
1610 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1611 // It might be interesting to track whether or not we are inside a catch
1612 // function, but that might make the algorithm more brittle than it needs
1613 // to be.
1614
1615 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001616 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001617 // or at the end of the catch block. However, a catch-all handler may call
1618 // end catch from the original landing pad. If the call occurs in a nested
1619 // landing pad block, we must skip it and continue so that the landing pad
1620 // gets cloned.
1621 auto *ParentBB = IntrinCall->getParent();
1622 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001623 return CloningDirector::SkipInstruction;
1624
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001625 // If an end catch occurs anywhere else we want to terminate the handler
1626 // with a return to the code that follows the endcatch call. If the
1627 // next instruction is not an unconditional branch, we need to split the
1628 // block to provide a clear target for the return instruction.
1629 BasicBlock *ContinueBB;
1630 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1631 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1632 if (!Branch || !Branch->isUnconditional()) {
1633 // We're interrupting the cloning process at this location, so the
1634 // const_cast we're doing here will not cause a problem.
1635 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1636 const_cast<Instruction *>(cast<Instruction>(Next)));
1637 } else {
1638 ContinueBB = Branch->getSuccessor(0);
1639 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001640
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001641 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1642 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001643
1644 // We just added a terminator to the cloned block.
1645 // Tell the caller to stop processing the current basic block so that
1646 // the branch instruction will be skipped.
1647 return CloningDirector::StopCloningBB;
1648}
1649
1650CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1651 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1652 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1653 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1654 // This causes a replacement that will collapse the landing pad CFG based
1655 // on the filter function we intend to match.
1656 if (Selector == CurrentSelector)
1657 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1658 else
1659 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1660 // Tell the caller not to clone this instruction.
1661 return CloningDirector::SkipInstruction;
1662}
1663
1664CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001665WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1666 const InvokeInst *Invoke, BasicBlock *NewBB) {
1667 return CloningDirector::CloneInstruction;
1668}
1669
1670CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001671WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1672 const ResumeInst *Resume, BasicBlock *NewBB) {
1673 // Resume instructions shouldn't be reachable from catch handlers.
1674 // We still need to handle it, but it will be pruned.
1675 BasicBlock::InstListType &InstList = NewBB->getInstList();
1676 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1677 return CloningDirector::StopCloningBB;
1678}
1679
Andrew Kaylorea8df612015-04-17 23:05:43 +00001680CloningDirector::CloningAction
1681WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1682 const CmpInst *Compare, BasicBlock *NewBB) {
1683 const IntrinsicInst *IntrinCall = nullptr;
1684 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1685 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001686 } else if (match(Compare->getOperand(1),
1687 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001688 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1689 }
1690 if (IntrinCall) {
1691 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1692 // This causes a replacement that will collapse the landing pad CFG based
1693 // on the filter function we intend to match.
1694 if (Selector == CurrentSelector->stripPointerCasts()) {
1695 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001696 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001697 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1698 }
1699 return CloningDirector::SkipInstruction;
1700 }
1701 return CloningDirector::CloneInstruction;
1702}
1703
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001704CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1705 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1706 // The MS runtime will terminate the process if an exception occurs in a
1707 // cleanup handler, so we shouldn't encounter landing pads in the actual
1708 // cleanup code, but they may appear in catch blocks. Depending on where
1709 // we started cloning we may see one, but it will get dropped during dead
1710 // block pruning.
1711 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1712 VMap[LPad] = NewInst;
1713 BasicBlock::InstListType &InstList = NewBB->getInstList();
1714 InstList.push_back(NewInst);
1715 return CloningDirector::StopCloningBB;
1716}
1717
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001718CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1719 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001720 // Cleanup code may flow into catch blocks or the catch block may be part
1721 // of a branch that will be optimized away. We'll insert a return
1722 // instruction now, but it may be pruned before the cloning process is
1723 // complete.
1724 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001725 return CloningDirector::StopCloningBB;
1726}
1727
1728CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1729 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001730 // Cleanup handlers nested within catch handlers may begin with a call to
1731 // eh.endcatch. We can just ignore that instruction.
1732 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001733}
1734
1735CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1736 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001737 // If we encounter a selector comparison while cloning a cleanup handler,
1738 // we want to stop cloning immediately. Anything after the dispatch
1739 // will be outlined into a different handler.
1740 BasicBlock *CatchHandler;
1741 Constant *Selector;
1742 BasicBlock *NextBB;
1743 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1744 CatchHandler, Selector, NextBB)) {
1745 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1746 return CloningDirector::StopCloningBB;
1747 }
1748 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001749 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001750 return CloningDirector::SkipInstruction;
1751}
1752
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001753CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1754 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1755 // All invokes in cleanup handlers can be replaced with calls.
1756 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1757 // Insert a normal call instruction...
1758 CallInst *NewCall =
1759 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1760 Invoke->getName(), NewBB);
1761 NewCall->setCallingConv(Invoke->getCallingConv());
1762 NewCall->setAttributes(Invoke->getAttributes());
1763 NewCall->setDebugLoc(Invoke->getDebugLoc());
1764 VMap[Invoke] = NewCall;
1765
Reid Kleckner6e48a822015-04-10 16:26:42 +00001766 // Remap the operands.
1767 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1768
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001769 // Insert an unconditional branch to the normal destination.
1770 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1771
1772 // The unwind destination won't be cloned into the new function, so
1773 // we don't need to clean up its phi nodes.
1774
1775 // We just added a terminator to the cloned block.
1776 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001777 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001778}
1779
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001780CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1781 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1782 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1783
1784 // We just added a terminator to the cloned block.
1785 // Tell the caller to stop processing the current basic block so that
1786 // the branch instruction will be skipped.
1787 return CloningDirector::StopCloningBB;
1788}
1789
Andrew Kaylorea8df612015-04-17 23:05:43 +00001790CloningDirector::CloningAction
1791WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1792 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001793 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1794 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1795 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1796 return CloningDirector::SkipInstruction;
1797 }
1798 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001799}
1800
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001801WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001802 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001803 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001804 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001805
1806 // New allocas should be inserted in the entry block, but after the parent FP
1807 // is established if it is an instruction.
1808 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1809 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1810 InsertPoint = FPInst->getNextNode();
1811 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001812}
1813
1814Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001815 // If we're asked to materialize a static alloca, we temporarily create an
1816 // alloca in the outlined function and add this to the FrameVarInfo map. When
1817 // all the outlining is complete, we'll replace these temporary allocas with
1818 // calls to llvm.framerecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001819 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00001820 assert(AV->isStaticAlloca() &&
1821 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00001822 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
1823 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001824 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001825 return NewAlloca;
1826 }
1827
Andrew Kaylor72029c62015-03-03 00:41:03 +00001828 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00001829 Function *Parent = isa<Instruction>(V)
1830 ? cast<Instruction>(V)->getParent()->getParent()
1831 : cast<Argument>(V)->getParent();
1832 errs()
1833 << "Failed to demote instruction used in exception handler of function "
1834 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00001835 errs() << " " << *V << '\n';
1836 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001837 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001838
Andrew Kaylor72029c62015-03-03 00:41:03 +00001839 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001840 return nullptr;
1841}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001842
Reid Kleckner3567d272015-04-02 21:13:31 +00001843void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
1844 // Catch parameter objects have to live in the parent frame. When we see a use
1845 // of a catch parameter, add a sentinel to the multimap to indicate that it's
1846 // used from another handler. This will prevent us from trying to sink the
1847 // alloca into the handler and ensure that the catch parameter is present in
1848 // the call to llvm.frameescape.
1849 FrameVarInfo[V].push_back(getCatchObjectSentinel());
1850}
1851
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001852// This function maps the catch and cleanup handlers that are reachable from the
1853// specified landing pad. The landing pad sequence will have this basic shape:
1854//
1855// <cleanup handler>
1856// <selector comparison>
1857// <catch handler>
1858// <cleanup handler>
1859// <selector comparison>
1860// <catch handler>
1861// <cleanup handler>
1862// ...
1863//
1864// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
1865// any arbitrary control flow, but all paths through the cleanup code must
1866// eventually reach the next selector comparison and no path can skip to a
1867// different selector comparisons, though some paths may terminate abnormally.
1868// Therefore, we will use a depth first search from the start of any given
1869// cleanup block and stop searching when we find the next selector comparison.
1870//
1871// If the landingpad instruction does not have a catch clause, we will assume
1872// that any instructions other than selector comparisons and catch handlers can
1873// be ignored. In practice, these will only be the boilerplate instructions.
1874//
1875// The catch handlers may also have any control structure, but we are only
1876// interested in the start of the catch handlers, so we don't need to actually
1877// follow the flow of the catch handlers. The start of the catch handlers can
1878// be located from the compare instructions, but they can be skipped in the
1879// flow by following the contrary branch.
1880void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
1881 LandingPadActions &Actions) {
1882 unsigned int NumClauses = LPad->getNumClauses();
1883 unsigned int HandlersFound = 0;
1884 BasicBlock *BB = LPad->getParent();
1885
1886 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
1887
1888 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00001889 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001890 return;
1891 }
1892
1893 VisitedBlockSet VisitedBlocks;
1894
1895 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001896 BasicBlock *NextBB = nullptr;
1897
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00001898 // Skip over filter clauses.
1899 if (LPad->isFilter(HandlersFound)) {
1900 ++HandlersFound;
1901 continue;
1902 }
1903
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001904 // See if the clause we're looking for is a catch-all.
1905 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00001906 Constant *ExpectedSelector =
1907 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00001908 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001909 // The catch all must occur last.
1910 assert(HandlersFound == NumClauses - 1);
1911
Andrew Kaylorea8df612015-04-17 23:05:43 +00001912 // There can be additional selector dispatches in the call chain that we
1913 // need to ignore.
1914 BasicBlock *CatchBlock = nullptr;
1915 Constant *Selector;
1916 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
1917 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00001918 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00001919 BB = NextBB;
1920 }
1921
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001922 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00001923 CatchHandler *Action = nullptr;
1924 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
1925 // If the CatchHandlerMap already has an entry for this BB, re-use it.
1926 Action = CatchHandlerMap[BB];
1927 assert(Action->getSelector() == ExpectedSelector);
1928 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001929 // We don't expect a selector dispatch, but there may be a call to
1930 // llvm.eh.begincatch, which separates catch handling code from
1931 // cleanup code in the same control flow. This call looks for the
1932 // begincatch intrinsic.
1933 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
1934 if (Action) {
1935 // For C++ EH, check if there is any interesting cleanup code before
1936 // we begin the catch. This is important because cleanups cannot
1937 // rethrow exceptions but code called from catches can. For SEH, it
1938 // isn't important if some finally code before a catch-all is executed
1939 // out of line or after recovering from the exception.
1940 if (Personality == EHPersonality::MSVC_CXX)
1941 findCleanupHandlers(Actions, BB, BB);
1942 } else {
1943 // If an action was not found, it means that the control flows
1944 // directly into the catch-all handler and there is no cleanup code.
1945 // That's an expected situation and we must create a catch action.
1946 // Since this is a catch-all handler, the selector won't actually
1947 // appear in the code anywhere. ExpectedSelector here is the constant
1948 // null ptr that we got from the landing pad instruction.
1949 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
1950 CatchHandlerMap[BB] = Action;
1951 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00001952 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001953 Actions.insertCatchHandler(Action);
1954 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
1955 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001956
1957 // Once we reach a catch-all, don't expect to hit a resume instruction.
1958 BB = nullptr;
1959 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001960 }
1961
1962 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00001963 assert(CatchAction);
1964
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001965 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00001966 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001967
Andrew Kaylorea8df612015-04-17 23:05:43 +00001968 // When the source program contains multiple nested try blocks the catch
1969 // handlers can get strung together in such a way that we can encounter
1970 // a dispatch for a selector that we've already had a handler for.
1971 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
1972 ++HandlersFound;
1973
1974 // Add the catch handler to the action list.
1975 DEBUG(dbgs() << " Found catch dispatch in block "
1976 << CatchAction->getStartBlock()->getName() << "\n");
1977 Actions.insertCatchHandler(CatchAction);
1978 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00001979 // Under some circumstances optimized IR will flow unconditionally into a
1980 // handler block without checking the selector. This can only happen if
1981 // the landing pad has a catch-all handler and the handler for the
1982 // preceeding catch clause is identical to the catch-call handler
1983 // (typically an empty catch). In this case, the handler must be shared
1984 // by all remaining clauses.
1985 if (isa<ConstantPointerNull>(
1986 CatchAction->getSelector()->stripPointerCasts())) {
1987 DEBUG(dbgs() << " Applying early catch-all handler in block "
1988 << CatchAction->getStartBlock()->getName()
1989 << " to all remaining clauses.\n");
1990 Actions.insertCatchHandler(CatchAction);
1991 return;
1992 }
1993
Andrew Kaylorea8df612015-04-17 23:05:43 +00001994 DEBUG(dbgs() << " Found extra catch dispatch in block "
1995 << CatchAction->getStartBlock()->getName() << "\n");
1996 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001997
1998 // Move on to the block after the catch handler.
1999 BB = NextBB;
2000 }
2001
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002002 // If we didn't wind up in a catch-all, see if there is any interesting code
2003 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002004 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002005
2006 // It's possible that some optimization moved code into a landingpad that
2007 // wasn't
2008 // previously being used for cleanup. If that happens, we need to execute
2009 // that
2010 // extra code from a cleanup handler.
2011 if (Actions.includesCleanup() && !LPad->isCleanup())
2012 LPad->setCleanup(true);
2013}
2014
2015// This function searches starting with the input block for the next
2016// block that terminates with a branch whose condition is based on a selector
2017// comparison. This may be the input block. See the mapLandingPadBlocks
2018// comments for a discussion of control flow assumptions.
2019//
2020CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2021 BasicBlock *&NextBB,
2022 VisitedBlockSet &VisitedBlocks) {
2023 // See if we've already found a catch handler use it.
2024 // Call count() first to avoid creating a null entry for blocks
2025 // we haven't seen before.
2026 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2027 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2028 NextBB = Action->getNextBB();
2029 return Action;
2030 }
2031
2032 // VisitedBlocks applies only to the current search. We still
2033 // need to consider blocks that we've visited while mapping other
2034 // landing pads.
2035 VisitedBlocks.insert(BB);
2036
2037 BasicBlock *CatchBlock = nullptr;
2038 Constant *Selector = nullptr;
2039
2040 // If this is the first time we've visited this block from any landing pad
2041 // look to see if it is a selector dispatch block.
2042 if (!CatchHandlerMap.count(BB)) {
2043 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2044 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2045 CatchHandlerMap[BB] = Action;
2046 return Action;
2047 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002048 // If we encounter a block containing an llvm.eh.begincatch before we
2049 // find a selector dispatch block, the handler is assumed to be
2050 // reached unconditionally. This happens for catch-all blocks, but
2051 // it can also happen for other catch handlers that have been combined
2052 // with the catch-all handler during optimization.
2053 if (isCatchBlock(BB)) {
2054 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2055 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2056 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2057 CatchHandlerMap[BB] = Action;
2058 return Action;
2059 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002060 }
2061
2062 // Visit each successor, looking for the dispatch.
2063 // FIXME: We expect to find the dispatch quickly, so this will probably
2064 // work better as a breadth first search.
2065 for (BasicBlock *Succ : successors(BB)) {
2066 if (VisitedBlocks.count(Succ))
2067 continue;
2068
2069 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2070 if (Action)
2071 return Action;
2072 }
2073 return nullptr;
2074}
2075
Reid Kleckner9405ef02015-04-10 23:12:29 +00002076// These are helper functions to combine repeated code from findCleanupHandlers.
2077static void createCleanupHandler(LandingPadActions &Actions,
2078 CleanupHandlerMapTy &CleanupHandlerMap,
2079 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002080 CleanupHandler *Action = new CleanupHandler(BB);
2081 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002082 Actions.insertCleanupHandler(Action);
2083 DEBUG(dbgs() << " Found cleanup code in block "
2084 << Action->getStartBlock()->getName() << "\n");
2085}
2086
Reid Kleckner9405ef02015-04-10 23:12:29 +00002087static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2088 Instruction *MaybeCall) {
2089 // Look for finally blocks that Clang has already outlined for us.
2090 // %fp = call i8* @llvm.frameaddress(i32 0)
2091 // call void @"fin$parent"(iN 1, i8* %fp)
2092 if (isFrameAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
2093 MaybeCall = MaybeCall->getNextNode();
2094 CallSite FinallyCall(MaybeCall);
2095 if (!FinallyCall || FinallyCall.arg_size() != 2)
2096 return CallSite();
2097 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2098 return CallSite();
2099 if (!isFrameAddressCall(FinallyCall.getArgument(1)))
2100 return CallSite();
2101 return FinallyCall;
2102}
2103
2104static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2105 // Skip single ubr blocks.
2106 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2107 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2108 if (Br && Br->isUnconditional())
2109 BB = Br->getSuccessor(0);
2110 else
2111 return BB;
2112 }
2113 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002114}
2115
2116// This function searches starting with the input block for the next block that
2117// contains code that is not part of a catch handler and would not be eliminated
2118// during handler outlining.
2119//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002120void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2121 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002122 // Here we will skip over the following:
2123 //
2124 // landing pad prolog:
2125 //
2126 // Unconditional branches
2127 //
2128 // Selector dispatch
2129 //
2130 // Resume pattern
2131 //
2132 // Anything else marks the start of an interesting block
2133
2134 BasicBlock *BB = StartBB;
2135 // Anything other than an unconditional branch will kick us out of this loop
2136 // one way or another.
2137 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002138 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002139 // If we've already scanned this block, don't scan it again. If it is
2140 // a cleanup block, there will be an action in the CleanupHandlerMap.
2141 // If we've scanned it and it is not a cleanup block, there will be a
2142 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2143 // be no entry in the CleanupHandlerMap. We must call count() first to
2144 // avoid creating a null entry for blocks we haven't scanned.
2145 if (CleanupHandlerMap.count(BB)) {
2146 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002147 Actions.insertCleanupHandler(Action);
2148 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002149 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002150 // FIXME: This cleanup might chain into another, and we need to discover
2151 // that.
2152 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002153 } else {
2154 // Here we handle the case where the cleanup handler map contains a
2155 // value for this block but the value is a nullptr. This means that
2156 // we have previously analyzed the block and determined that it did
2157 // not contain any cleanup code. Based on the earlier analysis, we
2158 // know the the block must end in either an unconditional branch, a
2159 // resume or a conditional branch that is predicated on a comparison
2160 // with a selector. Either the resume or the selector dispatch
2161 // would terminate the search for cleanup code, so the unconditional
2162 // branch is the only case for which we might need to continue
2163 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002164 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2165 if (SuccBB == BB || SuccBB == EndBB)
2166 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002167 BB = SuccBB;
2168 continue;
2169 }
2170 }
2171
2172 // Create an entry in the cleanup handler map for this block. Initially
2173 // we create an entry that says this isn't a cleanup block. If we find
2174 // cleanup code, the caller will replace this entry.
2175 CleanupHandlerMap[BB] = nullptr;
2176
2177 TerminatorInst *Terminator = BB->getTerminator();
2178
2179 // Landing pad blocks have extra instructions we need to accept.
2180 LandingPadMap *LPadMap = nullptr;
2181 if (BB->isLandingPad()) {
2182 LandingPadInst *LPad = BB->getLandingPadInst();
2183 LPadMap = &LPadMaps[LPad];
2184 if (!LPadMap->isInitialized())
2185 LPadMap->mapLandingPad(LPad);
2186 }
2187
2188 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002189 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2190 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002191 // resume { i8*, i32 } %lpad.val2
2192 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2193 InsertValueInst *Insert1 = nullptr;
2194 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002195 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002196 // If the resume value isn't a phi or landingpad value, it should be a
2197 // series of insertions. Identify them so we can avoid them when scanning
2198 // for cleanups.
2199 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002200 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002201 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002202 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002203 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2204 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002205 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002206 }
2207 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2208 II != IE; ++II) {
2209 Instruction *Inst = II;
2210 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2211 continue;
2212 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2213 continue;
2214 if (!Inst->hasOneUse() ||
2215 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002216 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002217 }
2218 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002219 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002220 }
2221
2222 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002223 if (Branch && Branch->isConditional()) {
2224 // Look for the selector dispatch.
2225 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2226 // %matches = icmp eq i32 %sel, %2
2227 // br i1 %matches, label %catch14, label %eh.resume
2228 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2229 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002230 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002231 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2232 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002233 Instruction *Inst = II;
2234 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2235 continue;
2236 if (Inst == Compare || Inst == Branch)
2237 continue;
2238 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2239 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002240 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002241 }
2242 // The selector dispatch block should always terminate our search.
2243 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002244 return;
2245 }
2246
2247 if (isAsynchronousEHPersonality(Personality)) {
2248 // If this is a landingpad block, split the block at the first non-landing
2249 // pad instruction.
2250 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2251 if (LPadMap) {
2252 while (MaybeCall != BB->getTerminator() &&
2253 LPadMap->isLandingPadSpecificInst(MaybeCall))
2254 MaybeCall = MaybeCall->getNextNode();
2255 }
2256
2257 // Look for outlined finally calls.
2258 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2259 Function *Fin = FinallyCall.getCalledFunction();
2260 assert(Fin && "outlined finally call should be direct");
2261 auto *Action = new CleanupHandler(BB);
2262 Action->setHandlerBlockOrFunc(Fin);
2263 Actions.insertCleanupHandler(Action);
2264 CleanupHandlerMap[BB] = Action;
2265 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2266 << Fin->getName() << " in block "
2267 << Action->getStartBlock()->getName() << "\n");
2268
2269 // Split the block if there were more interesting instructions and look
2270 // for finally calls in the normal successor block.
2271 BasicBlock *SuccBB = BB;
2272 if (FinallyCall.getInstruction() != BB->getTerminator() &&
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002273 FinallyCall.getInstruction()->getNextNode() !=
2274 BB->getTerminator()) {
2275 SuccBB =
2276 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002277 } else {
2278 if (FinallyCall.isInvoke()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002279 SuccBB =
2280 cast<InvokeInst>(FinallyCall.getInstruction())->getNormalDest();
Reid Kleckner9405ef02015-04-10 23:12:29 +00002281 } else {
2282 SuccBB = BB->getUniqueSuccessor();
Andrew Kaylor91307432015-04-28 22:01:51 +00002283 assert(SuccBB &&
2284 "splitOutlinedFinallyCalls didn't insert a branch");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002285 }
2286 }
2287 BB = SuccBB;
2288 if (BB == EndBB)
2289 return;
2290 continue;
2291 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002292 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002293
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002294 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002295 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2296 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002297 Instruction *Inst = II;
2298 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2299 continue;
2300 // Unconditional branches fall through to this loop.
2301 if (Inst == Branch)
2302 continue;
2303 // If this is a catch block, there is no cleanup code to be found.
2304 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002305 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002306 // If this a nested landing pad, it may contain an endcatch call.
2307 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002308 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002309 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002310 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002311 }
2312
2313 // Only unconditional branches in empty blocks should get this far.
2314 assert(Branch && Branch->isUnconditional());
2315 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002316 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002317 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002318 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002319}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002320
2321// This is a public function, declared in WinEHFuncInfo.h and is also
2322// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002323void llvm::parseEHActions(
2324 const IntrinsicInst *II,
2325 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002326 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2327 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002328 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002329 if (ActionKind == /*catch=*/1) {
2330 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2331 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2332 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2333 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2334 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002335 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2336 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002337 CH->setHandlerBlockOrFunc(Handler);
2338 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002339 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002340 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002341 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2342 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002343 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002344 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002345 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002346 } else {
2347 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002348 }
2349 }
2350 std::reverse(Actions.begin(), Actions.end());
2351}