blob: b062b1a29d3bb76f331780b1ba059cb92d516659 [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"
David Majnemerfd9f4772015-08-11 01:15:26 +000026#include "llvm/Analysis/CFG.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000027#include "llvm/Analysis/LibCallSemantics.h"
Reid Klecknerf12c0302015-06-09 21:42:19 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000029#include "llvm/CodeGen/WinEHFuncInfo.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000030#include "llvm/IR/Dominators.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000031#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PatternMatch.h"
37#include "llvm/Pass.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000038#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000039#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000041#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
Andrew Kaylor64622aa2015-04-01 17:21:25 +000043#include "llvm/Transforms/Utils/PromoteMemToReg.h"
David Majnemer459a64a2015-09-16 18:40:37 +000044#include "llvm/Transforms/Utils/SSAUpdater.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000045#include <memory>
46
47using namespace llvm;
48using namespace llvm::PatternMatch;
49
50#define DEBUG_TYPE "winehprepare"
51
David Majnemer459a64a2015-09-16 18:40:37 +000052static cl::opt<bool> DisableDemotion(
53 "disable-demotion", cl::Hidden,
54 cl::desc(
55 "Clone multicolor basic blocks but do not demote cross funclet values"),
56 cl::init(false));
57
58static cl::opt<bool> DisableCleanups(
59 "disable-cleanups", cl::Hidden,
60 cl::desc("Do not remove implausible terminators or other similar cleanups"),
61 cl::init(false));
62
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000063namespace {
64
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000065// This map is used to model frame variable usage during outlining, to
66// construct a structure type to hold the frame variables in a frame
67// allocation block, and to remap the frame variable allocas (including
68// spill locations as needed) to GEPs that get the variable from the
69// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000070typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000071
Reid Kleckner3567d272015-04-02 21:13:31 +000072// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
73// quite null.
74AllocaInst *getCatchObjectSentinel() {
75 return static_cast<AllocaInst *>(nullptr) + 1;
76}
77
Andrew Kaylor6b67d422015-03-11 23:22:06 +000078typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
79
Andrew Kaylor6b67d422015-03-11 23:22:06 +000080class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000081class LandingPadMap;
82
83typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
84typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
85
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000086class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000087public:
88 static char ID; // Pass identification, replacement for typeid.
89 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000090 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000091 if (TM)
Daniel Sanders110bf6d2015-06-24 13:25:57 +000092 TheTriple = TM->getTargetTriple();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000093 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000094
95 bool runOnFunction(Function &Fn) override;
96
97 bool doFinalization(Module &M) override;
98
99 void getAnalysisUsage(AnalysisUsage &AU) const override;
100
101 const char *getPassName() const override {
102 return "Windows exception handling preparation";
103 }
104
105private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000106 bool prepareExceptionHandlers(Function &F,
107 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000108 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000109 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000110 void demoteValuesLiveAcrossHandlers(Function &F,
111 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000112 void findSEHEHReturnPoints(Function &F,
113 SetVector<BasicBlock *> &EHReturnBlocks);
114 void findCXXEHReturnPoints(Function &F,
115 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000116 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
117 SetVector<BasicBlock*> &Targets);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000118 void completeNestedLandingPad(Function *ParentFn,
119 LandingPadInst *OutlinedLPad,
120 const LandingPadInst *OriginalLPad,
121 FrameVarInfoMap &VarInfo);
Reid Kleckner6511c8b2015-07-01 20:59:25 +0000122 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
123 const Twine &Name, Module *M, Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000124 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
125 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000126 FrameVarInfoMap &VarInfo);
David Majnemer7fddecc2015-06-17 20:52:32 +0000127 void addStubInvokeToHandlerIfNeeded(Function *Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000128
129 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
130 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
131 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000132 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
133 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000134
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000135 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000136 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
137 void
138 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
139 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
140 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
141 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
142 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
143 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
144 Function &F);
Joseph Tremouletec182852015-08-28 01:12:35 +0000145 bool prepareExplicitEH(Function &F,
146 SmallVectorImpl<BasicBlock *> &EntryBlocks);
David Majnemer67bff0d2015-09-16 20:42:16 +0000147 void replaceTerminatePadWithCleanup(Function &F);
Joseph Tremouletec182852015-08-28 01:12:35 +0000148 void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
David Majnemerb3d9b962015-09-16 18:40:24 +0000149 void demotePHIsOnFunclets(Function &F);
150 void demoteUsesBetweenFunclets(Function &F);
151 void demoteArgumentUses(Function &F);
152 void cloneCommonBlocks(Function &F,
153 SmallVectorImpl<BasicBlock *> &EntryBlocks);
154 void removeImplausibleTerminators(Function &F);
155 void cleanupPreparedFunclets(Function &F);
156 void verifyPreparedFunclets(Function &F);
David Majnemerfd9f4772015-08-11 01:15:26 +0000157
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000158 Triple TheTriple;
159
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000160 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000161 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000162 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000163 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000164 CatchHandlerMapTy CatchHandlerMap;
165 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000166 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000167 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
168 SmallPtrSet<BasicBlock *, 4> EHBlocks;
169 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000170
171 // This maps landing pad instructions found in outlined handlers to
172 // the landing pad instruction in the parent function from which they
173 // were cloned. The cloned/nested landing pad is used as the key
174 // because the landing pad may be cloned into multiple handlers.
175 // This map will be used to add the llvm.eh.actions call to the nested
176 // landing pads after all handlers have been outlined.
177 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
178
179 // This maps blocks in the parent function which are destinations of
180 // catch handlers to cloned blocks in (other) outlined handlers. This
181 // handles the case where a nested landing pads has a catch handler that
182 // returns to a handler function rather than the parent function.
183 // The original block is used as the key here because there should only
184 // ever be one handler function from which the cloned block is not pruned.
185 // The original block will be pruned from the parent function after all
186 // handlers have been outlined. This map will be used to adjust the
187 // return instructions of handlers which return to the block that was
188 // outlined into a handler. This is done after all handlers have been
189 // outlined but before the outlined code is pruned from the parent function.
190 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000191
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000192 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000193 // 32-bit EH.
194 DenseMap<Function *, Value *> HandlerToParentFP;
195
Reid Kleckner582786b2015-04-30 18:17:12 +0000196 AllocaInst *SEHExceptionCodeSlot = nullptr;
David Majnemerfd9f4772015-08-11 01:15:26 +0000197
198 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
199 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
Joseph Tremouletec182852015-08-28 01:12:35 +0000200 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000201};
202
203class WinEHFrameVariableMaterializer : public ValueMaterializer {
204public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000205 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000206 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000207 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000208
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000209 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000210
Reid Kleckner3567d272015-04-02 21:13:31 +0000211 void escapeCatchObject(Value *V);
212
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000213private:
214 FrameVarInfoMap &FrameVarInfo;
215 IRBuilder<> Builder;
216};
217
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000218class LandingPadMap {
219public:
220 LandingPadMap() : OriginLPad(nullptr) {}
221 void mapLandingPad(const LandingPadInst *LPad);
222
223 bool isInitialized() { return OriginLPad != nullptr; }
224
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000225 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000226 bool isLandingPadSpecificInst(const Instruction *Inst) const;
227
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000228 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
229 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000230
231private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000232 const LandingPadInst *OriginLPad;
233 // We will normally only see one of each of these instructions, but
234 // if more than one occurs for some reason we can handle that.
235 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
236 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000237};
238
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000239class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000240public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000241 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
242 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
243 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000244 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
245 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000246 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000247
248 CloningAction handleInstruction(ValueToValueMapTy &VMap,
249 const Instruction *Inst,
250 BasicBlock *NewBB) override;
251
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000252 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
253 const Instruction *Inst,
254 BasicBlock *NewBB) = 0;
255 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
256 const Instruction *Inst,
257 BasicBlock *NewBB) = 0;
258 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
259 const Instruction *Inst,
260 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000261 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
262 const IndirectBrInst *IBr,
263 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000264 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
265 const InvokeInst *Invoke,
266 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000267 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
268 const ResumeInst *Resume,
269 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000270 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
271 const CmpInst *Compare,
272 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000273 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
274 const LandingPadInst *LPad,
275 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000276
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000277 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
278
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000279protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000280 WinEHFrameVariableMaterializer Materializer;
281 Type *SelectorIDType;
282 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000283 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000284
285 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000286 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000287};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000288
289class WinEHCatchDirector : public WinEHCloningDirectorBase {
290public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000291 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000292 Function *CatchFn, Value *ParentFP, Value *Selector,
293 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000294 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
295 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000296 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000297 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000298 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
299 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000300
301 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
302 const Instruction *Inst,
303 BasicBlock *NewBB) override;
304 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
305 BasicBlock *NewBB) override;
306 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
307 const Instruction *Inst,
308 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000309 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
310 const IndirectBrInst *IBr,
311 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000312 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
313 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000314 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
315 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000316 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
317 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000318 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
319 const LandingPadInst *LPad,
320 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000321
Reid Kleckner3567d272015-04-02 21:13:31 +0000322 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000323 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
324
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000325private:
326 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000327
Reid Kleckner3567d272015-04-02 21:13:31 +0000328 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000329 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000330
331 // This will be a reference to the field of the same name in the WinEHPrepare
332 // object which instantiates this WinEHCatchDirector object.
333 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000334 DominatorTree *DT;
335 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000336};
337
338class WinEHCleanupDirector : public WinEHCloningDirectorBase {
339public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000340 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
341 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
342 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
343 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000344
345 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
346 const Instruction *Inst,
347 BasicBlock *NewBB) override;
348 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
349 BasicBlock *NewBB) override;
350 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
351 const Instruction *Inst,
352 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000353 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
354 const IndirectBrInst *IBr,
355 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000356 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
357 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000358 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
359 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000360 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
361 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000362 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
363 const LandingPadInst *LPad,
364 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000365};
366
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000367class LandingPadActions {
368public:
369 LandingPadActions() : HasCleanupHandlers(false) {}
370
371 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
372 void insertCleanupHandler(CleanupHandler *Action) {
373 Actions.push_back(Action);
374 HasCleanupHandlers = true;
375 }
376
377 bool includesCleanup() const { return HasCleanupHandlers; }
378
David Majnemercde33032015-03-30 22:58:10 +0000379 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000380 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
381 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
382
383private:
384 // Note that this class does not own the ActionHandler objects in this vector.
385 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
386 // in the WinEHPrepare class.
387 SmallVector<ActionHandler *, 4> Actions;
388 bool HasCleanupHandlers;
389};
390
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000391} // end anonymous namespace
392
393char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000394INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
395 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000396
397FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
398 return new WinEHPrepare(TM);
399}
400
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000401bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000402 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000403 return false;
404
David Majnemerfd9f4772015-08-11 01:15:26 +0000405 // No need to prepare outlined handlers.
406 if (Fn.hasFnAttribute("wineh-parent"))
David Majnemer09e1fdb2015-08-06 21:13:51 +0000407 return false;
408
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000409 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000410 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000411
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000412 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000413 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000414 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000415
David Majnemerfd9f4772015-08-11 01:15:26 +0000416 SmallVector<LandingPadInst *, 4> LPads;
417 SmallVector<ResumeInst *, 4> Resumes;
Joseph Tremouletec182852015-08-28 01:12:35 +0000418 SmallVector<BasicBlock *, 4> EntryBlocks;
David Majnemerfd9f4772015-08-11 01:15:26 +0000419 bool ForExplicitEH = false;
420 for (BasicBlock &BB : Fn) {
Joseph Tremouletec182852015-08-28 01:12:35 +0000421 Instruction *First = BB.getFirstNonPHI();
422 if (auto *LP = dyn_cast<LandingPadInst>(First)) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000423 LPads.push_back(LP);
Joseph Tremouletec182852015-08-28 01:12:35 +0000424 } else if (First->isEHPad()) {
425 if (!ForExplicitEH)
426 EntryBlocks.push_back(&Fn.getEntryBlock());
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000427 if (!isa<CatchEndPadInst>(First) && !isa<CleanupEndPadInst>(First))
Joseph Tremouletec182852015-08-28 01:12:35 +0000428 EntryBlocks.push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000429 ForExplicitEH = true;
David Majnemerfd9f4772015-08-11 01:15:26 +0000430 }
431 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
432 Resumes.push_back(Resume);
433 }
434
435 if (ForExplicitEH)
Joseph Tremouletec182852015-08-28 01:12:35 +0000436 return prepareExplicitEH(Fn, EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +0000437
438 // No need to prepare functions that lack landing pads.
439 if (LPads.empty())
440 return false;
441
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000442 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000443 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000444
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000445 // If there were any landing pads, prepareExceptionHandlers will make changes.
446 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000447 return true;
448}
449
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000450bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000451
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000452void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
453 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000454 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000455}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000456
Reid Klecknerfd7df282015-04-22 21:05:21 +0000457static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
458 Constant *&Selector, BasicBlock *&NextBB);
459
460// Finds blocks reachable from the starting set Worklist. Does not follow unwind
461// edges or blocks listed in StopPoints.
462static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
463 SetVector<BasicBlock *> &Worklist,
464 const SetVector<BasicBlock *> *StopPoints) {
465 while (!Worklist.empty()) {
466 BasicBlock *BB = Worklist.pop_back_val();
467
468 // Don't cross blocks that we should stop at.
469 if (StopPoints && StopPoints->count(BB))
470 continue;
471
472 if (!ReachableBBs.insert(BB).second)
473 continue; // Already visited.
474
475 // Don't follow unwind edges of invokes.
476 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
477 Worklist.insert(II->getNormalDest());
478 continue;
479 }
480
481 // Otherwise, follow all successors.
482 Worklist.insert(succ_begin(BB), succ_end(BB));
483 }
484}
485
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000486// Attempt to find an instruction where a block can be split before
487// a call to llvm.eh.begincatch and its operands. If the block
488// begins with the begincatch call or one of its adjacent operands
489// the block will not be split.
490static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
491 IntrinsicInst *II) {
492 // If the begincatch call is already the first instruction in the block,
493 // don't split.
494 Instruction *FirstNonPHI = BB->getFirstNonPHI();
495 if (II == FirstNonPHI)
496 return nullptr;
497
498 // If either operand is in the same basic block as the instruction and
499 // isn't used by another instruction before the begincatch call, include it
500 // in the split block.
501 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
502 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
503
504 Instruction *I = II->getPrevNode();
505 Instruction *LastI = II;
506
507 while (I == Op0 || I == Op1) {
508 // If the block begins with one of the operands and there are no other
509 // instructions between the operand and the begincatch call, don't split.
510 if (I == FirstNonPHI)
511 return nullptr;
512
513 LastI = I;
514 I = I->getPrevNode();
515 }
516
517 // If there is at least one instruction in the block before the begincatch
518 // call and its operands, split the block at either the begincatch or
519 // its operand.
520 return LastI;
521}
522
Reid Klecknerfd7df282015-04-22 21:05:21 +0000523/// Find all points where exceptional control rejoins normal control flow via
524/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000525void WinEHPrepare::findCXXEHReturnPoints(
526 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000527 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
528 BasicBlock *BB = BBI;
529 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000530 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000531 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000532 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
533 if (SplitPt) {
534 // Split the block before the llvm.eh.begincatch call to allow
535 // cleanup and catch code to be distinguished later.
536 // Do not update BBI because we still need to process the
537 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000538 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000539 break;
540 }
541 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000542 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
543 // Split the block after the call to llvm.eh.endcatch if there is
544 // anything other than an unconditional branch, or if the successor
545 // starts with a phi.
546 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
547 if (!Br || !Br->isUnconditional() ||
548 isa<PHINode>(Br->getSuccessor(0)->begin())) {
549 DEBUG(dbgs() << "splitting block " << BB->getName()
550 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000551 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000552 }
553 // The next BB is normal control flow.
554 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
555 break;
556 }
557 }
558 }
559}
560
561static bool isCatchAllLandingPad(const BasicBlock *BB) {
562 const LandingPadInst *LP = BB->getLandingPadInst();
563 if (!LP)
564 return false;
565 unsigned N = LP->getNumClauses();
566 return (N > 0 && LP->isCatch(N - 1) &&
567 isa<ConstantPointerNull>(LP->getClause(N - 1)));
568}
569
570/// Find all points where exceptions control rejoins normal control flow via
571/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000572void WinEHPrepare::findSEHEHReturnPoints(
573 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000574 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
575 BasicBlock *BB = BBI;
576 // If the landingpad is a catch-all, treat the whole lpad as if it is
577 // reachable from normal control flow.
578 // FIXME: This is imprecise. We need a better way of identifying where a
579 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
580 // is no difference.
581 if (isCatchAllLandingPad(BB)) {
582 EHReturnBlocks.insert(BB);
583 continue;
584 }
585
586 BasicBlock *CatchHandler;
587 BasicBlock *NextBB;
588 Constant *Selector;
589 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000590 // Split the edge if there are multiple predecessors. This creates a place
591 // where we can insert EH recovery code.
592 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000593 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
594 << " to " << CatchHandler->getName() << '\n');
595 BBI = CatchHandler = SplitCriticalEdge(
596 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
597 }
598 EHReturnBlocks.insert(CatchHandler);
599 }
600 }
601}
602
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000603void WinEHPrepare::identifyEHBlocks(Function &F,
604 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000605 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
606 << F.getName() << '\n');
607
608 // Build a set of all non-exceptional blocks and exceptional blocks.
609 // - Non-exceptional blocks are blocks reachable from the entry block while
610 // not following invoke unwind edges.
611 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
612 // not follow llvm.eh.endcatch blocks, which mark a transition from
613 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000614
615 if (Personality == EHPersonality::MSVC_CXX)
616 findCXXEHReturnPoints(F, EHReturnBlocks);
617 else
618 findSEHEHReturnPoints(F, EHReturnBlocks);
619
620 DEBUG({
621 dbgs() << "identified the following blocks as EH return points:\n";
622 for (BasicBlock *BB : EHReturnBlocks)
623 dbgs() << " " << BB->getName() << '\n';
624 });
625
Andrew Kaylor91307432015-04-28 22:01:51 +0000626// Join points should not have phis at this point, unless they are a
627// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000628#ifndef NDEBUG
629 for (BasicBlock *BB : EHReturnBlocks)
630 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
631 "non-lpad EH return block has phi");
632#endif
633
634 // Normal blocks are the blocks reachable from the entry block and all EH
635 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000636 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000637 Worklist = EHReturnBlocks;
638 Worklist.insert(&F.getEntryBlock());
639 findReachableBlocks(NormalBlocks, Worklist, nullptr);
640 DEBUG({
641 dbgs() << "marked the following blocks as normal:\n";
642 for (BasicBlock *BB : NormalBlocks)
643 dbgs() << " " << BB->getName() << '\n';
644 });
645
646 // Exceptional blocks are the blocks reachable from landingpads that don't
647 // cross EH return points.
648 Worklist.clear();
649 for (auto *LPI : LPads)
650 Worklist.insert(LPI->getParent());
651 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
652 DEBUG({
653 dbgs() << "marked the following blocks as exceptional:\n";
654 for (BasicBlock *BB : EHBlocks)
655 dbgs() << " " << BB->getName() << '\n';
656 });
657
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000658}
659
660/// Ensure that all values live into and out of exception handlers are stored
661/// in memory.
662/// FIXME: This falls down when values are defined in one handler and live into
663/// another handler. For example, a cleanup defines a value used only by a
664/// catch handler.
665void WinEHPrepare::demoteValuesLiveAcrossHandlers(
666 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
667 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
668 << F.getName() << '\n');
669
670 // identifyEHBlocks() should have been called before this function.
671 assert(!NormalBlocks.empty());
672
Reid Kleckner7ea77082015-07-10 22:21:54 +0000673 // Try to avoid demoting EH pointer and selector values. They get in the way
674 // of our pattern matching.
675 SmallPtrSet<Instruction *, 10> EHVals;
676 for (BasicBlock &BB : F) {
677 LandingPadInst *LP = BB.getLandingPadInst();
678 if (!LP)
679 continue;
680 EHVals.insert(LP);
681 for (User *U : LP->users()) {
682 auto *EI = dyn_cast<ExtractValueInst>(U);
683 if (!EI)
684 continue;
685 EHVals.insert(EI);
686 for (User *U2 : EI->users()) {
687 if (auto *PN = dyn_cast<PHINode>(U2))
688 EHVals.insert(PN);
689 }
690 }
691 }
692
Reid Klecknerfd7df282015-04-22 21:05:21 +0000693 SetVector<Argument *> ArgsToDemote;
694 SetVector<Instruction *> InstrsToDemote;
695 for (BasicBlock &BB : F) {
696 bool IsNormalBB = NormalBlocks.count(&BB);
697 bool IsEHBB = EHBlocks.count(&BB);
698 if (!IsNormalBB && !IsEHBB)
699 continue; // Blocks that are neither normal nor EH are unreachable.
700 for (Instruction &I : BB) {
701 for (Value *Op : I.operands()) {
702 // Don't demote static allocas, constants, and labels.
703 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
704 continue;
705 auto *AI = dyn_cast<AllocaInst>(Op);
706 if (AI && AI->isStaticAlloca())
707 continue;
708
709 if (auto *Arg = dyn_cast<Argument>(Op)) {
710 if (IsEHBB) {
711 DEBUG(dbgs() << "Demoting argument " << *Arg
712 << " used by EH instr: " << I << "\n");
713 ArgsToDemote.insert(Arg);
714 }
715 continue;
716 }
717
Reid Kleckner7ea77082015-07-10 22:21:54 +0000718 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000719 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000720 if (EHVals.count(OpI))
721 continue;
722
Reid Klecknerfd7df282015-04-22 21:05:21 +0000723 BasicBlock *OpBB = OpI->getParent();
724 // If a value is produced and consumed in the same BB, we don't need to
725 // demote it.
726 if (OpBB == &BB)
727 continue;
728 bool IsOpNormalBB = NormalBlocks.count(OpBB);
729 bool IsOpEHBB = EHBlocks.count(OpBB);
730 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
731 DEBUG({
732 dbgs() << "Demoting instruction live in-out from EH:\n";
733 dbgs() << "Instr: " << *OpI << '\n';
734 dbgs() << "User: " << I << '\n';
735 });
736 InstrsToDemote.insert(OpI);
737 }
738 }
739 }
740 }
741
742 // Demote values live into and out of handlers.
743 // FIXME: This demotion is inefficient. We should insert spills at the point
744 // of definition, insert one reload in each handler that uses the value, and
745 // insert reloads in the BB used to rejoin normal control flow.
746 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
747 for (Instruction *I : InstrsToDemote)
748 DemoteRegToStack(*I, false, AllocaInsertPt);
749
750 // Demote arguments separately, and only for uses in EH blocks.
751 for (Argument *Arg : ArgsToDemote) {
752 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
753 Arg->getName() + ".reg2mem", AllocaInsertPt);
754 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
755 for (User *U : Users) {
756 auto *I = dyn_cast<Instruction>(U);
757 if (I && EHBlocks.count(I->getParent())) {
758 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
759 U->replaceUsesOfWith(Arg, Reload);
760 }
761 }
762 new StoreInst(Arg, Slot, AllocaInsertPt);
763 }
764
765 // Demote landingpad phis, as the landingpad will be removed from the machine
766 // CFG.
767 for (LandingPadInst *LPI : LPads) {
768 BasicBlock *BB = LPI->getParent();
769 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
770 DemotePHIToStack(Phi, AllocaInsertPt);
771 }
772
773 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
774 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
775}
776
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000777bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000778 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000779 // Don't run on functions that are already prepared.
780 for (LandingPadInst *LPad : LPads) {
781 BasicBlock *LPadBB = LPad->getParent();
782 for (Instruction &Inst : *LPadBB)
783 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
784 return false;
785 }
786
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000787 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000788 demoteValuesLiveAcrossHandlers(F, LPads);
789
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000790 // These containers are used to re-map frame variables that are used in
791 // outlined catch and cleanup handlers. They will be populated as the
792 // handlers are outlined.
793 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000794
795 bool HandlersOutlined = false;
796
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000797 Module *M = F.getParent();
798 LLVMContext &Context = M->getContext();
799
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000800 // Create a new function to receive the handler contents.
801 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
802 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000803 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000804
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000805 if (isAsynchronousEHPersonality(Personality)) {
806 // FIXME: Switch the ehptr type to i32 and then switch this.
807 SEHExceptionCodeSlot =
808 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
809 F.getEntryBlock().getFirstInsertionPt());
810 }
811
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000812 // In order to handle the case where one outlined catch handler returns
813 // to a block within another outlined catch handler that would otherwise
814 // be unreachable, we need to outline the nested landing pad before we
815 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000816 if (!isAsynchronousEHPersonality(Personality))
817 std::sort(LPads.begin(), LPads.end(),
818 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
819 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000820 });
821
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000822 // This container stores the llvm.eh.recover and IndirectBr instructions
823 // that make up the body of each landing pad after it has been outlined.
824 // We need to defer the population of the target list for the indirectbr
825 // until all landing pads have been outlined so that we can handle the
826 // case of blocks in the target that are reached only from nested
827 // landing pads.
828 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
829
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000830 for (LandingPadInst *LPad : LPads) {
831 // Look for evidence that this landingpad has already been processed.
832 bool LPadHasActionList = false;
833 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000834 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000835 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
836 LPadHasActionList = true;
837 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000838 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000839 }
840
841 // If we've already outlined the handlers for this landingpad,
842 // there's nothing more to do here.
843 if (LPadHasActionList)
844 continue;
845
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000846 // If either of the values in the aggregate returned by the landing pad is
847 // extracted and stored to memory, promote the stored value to a register.
848 promoteLandingPadValues(LPad);
849
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000850 LandingPadActions Actions;
851 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000852
Reid Kleckner9405ef02015-04-10 23:12:29 +0000853 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000854 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000855 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000856 continue;
857 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000858
859 // SEH doesn't do any outlining for catches. Instead, pass the handler
860 // basic block addr to llvm.eh.actions and list the block as a return
861 // target.
862 if (isAsynchronousEHPersonality(Personality)) {
863 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
864 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000865 continue;
866 }
867 }
868
Reid Kleckner9405ef02015-04-10 23:12:29 +0000869 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
870 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000871
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000872 // Split the block after the landingpad instruction so that it is just a
873 // call to llvm.eh.actions followed by indirectbr.
874 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000875 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000876 // Erase the branch inserted by the split so we can insert indirectbr.
877 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000878
Reid Klecknere3af86e2015-04-23 21:22:30 +0000879 // Replace all extracted values with undef and ultimately replace the
880 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000881 SmallVector<Instruction *, 4> SEHCodeUses;
882 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000883 for (User *U : LPad->users()) {
884 auto *E = dyn_cast<ExtractValueInst>(U);
885 if (!E)
886 continue;
887 assert(E->getNumIndices() == 1 &&
888 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000889 unsigned Idx = *E->idx_begin();
890 assert((Idx == 0 || Idx == 1) && "unexpected index");
891 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
892 SEHCodeUses.push_back(E);
893 else
894 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000895 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000896 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000897 E->replaceAllUsesWith(UndefValue::get(E->getType()));
898 E->eraseFromParent();
899 }
900 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000901
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000902 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000903 while (!SEHCodeUses.empty()) {
904 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000905 SmallVector<Use *, 4> Uses;
906 for (Use &U : E->uses())
907 Uses.push_back(&U);
908 for (Use *U : Uses) {
909 auto *I = cast<Instruction>(U->getUser());
910 if (isa<ResumeInst>(I))
911 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000912 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000913 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000914 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000915 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000916 }
917 E->replaceAllUsesWith(UndefValue::get(E->getType()));
918 E->eraseFromParent();
919 }
920
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000921 // Add a call to describe the actions for this landing pad.
922 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000923 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000924 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000925 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000926 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000927 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000928 // Find the frame escape index of the exception object alloca in the
929 // parent.
930 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000931 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000932 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
933 auto I = FrameVarInfo.find(EHObj);
934 assert(I != FrameVarInfo.end() &&
935 "failed to map llvm.eh.begincatch var");
936 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
937 }
938 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000939 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000940 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000941 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000942 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000943 }
944 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000945 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000946
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000947 SetVector<BasicBlock *> ReturnTargets;
948 for (ActionHandler *Action : Actions) {
949 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
950 const auto &CatchTargets = CatchAction->getReturnTargets();
951 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000952 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000953 }
954 IndirectBrInst *Branch =
955 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
956 for (BasicBlock *Target : ReturnTargets)
957 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000958
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000959 if (!isAsynchronousEHPersonality(Personality)) {
960 // C++ EH must repopulate the targets later to handle the case of
961 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000962 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000963 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000964
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000965 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000966
967 // If nothing got outlined, there is no more processing to be done.
968 if (!HandlersOutlined)
969 return false;
970
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000971 // Replace any nested landing pad stubs with the correct action handler.
972 // This must be done before we remove unreachable blocks because it
973 // cleans up references to outlined blocks that will be deleted.
974 for (auto &LPadPair : NestedLPtoOriginalLP)
975 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000976 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000977
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000978 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000979 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000980 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000981 for (auto &LPadImplPair : LPadImpls) {
982 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
983 IndirectBrInst *Branch = LPadImplPair.second;
984
985 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000986 parseEHActions(Recover, ActionList);
987
988 // Add an indirect branch listing possible successors of the catch handlers.
989 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000990 for (const auto &Action : ActionList) {
991 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000992 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
993 getPossibleReturnTargets(&F, Handler, ReturnTargets);
994 }
995 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000996 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000997 // Clear any targets we already knew about.
998 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
999 BasicBlock *KnownTarget = Branch->getDestination(I);
1000 if (ReturnTargets.count(KnownTarget))
1001 ReturnTargets.remove(KnownTarget);
1002 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001003 for (BasicBlock *Target : ReturnTargets) {
1004 Branch->addDestination(Target);
1005 // The target may be a block that we excepted to get pruned.
1006 // If it is, it may contain a call to llvm.eh.endcatch.
1007 if (CheckedTargets.insert(Target)) {
1008 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
1009 // will be followed by an unconditional branch.
1010 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
1011 if (Br && Br->isUnconditional() &&
1012 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
1013 Instruction *Prev = Br->getPrevNode();
1014 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
1015 Prev->eraseFromParent();
1016 }
1017 }
1018 }
1019 }
1020 LPadImpls.clear();
1021
David Majnemercde33032015-03-30 22:58:10 +00001022 F.addFnAttr("wineh-parent", F.getName());
1023
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001024 // Delete any blocks that were only used by handlers that were outlined above.
1025 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001026
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001027 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001028 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001029 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001030
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001031 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001032 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001033 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001034 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +00001035 SmallVector<Value *, 8> AllocasToEscape;
1036
Reid Kleckner60381792015-07-07 22:25:32 +00001037 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +00001038 // keep escaping those objects.
1039 for (Instruction &I : F.front()) {
1040 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +00001041 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +00001042 auto Args = II->arg_operands();
1043 AllocasToEscape.append(Args.begin(), Args.end());
1044 II->eraseFromParent();
1045 break;
1046 }
1047 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001048
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001049 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +00001050 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001051 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001052 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001053 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001054 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001055
Reid Klecknerb4019412015-04-06 18:50:38 +00001056 // FIXME: We should try to sink unescaped allocas from the parent frame into
1057 // the child frame. If the alloca is escaped, we have to use the lifetime
1058 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001059
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001060 // Add this alloca to the list of things to escape.
1061 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001062
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001063 // Next replace all outlined allocas that are mapped to it.
1064 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001065 if (TempAlloca == getCatchObjectSentinel())
1066 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001067 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001068 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1069 assert(FP);
1070
Reid Kleckner60381792015-07-07 22:25:32 +00001071 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001072 Builder.SetInsertPoint(TempAlloca);
1073 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1074 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001075 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001076 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001077 Instruction *RecoveredAlloca =
1078 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1079
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001080 // Add a pointer bitcast if the alloca wasn't an i8.
1081 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1082 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001083 RecoveredAlloca = cast<Instruction>(
1084 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001085 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001086 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1087 TempAlloca->removeFromParent();
1088 RecoveredAlloca->takeName(TempAlloca);
1089 delete TempAlloca;
1090 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001091 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001092
Reid Kleckner60381792015-07-07 22:25:32 +00001093 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001094 // block.
1095 Builder.SetInsertPoint(&F.getEntryBlock().back());
1096 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1097
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001098 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001099 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1100 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1101 for (User *U : SEHExceptionCodeSlot->users()) {
1102 if (auto *Inst = dyn_cast<Instruction>(U))
1103 UserBlocks.insert(Inst->getParent());
1104 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001105 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001106 // After the promotion, kill off dead instructions.
1107 for (BasicBlock *BB : UserBlocks)
1108 SimplifyInstructionsInBlock(BB, LibInfo);
1109 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001110 }
1111
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001112 // Clean up the handler action maps we created for this function
1113 DeleteContainerSeconds(CatchHandlerMap);
1114 CatchHandlerMap.clear();
1115 DeleteContainerSeconds(CleanupHandlerMap);
1116 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001117 HandlerToParentFP.clear();
1118 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001119 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001120 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001121 EHBlocks.clear();
1122 NormalBlocks.clear();
1123 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001124
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001125 return HandlersOutlined;
1126}
1127
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001128void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1129 // If the return values of the landing pad instruction are extracted and
1130 // stored to memory, we want to promote the store locations to reg values.
1131 SmallVector<AllocaInst *, 2> EHAllocas;
1132
1133 // The landingpad instruction returns an aggregate value. Typically, its
1134 // value will be passed to a pair of extract value instructions and the
1135 // results of those extracts are often passed to store instructions.
1136 // In unoptimized code the stored value will often be loaded and then stored
1137 // again.
1138 for (auto *U : LPad->users()) {
1139 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1140 if (!Extract)
1141 continue;
1142
1143 for (auto *EU : Extract->users()) {
1144 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1145 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1146 EHAllocas.push_back(AV);
1147 }
1148 }
1149 }
1150
1151 // We can't do this without a dominator tree.
1152 assert(DT);
1153
1154 if (!EHAllocas.empty()) {
1155 PromoteMemToReg(EHAllocas, *DT);
1156 EHAllocas.clear();
1157 }
Reid Kleckner86762142015-04-16 00:02:04 +00001158
1159 // After promotion, some extracts may be trivially dead. Remove them.
1160 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1161 for (auto *U : Users)
1162 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001163}
1164
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001165void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1166 Function *HandlerF,
1167 SetVector<BasicBlock*> &Targets) {
1168 for (BasicBlock &BB : *HandlerF) {
1169 // If the handler contains landing pads, check for any
1170 // handlers that may return directly to a block in the
1171 // parent function.
1172 if (auto *LPI = BB.getLandingPadInst()) {
1173 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001174 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001175 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001176 for (const auto &Action : ActionList) {
1177 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001178 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1179 getPossibleReturnTargets(ParentF, NestedF, Targets);
1180 }
1181 }
1182 }
1183
1184 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1185 if (!Ret)
1186 continue;
1187
1188 // Handler functions must always return a block address.
1189 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1190
1191 // If this is the handler for a nested landing pad, the
1192 // return address may have been remapped to a block in the
1193 // parent handler. We're not interested in those.
1194 if (BA->getFunction() != ParentF)
1195 continue;
1196
1197 Targets.insert(BA->getBasicBlock());
1198 }
1199}
1200
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001201void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1202 LandingPadInst *OutlinedLPad,
1203 const LandingPadInst *OriginalLPad,
1204 FrameVarInfoMap &FrameVarInfo) {
1205 // Get the nested block and erase the unreachable instruction that was
1206 // temporarily inserted as its terminator.
1207 LLVMContext &Context = ParentFn->getContext();
1208 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001209 // If the nested landing pad was outlined before the landing pad that enclosed
1210 // it, it will already be in outlined form. In that case, we just need to see
1211 // if the returns and the enclosing branch instruction need to be updated.
1212 IndirectBrInst *Branch =
1213 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1214 if (!Branch) {
1215 // If the landing pad wasn't in outlined form, it should be a stub with
1216 // an unreachable terminator.
1217 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1218 OutlinedBB->getTerminator()->eraseFromParent();
1219 // That should leave OutlinedLPad as the last instruction in its block.
1220 assert(&OutlinedBB->back() == OutlinedLPad);
1221 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001222
1223 // The original landing pad will have already had its action intrinsic
1224 // built by the outlining loop. We need to clone that into the outlined
1225 // location. It may also be necessary to add references to the exception
1226 // variables to the outlined handler in which this landing pad is nested
1227 // and remap return instructions in the nested handlers that should return
1228 // to an address in the outlined handler.
1229 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001230 BasicBlock::const_iterator II = OriginalLPad;
1231 ++II;
1232 // The instruction after the landing pad should now be a call to eh.actions.
1233 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001234 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001235
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001236 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001237 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001238 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001239 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001240 for (const auto &Action : ActionList) {
1241 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001242 if (!Catch)
1243 continue;
1244 // The dyn_cast to function here selects C++ catch handlers and skips
1245 // SEH catch handlers.
1246 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1247 if (!Handler)
1248 continue;
1249 // Visit all the return instructions, looking for places that return
1250 // to a location within OutlinedHandlerFn.
1251 for (BasicBlock &NestedHandlerBB : *Handler) {
1252 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1253 if (!Ret)
1254 continue;
1255
1256 // Handler functions must always return a block address.
1257 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1258 // The original target will have been in the main parent function,
1259 // but if it is the address of a block that has been outlined, it
1260 // should be a block that was outlined into OutlinedHandlerFn.
1261 assert(BA->getFunction() == ParentFn);
1262
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001263 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001264 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1265 continue;
1266
1267 // If the return value is the address ofF a block that we
1268 // previously outlined into the parent handler function, replace
1269 // the return instruction and add the mapped target to the list
1270 // of possible return addresses.
1271 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1272 assert(MappedBB->getParent() == OutlinedHandlerFn);
1273 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1274 Ret->eraseFromParent();
1275 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1276 ActionTargets.push_back(NewBA);
1277 }
1278 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001279 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001280
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001281 if (Branch) {
1282 // If the landing pad was already in outlined form, just update its targets.
1283 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1284 Branch->removeDestination(I);
1285 // Add the previously collected action targets.
1286 for (auto *Target : ActionTargets)
1287 Branch->addDestination(Target->getBasicBlock());
1288 } else {
1289 // If the landing pad was previously stubbed out, fill in its outlined form.
1290 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1291 OutlinedBB->getInstList().push_back(NewEHActions);
1292
1293 // Insert an indirect branch into the outlined landing pad BB.
1294 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1295 // Add the previously collected action targets.
1296 for (auto *Target : ActionTargets)
1297 IBr->addDestination(Target->getBasicBlock());
1298 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001299}
1300
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001301// This function examines a block to determine whether the block ends with a
1302// conditional branch to a catch handler based on a selector comparison.
1303// This function is used both by the WinEHPrepare::findSelectorComparison() and
1304// WinEHCleanupDirector::handleTypeIdFor().
1305static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1306 Constant *&Selector, BasicBlock *&NextBB) {
1307 ICmpInst::Predicate Pred;
1308 BasicBlock *TBB, *FBB;
1309 Value *LHS, *RHS;
1310
1311 if (!match(BB->getTerminator(),
1312 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1313 return false;
1314
1315 if (!match(LHS,
1316 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1317 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1318 return false;
1319
1320 if (Pred == CmpInst::ICMP_EQ) {
1321 CatchHandler = TBB;
1322 NextBB = FBB;
1323 return true;
1324 }
1325
1326 if (Pred == CmpInst::ICMP_NE) {
1327 CatchHandler = FBB;
1328 NextBB = TBB;
1329 return true;
1330 }
1331
1332 return false;
1333}
1334
Andrew Kaylor41758512015-04-20 22:04:09 +00001335static bool isCatchBlock(BasicBlock *BB) {
1336 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1337 II != IE; ++II) {
1338 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1339 return true;
1340 }
1341 return false;
1342}
1343
David Majnemer7fddecc2015-06-17 20:52:32 +00001344static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001345 // FIXME: Finish this!
1346 LLVMContext &Context = Handler->getContext();
1347 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1348 Handler->getBasicBlockList().push_back(StubBB);
1349 IRBuilder<> Builder(StubBB);
1350 LandingPadInst *LPad = Builder.CreateLandingPad(
1351 llvm::StructType::get(Type::getInt8PtrTy(Context),
1352 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001353 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001354 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001355 Function *ActionIntrin =
1356 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001357 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001358 LPad->setCleanup(true);
1359 Builder.CreateUnreachable();
1360 return StubBB;
1361}
1362
1363// Cycles through the blocks in an outlined handler function looking for an
1364// invoke instruction and inserts an invoke of llvm.donothing with an empty
1365// landing pad if none is found. The code that generates the .xdata tables for
1366// the handler needs at least one landing pad to identify the parent function's
1367// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001368void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001369 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001370 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001371 for (BasicBlock &BB : *Handler) {
1372 TerminatorInst *Terminator = BB.getTerminator();
1373 // If we find an invoke, there is nothing to be done.
1374 auto *II = dyn_cast<InvokeInst>(Terminator);
1375 if (II)
1376 return;
1377 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001378 if (!Ret)
1379 Ret = dyn_cast<ReturnInst>(Terminator);
1380 // If we haven't recorded an unreachable instruction, try this terminator.
1381 if (!Unreached)
1382 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001383 }
1384
1385 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001386 // at least one return or unreachable instruction. We'll insert an invoke of
1387 // llvm.donothing ahead of that instruction.
1388 assert(Ret || Unreached);
1389 TerminatorInst *Term;
1390 if (Ret)
1391 Term = Ret;
1392 else
1393 Term = Unreached;
1394 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001395 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001396 // SplitBlock adds an unconditional branch instruction at the end of the
1397 // parent block. We want to replace that with an invoke call, so we can
1398 // erase it now.
1399 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001400 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001401 Function *F =
1402 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1403 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1404}
1405
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001406// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1407// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001408Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1409 const Twine &Name, Module *M,
1410 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001411 // x64 uses a two-argument prototype where the parent FP is the second
1412 // argument. x86 uses no arguments, just the incoming EBP value.
1413 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001414 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001415 FunctionType *FnType;
1416 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001417 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1418 FnType = FunctionType::get(RetTy, ArgTys, false);
1419 } else {
1420 FnType = FunctionType::get(RetTy, None, false);
1421 }
1422
1423 Function *Handler =
1424 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1425 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1426 Handler->getBasicBlockList().push_front(Entry);
1427 if (TheTriple.getArch() == Triple::x86_64) {
1428 ParentFP = &(Handler->getArgumentList().back());
1429 } else {
1430 assert(M);
1431 Function *FrameAddressFn =
1432 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001433 Function *RecoverFPFn =
1434 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1435 IRBuilder<> Builder(&Handler->getEntryBlock());
1436 Value *EBP =
1437 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1438 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1439 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001440 }
1441 return Handler;
1442}
1443
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001444bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1445 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001446 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001447 Module *M = SrcFn->getParent();
1448 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001449 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001450
1451 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001452 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001453 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001454 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001455 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001456 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001457 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001458 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001459 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001460 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001461 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001462 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001463 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001464 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001465
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001466 // Generate a standard prolog to setup the frame recovery structure.
1467 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001468 Builder.SetInsertPoint(Entry);
1469 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1470
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001471 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001472
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001473 ValueToValueMapTy VMap;
1474
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001475 LandingPadMap &LPadMap = LPadMaps[LPad];
1476 if (!LPadMap.isInitialized())
1477 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001478 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1479 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001480 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1481 LPadMap, NestedLPtoOriginalLP, DT,
1482 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001483 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1484 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001485 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001486 Director.reset(
1487 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001488 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1489 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001490 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001491
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001492 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001493 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001494
Andrew Kaylor3170e562015-03-20 21:42:54 +00001495 // If the start block contains PHI nodes, we need to map them.
1496 BasicBlock::iterator II = StartBB->begin();
1497 while (auto *PN = dyn_cast<PHINode>(II)) {
1498 bool Mapped = false;
1499 // Look for PHI values that we have already mapped (such as the selector).
1500 for (Value *Val : PN->incoming_values()) {
1501 if (VMap.count(Val)) {
1502 VMap[PN] = VMap[Val];
1503 Mapped = true;
1504 }
1505 }
1506 // If we didn't find a match for this value, map it as an undef.
1507 if (!Mapped) {
1508 VMap[PN] = UndefValue::get(PN->getType());
1509 }
1510 ++II;
1511 }
1512
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001513 // The landing pad value may be used by PHI nodes. It will ultimately be
1514 // eliminated, but we need it in the map for intermediate handling.
1515 VMap[LPad] = UndefValue::get(LPad->getType());
1516
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001517 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001518 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001519
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001520 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001521 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001522 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001523
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001524 // Move all the instructions in the cloned "entry" block into our entry block.
1525 // Depending on how the parent function was laid out, the block that will
1526 // correspond to the outlined entry block may not be the first block in the
1527 // list. We can recognize it, however, as the cloned block which has no
1528 // predecessors. Any other block wouldn't have been cloned if it didn't
1529 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001530 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001531 while (!pred_empty(ClonedIt))
1532 ++ClonedIt;
1533 BasicBlock *ClonedEntryBB = ClonedIt;
1534 assert(ClonedEntryBB);
1535 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1536 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001537
Andrew Kaylorbb111322015-04-07 21:30:23 +00001538 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001539 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001540
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001541 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1542 WinEHCatchDirector *CatchDirector =
1543 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1544 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1545 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001546
1547 // Look for blocks that are not part of the landing pad that we just
1548 // outlined but terminate with a call to llvm.eh.endcatch and a
1549 // branch to a block that is in the handler we just outlined.
1550 // These blocks will be part of a nested landing pad that intends to
1551 // return to an address in this handler. This case is best handled
1552 // after both landing pads have been outlined, so for now we'll just
1553 // save the association of the blocks in LPadTargetBlocks. The
1554 // return instructions which are created from these branches will be
1555 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001556 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001557 // VMap maps all values and blocks that were just cloned, but dead
1558 // blocks which were pruned will map to nullptr.
1559 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1560 continue;
1561 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1562 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1563 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1564 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1565 continue;
1566 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1567 --II;
1568 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1569 // This would indicate that a nested landing pad wants to return
1570 // to a block that is outlined into two different handlers.
1571 assert(!LPadTargetBlocks.count(MappedBB));
1572 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1573 }
1574 }
1575 }
1576 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001577
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001578 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001579
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001580 return true;
1581}
1582
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001583/// This BB must end in a selector dispatch. All we need to do is pass the
1584/// handler block to llvm.eh.actions and list it as a possible indirectbr
1585/// target.
1586void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1587 BasicBlock *StartBB) {
1588 BasicBlock *HandlerBB;
1589 BasicBlock *NextBB;
1590 Constant *Selector;
1591 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1592 if (Res) {
1593 // If this was EH dispatch, this must be a conditional branch to the handler
1594 // block.
1595 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1596 // leading to crashes if some optimization hoists stuff here.
1597 assert(CatchAction->getSelector() && HandlerBB &&
1598 "expected catch EH dispatch");
1599 } else {
1600 // This must be a catch-all. Split the block after the landingpad.
1601 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001602 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001603 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001604 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1605 Function *EHCodeFn = Intrinsic::getDeclaration(
1606 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001607 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001608 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1609 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001610 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1611 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1612 CatchAction->setReturnTargets(Targets);
1613}
1614
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001615void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1616 // Each instance of this class should only ever be used to map a single
1617 // landing pad.
1618 assert(OriginLPad == nullptr || OriginLPad == LPad);
1619
1620 // If the landing pad has already been mapped, there's nothing more to do.
1621 if (OriginLPad == LPad)
1622 return;
1623
1624 OriginLPad = LPad;
1625
1626 // The landingpad instruction returns an aggregate value. Typically, its
1627 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001628 // results of those extracts will have been promoted to reg values before
1629 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001630 for (auto *U : LPad->users()) {
1631 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1632 if (!Extract)
1633 continue;
1634 assert(Extract->getNumIndices() == 1 &&
1635 "Unexpected operation: extracting both landing pad values");
1636 unsigned int Idx = *(Extract->idx_begin());
1637 assert((Idx == 0 || Idx == 1) &&
1638 "Unexpected operation: extracting an unknown landing pad element");
1639 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001640 ExtractedEHPtrs.push_back(Extract);
1641 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001642 ExtractedSelectors.push_back(Extract);
1643 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001644 }
1645}
1646
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001647bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1648 return BB->getLandingPadInst() == OriginLPad;
1649}
1650
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001651bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1652 if (Inst == OriginLPad)
1653 return true;
1654 for (auto *Extract : ExtractedEHPtrs) {
1655 if (Inst == Extract)
1656 return true;
1657 }
1658 for (auto *Extract : ExtractedSelectors) {
1659 if (Inst == Extract)
1660 return true;
1661 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001662 return false;
1663}
1664
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001665void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1666 Value *SelectorValue) const {
1667 // Remap all landing pad extract instructions to the specified values.
1668 for (auto *Extract : ExtractedEHPtrs)
1669 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001670 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001671 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001672}
1673
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001674static bool isLocalAddressCall(const Value *V) {
1675 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001676}
1677
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001678CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001679 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001680 // If this is one of the boilerplate landing pad instructions, skip it.
1681 // The instruction will have already been remapped in VMap.
1682 if (LPadMap.isLandingPadSpecificInst(Inst))
1683 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001684
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001685 // Nested landing pads that have not already been outlined will be cloned as
1686 // stubs, with just the landingpad instruction and an unreachable instruction.
1687 // When all landingpads have been outlined, we'll replace this with the
1688 // llvm.eh.actions call and indirect branch created when the landing pad was
1689 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001690 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1691 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001692 }
1693
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001694 // Nested landing pads that have already been outlined will be cloned in their
1695 // outlined form, but we need to intercept the ibr instruction to filter out
1696 // targets that do not return to the handler we are outlining.
1697 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1698 return handleIndirectBr(VMap, IBr, NewBB);
1699 }
1700
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001701 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1702 return handleInvoke(VMap, Invoke, NewBB);
1703
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001704 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1705 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001706
Andrew Kaylorea8df612015-04-17 23:05:43 +00001707 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1708 return handleCompare(VMap, Cmp, NewBB);
1709
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001710 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1711 return handleBeginCatch(VMap, Inst, NewBB);
1712 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1713 return handleEndCatch(VMap, Inst, NewBB);
1714 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1715 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001716
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001717 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001718 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001719 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001720 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001721 return CloningDirector::SkipInstruction;
1722 }
1723
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001724 // Continue with the default cloning behavior.
1725 return CloningDirector::CloneInstruction;
1726}
1727
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001728CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1729 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001730 // If the instruction after the landing pad is a call to llvm.eh.actions
1731 // the landing pad has already been outlined. In this case, we should
1732 // clone it because it may return to a block in the handler we are
1733 // outlining now that would otherwise be unreachable. The landing pads
1734 // are sorted before outlining begins to enable this case to work
1735 // properly.
1736 const Instruction *NextI = LPad->getNextNode();
1737 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1738 return CloningDirector::CloneInstruction;
1739
1740 // If the landing pad hasn't been outlined yet, the landing pad we are
1741 // outlining now does not dominate it and so it cannot return to a block
1742 // in this handler. In that case, we can just insert a stub landing
1743 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001744 Instruction *NewInst = LPad->clone();
1745 if (LPad->hasName())
1746 NewInst->setName(LPad->getName());
1747 // Save this correlation for later processing.
1748 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1749 VMap[LPad] = NewInst;
1750 BasicBlock::InstListType &InstList = NewBB->getInstList();
1751 InstList.push_back(NewInst);
1752 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1753 return CloningDirector::StopCloningBB;
1754}
1755
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001756CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1757 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1758 // The argument to the call is some form of the first element of the
1759 // landingpad aggregate value, but that doesn't matter. It isn't used
1760 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001761 // The second argument is an outparameter where the exception object will be
1762 // stored. Typically the exception object is a scalar, but it can be an
1763 // aggregate when catching by value.
1764 // FIXME: Leave something behind to indicate where the exception object lives
1765 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001766 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1767 "llvm.eh.begincatch found while "
1768 "outlining catch handler.");
1769 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001770 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1771 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001772 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1773 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001774 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001775 return CloningDirector::SkipInstruction;
1776}
1777
1778CloningDirector::CloningAction
1779WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1780 const Instruction *Inst, BasicBlock *NewBB) {
1781 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1782 // It might be interesting to track whether or not we are inside a catch
1783 // function, but that might make the algorithm more brittle than it needs
1784 // to be.
1785
1786 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001787 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001788 // or at the end of the catch block. However, a catch-all handler may call
1789 // end catch from the original landing pad. If the call occurs in a nested
1790 // landing pad block, we must skip it and continue so that the landing pad
1791 // gets cloned.
1792 auto *ParentBB = IntrinCall->getParent();
1793 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001794 return CloningDirector::SkipInstruction;
1795
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001796 // If an end catch occurs anywhere else we want to terminate the handler
1797 // with a return to the code that follows the endcatch call. If the
1798 // next instruction is not an unconditional branch, we need to split the
1799 // block to provide a clear target for the return instruction.
1800 BasicBlock *ContinueBB;
1801 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1802 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1803 if (!Branch || !Branch->isUnconditional()) {
1804 // We're interrupting the cloning process at this location, so the
1805 // const_cast we're doing here will not cause a problem.
1806 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1807 const_cast<Instruction *>(cast<Instruction>(Next)));
1808 } else {
1809 ContinueBB = Branch->getSuccessor(0);
1810 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001811
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001812 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1813 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001814
1815 // We just added a terminator to the cloned block.
1816 // Tell the caller to stop processing the current basic block so that
1817 // the branch instruction will be skipped.
1818 return CloningDirector::StopCloningBB;
1819}
1820
1821CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1822 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1823 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1824 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1825 // This causes a replacement that will collapse the landing pad CFG based
1826 // on the filter function we intend to match.
1827 if (Selector == CurrentSelector)
1828 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1829 else
1830 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1831 // Tell the caller not to clone this instruction.
1832 return CloningDirector::SkipInstruction;
1833}
1834
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001835CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1836 ValueToValueMapTy &VMap,
1837 const IndirectBrInst *IBr,
1838 BasicBlock *NewBB) {
1839 // If this indirect branch is not part of a landing pad block, just clone it.
1840 const BasicBlock *ParentBB = IBr->getParent();
1841 if (!ParentBB->isLandingPad())
1842 return CloningDirector::CloneInstruction;
1843
1844 // If it is part of a landing pad, we want to filter out target blocks
1845 // that are not part of the handler we are outlining.
1846 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1847
1848 // Save this correlation for later processing.
1849 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1850
1851 // We should only get here for landing pads that have already been outlined.
1852 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1853
1854 // Copy the indirectbr, but only include targets that were previously
1855 // identified as EH blocks and are dominated by the nested landing pad.
1856 SetVector<const BasicBlock *> ReturnTargets;
1857 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1858 auto *TargetBB = IBr->getDestination(I);
1859 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1860 DT->dominates(ParentBB, TargetBB)) {
1861 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1862 ReturnTargets.insert(TargetBB);
1863 }
1864 }
1865 IndirectBrInst *NewBranch =
1866 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1867 ReturnTargets.size(), NewBB);
1868 for (auto *Target : ReturnTargets)
1869 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1870
1871 // The operands and targets of the branch instruction are remapped later
1872 // because it is a terminator. Tell the cloning code to clone the
1873 // blocks we just added to the target list.
1874 return CloningDirector::CloneSuccessors;
1875}
1876
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001877CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001878WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1879 const InvokeInst *Invoke, BasicBlock *NewBB) {
1880 return CloningDirector::CloneInstruction;
1881}
1882
1883CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001884WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1885 const ResumeInst *Resume, BasicBlock *NewBB) {
1886 // Resume instructions shouldn't be reachable from catch handlers.
1887 // We still need to handle it, but it will be pruned.
1888 BasicBlock::InstListType &InstList = NewBB->getInstList();
1889 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1890 return CloningDirector::StopCloningBB;
1891}
1892
Andrew Kaylorea8df612015-04-17 23:05:43 +00001893CloningDirector::CloningAction
1894WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1895 const CmpInst *Compare, BasicBlock *NewBB) {
1896 const IntrinsicInst *IntrinCall = nullptr;
1897 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1898 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001899 } else if (match(Compare->getOperand(1),
1900 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001901 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1902 }
1903 if (IntrinCall) {
1904 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1905 // This causes a replacement that will collapse the landing pad CFG based
1906 // on the filter function we intend to match.
1907 if (Selector == CurrentSelector->stripPointerCasts()) {
1908 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001909 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001910 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1911 }
1912 return CloningDirector::SkipInstruction;
1913 }
1914 return CloningDirector::CloneInstruction;
1915}
1916
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001917CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1918 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1919 // The MS runtime will terminate the process if an exception occurs in a
1920 // cleanup handler, so we shouldn't encounter landing pads in the actual
1921 // cleanup code, but they may appear in catch blocks. Depending on where
1922 // we started cloning we may see one, but it will get dropped during dead
1923 // block pruning.
1924 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1925 VMap[LPad] = NewInst;
1926 BasicBlock::InstListType &InstList = NewBB->getInstList();
1927 InstList.push_back(NewInst);
1928 return CloningDirector::StopCloningBB;
1929}
1930
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001931CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1932 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001933 // Cleanup code may flow into catch blocks or the catch block may be part
1934 // of a branch that will be optimized away. We'll insert a return
1935 // instruction now, but it may be pruned before the cloning process is
1936 // complete.
1937 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001938 return CloningDirector::StopCloningBB;
1939}
1940
1941CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1942 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001943 // Cleanup handlers nested within catch handlers may begin with a call to
1944 // eh.endcatch. We can just ignore that instruction.
1945 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001946}
1947
1948CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1949 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001950 // If we encounter a selector comparison while cloning a cleanup handler,
1951 // we want to stop cloning immediately. Anything after the dispatch
1952 // will be outlined into a different handler.
1953 BasicBlock *CatchHandler;
1954 Constant *Selector;
1955 BasicBlock *NextBB;
1956 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1957 CatchHandler, Selector, NextBB)) {
1958 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1959 return CloningDirector::StopCloningBB;
1960 }
1961 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001962 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001963 return CloningDirector::SkipInstruction;
1964}
1965
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001966CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1967 ValueToValueMapTy &VMap,
1968 const IndirectBrInst *IBr,
1969 BasicBlock *NewBB) {
1970 // No special handling is required for cleanup cloning.
1971 return CloningDirector::CloneInstruction;
1972}
1973
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001974CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1975 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1976 // All invokes in cleanup handlers can be replaced with calls.
1977 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1978 // Insert a normal call instruction...
1979 CallInst *NewCall =
1980 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1981 Invoke->getName(), NewBB);
1982 NewCall->setCallingConv(Invoke->getCallingConv());
1983 NewCall->setAttributes(Invoke->getAttributes());
1984 NewCall->setDebugLoc(Invoke->getDebugLoc());
1985 VMap[Invoke] = NewCall;
1986
Reid Kleckner6e48a822015-04-10 16:26:42 +00001987 // Remap the operands.
1988 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1989
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001990 // Insert an unconditional branch to the normal destination.
1991 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1992
1993 // The unwind destination won't be cloned into the new function, so
1994 // we don't need to clean up its phi nodes.
1995
1996 // We just added a terminator to the cloned block.
1997 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001998 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001999}
2000
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00002001CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
2002 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
2003 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
2004
2005 // We just added a terminator to the cloned block.
2006 // Tell the caller to stop processing the current basic block so that
2007 // the branch instruction will be skipped.
2008 return CloningDirector::StopCloningBB;
2009}
2010
Andrew Kaylorea8df612015-04-17 23:05:43 +00002011CloningDirector::CloningAction
2012WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
2013 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00002014 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
2015 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
2016 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
2017 return CloningDirector::SkipInstruction;
2018 }
2019 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00002020}
2021
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002022WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002023 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002024 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002025 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002026
2027 // New allocas should be inserted in the entry block, but after the parent FP
2028 // is established if it is an instruction.
2029 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2030 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2031 InsertPoint = FPInst->getNextNode();
2032 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002033}
2034
2035Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002036 // If we're asked to materialize a static alloca, we temporarily create an
2037 // alloca in the outlined function and add this to the FrameVarInfo map. When
2038 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00002039 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002040 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002041 assert(AV->isStaticAlloca() &&
2042 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00002043 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2044 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00002045 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002046 return NewAlloca;
2047 }
2048
Andrew Kaylor72029c62015-03-03 00:41:03 +00002049 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00002050 Function *Parent = isa<Instruction>(V)
2051 ? cast<Instruction>(V)->getParent()->getParent()
2052 : cast<Argument>(V)->getParent();
2053 errs()
2054 << "Failed to demote instruction used in exception handler of function "
2055 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002056 errs() << " " << *V << '\n';
2057 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002058 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002059
Andrew Kaylor72029c62015-03-03 00:41:03 +00002060 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002061 return nullptr;
2062}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002063
Reid Kleckner3567d272015-04-02 21:13:31 +00002064void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2065 // Catch parameter objects have to live in the parent frame. When we see a use
2066 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2067 // used from another handler. This will prevent us from trying to sink the
2068 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002069 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002070 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2071}
2072
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002073// This function maps the catch and cleanup handlers that are reachable from the
2074// specified landing pad. The landing pad sequence will have this basic shape:
2075//
2076// <cleanup handler>
2077// <selector comparison>
2078// <catch handler>
2079// <cleanup handler>
2080// <selector comparison>
2081// <catch handler>
2082// <cleanup handler>
2083// ...
2084//
2085// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2086// any arbitrary control flow, but all paths through the cleanup code must
2087// eventually reach the next selector comparison and no path can skip to a
2088// different selector comparisons, though some paths may terminate abnormally.
2089// Therefore, we will use a depth first search from the start of any given
2090// cleanup block and stop searching when we find the next selector comparison.
2091//
2092// If the landingpad instruction does not have a catch clause, we will assume
2093// that any instructions other than selector comparisons and catch handlers can
2094// be ignored. In practice, these will only be the boilerplate instructions.
2095//
2096// The catch handlers may also have any control structure, but we are only
2097// interested in the start of the catch handlers, so we don't need to actually
2098// follow the flow of the catch handlers. The start of the catch handlers can
2099// be located from the compare instructions, but they can be skipped in the
2100// flow by following the contrary branch.
2101void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2102 LandingPadActions &Actions) {
2103 unsigned int NumClauses = LPad->getNumClauses();
2104 unsigned int HandlersFound = 0;
2105 BasicBlock *BB = LPad->getParent();
2106
2107 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2108
2109 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002110 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002111 return;
2112 }
2113
2114 VisitedBlockSet VisitedBlocks;
2115
2116 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002117 BasicBlock *NextBB = nullptr;
2118
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002119 // Skip over filter clauses.
2120 if (LPad->isFilter(HandlersFound)) {
2121 ++HandlersFound;
2122 continue;
2123 }
2124
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002125 // See if the clause we're looking for is a catch-all.
2126 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002127 Constant *ExpectedSelector =
2128 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002129 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002130 // The catch all must occur last.
2131 assert(HandlersFound == NumClauses - 1);
2132
Andrew Kaylorea8df612015-04-17 23:05:43 +00002133 // There can be additional selector dispatches in the call chain that we
2134 // need to ignore.
2135 BasicBlock *CatchBlock = nullptr;
2136 Constant *Selector;
2137 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2138 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002139 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002140 BB = NextBB;
2141 }
2142
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002143 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002144 CatchHandler *Action = nullptr;
2145 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2146 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2147 Action = CatchHandlerMap[BB];
2148 assert(Action->getSelector() == ExpectedSelector);
2149 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002150 // We don't expect a selector dispatch, but there may be a call to
2151 // llvm.eh.begincatch, which separates catch handling code from
2152 // cleanup code in the same control flow. This call looks for the
2153 // begincatch intrinsic.
2154 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2155 if (Action) {
2156 // For C++ EH, check if there is any interesting cleanup code before
2157 // we begin the catch. This is important because cleanups cannot
2158 // rethrow exceptions but code called from catches can. For SEH, it
2159 // isn't important if some finally code before a catch-all is executed
2160 // out of line or after recovering from the exception.
2161 if (Personality == EHPersonality::MSVC_CXX)
2162 findCleanupHandlers(Actions, BB, BB);
2163 } else {
2164 // If an action was not found, it means that the control flows
2165 // directly into the catch-all handler and there is no cleanup code.
2166 // That's an expected situation and we must create a catch action.
2167 // Since this is a catch-all handler, the selector won't actually
2168 // appear in the code anywhere. ExpectedSelector here is the constant
2169 // null ptr that we got from the landing pad instruction.
2170 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2171 CatchHandlerMap[BB] = Action;
2172 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002173 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002174 Actions.insertCatchHandler(Action);
2175 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2176 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002177
2178 // Once we reach a catch-all, don't expect to hit a resume instruction.
2179 BB = nullptr;
2180 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002181 }
2182
2183 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002184 assert(CatchAction);
2185
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002186 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002187 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002188
Andrew Kaylorea8df612015-04-17 23:05:43 +00002189 // When the source program contains multiple nested try blocks the catch
2190 // handlers can get strung together in such a way that we can encounter
2191 // a dispatch for a selector that we've already had a handler for.
2192 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2193 ++HandlersFound;
2194
2195 // Add the catch handler to the action list.
2196 DEBUG(dbgs() << " Found catch dispatch in block "
2197 << CatchAction->getStartBlock()->getName() << "\n");
2198 Actions.insertCatchHandler(CatchAction);
2199 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002200 // Under some circumstances optimized IR will flow unconditionally into a
2201 // handler block without checking the selector. This can only happen if
2202 // the landing pad has a catch-all handler and the handler for the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002203 // preceding catch clause is identical to the catch-call handler
Andrew Kaylor41758512015-04-20 22:04:09 +00002204 // (typically an empty catch). In this case, the handler must be shared
2205 // by all remaining clauses.
2206 if (isa<ConstantPointerNull>(
2207 CatchAction->getSelector()->stripPointerCasts())) {
2208 DEBUG(dbgs() << " Applying early catch-all handler in block "
2209 << CatchAction->getStartBlock()->getName()
2210 << " to all remaining clauses.\n");
2211 Actions.insertCatchHandler(CatchAction);
2212 return;
2213 }
2214
Andrew Kaylorea8df612015-04-17 23:05:43 +00002215 DEBUG(dbgs() << " Found extra catch dispatch in block "
2216 << CatchAction->getStartBlock()->getName() << "\n");
2217 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002218
2219 // Move on to the block after the catch handler.
2220 BB = NextBB;
2221 }
2222
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002223 // If we didn't wind up in a catch-all, see if there is any interesting code
2224 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002225 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002226
2227 // It's possible that some optimization moved code into a landingpad that
2228 // wasn't
2229 // previously being used for cleanup. If that happens, we need to execute
2230 // that
2231 // extra code from a cleanup handler.
2232 if (Actions.includesCleanup() && !LPad->isCleanup())
2233 LPad->setCleanup(true);
2234}
2235
2236// This function searches starting with the input block for the next
2237// block that terminates with a branch whose condition is based on a selector
2238// comparison. This may be the input block. See the mapLandingPadBlocks
2239// comments for a discussion of control flow assumptions.
2240//
2241CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2242 BasicBlock *&NextBB,
2243 VisitedBlockSet &VisitedBlocks) {
2244 // See if we've already found a catch handler use it.
2245 // Call count() first to avoid creating a null entry for blocks
2246 // we haven't seen before.
2247 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2248 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2249 NextBB = Action->getNextBB();
2250 return Action;
2251 }
2252
2253 // VisitedBlocks applies only to the current search. We still
2254 // need to consider blocks that we've visited while mapping other
2255 // landing pads.
2256 VisitedBlocks.insert(BB);
2257
2258 BasicBlock *CatchBlock = nullptr;
2259 Constant *Selector = nullptr;
2260
2261 // If this is the first time we've visited this block from any landing pad
2262 // look to see if it is a selector dispatch block.
2263 if (!CatchHandlerMap.count(BB)) {
2264 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2265 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2266 CatchHandlerMap[BB] = Action;
2267 return Action;
2268 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002269 // If we encounter a block containing an llvm.eh.begincatch before we
2270 // find a selector dispatch block, the handler is assumed to be
2271 // reached unconditionally. This happens for catch-all blocks, but
2272 // it can also happen for other catch handlers that have been combined
2273 // with the catch-all handler during optimization.
2274 if (isCatchBlock(BB)) {
2275 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2276 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2277 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2278 CatchHandlerMap[BB] = Action;
2279 return Action;
2280 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002281 }
2282
2283 // Visit each successor, looking for the dispatch.
2284 // FIXME: We expect to find the dispatch quickly, so this will probably
2285 // work better as a breadth first search.
2286 for (BasicBlock *Succ : successors(BB)) {
2287 if (VisitedBlocks.count(Succ))
2288 continue;
2289
2290 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2291 if (Action)
2292 return Action;
2293 }
2294 return nullptr;
2295}
2296
Reid Kleckner9405ef02015-04-10 23:12:29 +00002297// These are helper functions to combine repeated code from findCleanupHandlers.
2298static void createCleanupHandler(LandingPadActions &Actions,
2299 CleanupHandlerMapTy &CleanupHandlerMap,
2300 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002301 CleanupHandler *Action = new CleanupHandler(BB);
2302 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002303 Actions.insertCleanupHandler(Action);
2304 DEBUG(dbgs() << " Found cleanup code in block "
2305 << Action->getStartBlock()->getName() << "\n");
2306}
2307
Reid Kleckner9405ef02015-04-10 23:12:29 +00002308static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2309 Instruction *MaybeCall) {
2310 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002311 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002312 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002313 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002314 MaybeCall = MaybeCall->getNextNode();
2315 CallSite FinallyCall(MaybeCall);
2316 if (!FinallyCall || FinallyCall.arg_size() != 2)
2317 return CallSite();
2318 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2319 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002320 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002321 return CallSite();
2322 return FinallyCall;
2323}
2324
2325static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2326 // Skip single ubr blocks.
2327 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2328 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2329 if (Br && Br->isUnconditional())
2330 BB = Br->getSuccessor(0);
2331 else
2332 return BB;
2333 }
2334 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002335}
2336
2337// This function searches starting with the input block for the next block that
2338// contains code that is not part of a catch handler and would not be eliminated
2339// during handler outlining.
2340//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002341void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2342 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002343 // Here we will skip over the following:
2344 //
2345 // landing pad prolog:
2346 //
2347 // Unconditional branches
2348 //
2349 // Selector dispatch
2350 //
2351 // Resume pattern
2352 //
2353 // Anything else marks the start of an interesting block
2354
2355 BasicBlock *BB = StartBB;
2356 // Anything other than an unconditional branch will kick us out of this loop
2357 // one way or another.
2358 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002359 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002360 // If we've already scanned this block, don't scan it again. If it is
2361 // a cleanup block, there will be an action in the CleanupHandlerMap.
2362 // If we've scanned it and it is not a cleanup block, there will be a
2363 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2364 // be no entry in the CleanupHandlerMap. We must call count() first to
2365 // avoid creating a null entry for blocks we haven't scanned.
2366 if (CleanupHandlerMap.count(BB)) {
2367 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002368 Actions.insertCleanupHandler(Action);
2369 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002370 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002371 // FIXME: This cleanup might chain into another, and we need to discover
2372 // that.
2373 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002374 } else {
2375 // Here we handle the case where the cleanup handler map contains a
2376 // value for this block but the value is a nullptr. This means that
2377 // we have previously analyzed the block and determined that it did
2378 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002379 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002380 // resume or a conditional branch that is predicated on a comparison
2381 // with a selector. Either the resume or the selector dispatch
2382 // would terminate the search for cleanup code, so the unconditional
2383 // branch is the only case for which we might need to continue
2384 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002385 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2386 if (SuccBB == BB || SuccBB == EndBB)
2387 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002388 BB = SuccBB;
2389 continue;
2390 }
2391 }
2392
2393 // Create an entry in the cleanup handler map for this block. Initially
2394 // we create an entry that says this isn't a cleanup block. If we find
2395 // cleanup code, the caller will replace this entry.
2396 CleanupHandlerMap[BB] = nullptr;
2397
2398 TerminatorInst *Terminator = BB->getTerminator();
2399
2400 // Landing pad blocks have extra instructions we need to accept.
2401 LandingPadMap *LPadMap = nullptr;
2402 if (BB->isLandingPad()) {
2403 LandingPadInst *LPad = BB->getLandingPadInst();
2404 LPadMap = &LPadMaps[LPad];
2405 if (!LPadMap->isInitialized())
2406 LPadMap->mapLandingPad(LPad);
2407 }
2408
2409 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002410 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2411 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002412 // resume { i8*, i32 } %lpad.val2
2413 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2414 InsertValueInst *Insert1 = nullptr;
2415 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002416 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002417 // If the resume value isn't a phi or landingpad value, it should be a
2418 // series of insertions. Identify them so we can avoid them when scanning
2419 // for cleanups.
2420 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002421 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002422 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002423 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002424 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2425 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002426 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002427 }
2428 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2429 II != IE; ++II) {
2430 Instruction *Inst = II;
2431 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2432 continue;
2433 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2434 continue;
2435 if (!Inst->hasOneUse() ||
2436 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002437 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002438 }
2439 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002440 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002441 }
2442
2443 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002444 if (Branch && Branch->isConditional()) {
2445 // Look for the selector dispatch.
2446 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2447 // %matches = icmp eq i32 %sel, %2
2448 // br i1 %matches, label %catch14, label %eh.resume
2449 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2450 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002451 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002452 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2453 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002454 Instruction *Inst = II;
2455 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2456 continue;
2457 if (Inst == Compare || Inst == Branch)
2458 continue;
2459 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2460 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002461 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002462 }
2463 // The selector dispatch block should always terminate our search.
2464 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002465 return;
2466 }
2467
2468 if (isAsynchronousEHPersonality(Personality)) {
2469 // If this is a landingpad block, split the block at the first non-landing
2470 // pad instruction.
2471 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2472 if (LPadMap) {
2473 while (MaybeCall != BB->getTerminator() &&
2474 LPadMap->isLandingPadSpecificInst(MaybeCall))
2475 MaybeCall = MaybeCall->getNextNode();
2476 }
2477
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002478 // Look for outlined finally calls on x64, since those happen to match the
2479 // prototype provided by the runtime.
2480 if (TheTriple.getArch() == Triple::x86_64) {
2481 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2482 Function *Fin = FinallyCall.getCalledFunction();
2483 assert(Fin && "outlined finally call should be direct");
2484 auto *Action = new CleanupHandler(BB);
2485 Action->setHandlerBlockOrFunc(Fin);
2486 Actions.insertCleanupHandler(Action);
2487 CleanupHandlerMap[BB] = Action;
2488 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2489 << Fin->getName() << " in block "
2490 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002491
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002492 // Split the block if there were more interesting instructions and
2493 // look for finally calls in the normal successor block.
2494 BasicBlock *SuccBB = BB;
2495 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2496 FinallyCall.getInstruction()->getNextNode() !=
2497 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002498 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002499 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002500 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002501 if (FinallyCall.isInvoke()) {
2502 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2503 ->getNormalDest();
2504 } else {
2505 SuccBB = BB->getUniqueSuccessor();
2506 assert(SuccBB &&
2507 "splitOutlinedFinallyCalls didn't insert a branch");
2508 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002509 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002510 BB = SuccBB;
2511 if (BB == EndBB)
2512 return;
2513 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002514 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002515 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002516 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002517
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002518 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002519 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2520 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002521 Instruction *Inst = II;
2522 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2523 continue;
2524 // Unconditional branches fall through to this loop.
2525 if (Inst == Branch)
2526 continue;
2527 // If this is a catch block, there is no cleanup code to be found.
2528 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002529 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002530 // If this a nested landing pad, it may contain an endcatch call.
2531 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002532 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002533 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002534 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002535 }
2536
2537 // Only unconditional branches in empty blocks should get this far.
2538 assert(Branch && Branch->isUnconditional());
2539 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002540 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002541 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002542 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002543}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002544
2545// This is a public function, declared in WinEHFuncInfo.h and is also
2546// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002547void llvm::parseEHActions(
2548 const IntrinsicInst *II,
2549 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002550 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2551 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002552 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2553 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002554 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002555 if (ActionKind == /*catch=*/1) {
2556 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2557 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2558 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2559 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2560 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002561 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2562 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002563 CH->setHandlerBlockOrFunc(Handler);
2564 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002565 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002566 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002567 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2568 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002569 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002570 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002571 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002572 } else {
2573 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002574 }
2575 }
2576 std::reverse(Actions.begin(), Actions.end());
2577}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002578
David Majnemer0ad363e2015-08-18 19:07:12 +00002579static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2580 const Value *V) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002581 WinEHUnwindMapEntry UME;
2582 UME.ToState = ToState;
David Majnemer0ad363e2015-08-18 19:07:12 +00002583 UME.Cleanup = V;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002584 FuncInfo.UnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +00002585 return FuncInfo.getLastStateNumber();
2586}
2587
2588static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2589 int TryHigh, int CatchHigh,
2590 ArrayRef<const CatchPadInst *> Handlers) {
2591 WinEHTryBlockMapEntry TBME;
2592 TBME.TryLow = TryLow;
2593 TBME.TryHigh = TryHigh;
2594 TBME.CatchHigh = CatchHigh;
2595 assert(TBME.TryLow <= TBME.TryHigh);
2596 for (const CatchPadInst *CPI : Handlers) {
2597 WinEHHandlerType HT;
2598 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
Reid Klecknerb005d282015-09-16 20:16:27 +00002599 if (TypeInfo->isNullValue())
David Majnemer0ad363e2015-08-18 19:07:12 +00002600 HT.TypeDescriptor = nullptr;
Reid Klecknerb005d282015-09-16 20:16:27 +00002601 else
2602 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2603 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
Reid Kleckner0e288232015-08-27 23:27:47 +00002604 HT.Handler = CPI->getNormalDest();
Reid Klecknerb005d282015-09-16 20:16:27 +00002605 HT.CatchObjRecoverIdx = -2;
2606 if (isa<ConstantPointerNull>(CPI->getArgOperand(2)))
2607 HT.CatchObj.Alloca = nullptr;
2608 else
2609 HT.CatchObj.Alloca = cast<AllocaInst>(CPI->getArgOperand(2));
David Majnemer0ad363e2015-08-18 19:07:12 +00002610 TBME.HandlerArray.push_back(HT);
2611 }
2612 FuncInfo.TryBlockMap.push_back(TBME);
2613}
2614
Reid Kleckner94b704c2015-09-09 21:10:03 +00002615static const CatchPadInst *getSingleCatchPadPredecessor(const BasicBlock *BB) {
2616 for (const BasicBlock *PredBlock : predecessors(BB))
2617 if (auto *CPI = dyn_cast<CatchPadInst>(PredBlock->getFirstNonPHI()))
2618 return CPI;
David Majnemer0ad363e2015-08-18 19:07:12 +00002619 return nullptr;
2620}
2621
Reid Kleckner94b704c2015-09-09 21:10:03 +00002622/// Find all the catchpads that feed directly into the catchendpad. Frontends
2623/// using this personality should ensure that each catchendpad and catchpad has
2624/// one or zero catchpad predecessors.
2625///
2626/// The following C++ generates the IR after it:
2627/// try {
2628/// } catch (A) {
2629/// } catch (B) {
2630/// }
2631///
2632/// IR:
2633/// %catchpad.A
2634/// catchpad [i8* A typeinfo]
2635/// to label %catch.A unwind label %catchpad.B
2636/// %catchpad.B
2637/// catchpad [i8* B typeinfo]
2638/// to label %catch.B unwind label %endcatches
2639/// %endcatches
2640/// catchendblock unwind to caller
Benjamin Kramer3c96f0a2015-09-22 14:34:57 +00002641static void
2642findCatchPadsForCatchEndPad(const BasicBlock *CatchEndBB,
2643 SmallVectorImpl<const CatchPadInst *> &Handlers) {
Reid Kleckner94b704c2015-09-09 21:10:03 +00002644 const CatchPadInst *CPI = getSingleCatchPadPredecessor(CatchEndBB);
2645 while (CPI) {
2646 Handlers.push_back(CPI);
2647 CPI = getSingleCatchPadPredecessor(CPI->getParent());
2648 }
2649 // We've pushed these back into reverse source order. Reverse them to get
2650 // the list back into source order.
2651 std::reverse(Handlers.begin(), Handlers.end());
2652}
2653
David Majnemer0ad363e2015-08-18 19:07:12 +00002654// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
2655// to. If the unwind edge came from an invoke, return null.
2656static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
2657 const TerminatorInst *TI = BB->getTerminator();
2658 if (isa<InvokeInst>(TI))
2659 return nullptr;
Reid Kleckner7bb20bd2015-09-10 21:46:36 +00002660 if (TI->isEHPad())
David Majnemer0ad363e2015-08-18 19:07:12 +00002661 return BB;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002662 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00002663}
2664
Reid Kleckner94b704c2015-09-09 21:10:03 +00002665static void calculateExplicitCXXStateNumbers(WinEHFuncInfo &FuncInfo,
2666 const BasicBlock &BB,
2667 int ParentState) {
David Majnemer0ad363e2015-08-18 19:07:12 +00002668 assert(BB.isEHPad());
2669 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
2670 // All catchpad instructions will be handled when we process their
2671 // respective catchendpad instruction.
2672 if (isa<CatchPadInst>(FirstNonPHI))
2673 return;
2674
2675 if (isa<CatchEndPadInst>(FirstNonPHI)) {
David Majnemer0ad363e2015-08-18 19:07:12 +00002676 SmallVector<const CatchPadInst *, 2> Handlers;
Reid Kleckner94b704c2015-09-09 21:10:03 +00002677 findCatchPadsForCatchEndPad(&BB, Handlers);
2678 const BasicBlock *FirstTryPad = Handlers.front()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00002679 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
2680 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
Reid Kleckner94b704c2015-09-09 21:10:03 +00002681 for (const BasicBlock *PredBlock : predecessors(FirstTryPad))
David Majnemer0ad363e2015-08-18 19:07:12 +00002682 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00002683 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, TryLow);
David Majnemer0ad363e2015-08-18 19:07:12 +00002684 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
Reid Kleckner94b704c2015-09-09 21:10:03 +00002685
2686 // catchpads are separate funclets in C++ EH due to the way rethrow works.
2687 // In SEH, they aren't, so no invokes will unwind to the catchendpad.
David Majnemer0ad363e2015-08-18 19:07:12 +00002688 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
2689 int TryHigh = CatchLow - 1;
2690 for (const BasicBlock *PredBlock : predecessors(&BB))
2691 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00002692 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CatchLow);
David Majnemer0ad363e2015-08-18 19:07:12 +00002693 int CatchHigh = FuncInfo.getLastStateNumber();
2694 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
Reid Kleckner94b704c2015-09-09 21:10:03 +00002695 DEBUG(dbgs() << "TryLow[" << FirstTryPad->getName() << "]: " << TryLow
David Majnemer0ad363e2015-08-18 19:07:12 +00002696 << '\n');
Reid Kleckner94b704c2015-09-09 21:10:03 +00002697 DEBUG(dbgs() << "TryHigh[" << FirstTryPad->getName() << "]: " << TryHigh
David Majnemer0ad363e2015-08-18 19:07:12 +00002698 << '\n');
Reid Kleckner94b704c2015-09-09 21:10:03 +00002699 DEBUG(dbgs() << "CatchHigh[" << FirstTryPad->getName() << "]: " << CatchHigh
David Majnemer0ad363e2015-08-18 19:07:12 +00002700 << '\n');
2701 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
2702 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
2703 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
2704 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
2705 << BB.getName() << '\n');
2706 for (const BasicBlock *PredBlock : predecessors(&BB))
2707 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
Reid Kleckner94b704c2015-09-09 21:10:03 +00002708 calculateExplicitCXXStateNumbers(FuncInfo, *PredBlock, CleanupState);
David Majnemer0ad363e2015-08-18 19:07:12 +00002709 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
2710 report_fatal_error("Not yet implemented!");
2711 } else {
2712 llvm_unreachable("unexpected EH Pad!");
2713 }
2714}
2715
Reid Kleckner94b704c2015-09-09 21:10:03 +00002716static int addSEHHandler(WinEHFuncInfo &FuncInfo, int ParentState,
Reid Kleckner78783912015-09-10 00:25:23 +00002717 const Function *Filter, const BasicBlock *Handler) {
Reid Kleckner94b704c2015-09-09 21:10:03 +00002718 SEHUnwindMapEntry Entry;
2719 Entry.ToState = ParentState;
2720 Entry.Filter = Filter;
2721 Entry.Handler = Handler;
2722 FuncInfo.SEHUnwindMap.push_back(Entry);
2723 return FuncInfo.SEHUnwindMap.size() - 1;
2724}
2725
2726static void calculateExplicitSEHStateNumbers(WinEHFuncInfo &FuncInfo,
2727 const BasicBlock &BB,
2728 int ParentState) {
2729 assert(BB.isEHPad());
2730 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
2731 // All catchpad instructions will be handled when we process their
2732 // respective catchendpad instruction.
2733 if (isa<CatchPadInst>(FirstNonPHI))
2734 return;
2735
2736 if (isa<CatchEndPadInst>(FirstNonPHI)) {
2737 // Extract the filter function and the __except basic block and create a
2738 // state for them.
2739 SmallVector<const CatchPadInst *, 1> Handlers;
2740 findCatchPadsForCatchEndPad(&BB, Handlers);
2741 assert(Handlers.size() == 1 &&
2742 "SEH doesn't have multiple handlers per __try");
2743 const CatchPadInst *CPI = Handlers.front();
2744 const BasicBlock *CatchPadBB = CPI->getParent();
2745 const Function *Filter =
2746 cast<Function>(CPI->getArgOperand(0)->stripPointerCasts());
2747 int TryState =
2748 addSEHHandler(FuncInfo, ParentState, Filter, CPI->getNormalDest());
2749
2750 // Everything in the __try block uses TryState as its parent state.
2751 FuncInfo.EHPadStateMap[CPI] = TryState;
2752 DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
2753 << CatchPadBB->getName() << '\n');
2754 for (const BasicBlock *PredBlock : predecessors(CatchPadBB))
2755 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2756 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, TryState);
2757
2758 // Everything in the __except block unwinds to ParentState, just like code
2759 // outside the __try.
2760 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
2761 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
2762 << BB.getName() << '\n');
2763 for (const BasicBlock *PredBlock : predecessors(&BB))
2764 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2765 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
2766 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
2767 int CleanupState =
2768 addSEHHandler(FuncInfo, ParentState, /*Filter=*/nullptr, &BB);
2769 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
2770 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
2771 << BB.getName() << '\n');
2772 for (const BasicBlock *PredBlock : predecessors(&BB))
2773 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2774 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, CleanupState);
Reid Kleckner7bb20bd2015-09-10 21:46:36 +00002775 } else if (isa<CleanupEndPadInst>(FirstNonPHI)) {
2776 // Anything unwinding through CleanupEndPadInst is in ParentState.
2777 FuncInfo.EHPadStateMap[FirstNonPHI] = ParentState;
2778 DEBUG(dbgs() << "Assigning state #" << ParentState << " to BB "
2779 << BB.getName() << '\n');
2780 for (const BasicBlock *PredBlock : predecessors(&BB))
2781 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2782 calculateExplicitSEHStateNumbers(FuncInfo, *PredBlock, ParentState);
Reid Kleckner94b704c2015-09-09 21:10:03 +00002783 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
2784 report_fatal_error("Not yet implemented!");
2785 } else {
2786 llvm_unreachable("unexpected EH Pad!");
2787 }
2788}
2789
2790/// Check if the EH Pad unwinds to caller. Cleanups are a little bit of a
2791/// special case because we have to look at the cleanupret instruction that uses
2792/// the cleanuppad.
2793static bool doesEHPadUnwindToCaller(const Instruction *EHPad) {
2794 auto *CPI = dyn_cast<CleanupPadInst>(EHPad);
2795 if (!CPI)
2796 return EHPad->mayThrow();
2797
2798 // This cleanup does not return or unwind, so we say it unwinds to caller.
2799 if (CPI->use_empty())
2800 return true;
2801
2802 const Instruction *User = CPI->user_back();
2803 if (auto *CRI = dyn_cast<CleanupReturnInst>(User))
2804 return CRI->unwindsToCaller();
2805 return cast<CleanupEndPadInst>(User)->unwindsToCaller();
2806}
2807
Reid Kleckner813f1b62015-09-16 22:14:46 +00002808void llvm::calculateSEHStateNumbers(const Function *Fn,
Reid Kleckner94b704c2015-09-09 21:10:03 +00002809 WinEHFuncInfo &FuncInfo) {
2810 // Don't compute state numbers twice.
2811 if (!FuncInfo.SEHUnwindMap.empty())
2812 return;
2813
Reid Kleckner813f1b62015-09-16 22:14:46 +00002814 for (const BasicBlock &BB : *Fn) {
Reid Kleckner94b704c2015-09-09 21:10:03 +00002815 if (!BB.isEHPad() || !doesEHPadUnwindToCaller(BB.getFirstNonPHI()))
2816 continue;
2817 calculateExplicitSEHStateNumbers(FuncInfo, BB, -1);
2818 }
2819}
2820
Reid Kleckner813f1b62015-09-16 22:14:46 +00002821void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002822 WinEHFuncInfo &FuncInfo) {
2823 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +00002824 if (!FuncInfo.EHPadStateMap.empty())
2825 return;
2826
Reid Kleckner813f1b62015-09-16 22:14:46 +00002827 for (const BasicBlock &BB : *Fn) {
David Majnemer0ad363e2015-08-18 19:07:12 +00002828 if (!BB.isEHPad())
2829 continue;
Reid Kleckner813f1b62015-09-16 22:14:46 +00002830 if (BB.isLandingPad())
2831 report_fatal_error("MSVC C++ EH cannot use landingpads");
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00002832 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
2833 // Skip cleanupendpads; they are exits, not entries.
2834 if (isa<CleanupEndPadInst>(FirstNonPHI))
2835 continue;
Reid Kleckner94b704c2015-09-09 21:10:03 +00002836 if (!doesEHPadUnwindToCaller(FirstNonPHI))
David Majnemer0ad363e2015-08-18 19:07:12 +00002837 continue;
Reid Kleckner94b704c2015-09-09 21:10:03 +00002838 calculateExplicitCXXStateNumbers(FuncInfo, BB, -1);
David Majnemer0ad363e2015-08-18 19:07:12 +00002839 }
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002840}
David Majnemerfd9f4772015-08-11 01:15:26 +00002841
David Majnemer67bff0d2015-09-16 20:42:16 +00002842void WinEHPrepare::replaceTerminatePadWithCleanup(Function &F) {
2843 if (Personality != EHPersonality::MSVC_CXX)
2844 return;
2845 for (BasicBlock &BB : F) {
2846 Instruction *First = BB.getFirstNonPHI();
2847 auto *TPI = dyn_cast<TerminatePadInst>(First);
2848 if (!TPI)
2849 continue;
2850
2851 if (TPI->getNumArgOperands() != 1)
2852 report_fatal_error(
2853 "Expected a unary terminatepad for MSVC C++ personalities!");
2854
2855 auto *TerminateFn = dyn_cast<Function>(TPI->getArgOperand(0));
2856 if (!TerminateFn)
2857 report_fatal_error("Function operand expected in terminatepad for MSVC "
2858 "C++ personalities!");
2859
2860 // Insert the cleanuppad instruction.
2861 auto *CPI = CleanupPadInst::Create(
2862 BB.getContext(), {}, Twine("terminatepad.for.", BB.getName()), &BB);
2863
2864 // Insert the call to the terminate instruction.
2865 auto *CallTerminate = CallInst::Create(TerminateFn, {}, &BB);
2866 CallTerminate->setDoesNotThrow();
2867 CallTerminate->setDoesNotReturn();
2868 CallTerminate->setCallingConv(TerminateFn->getCallingConv());
2869
2870 // Insert a new terminator for the cleanuppad using the same successor as
2871 // the terminatepad.
2872 CleanupReturnInst::Create(CPI, TPI->getUnwindDest(), &BB);
2873
2874 // Let's remove the terminatepad now that we've inserted the new
2875 // instructions.
2876 TPI->eraseFromParent();
2877 }
2878}
2879
Joseph Tremouletec182852015-08-28 01:12:35 +00002880void WinEHPrepare::colorFunclets(Function &F,
2881 SmallVectorImpl<BasicBlock *> &EntryBlocks) {
2882 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
2883 BasicBlock *EntryBlock = &F.getEntryBlock();
David Majnemerfd9f4772015-08-11 01:15:26 +00002884
Joseph Tremouletec182852015-08-28 01:12:35 +00002885 // Build up the color map, which maps each block to its set of 'colors'.
2886 // For any block B, the "colors" of B are the set of funclets F (possibly
2887 // including a root "funclet" representing the main function), such that
2888 // F will need to directly contain B or a copy of B (where the term "directly
2889 // contain" is used to distinguish from being "transitively contained" in
2890 // a nested funclet).
2891 // Use a CFG walk driven by a worklist of (block, color) pairs. The "color"
2892 // sets attached during this processing to a block which is the entry of some
2893 // funclet F is actually the set of F's parents -- i.e. the union of colors
2894 // of all predecessors of F's entry. For all other blocks, the color sets
2895 // are as defined above. A post-pass fixes up the block color map to reflect
2896 // the same sense of "color" for funclet entries as for other blocks.
2897
2898 Worklist.push_back({EntryBlock, EntryBlock});
David Majnemerfd9f4772015-08-11 01:15:26 +00002899
2900 while (!Worklist.empty()) {
Joseph Tremouletec182852015-08-28 01:12:35 +00002901 BasicBlock *Visiting;
2902 BasicBlock *Color;
2903 std::tie(Visiting, Color) = Worklist.pop_back_val();
2904 Instruction *VisitingHead = Visiting->getFirstNonPHI();
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00002905 if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead) &&
2906 !isa<CleanupEndPadInst>(VisitingHead)) {
Joseph Tremouletec182852015-08-28 01:12:35 +00002907 // Mark this as a funclet head as a member of itself.
2908 FuncletBlocks[Visiting].insert(Visiting);
2909 // Queue exits with the parent color.
2910 for (User *Exit : VisitingHead->users()) {
2911 for (BasicBlock *Succ :
2912 successors(cast<Instruction>(Exit)->getParent())) {
2913 if (BlockColors[Succ].insert(Color).second) {
2914 Worklist.push_back({Succ, Color});
2915 }
2916 }
2917 }
2918 // Handle CatchPad specially since its successors need different colors.
2919 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
2920 // Visit the normal successor with the color of the new EH pad, and
2921 // visit the unwind successor with the color of the parent.
2922 BasicBlock *NormalSucc = CatchPad->getNormalDest();
2923 if (BlockColors[NormalSucc].insert(Visiting).second) {
2924 Worklist.push_back({NormalSucc, Visiting});
2925 }
2926 BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
2927 if (BlockColors[UnwindSucc].insert(Color).second) {
2928 Worklist.push_back({UnwindSucc, Color});
2929 }
2930 continue;
2931 }
2932 // Switch color to the current node, except for terminate pads which
2933 // have no bodies and only unwind successors and so need their successors
2934 // visited with the color of the parent.
2935 if (!isa<TerminatePadInst>(VisitingHead))
2936 Color = Visiting;
2937 } else {
2938 // Note that this is a member of the given color.
2939 FuncletBlocks[Color].insert(Visiting);
Joseph Tremouletf3aff312015-09-10 16:51:25 +00002940 }
2941
2942 TerminatorInst *Terminator = Visiting->getTerminator();
2943 if (isa<CleanupReturnInst>(Terminator) ||
2944 isa<CatchReturnInst>(Terminator) ||
2945 isa<CleanupEndPadInst>(Terminator)) {
2946 // These blocks' successors have already been queued with the parent
2947 // color.
2948 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +00002949 }
Joseph Tremouletec182852015-08-28 01:12:35 +00002950 for (BasicBlock *Succ : successors(Visiting)) {
2951 if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
2952 // The catchendpad needs to be visited with the parent's color, not
2953 // the current color. This will happen in the code above that visits
2954 // any catchpad unwind successor with the parent color, so we can
2955 // safely skip this successor here.
2956 continue;
2957 }
2958 if (BlockColors[Succ].insert(Color).second) {
2959 Worklist.push_back({Succ, Color});
2960 }
2961 }
2962 }
David Majnemerfd9f4772015-08-11 01:15:26 +00002963
Joseph Tremouletec182852015-08-28 01:12:35 +00002964 // The processing above actually accumulated the parent set for this
2965 // funclet into the color set for its entry; use the parent set to
2966 // populate the children map, and reset the color set to include just
2967 // the funclet itself (no instruction can target a funclet entry except on
2968 // that transitions to the child funclet).
2969 for (BasicBlock *FuncletEntry : EntryBlocks) {
2970 std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
2971 for (BasicBlock *Parent : ColorMapItem)
2972 FuncletChildren[Parent].insert(FuncletEntry);
2973 ColorMapItem.clear();
2974 ColorMapItem.insert(FuncletEntry);
David Majnemerfd9f4772015-08-11 01:15:26 +00002975 }
2976}
2977
David Majnemerb3d9b962015-09-16 18:40:24 +00002978void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00002979 // Strip PHI nodes off of EH pads.
2980 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +00002981 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
2982 BasicBlock *BB = FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00002983 if (!BB->isEHPad())
2984 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +00002985 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
2986 Instruction *I = BI++;
2987 auto *PN = dyn_cast<PHINode>(I);
2988 // Stop at the first non-PHI.
2989 if (!PN)
2990 break;
David Majnemerfd9f4772015-08-11 01:15:26 +00002991
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00002992 AllocaInst *SpillSlot = insertPHILoads(PN, F);
2993 if (SpillSlot)
2994 insertPHIStores(PN, SpillSlot);
2995
2996 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +00002997 }
2998 }
2999
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003000 for (auto *PN : PHINodes) {
3001 // There may be lingering uses on other EH PHIs being removed
3002 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3003 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +00003004 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003005}
David Majnemerfd9f4772015-08-11 01:15:26 +00003006
David Majnemerb3d9b962015-09-16 18:40:24 +00003007void WinEHPrepare::demoteUsesBetweenFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003008 // Turn all inter-funclet uses of a Value into loads and stores.
3009 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3010 BasicBlock *BB = FI++;
3011 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3012 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3013 Instruction *I = BI++;
3014 // Funclets are permitted to use static allocas.
3015 if (auto *AI = dyn_cast<AllocaInst>(I))
3016 if (AI->isStaticAlloca())
3017 continue;
3018
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003019 demoteNonlocalUses(I, ColorsForBB, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003020 }
3021 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003022}
3023
3024void WinEHPrepare::demoteArgumentUses(Function &F) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003025 // Also demote function parameters used in funclets.
3026 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3027 for (Argument &Arg : F.args())
3028 demoteNonlocalUses(&Arg, ColorsForEntry, F);
David Majnemerb3d9b962015-09-16 18:40:24 +00003029}
David Majnemerfd9f4772015-08-11 01:15:26 +00003030
David Majnemerb3d9b962015-09-16 18:40:24 +00003031void WinEHPrepare::cloneCommonBlocks(
3032 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003033 // We need to clone all blocks which belong to multiple funclets. Values are
3034 // remapped throughout the funclet to propogate both the new instructions
3035 // *and* the new basic blocks themselves.
Joseph Tremouletec182852015-08-28 01:12:35 +00003036 for (BasicBlock *FuncletPadBB : EntryBlocks) {
3037 std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
David Majnemerfd9f4772015-08-11 01:15:26 +00003038
3039 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3040 ValueToValueMapTy VMap;
3041 for (BasicBlock *BB : BlocksInFunclet) {
3042 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3043 // We don't need to do anything if the block is monochromatic.
3044 size_t NumColorsForBB = ColorsForBB.size();
3045 if (NumColorsForBB == 1)
3046 continue;
3047
David Majnemerfd9f4772015-08-11 01:15:26 +00003048 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +00003049 BasicBlock *CBB =
3050 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
3051 // Insert the clone immediately after the original to ensure determinism
3052 // and to keep the same relative ordering of any funclet's blocks.
3053 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +00003054
3055 // Add basic block mapping.
3056 VMap[BB] = CBB;
3057
3058 // Record delta operations that we need to perform to our color mappings.
3059 Orig2Clone[BB] = CBB;
3060 }
3061
3062 // Update our color mappings to reflect that one block has lost a color and
3063 // another has gained a color.
3064 for (auto &BBMapping : Orig2Clone) {
3065 BasicBlock *OldBlock = BBMapping.first;
3066 BasicBlock *NewBlock = BBMapping.second;
3067
3068 BlocksInFunclet.insert(NewBlock);
3069 BlockColors[NewBlock].insert(FuncletPadBB);
3070
3071 BlocksInFunclet.erase(OldBlock);
3072 BlockColors[OldBlock].erase(FuncletPadBB);
3073 }
3074
3075 // Loop over all of the instructions in the function, fixing up operand
3076 // references as we go. This uses VMap to do all the hard work.
3077 for (BasicBlock *BB : BlocksInFunclet)
3078 // Loop over all instructions, fixing each one as we find it...
3079 for (Instruction &I : *BB)
3080 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
David Majnemer459a64a2015-09-16 18:40:37 +00003081
3082 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
3083 // the PHI nodes for NewBB now.
3084 for (auto &BBMapping : Orig2Clone) {
3085 BasicBlock *OldBlock = BBMapping.first;
3086 BasicBlock *NewBlock = BBMapping.second;
3087 for (BasicBlock *SuccBB : successors(NewBlock)) {
3088 for (Instruction &SuccI : *SuccBB) {
3089 auto *SuccPN = dyn_cast<PHINode>(&SuccI);
3090 if (!SuccPN)
3091 break;
3092
3093 // Ok, we have a PHI node. Figure out what the incoming value was for
3094 // the OldBlock.
3095 int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
3096 if (OldBlockIdx == -1)
3097 break;
3098 Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
3099
3100 // Remap the value if necessary.
3101 if (auto *Inst = dyn_cast<Instruction>(IV)) {
3102 ValueToValueMapTy::iterator I = VMap.find(Inst);
3103 if (I != VMap.end())
3104 IV = I->second;
3105 }
3106
3107 SuccPN->addIncoming(IV, NewBlock);
3108 }
3109 }
3110 }
3111
3112 for (ValueToValueMapTy::value_type VT : VMap) {
3113 // If there were values defined in BB that are used outside the funclet,
3114 // then we now have to update all uses of the value to use either the
3115 // original value, the cloned value, or some PHI derived value. This can
3116 // require arbitrary PHI insertion, of which we are prepared to do, clean
3117 // these up now.
3118 SmallVector<Use *, 16> UsesToRename;
3119
3120 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
3121 if (!OldI)
3122 continue;
3123 auto *NewI = cast<Instruction>(VT.second);
3124 // Scan all uses of this instruction to see if it is used outside of its
3125 // funclet, and if so, record them in UsesToRename.
3126 for (Use &U : OldI->uses()) {
3127 Instruction *UserI = cast<Instruction>(U.getUser());
3128 BasicBlock *UserBB = UserI->getParent();
3129 std::set<BasicBlock *> &ColorsForUserBB = BlockColors[UserBB];
3130 assert(!ColorsForUserBB.empty());
3131 if (ColorsForUserBB.size() > 1 ||
3132 *ColorsForUserBB.begin() != FuncletPadBB)
3133 UsesToRename.push_back(&U);
3134 }
3135
3136 // If there are no uses outside the block, we're done with this
3137 // instruction.
3138 if (UsesToRename.empty())
3139 continue;
3140
3141 // We found a use of OldI outside of the funclet. Rename all uses of OldI
3142 // that are outside its funclet to be uses of the appropriate PHI node
3143 // etc.
3144 SSAUpdater SSAUpdate;
3145 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
3146 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
3147 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
3148
3149 while (!UsesToRename.empty())
3150 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
3151 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003152 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003153}
David Majnemerfd9f4772015-08-11 01:15:26 +00003154
David Majnemerb3d9b962015-09-16 18:40:24 +00003155void WinEHPrepare::removeImplausibleTerminators(Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003156 // Remove implausible terminators and replace them with UnreachableInst.
3157 for (auto &Funclet : FuncletBlocks) {
3158 BasicBlock *FuncletPadBB = Funclet.first;
3159 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3160 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3161 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3162 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3163
3164 for (BasicBlock *BB : BlocksInFunclet) {
3165 TerminatorInst *TI = BB->getTerminator();
3166 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3167 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3168 // The token consumed by a CatchReturnInst must match the funclet token.
3169 bool IsUnreachableCatchret = false;
3170 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003171 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003172 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemer83f4bb22015-08-17 20:56:39 +00003173 bool IsUnreachableCleanupret = false;
3174 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003175 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003176 // The token consumed by a CleanupEndPadInst must match the funclet token.
3177 bool IsUnreachableCleanupendpad = false;
3178 if (auto *CEPI = dyn_cast<CleanupEndPadInst>(TI))
3179 IsUnreachableCleanupendpad = CEPI->getCleanupPad() != CleanupPad;
3180 if (IsUnreachableRet || IsUnreachableCatchret ||
3181 IsUnreachableCleanupret || IsUnreachableCleanupendpad) {
David Majnemer459a64a2015-09-16 18:40:37 +00003182 // Loop through all of our successors and make sure they know that one
3183 // of their predecessors is going away.
3184 for (BasicBlock *SuccBB : TI->successors())
3185 SuccBB->removePredecessor(BB);
3186
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003187 if (IsUnreachableCleanupendpad) {
3188 // We can't simply replace a cleanupendpad with unreachable, because
3189 // its predecessor edges are EH edges and unreachable is not an EH
3190 // pad. Change all predecessors to the "unwind to caller" form.
3191 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
3192 PI != PE;) {
3193 BasicBlock *Pred = *PI++;
3194 removeUnwindEdge(Pred);
3195 }
3196 }
3197
David Majnemer83f4bb22015-08-17 20:56:39 +00003198 new UnreachableInst(BB->getContext(), TI);
3199 TI->eraseFromParent();
3200 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003201 // FIXME: Check for invokes/cleanuprets/cleanupendpads which unwind to
3202 // implausible catchendpads (i.e. catchendpad not in immediate parent
3203 // funclet).
David Majnemer83f4bb22015-08-17 20:56:39 +00003204 }
3205 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003206}
David Majnemer83f4bb22015-08-17 20:56:39 +00003207
David Majnemerb3d9b962015-09-16 18:40:24 +00003208void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003209 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3210 // branches, etc.
3211 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3212 BasicBlock *BB = FI++;
3213 SimplifyInstructionsInBlock(BB);
3214 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3215 MergeBlockIntoPredecessor(BB);
3216 }
3217
David Majnemerfd9f4772015-08-11 01:15:26 +00003218 // We might have some unreachable blocks after cleaning up some impossible
3219 // control flow.
3220 removeUnreachableBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00003221}
David Majnemerfd9f4772015-08-11 01:15:26 +00003222
David Majnemerb3d9b962015-09-16 18:40:24 +00003223void WinEHPrepare::verifyPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003224 // Recolor the CFG to verify that all is well.
3225 for (BasicBlock &BB : F) {
3226 size_t NumColors = BlockColors[&BB].size();
3227 assert(NumColors == 1 && "Expected monochromatic BB!");
3228 if (NumColors == 0)
3229 report_fatal_error("Uncolored BB!");
3230 if (NumColors > 1)
3231 report_fatal_error("Multicolor BB!");
David Majnemer459a64a2015-09-16 18:40:37 +00003232 if (!DisableDemotion) {
3233 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3234 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3235 if (EHPadHasPHI)
3236 report_fatal_error("EH Pad still has a PHI!");
3237 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003238 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003239}
3240
3241bool WinEHPrepare::prepareExplicitEH(
3242 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3243 // Remove unreachable blocks. It is not valuable to assign them a color and
3244 // their existence can trick us into thinking values are alive when they are
3245 // not.
3246 removeUnreachableBlocks(F);
3247
David Majnemer67bff0d2015-09-16 20:42:16 +00003248 replaceTerminatePadWithCleanup(F);
3249
David Majnemerb3d9b962015-09-16 18:40:24 +00003250 // Determine which blocks are reachable from which funclet entries.
3251 colorFunclets(F, EntryBlocks);
3252
David Majnemer459a64a2015-09-16 18:40:37 +00003253 if (!DisableDemotion) {
3254 demotePHIsOnFunclets(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00003255
David Majnemer459a64a2015-09-16 18:40:37 +00003256 demoteUsesBetweenFunclets(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00003257
David Majnemer459a64a2015-09-16 18:40:37 +00003258 demoteArgumentUses(F);
3259 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003260
3261 cloneCommonBlocks(F, EntryBlocks);
3262
David Majnemer459a64a2015-09-16 18:40:37 +00003263 if (!DisableCleanups) {
3264 removeImplausibleTerminators(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00003265
David Majnemer459a64a2015-09-16 18:40:37 +00003266 cleanupPreparedFunclets(F);
3267 }
David Majnemerb3d9b962015-09-16 18:40:24 +00003268
3269 verifyPreparedFunclets(F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003270
3271 BlockColors.clear();
3272 FuncletBlocks.clear();
Joseph Tremouletec182852015-08-28 01:12:35 +00003273 FuncletChildren.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00003274
David Majnemerfd9f4772015-08-11 01:15:26 +00003275 return true;
3276}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003277
3278// TODO: Share loads when one use dominates another, or when a catchpad exit
3279// dominates uses (needs dominators).
3280AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3281 BasicBlock *PHIBlock = PN->getParent();
3282 AllocaInst *SpillSlot = nullptr;
3283
3284 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3285 // Insert a load in place of the PHI and replace all uses.
3286 SpillSlot = new AllocaInst(PN->getType(), nullptr,
3287 Twine(PN->getName(), ".wineh.spillslot"),
3288 F.getEntryBlock().begin());
3289 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3290 PHIBlock->getFirstInsertionPt());
3291 PN->replaceAllUsesWith(V);
3292 return SpillSlot;
3293 }
3294
3295 DenseMap<BasicBlock *, Value *> Loads;
3296 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3297 UI != UE;) {
3298 Use &U = *UI++;
3299 auto *UsingInst = cast<Instruction>(U.getUser());
3300 BasicBlock *UsingBB = UsingInst->getParent();
3301 if (UsingBB->isEHPad()) {
3302 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
3303 // stores for it separately.
3304 assert(isa<PHINode>(UsingInst));
3305 continue;
3306 }
3307 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3308 }
3309 return SpillSlot;
3310}
3311
3312// TODO: improve store placement. Inserting at def is probably good, but need
3313// to be careful not to introduce interfering stores (needs liveness analysis).
3314// TODO: identify related phi nodes that can share spill slots, and share them
3315// (also needs liveness).
3316void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3317 AllocaInst *SpillSlot) {
3318 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3319 // stored to the spill slot by the end of the given Block.
3320 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3321
3322 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3323
3324 while (!Worklist.empty()) {
3325 BasicBlock *EHBlock;
3326 Value *InVal;
3327 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3328
3329 PHINode *PN = dyn_cast<PHINode>(InVal);
3330 if (PN && PN->getParent() == EHBlock) {
3331 // The value is defined by another PHI we need to remove, with no room to
3332 // insert a store after the PHI, so each predecessor needs to store its
3333 // incoming value.
3334 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3335 Value *PredVal = PN->getIncomingValue(i);
3336
3337 // Undef can safely be skipped.
3338 if (isa<UndefValue>(PredVal))
3339 continue;
3340
3341 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3342 }
3343 } else {
3344 // We need to store InVal, which dominates EHBlock, but can't put a store
3345 // in EHBlock, so need to put stores in each predecessor.
3346 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3347 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3348 }
3349 }
3350 }
3351}
3352
3353void WinEHPrepare::insertPHIStore(
3354 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3355 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3356
3357 if (PredBlock->isEHPad() &&
3358 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3359 // Pred is unsplittable, so we need to queue it on the worklist.
3360 Worklist.push_back({PredBlock, PredVal});
3361 return;
3362 }
3363
3364 // Otherwise, insert the store at the end of the basic block.
3365 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3366}
3367
3368// TODO: Share loads for same-funclet uses (requires dominators if funclets
3369// aren't properly nested).
3370void WinEHPrepare::demoteNonlocalUses(Value *V,
3371 std::set<BasicBlock *> &ColorsForBB,
3372 Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003373 // Tokens can only be used non-locally due to control flow involving
3374 // unreachable edges. Don't try to demote the token usage, we'll simply
3375 // delete the cloned user later.
3376 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3377 return;
3378
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003379 DenseMap<BasicBlock *, Value *> Loads;
3380 AllocaInst *SpillSlot = nullptr;
3381 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3382 Use &U = *UI++;
3383 auto *UsingInst = cast<Instruction>(U.getUser());
3384 BasicBlock *UsingBB = UsingInst->getParent();
3385
Joseph Tremouletec182852015-08-28 01:12:35 +00003386 // Is the Use inside a block which is colored the same as the Def?
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003387 // If so, we don't need to escape the Def because we will clone
3388 // ourselves our own private copy.
3389 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
Joseph Tremouletec182852015-08-28 01:12:35 +00003390 if (ColorsForUsingBB == ColorsForBB)
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003391 continue;
3392
3393 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3394 }
3395 if (SpillSlot) {
3396 // Insert stores of the computed value into the stack slot.
3397 // We have to be careful if I is an invoke instruction,
3398 // because we can't insert the store AFTER the terminator instruction.
3399 BasicBlock::iterator InsertPt;
3400 if (isa<Argument>(V)) {
3401 InsertPt = F.getEntryBlock().getTerminator();
3402 } else if (isa<TerminatorInst>(V)) {
3403 auto *II = cast<InvokeInst>(V);
3404 // We cannot demote invoke instructions to the stack if their normal
3405 // edge is critical. Therefore, split the critical edge and create a
3406 // basic block into which the store can be inserted.
3407 if (!II->getNormalDest()->getSinglePredecessor()) {
3408 unsigned SuccNum =
3409 GetSuccessorNumber(II->getParent(), II->getNormalDest());
3410 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3411 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3412 assert(NewBlock && "Unable to split critical edge.");
3413 // Update the color mapping for the newly split edge.
3414 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3415 BlockColors[NewBlock] = ColorsForUsingBB;
3416 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3417 FuncletBlocks[FuncletPad].insert(NewBlock);
3418 }
3419 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3420 } else {
3421 InsertPt = cast<Instruction>(V);
3422 ++InsertPt;
3423 // Don't insert before PHI nodes or EH pad instrs.
3424 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3425 ;
3426 }
3427 new StoreInst(V, SpillSlot, InsertPt);
3428 }
3429}
3430
3431void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3432 DenseMap<BasicBlock *, Value *> &Loads,
3433 Function &F) {
3434 // Lazilly create the spill slot.
3435 if (!SpillSlot)
3436 SpillSlot = new AllocaInst(V->getType(), nullptr,
3437 Twine(V->getName(), ".wineh.spillslot"),
3438 F.getEntryBlock().begin());
3439
3440 auto *UsingInst = cast<Instruction>(U.getUser());
3441 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3442 // If this is a PHI node, we can't insert a load of the value before
3443 // the use. Instead insert the load in the predecessor block
3444 // corresponding to the incoming value.
3445 //
3446 // Note that if there are multiple edges from a basic block to this
3447 // PHI node that we cannot have multiple loads. The problem is that
3448 // the resulting PHI node will have multiple values (from each load)
3449 // coming in from the same block, which is illegal SSA form.
3450 // For this reason, we keep track of and reuse loads we insert.
3451 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00003452 if (auto *CatchRet =
3453 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3454 // Putting a load above a catchret and use on the phi would still leave
3455 // a cross-funclet def/use. We need to split the edge, change the
3456 // catchret to target the new block, and put the load there.
3457 BasicBlock *PHIBlock = UsingInst->getParent();
3458 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3459 // SplitEdge gives us:
3460 // IncomingBlock:
3461 // ...
3462 // br label %NewBlock
3463 // NewBlock:
3464 // catchret label %PHIBlock
3465 // But we need:
3466 // IncomingBlock:
3467 // ...
3468 // catchret label %NewBlock
3469 // NewBlock:
3470 // br label %PHIBlock
3471 // So move the terminators to each others' blocks and swap their
3472 // successors.
3473 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3474 Goto->removeFromParent();
3475 CatchRet->removeFromParent();
3476 IncomingBlock->getInstList().push_back(CatchRet);
3477 NewBlock->getInstList().push_back(Goto);
3478 Goto->setSuccessor(0, PHIBlock);
3479 CatchRet->setSuccessor(NewBlock);
3480 // Update the color mapping for the newly split edge.
3481 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3482 BlockColors[NewBlock] = ColorsForPHIBlock;
3483 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3484 FuncletBlocks[FuncletPad].insert(NewBlock);
3485 // Treat the new block as incoming for load insertion.
3486 IncomingBlock = NewBlock;
3487 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003488 Value *&Load = Loads[IncomingBlock];
3489 // Insert the load into the predecessor block
3490 if (!Load)
3491 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3492 /*Volatile=*/false, IncomingBlock->getTerminator());
3493
3494 U.set(Load);
3495 } else {
3496 // Reload right before the old use.
3497 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3498 /*Volatile=*/false, UsingInst);
3499 U.set(Load);
3500 }
3501}