blob: 8c15b7e4413b7e3ba25c0addca6e153e04168c1b [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"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000044#include <memory>
45
46using namespace llvm;
47using namespace llvm::PatternMatch;
48
49#define DEBUG_TYPE "winehprepare"
50
51namespace {
52
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000053// This map is used to model frame variable usage during outlining, to
54// construct a structure type to hold the frame variables in a frame
55// allocation block, and to remap the frame variable allocas (including
56// spill locations as needed) to GEPs that get the variable from the
57// frame allocation structure.
Reid Klecknercfb9ce52015-03-05 18:26:34 +000058typedef MapVector<Value *, TinyPtrVector<AllocaInst *>> FrameVarInfoMap;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000059
Reid Kleckner3567d272015-04-02 21:13:31 +000060// TinyPtrVector cannot hold nullptr, so we need our own sentinel that isn't
61// quite null.
62AllocaInst *getCatchObjectSentinel() {
63 return static_cast<AllocaInst *>(nullptr) + 1;
64}
65
Andrew Kaylor6b67d422015-03-11 23:22:06 +000066typedef SmallSet<BasicBlock *, 4> VisitedBlockSet;
67
Andrew Kaylor6b67d422015-03-11 23:22:06 +000068class LandingPadActions;
Andrew Kaylor6b67d422015-03-11 23:22:06 +000069class LandingPadMap;
70
71typedef DenseMap<const BasicBlock *, CatchHandler *> CatchHandlerMapTy;
72typedef DenseMap<const BasicBlock *, CleanupHandler *> CleanupHandlerMapTy;
73
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000074class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000075public:
76 static char ID; // Pass identification, replacement for typeid.
77 WinEHPrepare(const TargetMachine *TM = nullptr)
Reid Kleckner582786b2015-04-30 18:17:12 +000078 : FunctionPass(ID) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000079 if (TM)
Daniel Sanders110bf6d2015-06-24 13:25:57 +000080 TheTriple = TM->getTargetTriple();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +000081 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000082
83 bool runOnFunction(Function &Fn) override;
84
85 bool doFinalization(Module &M) override;
86
87 void getAnalysisUsage(AnalysisUsage &AU) const override;
88
89 const char *getPassName() const override {
90 return "Windows exception handling preparation";
91 }
92
93private:
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000094 bool prepareExceptionHandlers(Function &F,
95 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylora6c5b962015-05-20 23:22:24 +000096 void identifyEHBlocks(Function &F, SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor64622aa2015-04-01 17:21:25 +000097 void promoteLandingPadValues(LandingPadInst *LPad);
Reid Klecknerfd7df282015-04-22 21:05:21 +000098 void demoteValuesLiveAcrossHandlers(Function &F,
99 SmallVectorImpl<LandingPadInst *> &LPads);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000100 void findSEHEHReturnPoints(Function &F,
101 SetVector<BasicBlock *> &EHReturnBlocks);
102 void findCXXEHReturnPoints(Function &F,
103 SetVector<BasicBlock *> &EHReturnBlocks);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000104 void getPossibleReturnTargets(Function *ParentF, Function *HandlerF,
105 SetVector<BasicBlock*> &Targets);
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000106 void completeNestedLandingPad(Function *ParentFn,
107 LandingPadInst *OutlinedLPad,
108 const LandingPadInst *OriginalLPad,
109 FrameVarInfoMap &VarInfo);
Reid Kleckner6511c8b2015-07-01 20:59:25 +0000110 Function *createHandlerFunc(Function *ParentFn, Type *RetTy,
111 const Twine &Name, Module *M, Value *&ParentFP);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000112 bool outlineHandler(ActionHandler *Action, Function *SrcFn,
113 LandingPadInst *LPad, BasicBlock *StartBB,
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000114 FrameVarInfoMap &VarInfo);
David Majnemer7fddecc2015-06-17 20:52:32 +0000115 void addStubInvokeToHandlerIfNeeded(Function *Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000116
117 void mapLandingPadBlocks(LandingPadInst *LPad, LandingPadActions &Actions);
118 CatchHandler *findCatchHandler(BasicBlock *BB, BasicBlock *&NextBB,
119 VisitedBlockSet &VisitedBlocks);
Reid Kleckner9405ef02015-04-10 23:12:29 +0000120 void findCleanupHandlers(LandingPadActions &Actions, BasicBlock *StartBB,
121 BasicBlock *EndBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000122
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000123 void processSEHCatchHandler(CatchHandler *Handler, BasicBlock *StartBB);
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000124 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
125 void
126 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
127 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
128 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
129 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
130 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
131 void demoteNonlocalUses(Value *V, std::set<BasicBlock *> &ColorsForBB,
132 Function &F);
Joseph Tremouletec182852015-08-28 01:12:35 +0000133 bool prepareExplicitEH(Function &F,
134 SmallVectorImpl<BasicBlock *> &EntryBlocks);
135 void colorFunclets(Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +0000136
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000137 Triple TheTriple;
138
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000139 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000140 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000141 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000142 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000143 CatchHandlerMapTy CatchHandlerMap;
144 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000145 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000146 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
147 SmallPtrSet<BasicBlock *, 4> EHBlocks;
148 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000149
150 // This maps landing pad instructions found in outlined handlers to
151 // the landing pad instruction in the parent function from which they
152 // were cloned. The cloned/nested landing pad is used as the key
153 // because the landing pad may be cloned into multiple handlers.
154 // This map will be used to add the llvm.eh.actions call to the nested
155 // landing pads after all handlers have been outlined.
156 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
157
158 // This maps blocks in the parent function which are destinations of
159 // catch handlers to cloned blocks in (other) outlined handlers. This
160 // handles the case where a nested landing pads has a catch handler that
161 // returns to a handler function rather than the parent function.
162 // The original block is used as the key here because there should only
163 // ever be one handler function from which the cloned block is not pruned.
164 // The original block will be pruned from the parent function after all
165 // handlers have been outlined. This map will be used to adjust the
166 // return instructions of handlers which return to the block that was
167 // outlined into a handler. This is done after all handlers have been
168 // outlined but before the outlined code is pruned from the parent function.
169 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000170
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000171 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000172 // 32-bit EH.
173 DenseMap<Function *, Value *> HandlerToParentFP;
174
Reid Kleckner582786b2015-04-30 18:17:12 +0000175 AllocaInst *SEHExceptionCodeSlot = nullptr;
David Majnemerfd9f4772015-08-11 01:15:26 +0000176
177 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
178 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
Joseph Tremouletec182852015-08-28 01:12:35 +0000179 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletChildren;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000180};
181
182class WinEHFrameVariableMaterializer : public ValueMaterializer {
183public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000184 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000185 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000186 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000187
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000188 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000189
Reid Kleckner3567d272015-04-02 21:13:31 +0000190 void escapeCatchObject(Value *V);
191
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000192private:
193 FrameVarInfoMap &FrameVarInfo;
194 IRBuilder<> Builder;
195};
196
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000197class LandingPadMap {
198public:
199 LandingPadMap() : OriginLPad(nullptr) {}
200 void mapLandingPad(const LandingPadInst *LPad);
201
202 bool isInitialized() { return OriginLPad != nullptr; }
203
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000204 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000205 bool isLandingPadSpecificInst(const Instruction *Inst) const;
206
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000207 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
208 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000209
210private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000211 const LandingPadInst *OriginLPad;
212 // We will normally only see one of each of these instructions, but
213 // if more than one occurs for some reason we can handle that.
214 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
215 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000216};
217
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000218class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000219public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000220 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
221 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
222 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000223 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
224 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000225 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000226
227 CloningAction handleInstruction(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) override;
230
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000231 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
232 const Instruction *Inst,
233 BasicBlock *NewBB) = 0;
234 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
235 const Instruction *Inst,
236 BasicBlock *NewBB) = 0;
237 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
238 const Instruction *Inst,
239 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000240 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
241 const IndirectBrInst *IBr,
242 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000243 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
244 const InvokeInst *Invoke,
245 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000246 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
247 const ResumeInst *Resume,
248 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000249 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
250 const CmpInst *Compare,
251 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000252 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
253 const LandingPadInst *LPad,
254 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000255
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000256 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
257
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000258protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000259 WinEHFrameVariableMaterializer Materializer;
260 Type *SelectorIDType;
261 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000262 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000263
264 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000265 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000266};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000267
268class WinEHCatchDirector : public WinEHCloningDirectorBase {
269public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000270 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000271 Function *CatchFn, Value *ParentFP, Value *Selector,
272 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000273 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
274 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000275 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000276 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000277 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
278 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000279
280 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
281 const Instruction *Inst,
282 BasicBlock *NewBB) override;
283 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
284 BasicBlock *NewBB) override;
285 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
286 const Instruction *Inst,
287 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000288 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
289 const IndirectBrInst *IBr,
290 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000291 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
292 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000293 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
294 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000295 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
296 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000297 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
298 const LandingPadInst *LPad,
299 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000300
Reid Kleckner3567d272015-04-02 21:13:31 +0000301 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000302 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
303
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000304private:
305 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000306
Reid Kleckner3567d272015-04-02 21:13:31 +0000307 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000308 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000309
310 // This will be a reference to the field of the same name in the WinEHPrepare
311 // object which instantiates this WinEHCatchDirector object.
312 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000313 DominatorTree *DT;
314 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000315};
316
317class WinEHCleanupDirector : public WinEHCloningDirectorBase {
318public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000319 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
320 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
321 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
322 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000323
324 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
325 const Instruction *Inst,
326 BasicBlock *NewBB) override;
327 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
328 BasicBlock *NewBB) override;
329 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
330 const Instruction *Inst,
331 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000332 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
333 const IndirectBrInst *IBr,
334 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000335 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
336 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000337 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
338 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000339 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
340 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000341 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
342 const LandingPadInst *LPad,
343 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000344};
345
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000346class LandingPadActions {
347public:
348 LandingPadActions() : HasCleanupHandlers(false) {}
349
350 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
351 void insertCleanupHandler(CleanupHandler *Action) {
352 Actions.push_back(Action);
353 HasCleanupHandlers = true;
354 }
355
356 bool includesCleanup() const { return HasCleanupHandlers; }
357
David Majnemercde33032015-03-30 22:58:10 +0000358 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000359 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
360 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
361
362private:
363 // Note that this class does not own the ActionHandler objects in this vector.
364 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
365 // in the WinEHPrepare class.
366 SmallVector<ActionHandler *, 4> Actions;
367 bool HasCleanupHandlers;
368};
369
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370} // end anonymous namespace
371
372char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000373INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
374 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000375
376FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
377 return new WinEHPrepare(TM);
378}
379
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000381 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000382 return false;
383
David Majnemerfd9f4772015-08-11 01:15:26 +0000384 // No need to prepare outlined handlers.
385 if (Fn.hasFnAttribute("wineh-parent"))
David Majnemer09e1fdb2015-08-06 21:13:51 +0000386 return false;
387
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000388 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000389 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000390
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000391 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000392 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000393 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000394
David Majnemerfd9f4772015-08-11 01:15:26 +0000395 SmallVector<LandingPadInst *, 4> LPads;
396 SmallVector<ResumeInst *, 4> Resumes;
Joseph Tremouletec182852015-08-28 01:12:35 +0000397 SmallVector<BasicBlock *, 4> EntryBlocks;
David Majnemerfd9f4772015-08-11 01:15:26 +0000398 bool ForExplicitEH = false;
399 for (BasicBlock &BB : Fn) {
Joseph Tremouletec182852015-08-28 01:12:35 +0000400 Instruction *First = BB.getFirstNonPHI();
401 if (auto *LP = dyn_cast<LandingPadInst>(First)) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000402 LPads.push_back(LP);
Joseph Tremouletec182852015-08-28 01:12:35 +0000403 } else if (First->isEHPad()) {
404 if (!ForExplicitEH)
405 EntryBlocks.push_back(&Fn.getEntryBlock());
406 if (!isa<CatchEndPadInst>(First))
407 EntryBlocks.push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000408 ForExplicitEH = true;
David Majnemerfd9f4772015-08-11 01:15:26 +0000409 }
410 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
411 Resumes.push_back(Resume);
412 }
413
414 if (ForExplicitEH)
Joseph Tremouletec182852015-08-28 01:12:35 +0000415 return prepareExplicitEH(Fn, EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +0000416
417 // No need to prepare functions that lack landing pads.
418 if (LPads.empty())
419 return false;
420
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000421 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000422 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000423
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000424 // If there were any landing pads, prepareExceptionHandlers will make changes.
425 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000426 return true;
427}
428
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000429bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000430
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000431void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
432 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000433 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000434}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000435
Reid Klecknerfd7df282015-04-22 21:05:21 +0000436static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
437 Constant *&Selector, BasicBlock *&NextBB);
438
439// Finds blocks reachable from the starting set Worklist. Does not follow unwind
440// edges or blocks listed in StopPoints.
441static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
442 SetVector<BasicBlock *> &Worklist,
443 const SetVector<BasicBlock *> *StopPoints) {
444 while (!Worklist.empty()) {
445 BasicBlock *BB = Worklist.pop_back_val();
446
447 // Don't cross blocks that we should stop at.
448 if (StopPoints && StopPoints->count(BB))
449 continue;
450
451 if (!ReachableBBs.insert(BB).second)
452 continue; // Already visited.
453
454 // Don't follow unwind edges of invokes.
455 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
456 Worklist.insert(II->getNormalDest());
457 continue;
458 }
459
460 // Otherwise, follow all successors.
461 Worklist.insert(succ_begin(BB), succ_end(BB));
462 }
463}
464
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000465// Attempt to find an instruction where a block can be split before
466// a call to llvm.eh.begincatch and its operands. If the block
467// begins with the begincatch call or one of its adjacent operands
468// the block will not be split.
469static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
470 IntrinsicInst *II) {
471 // If the begincatch call is already the first instruction in the block,
472 // don't split.
473 Instruction *FirstNonPHI = BB->getFirstNonPHI();
474 if (II == FirstNonPHI)
475 return nullptr;
476
477 // If either operand is in the same basic block as the instruction and
478 // isn't used by another instruction before the begincatch call, include it
479 // in the split block.
480 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
481 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
482
483 Instruction *I = II->getPrevNode();
484 Instruction *LastI = II;
485
486 while (I == Op0 || I == Op1) {
487 // If the block begins with one of the operands and there are no other
488 // instructions between the operand and the begincatch call, don't split.
489 if (I == FirstNonPHI)
490 return nullptr;
491
492 LastI = I;
493 I = I->getPrevNode();
494 }
495
496 // If there is at least one instruction in the block before the begincatch
497 // call and its operands, split the block at either the begincatch or
498 // its operand.
499 return LastI;
500}
501
Reid Klecknerfd7df282015-04-22 21:05:21 +0000502/// Find all points where exceptional control rejoins normal control flow via
503/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000504void WinEHPrepare::findCXXEHReturnPoints(
505 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000506 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
507 BasicBlock *BB = BBI;
508 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000509 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000510 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000511 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
512 if (SplitPt) {
513 // Split the block before the llvm.eh.begincatch call to allow
514 // cleanup and catch code to be distinguished later.
515 // Do not update BBI because we still need to process the
516 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000517 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000518 break;
519 }
520 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000521 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
522 // Split the block after the call to llvm.eh.endcatch if there is
523 // anything other than an unconditional branch, or if the successor
524 // starts with a phi.
525 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
526 if (!Br || !Br->isUnconditional() ||
527 isa<PHINode>(Br->getSuccessor(0)->begin())) {
528 DEBUG(dbgs() << "splitting block " << BB->getName()
529 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000530 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000531 }
532 // The next BB is normal control flow.
533 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
534 break;
535 }
536 }
537 }
538}
539
540static bool isCatchAllLandingPad(const BasicBlock *BB) {
541 const LandingPadInst *LP = BB->getLandingPadInst();
542 if (!LP)
543 return false;
544 unsigned N = LP->getNumClauses();
545 return (N > 0 && LP->isCatch(N - 1) &&
546 isa<ConstantPointerNull>(LP->getClause(N - 1)));
547}
548
549/// Find all points where exceptions control rejoins normal control flow via
550/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000551void WinEHPrepare::findSEHEHReturnPoints(
552 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000553 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
554 BasicBlock *BB = BBI;
555 // If the landingpad is a catch-all, treat the whole lpad as if it is
556 // reachable from normal control flow.
557 // FIXME: This is imprecise. We need a better way of identifying where a
558 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
559 // is no difference.
560 if (isCatchAllLandingPad(BB)) {
561 EHReturnBlocks.insert(BB);
562 continue;
563 }
564
565 BasicBlock *CatchHandler;
566 BasicBlock *NextBB;
567 Constant *Selector;
568 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000569 // Split the edge if there are multiple predecessors. This creates a place
570 // where we can insert EH recovery code.
571 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000572 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
573 << " to " << CatchHandler->getName() << '\n');
574 BBI = CatchHandler = SplitCriticalEdge(
575 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
576 }
577 EHReturnBlocks.insert(CatchHandler);
578 }
579 }
580}
581
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000582void WinEHPrepare::identifyEHBlocks(Function &F,
583 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000584 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
585 << F.getName() << '\n');
586
587 // Build a set of all non-exceptional blocks and exceptional blocks.
588 // - Non-exceptional blocks are blocks reachable from the entry block while
589 // not following invoke unwind edges.
590 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
591 // not follow llvm.eh.endcatch blocks, which mark a transition from
592 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000593
594 if (Personality == EHPersonality::MSVC_CXX)
595 findCXXEHReturnPoints(F, EHReturnBlocks);
596 else
597 findSEHEHReturnPoints(F, EHReturnBlocks);
598
599 DEBUG({
600 dbgs() << "identified the following blocks as EH return points:\n";
601 for (BasicBlock *BB : EHReturnBlocks)
602 dbgs() << " " << BB->getName() << '\n';
603 });
604
Andrew Kaylor91307432015-04-28 22:01:51 +0000605// Join points should not have phis at this point, unless they are a
606// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000607#ifndef NDEBUG
608 for (BasicBlock *BB : EHReturnBlocks)
609 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
610 "non-lpad EH return block has phi");
611#endif
612
613 // Normal blocks are the blocks reachable from the entry block and all EH
614 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000615 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000616 Worklist = EHReturnBlocks;
617 Worklist.insert(&F.getEntryBlock());
618 findReachableBlocks(NormalBlocks, Worklist, nullptr);
619 DEBUG({
620 dbgs() << "marked the following blocks as normal:\n";
621 for (BasicBlock *BB : NormalBlocks)
622 dbgs() << " " << BB->getName() << '\n';
623 });
624
625 // Exceptional blocks are the blocks reachable from landingpads that don't
626 // cross EH return points.
627 Worklist.clear();
628 for (auto *LPI : LPads)
629 Worklist.insert(LPI->getParent());
630 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
631 DEBUG({
632 dbgs() << "marked the following blocks as exceptional:\n";
633 for (BasicBlock *BB : EHBlocks)
634 dbgs() << " " << BB->getName() << '\n';
635 });
636
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000637}
638
639/// Ensure that all values live into and out of exception handlers are stored
640/// in memory.
641/// FIXME: This falls down when values are defined in one handler and live into
642/// another handler. For example, a cleanup defines a value used only by a
643/// catch handler.
644void WinEHPrepare::demoteValuesLiveAcrossHandlers(
645 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
646 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
647 << F.getName() << '\n');
648
649 // identifyEHBlocks() should have been called before this function.
650 assert(!NormalBlocks.empty());
651
Reid Kleckner7ea77082015-07-10 22:21:54 +0000652 // Try to avoid demoting EH pointer and selector values. They get in the way
653 // of our pattern matching.
654 SmallPtrSet<Instruction *, 10> EHVals;
655 for (BasicBlock &BB : F) {
656 LandingPadInst *LP = BB.getLandingPadInst();
657 if (!LP)
658 continue;
659 EHVals.insert(LP);
660 for (User *U : LP->users()) {
661 auto *EI = dyn_cast<ExtractValueInst>(U);
662 if (!EI)
663 continue;
664 EHVals.insert(EI);
665 for (User *U2 : EI->users()) {
666 if (auto *PN = dyn_cast<PHINode>(U2))
667 EHVals.insert(PN);
668 }
669 }
670 }
671
Reid Klecknerfd7df282015-04-22 21:05:21 +0000672 SetVector<Argument *> ArgsToDemote;
673 SetVector<Instruction *> InstrsToDemote;
674 for (BasicBlock &BB : F) {
675 bool IsNormalBB = NormalBlocks.count(&BB);
676 bool IsEHBB = EHBlocks.count(&BB);
677 if (!IsNormalBB && !IsEHBB)
678 continue; // Blocks that are neither normal nor EH are unreachable.
679 for (Instruction &I : BB) {
680 for (Value *Op : I.operands()) {
681 // Don't demote static allocas, constants, and labels.
682 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
683 continue;
684 auto *AI = dyn_cast<AllocaInst>(Op);
685 if (AI && AI->isStaticAlloca())
686 continue;
687
688 if (auto *Arg = dyn_cast<Argument>(Op)) {
689 if (IsEHBB) {
690 DEBUG(dbgs() << "Demoting argument " << *Arg
691 << " used by EH instr: " << I << "\n");
692 ArgsToDemote.insert(Arg);
693 }
694 continue;
695 }
696
Reid Kleckner7ea77082015-07-10 22:21:54 +0000697 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000698 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000699 if (EHVals.count(OpI))
700 continue;
701
Reid Klecknerfd7df282015-04-22 21:05:21 +0000702 BasicBlock *OpBB = OpI->getParent();
703 // If a value is produced and consumed in the same BB, we don't need to
704 // demote it.
705 if (OpBB == &BB)
706 continue;
707 bool IsOpNormalBB = NormalBlocks.count(OpBB);
708 bool IsOpEHBB = EHBlocks.count(OpBB);
709 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
710 DEBUG({
711 dbgs() << "Demoting instruction live in-out from EH:\n";
712 dbgs() << "Instr: " << *OpI << '\n';
713 dbgs() << "User: " << I << '\n';
714 });
715 InstrsToDemote.insert(OpI);
716 }
717 }
718 }
719 }
720
721 // Demote values live into and out of handlers.
722 // FIXME: This demotion is inefficient. We should insert spills at the point
723 // of definition, insert one reload in each handler that uses the value, and
724 // insert reloads in the BB used to rejoin normal control flow.
725 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
726 for (Instruction *I : InstrsToDemote)
727 DemoteRegToStack(*I, false, AllocaInsertPt);
728
729 // Demote arguments separately, and only for uses in EH blocks.
730 for (Argument *Arg : ArgsToDemote) {
731 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
732 Arg->getName() + ".reg2mem", AllocaInsertPt);
733 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
734 for (User *U : Users) {
735 auto *I = dyn_cast<Instruction>(U);
736 if (I && EHBlocks.count(I->getParent())) {
737 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
738 U->replaceUsesOfWith(Arg, Reload);
739 }
740 }
741 new StoreInst(Arg, Slot, AllocaInsertPt);
742 }
743
744 // Demote landingpad phis, as the landingpad will be removed from the machine
745 // CFG.
746 for (LandingPadInst *LPI : LPads) {
747 BasicBlock *BB = LPI->getParent();
748 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
749 DemotePHIToStack(Phi, AllocaInsertPt);
750 }
751
752 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
753 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
754}
755
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000756bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000757 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000758 // Don't run on functions that are already prepared.
759 for (LandingPadInst *LPad : LPads) {
760 BasicBlock *LPadBB = LPad->getParent();
761 for (Instruction &Inst : *LPadBB)
762 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
763 return false;
764 }
765
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000766 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000767 demoteValuesLiveAcrossHandlers(F, LPads);
768
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000769 // These containers are used to re-map frame variables that are used in
770 // outlined catch and cleanup handlers. They will be populated as the
771 // handlers are outlined.
772 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000773
774 bool HandlersOutlined = false;
775
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000776 Module *M = F.getParent();
777 LLVMContext &Context = M->getContext();
778
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000779 // Create a new function to receive the handler contents.
780 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
781 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000782 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000783
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000784 if (isAsynchronousEHPersonality(Personality)) {
785 // FIXME: Switch the ehptr type to i32 and then switch this.
786 SEHExceptionCodeSlot =
787 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
788 F.getEntryBlock().getFirstInsertionPt());
789 }
790
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000791 // In order to handle the case where one outlined catch handler returns
792 // to a block within another outlined catch handler that would otherwise
793 // be unreachable, we need to outline the nested landing pad before we
794 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000795 if (!isAsynchronousEHPersonality(Personality))
796 std::sort(LPads.begin(), LPads.end(),
797 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
798 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000799 });
800
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000801 // This container stores the llvm.eh.recover and IndirectBr instructions
802 // that make up the body of each landing pad after it has been outlined.
803 // We need to defer the population of the target list for the indirectbr
804 // until all landing pads have been outlined so that we can handle the
805 // case of blocks in the target that are reached only from nested
806 // landing pads.
807 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
808
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000809 for (LandingPadInst *LPad : LPads) {
810 // Look for evidence that this landingpad has already been processed.
811 bool LPadHasActionList = false;
812 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000813 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000814 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
815 LPadHasActionList = true;
816 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000817 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000818 }
819
820 // If we've already outlined the handlers for this landingpad,
821 // there's nothing more to do here.
822 if (LPadHasActionList)
823 continue;
824
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000825 // If either of the values in the aggregate returned by the landing pad is
826 // extracted and stored to memory, promote the stored value to a register.
827 promoteLandingPadValues(LPad);
828
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000829 LandingPadActions Actions;
830 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000831
Reid Kleckner9405ef02015-04-10 23:12:29 +0000832 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000833 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000834 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000835 continue;
836 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000837
838 // SEH doesn't do any outlining for catches. Instead, pass the handler
839 // basic block addr to llvm.eh.actions and list the block as a return
840 // target.
841 if (isAsynchronousEHPersonality(Personality)) {
842 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
843 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000844 continue;
845 }
846 }
847
Reid Kleckner9405ef02015-04-10 23:12:29 +0000848 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
849 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000850
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000851 // Split the block after the landingpad instruction so that it is just a
852 // call to llvm.eh.actions followed by indirectbr.
853 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000854 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000855 // Erase the branch inserted by the split so we can insert indirectbr.
856 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000857
Reid Klecknere3af86e2015-04-23 21:22:30 +0000858 // Replace all extracted values with undef and ultimately replace the
859 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000860 SmallVector<Instruction *, 4> SEHCodeUses;
861 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000862 for (User *U : LPad->users()) {
863 auto *E = dyn_cast<ExtractValueInst>(U);
864 if (!E)
865 continue;
866 assert(E->getNumIndices() == 1 &&
867 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000868 unsigned Idx = *E->idx_begin();
869 assert((Idx == 0 || Idx == 1) && "unexpected index");
870 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
871 SEHCodeUses.push_back(E);
872 else
873 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000874 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000875 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000876 E->replaceAllUsesWith(UndefValue::get(E->getType()));
877 E->eraseFromParent();
878 }
879 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000880
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000881 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000882 while (!SEHCodeUses.empty()) {
883 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000884 SmallVector<Use *, 4> Uses;
885 for (Use &U : E->uses())
886 Uses.push_back(&U);
887 for (Use *U : Uses) {
888 auto *I = cast<Instruction>(U->getUser());
889 if (isa<ResumeInst>(I))
890 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000891 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000892 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000893 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000894 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000895 }
896 E->replaceAllUsesWith(UndefValue::get(E->getType()));
897 E->eraseFromParent();
898 }
899
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000900 // Add a call to describe the actions for this landing pad.
901 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000902 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000903 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000904 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000905 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000906 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000907 // Find the frame escape index of the exception object alloca in the
908 // parent.
909 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000910 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000911 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
912 auto I = FrameVarInfo.find(EHObj);
913 assert(I != FrameVarInfo.end() &&
914 "failed to map llvm.eh.begincatch var");
915 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
916 }
917 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000918 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000919 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000920 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000921 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000922 }
923 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000924 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000925
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000926 SetVector<BasicBlock *> ReturnTargets;
927 for (ActionHandler *Action : Actions) {
928 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
929 const auto &CatchTargets = CatchAction->getReturnTargets();
930 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000931 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000932 }
933 IndirectBrInst *Branch =
934 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
935 for (BasicBlock *Target : ReturnTargets)
936 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000937
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000938 if (!isAsynchronousEHPersonality(Personality)) {
939 // C++ EH must repopulate the targets later to handle the case of
940 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000941 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000942 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000943
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000944 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000945
946 // If nothing got outlined, there is no more processing to be done.
947 if (!HandlersOutlined)
948 return false;
949
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000950 // Replace any nested landing pad stubs with the correct action handler.
951 // This must be done before we remove unreachable blocks because it
952 // cleans up references to outlined blocks that will be deleted.
953 for (auto &LPadPair : NestedLPtoOriginalLP)
954 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000955 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000956
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000957 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000958 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000959 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000960 for (auto &LPadImplPair : LPadImpls) {
961 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
962 IndirectBrInst *Branch = LPadImplPair.second;
963
964 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000965 parseEHActions(Recover, ActionList);
966
967 // Add an indirect branch listing possible successors of the catch handlers.
968 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000969 for (const auto &Action : ActionList) {
970 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000971 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
972 getPossibleReturnTargets(&F, Handler, ReturnTargets);
973 }
974 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000975 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000976 // Clear any targets we already knew about.
977 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
978 BasicBlock *KnownTarget = Branch->getDestination(I);
979 if (ReturnTargets.count(KnownTarget))
980 ReturnTargets.remove(KnownTarget);
981 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000982 for (BasicBlock *Target : ReturnTargets) {
983 Branch->addDestination(Target);
984 // The target may be a block that we excepted to get pruned.
985 // If it is, it may contain a call to llvm.eh.endcatch.
986 if (CheckedTargets.insert(Target)) {
987 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
988 // will be followed by an unconditional branch.
989 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
990 if (Br && Br->isUnconditional() &&
991 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
992 Instruction *Prev = Br->getPrevNode();
993 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
994 Prev->eraseFromParent();
995 }
996 }
997 }
998 }
999 LPadImpls.clear();
1000
David Majnemercde33032015-03-30 22:58:10 +00001001 F.addFnAttr("wineh-parent", F.getName());
1002
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001003 // Delete any blocks that were only used by handlers that were outlined above.
1004 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001005
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001006 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001007 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001008 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001009
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001010 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001011 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001012 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +00001013 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +00001014 SmallVector<Value *, 8> AllocasToEscape;
1015
Reid Kleckner60381792015-07-07 22:25:32 +00001016 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +00001017 // keep escaping those objects.
1018 for (Instruction &I : F.front()) {
1019 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +00001020 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +00001021 auto Args = II->arg_operands();
1022 AllocasToEscape.append(Args.begin(), Args.end());
1023 II->eraseFromParent();
1024 break;
1025 }
1026 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001027
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001028 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +00001029 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001030 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001031 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001032 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001033 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001034
Reid Klecknerb4019412015-04-06 18:50:38 +00001035 // FIXME: We should try to sink unescaped allocas from the parent frame into
1036 // the child frame. If the alloca is escaped, we have to use the lifetime
1037 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001038
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001039 // Add this alloca to the list of things to escape.
1040 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001041
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001042 // Next replace all outlined allocas that are mapped to it.
1043 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001044 if (TempAlloca == getCatchObjectSentinel())
1045 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001046 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001047 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1048 assert(FP);
1049
Reid Kleckner60381792015-07-07 22:25:32 +00001050 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001051 Builder.SetInsertPoint(TempAlloca);
1052 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1053 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001054 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001055 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001056 Instruction *RecoveredAlloca =
1057 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1058
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001059 // Add a pointer bitcast if the alloca wasn't an i8.
1060 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1061 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001062 RecoveredAlloca = cast<Instruction>(
1063 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001064 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001065 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1066 TempAlloca->removeFromParent();
1067 RecoveredAlloca->takeName(TempAlloca);
1068 delete TempAlloca;
1069 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001070 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001071
Reid Kleckner60381792015-07-07 22:25:32 +00001072 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001073 // block.
1074 Builder.SetInsertPoint(&F.getEntryBlock().back());
1075 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1076
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001077 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001078 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1079 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1080 for (User *U : SEHExceptionCodeSlot->users()) {
1081 if (auto *Inst = dyn_cast<Instruction>(U))
1082 UserBlocks.insert(Inst->getParent());
1083 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001084 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001085 // After the promotion, kill off dead instructions.
1086 for (BasicBlock *BB : UserBlocks)
1087 SimplifyInstructionsInBlock(BB, LibInfo);
1088 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001089 }
1090
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001091 // Clean up the handler action maps we created for this function
1092 DeleteContainerSeconds(CatchHandlerMap);
1093 CatchHandlerMap.clear();
1094 DeleteContainerSeconds(CleanupHandlerMap);
1095 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001096 HandlerToParentFP.clear();
1097 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001098 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001099 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001100 EHBlocks.clear();
1101 NormalBlocks.clear();
1102 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001103
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001104 return HandlersOutlined;
1105}
1106
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001107void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1108 // If the return values of the landing pad instruction are extracted and
1109 // stored to memory, we want to promote the store locations to reg values.
1110 SmallVector<AllocaInst *, 2> EHAllocas;
1111
1112 // The landingpad instruction returns an aggregate value. Typically, its
1113 // value will be passed to a pair of extract value instructions and the
1114 // results of those extracts are often passed to store instructions.
1115 // In unoptimized code the stored value will often be loaded and then stored
1116 // again.
1117 for (auto *U : LPad->users()) {
1118 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1119 if (!Extract)
1120 continue;
1121
1122 for (auto *EU : Extract->users()) {
1123 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1124 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1125 EHAllocas.push_back(AV);
1126 }
1127 }
1128 }
1129
1130 // We can't do this without a dominator tree.
1131 assert(DT);
1132
1133 if (!EHAllocas.empty()) {
1134 PromoteMemToReg(EHAllocas, *DT);
1135 EHAllocas.clear();
1136 }
Reid Kleckner86762142015-04-16 00:02:04 +00001137
1138 // After promotion, some extracts may be trivially dead. Remove them.
1139 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1140 for (auto *U : Users)
1141 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001142}
1143
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001144void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1145 Function *HandlerF,
1146 SetVector<BasicBlock*> &Targets) {
1147 for (BasicBlock &BB : *HandlerF) {
1148 // If the handler contains landing pads, check for any
1149 // handlers that may return directly to a block in the
1150 // parent function.
1151 if (auto *LPI = BB.getLandingPadInst()) {
1152 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001153 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001154 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001155 for (const auto &Action : ActionList) {
1156 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001157 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1158 getPossibleReturnTargets(ParentF, NestedF, Targets);
1159 }
1160 }
1161 }
1162
1163 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1164 if (!Ret)
1165 continue;
1166
1167 // Handler functions must always return a block address.
1168 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1169
1170 // If this is the handler for a nested landing pad, the
1171 // return address may have been remapped to a block in the
1172 // parent handler. We're not interested in those.
1173 if (BA->getFunction() != ParentF)
1174 continue;
1175
1176 Targets.insert(BA->getBasicBlock());
1177 }
1178}
1179
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001180void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1181 LandingPadInst *OutlinedLPad,
1182 const LandingPadInst *OriginalLPad,
1183 FrameVarInfoMap &FrameVarInfo) {
1184 // Get the nested block and erase the unreachable instruction that was
1185 // temporarily inserted as its terminator.
1186 LLVMContext &Context = ParentFn->getContext();
1187 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001188 // If the nested landing pad was outlined before the landing pad that enclosed
1189 // it, it will already be in outlined form. In that case, we just need to see
1190 // if the returns and the enclosing branch instruction need to be updated.
1191 IndirectBrInst *Branch =
1192 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1193 if (!Branch) {
1194 // If the landing pad wasn't in outlined form, it should be a stub with
1195 // an unreachable terminator.
1196 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1197 OutlinedBB->getTerminator()->eraseFromParent();
1198 // That should leave OutlinedLPad as the last instruction in its block.
1199 assert(&OutlinedBB->back() == OutlinedLPad);
1200 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001201
1202 // The original landing pad will have already had its action intrinsic
1203 // built by the outlining loop. We need to clone that into the outlined
1204 // location. It may also be necessary to add references to the exception
1205 // variables to the outlined handler in which this landing pad is nested
1206 // and remap return instructions in the nested handlers that should return
1207 // to an address in the outlined handler.
1208 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001209 BasicBlock::const_iterator II = OriginalLPad;
1210 ++II;
1211 // The instruction after the landing pad should now be a call to eh.actions.
1212 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001213 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001214
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001215 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001216 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001217 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001218 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001219 for (const auto &Action : ActionList) {
1220 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001221 if (!Catch)
1222 continue;
1223 // The dyn_cast to function here selects C++ catch handlers and skips
1224 // SEH catch handlers.
1225 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1226 if (!Handler)
1227 continue;
1228 // Visit all the return instructions, looking for places that return
1229 // to a location within OutlinedHandlerFn.
1230 for (BasicBlock &NestedHandlerBB : *Handler) {
1231 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1232 if (!Ret)
1233 continue;
1234
1235 // Handler functions must always return a block address.
1236 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1237 // The original target will have been in the main parent function,
1238 // but if it is the address of a block that has been outlined, it
1239 // should be a block that was outlined into OutlinedHandlerFn.
1240 assert(BA->getFunction() == ParentFn);
1241
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001242 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001243 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1244 continue;
1245
1246 // If the return value is the address ofF a block that we
1247 // previously outlined into the parent handler function, replace
1248 // the return instruction and add the mapped target to the list
1249 // of possible return addresses.
1250 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1251 assert(MappedBB->getParent() == OutlinedHandlerFn);
1252 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1253 Ret->eraseFromParent();
1254 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1255 ActionTargets.push_back(NewBA);
1256 }
1257 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001258 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001259
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001260 if (Branch) {
1261 // If the landing pad was already in outlined form, just update its targets.
1262 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1263 Branch->removeDestination(I);
1264 // Add the previously collected action targets.
1265 for (auto *Target : ActionTargets)
1266 Branch->addDestination(Target->getBasicBlock());
1267 } else {
1268 // If the landing pad was previously stubbed out, fill in its outlined form.
1269 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1270 OutlinedBB->getInstList().push_back(NewEHActions);
1271
1272 // Insert an indirect branch into the outlined landing pad BB.
1273 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1274 // Add the previously collected action targets.
1275 for (auto *Target : ActionTargets)
1276 IBr->addDestination(Target->getBasicBlock());
1277 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001278}
1279
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001280// This function examines a block to determine whether the block ends with a
1281// conditional branch to a catch handler based on a selector comparison.
1282// This function is used both by the WinEHPrepare::findSelectorComparison() and
1283// WinEHCleanupDirector::handleTypeIdFor().
1284static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1285 Constant *&Selector, BasicBlock *&NextBB) {
1286 ICmpInst::Predicate Pred;
1287 BasicBlock *TBB, *FBB;
1288 Value *LHS, *RHS;
1289
1290 if (!match(BB->getTerminator(),
1291 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1292 return false;
1293
1294 if (!match(LHS,
1295 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1296 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1297 return false;
1298
1299 if (Pred == CmpInst::ICMP_EQ) {
1300 CatchHandler = TBB;
1301 NextBB = FBB;
1302 return true;
1303 }
1304
1305 if (Pred == CmpInst::ICMP_NE) {
1306 CatchHandler = FBB;
1307 NextBB = TBB;
1308 return true;
1309 }
1310
1311 return false;
1312}
1313
Andrew Kaylor41758512015-04-20 22:04:09 +00001314static bool isCatchBlock(BasicBlock *BB) {
1315 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1316 II != IE; ++II) {
1317 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1318 return true;
1319 }
1320 return false;
1321}
1322
David Majnemer7fddecc2015-06-17 20:52:32 +00001323static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001324 // FIXME: Finish this!
1325 LLVMContext &Context = Handler->getContext();
1326 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1327 Handler->getBasicBlockList().push_back(StubBB);
1328 IRBuilder<> Builder(StubBB);
1329 LandingPadInst *LPad = Builder.CreateLandingPad(
1330 llvm::StructType::get(Type::getInt8PtrTy(Context),
1331 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001332 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001333 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001334 Function *ActionIntrin =
1335 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001336 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001337 LPad->setCleanup(true);
1338 Builder.CreateUnreachable();
1339 return StubBB;
1340}
1341
1342// Cycles through the blocks in an outlined handler function looking for an
1343// invoke instruction and inserts an invoke of llvm.donothing with an empty
1344// landing pad if none is found. The code that generates the .xdata tables for
1345// the handler needs at least one landing pad to identify the parent function's
1346// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001347void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001348 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001349 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001350 for (BasicBlock &BB : *Handler) {
1351 TerminatorInst *Terminator = BB.getTerminator();
1352 // If we find an invoke, there is nothing to be done.
1353 auto *II = dyn_cast<InvokeInst>(Terminator);
1354 if (II)
1355 return;
1356 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001357 if (!Ret)
1358 Ret = dyn_cast<ReturnInst>(Terminator);
1359 // If we haven't recorded an unreachable instruction, try this terminator.
1360 if (!Unreached)
1361 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001362 }
1363
1364 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001365 // at least one return or unreachable instruction. We'll insert an invoke of
1366 // llvm.donothing ahead of that instruction.
1367 assert(Ret || Unreached);
1368 TerminatorInst *Term;
1369 if (Ret)
1370 Term = Ret;
1371 else
1372 Term = Unreached;
1373 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001374 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001375 // SplitBlock adds an unconditional branch instruction at the end of the
1376 // parent block. We want to replace that with an invoke call, so we can
1377 // erase it now.
1378 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001379 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001380 Function *F =
1381 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1382 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1383}
1384
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001385// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1386// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001387Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1388 const Twine &Name, Module *M,
1389 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001390 // x64 uses a two-argument prototype where the parent FP is the second
1391 // argument. x86 uses no arguments, just the incoming EBP value.
1392 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001393 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001394 FunctionType *FnType;
1395 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001396 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1397 FnType = FunctionType::get(RetTy, ArgTys, false);
1398 } else {
1399 FnType = FunctionType::get(RetTy, None, false);
1400 }
1401
1402 Function *Handler =
1403 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1404 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1405 Handler->getBasicBlockList().push_front(Entry);
1406 if (TheTriple.getArch() == Triple::x86_64) {
1407 ParentFP = &(Handler->getArgumentList().back());
1408 } else {
1409 assert(M);
1410 Function *FrameAddressFn =
1411 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001412 Function *RecoverFPFn =
1413 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1414 IRBuilder<> Builder(&Handler->getEntryBlock());
1415 Value *EBP =
1416 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1417 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1418 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001419 }
1420 return Handler;
1421}
1422
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001423bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1424 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001425 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001426 Module *M = SrcFn->getParent();
1427 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001428 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001429
1430 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001431 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001432 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001433 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001434 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001435 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001436 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001437 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001438 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001439 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001440 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001441 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001442 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001443 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001444
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001445 // Generate a standard prolog to setup the frame recovery structure.
1446 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001447 Builder.SetInsertPoint(Entry);
1448 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1449
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001450 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001451
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001452 ValueToValueMapTy VMap;
1453
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001454 LandingPadMap &LPadMap = LPadMaps[LPad];
1455 if (!LPadMap.isInitialized())
1456 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001457 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1458 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001459 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1460 LPadMap, NestedLPtoOriginalLP, DT,
1461 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001462 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1463 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001464 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001465 Director.reset(
1466 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001467 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1468 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001469 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001470
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001471 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001472 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001473
Andrew Kaylor3170e562015-03-20 21:42:54 +00001474 // If the start block contains PHI nodes, we need to map them.
1475 BasicBlock::iterator II = StartBB->begin();
1476 while (auto *PN = dyn_cast<PHINode>(II)) {
1477 bool Mapped = false;
1478 // Look for PHI values that we have already mapped (such as the selector).
1479 for (Value *Val : PN->incoming_values()) {
1480 if (VMap.count(Val)) {
1481 VMap[PN] = VMap[Val];
1482 Mapped = true;
1483 }
1484 }
1485 // If we didn't find a match for this value, map it as an undef.
1486 if (!Mapped) {
1487 VMap[PN] = UndefValue::get(PN->getType());
1488 }
1489 ++II;
1490 }
1491
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001492 // The landing pad value may be used by PHI nodes. It will ultimately be
1493 // eliminated, but we need it in the map for intermediate handling.
1494 VMap[LPad] = UndefValue::get(LPad->getType());
1495
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001496 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001497 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001498
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001499 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001501 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001502
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001503 // Move all the instructions in the cloned "entry" block into our entry block.
1504 // Depending on how the parent function was laid out, the block that will
1505 // correspond to the outlined entry block may not be the first block in the
1506 // list. We can recognize it, however, as the cloned block which has no
1507 // predecessors. Any other block wouldn't have been cloned if it didn't
1508 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001509 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001510 while (!pred_empty(ClonedIt))
1511 ++ClonedIt;
1512 BasicBlock *ClonedEntryBB = ClonedIt;
1513 assert(ClonedEntryBB);
1514 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1515 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001516
Andrew Kaylorbb111322015-04-07 21:30:23 +00001517 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001518 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001519
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001520 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1521 WinEHCatchDirector *CatchDirector =
1522 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1523 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1524 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001525
1526 // Look for blocks that are not part of the landing pad that we just
1527 // outlined but terminate with a call to llvm.eh.endcatch and a
1528 // branch to a block that is in the handler we just outlined.
1529 // These blocks will be part of a nested landing pad that intends to
1530 // return to an address in this handler. This case is best handled
1531 // after both landing pads have been outlined, so for now we'll just
1532 // save the association of the blocks in LPadTargetBlocks. The
1533 // return instructions which are created from these branches will be
1534 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001535 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001536 // VMap maps all values and blocks that were just cloned, but dead
1537 // blocks which were pruned will map to nullptr.
1538 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1539 continue;
1540 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1541 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1542 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1543 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1544 continue;
1545 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1546 --II;
1547 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1548 // This would indicate that a nested landing pad wants to return
1549 // to a block that is outlined into two different handlers.
1550 assert(!LPadTargetBlocks.count(MappedBB));
1551 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1552 }
1553 }
1554 }
1555 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001556
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001557 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001558
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001559 return true;
1560}
1561
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001562/// This BB must end in a selector dispatch. All we need to do is pass the
1563/// handler block to llvm.eh.actions and list it as a possible indirectbr
1564/// target.
1565void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1566 BasicBlock *StartBB) {
1567 BasicBlock *HandlerBB;
1568 BasicBlock *NextBB;
1569 Constant *Selector;
1570 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1571 if (Res) {
1572 // If this was EH dispatch, this must be a conditional branch to the handler
1573 // block.
1574 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1575 // leading to crashes if some optimization hoists stuff here.
1576 assert(CatchAction->getSelector() && HandlerBB &&
1577 "expected catch EH dispatch");
1578 } else {
1579 // This must be a catch-all. Split the block after the landingpad.
1580 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001581 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001582 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001583 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1584 Function *EHCodeFn = Intrinsic::getDeclaration(
1585 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001586 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001587 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1588 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001589 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1590 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1591 CatchAction->setReturnTargets(Targets);
1592}
1593
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001594void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1595 // Each instance of this class should only ever be used to map a single
1596 // landing pad.
1597 assert(OriginLPad == nullptr || OriginLPad == LPad);
1598
1599 // If the landing pad has already been mapped, there's nothing more to do.
1600 if (OriginLPad == LPad)
1601 return;
1602
1603 OriginLPad = LPad;
1604
1605 // The landingpad instruction returns an aggregate value. Typically, its
1606 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001607 // results of those extracts will have been promoted to reg values before
1608 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001609 for (auto *U : LPad->users()) {
1610 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1611 if (!Extract)
1612 continue;
1613 assert(Extract->getNumIndices() == 1 &&
1614 "Unexpected operation: extracting both landing pad values");
1615 unsigned int Idx = *(Extract->idx_begin());
1616 assert((Idx == 0 || Idx == 1) &&
1617 "Unexpected operation: extracting an unknown landing pad element");
1618 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001619 ExtractedEHPtrs.push_back(Extract);
1620 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001621 ExtractedSelectors.push_back(Extract);
1622 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001623 }
1624}
1625
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001626bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1627 return BB->getLandingPadInst() == OriginLPad;
1628}
1629
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001630bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1631 if (Inst == OriginLPad)
1632 return true;
1633 for (auto *Extract : ExtractedEHPtrs) {
1634 if (Inst == Extract)
1635 return true;
1636 }
1637 for (auto *Extract : ExtractedSelectors) {
1638 if (Inst == Extract)
1639 return true;
1640 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001641 return false;
1642}
1643
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001644void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1645 Value *SelectorValue) const {
1646 // Remap all landing pad extract instructions to the specified values.
1647 for (auto *Extract : ExtractedEHPtrs)
1648 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001649 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001650 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001651}
1652
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001653static bool isLocalAddressCall(const Value *V) {
1654 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001655}
1656
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001657CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001658 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001659 // If this is one of the boilerplate landing pad instructions, skip it.
1660 // The instruction will have already been remapped in VMap.
1661 if (LPadMap.isLandingPadSpecificInst(Inst))
1662 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001663
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001664 // Nested landing pads that have not already been outlined will be cloned as
1665 // stubs, with just the landingpad instruction and an unreachable instruction.
1666 // When all landingpads have been outlined, we'll replace this with the
1667 // llvm.eh.actions call and indirect branch created when the landing pad was
1668 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001669 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1670 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001671 }
1672
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001673 // Nested landing pads that have already been outlined will be cloned in their
1674 // outlined form, but we need to intercept the ibr instruction to filter out
1675 // targets that do not return to the handler we are outlining.
1676 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1677 return handleIndirectBr(VMap, IBr, NewBB);
1678 }
1679
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001680 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1681 return handleInvoke(VMap, Invoke, NewBB);
1682
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001683 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1684 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001685
Andrew Kaylorea8df612015-04-17 23:05:43 +00001686 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1687 return handleCompare(VMap, Cmp, NewBB);
1688
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001689 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1690 return handleBeginCatch(VMap, Inst, NewBB);
1691 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1692 return handleEndCatch(VMap, Inst, NewBB);
1693 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1694 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001695
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001696 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001697 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001698 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001699 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001700 return CloningDirector::SkipInstruction;
1701 }
1702
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001703 // Continue with the default cloning behavior.
1704 return CloningDirector::CloneInstruction;
1705}
1706
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001707CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1708 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001709 // If the instruction after the landing pad is a call to llvm.eh.actions
1710 // the landing pad has already been outlined. In this case, we should
1711 // clone it because it may return to a block in the handler we are
1712 // outlining now that would otherwise be unreachable. The landing pads
1713 // are sorted before outlining begins to enable this case to work
1714 // properly.
1715 const Instruction *NextI = LPad->getNextNode();
1716 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1717 return CloningDirector::CloneInstruction;
1718
1719 // If the landing pad hasn't been outlined yet, the landing pad we are
1720 // outlining now does not dominate it and so it cannot return to a block
1721 // in this handler. In that case, we can just insert a stub landing
1722 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001723 Instruction *NewInst = LPad->clone();
1724 if (LPad->hasName())
1725 NewInst->setName(LPad->getName());
1726 // Save this correlation for later processing.
1727 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1728 VMap[LPad] = NewInst;
1729 BasicBlock::InstListType &InstList = NewBB->getInstList();
1730 InstList.push_back(NewInst);
1731 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1732 return CloningDirector::StopCloningBB;
1733}
1734
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001735CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1736 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1737 // The argument to the call is some form of the first element of the
1738 // landingpad aggregate value, but that doesn't matter. It isn't used
1739 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001740 // The second argument is an outparameter where the exception object will be
1741 // stored. Typically the exception object is a scalar, but it can be an
1742 // aggregate when catching by value.
1743 // FIXME: Leave something behind to indicate where the exception object lives
1744 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001745 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1746 "llvm.eh.begincatch found while "
1747 "outlining catch handler.");
1748 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001749 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1750 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001751 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1752 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001753 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001754 return CloningDirector::SkipInstruction;
1755}
1756
1757CloningDirector::CloningAction
1758WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1759 const Instruction *Inst, BasicBlock *NewBB) {
1760 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1761 // It might be interesting to track whether or not we are inside a catch
1762 // function, but that might make the algorithm more brittle than it needs
1763 // to be.
1764
1765 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001766 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001767 // or at the end of the catch block. However, a catch-all handler may call
1768 // end catch from the original landing pad. If the call occurs in a nested
1769 // landing pad block, we must skip it and continue so that the landing pad
1770 // gets cloned.
1771 auto *ParentBB = IntrinCall->getParent();
1772 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001773 return CloningDirector::SkipInstruction;
1774
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001775 // If an end catch occurs anywhere else we want to terminate the handler
1776 // with a return to the code that follows the endcatch call. If the
1777 // next instruction is not an unconditional branch, we need to split the
1778 // block to provide a clear target for the return instruction.
1779 BasicBlock *ContinueBB;
1780 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1781 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1782 if (!Branch || !Branch->isUnconditional()) {
1783 // We're interrupting the cloning process at this location, so the
1784 // const_cast we're doing here will not cause a problem.
1785 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1786 const_cast<Instruction *>(cast<Instruction>(Next)));
1787 } else {
1788 ContinueBB = Branch->getSuccessor(0);
1789 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001790
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001791 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1792 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001793
1794 // We just added a terminator to the cloned block.
1795 // Tell the caller to stop processing the current basic block so that
1796 // the branch instruction will be skipped.
1797 return CloningDirector::StopCloningBB;
1798}
1799
1800CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1801 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1802 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1803 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1804 // This causes a replacement that will collapse the landing pad CFG based
1805 // on the filter function we intend to match.
1806 if (Selector == CurrentSelector)
1807 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1808 else
1809 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1810 // Tell the caller not to clone this instruction.
1811 return CloningDirector::SkipInstruction;
1812}
1813
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001814CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1815 ValueToValueMapTy &VMap,
1816 const IndirectBrInst *IBr,
1817 BasicBlock *NewBB) {
1818 // If this indirect branch is not part of a landing pad block, just clone it.
1819 const BasicBlock *ParentBB = IBr->getParent();
1820 if (!ParentBB->isLandingPad())
1821 return CloningDirector::CloneInstruction;
1822
1823 // If it is part of a landing pad, we want to filter out target blocks
1824 // that are not part of the handler we are outlining.
1825 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1826
1827 // Save this correlation for later processing.
1828 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1829
1830 // We should only get here for landing pads that have already been outlined.
1831 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1832
1833 // Copy the indirectbr, but only include targets that were previously
1834 // identified as EH blocks and are dominated by the nested landing pad.
1835 SetVector<const BasicBlock *> ReturnTargets;
1836 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1837 auto *TargetBB = IBr->getDestination(I);
1838 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1839 DT->dominates(ParentBB, TargetBB)) {
1840 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1841 ReturnTargets.insert(TargetBB);
1842 }
1843 }
1844 IndirectBrInst *NewBranch =
1845 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1846 ReturnTargets.size(), NewBB);
1847 for (auto *Target : ReturnTargets)
1848 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1849
1850 // The operands and targets of the branch instruction are remapped later
1851 // because it is a terminator. Tell the cloning code to clone the
1852 // blocks we just added to the target list.
1853 return CloningDirector::CloneSuccessors;
1854}
1855
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001856CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001857WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1858 const InvokeInst *Invoke, BasicBlock *NewBB) {
1859 return CloningDirector::CloneInstruction;
1860}
1861
1862CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001863WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1864 const ResumeInst *Resume, BasicBlock *NewBB) {
1865 // Resume instructions shouldn't be reachable from catch handlers.
1866 // We still need to handle it, but it will be pruned.
1867 BasicBlock::InstListType &InstList = NewBB->getInstList();
1868 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1869 return CloningDirector::StopCloningBB;
1870}
1871
Andrew Kaylorea8df612015-04-17 23:05:43 +00001872CloningDirector::CloningAction
1873WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1874 const CmpInst *Compare, BasicBlock *NewBB) {
1875 const IntrinsicInst *IntrinCall = nullptr;
1876 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1877 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001878 } else if (match(Compare->getOperand(1),
1879 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001880 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1881 }
1882 if (IntrinCall) {
1883 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1884 // This causes a replacement that will collapse the landing pad CFG based
1885 // on the filter function we intend to match.
1886 if (Selector == CurrentSelector->stripPointerCasts()) {
1887 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001888 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001889 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1890 }
1891 return CloningDirector::SkipInstruction;
1892 }
1893 return CloningDirector::CloneInstruction;
1894}
1895
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001896CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1897 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1898 // The MS runtime will terminate the process if an exception occurs in a
1899 // cleanup handler, so we shouldn't encounter landing pads in the actual
1900 // cleanup code, but they may appear in catch blocks. Depending on where
1901 // we started cloning we may see one, but it will get dropped during dead
1902 // block pruning.
1903 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1904 VMap[LPad] = NewInst;
1905 BasicBlock::InstListType &InstList = NewBB->getInstList();
1906 InstList.push_back(NewInst);
1907 return CloningDirector::StopCloningBB;
1908}
1909
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001910CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1911 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001912 // Cleanup code may flow into catch blocks or the catch block may be part
1913 // of a branch that will be optimized away. We'll insert a return
1914 // instruction now, but it may be pruned before the cloning process is
1915 // complete.
1916 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001917 return CloningDirector::StopCloningBB;
1918}
1919
1920CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1921 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001922 // Cleanup handlers nested within catch handlers may begin with a call to
1923 // eh.endcatch. We can just ignore that instruction.
1924 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001925}
1926
1927CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1928 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001929 // If we encounter a selector comparison while cloning a cleanup handler,
1930 // we want to stop cloning immediately. Anything after the dispatch
1931 // will be outlined into a different handler.
1932 BasicBlock *CatchHandler;
1933 Constant *Selector;
1934 BasicBlock *NextBB;
1935 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1936 CatchHandler, Selector, NextBB)) {
1937 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1938 return CloningDirector::StopCloningBB;
1939 }
1940 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001941 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001942 return CloningDirector::SkipInstruction;
1943}
1944
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001945CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1946 ValueToValueMapTy &VMap,
1947 const IndirectBrInst *IBr,
1948 BasicBlock *NewBB) {
1949 // No special handling is required for cleanup cloning.
1950 return CloningDirector::CloneInstruction;
1951}
1952
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001953CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1954 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1955 // All invokes in cleanup handlers can be replaced with calls.
1956 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1957 // Insert a normal call instruction...
1958 CallInst *NewCall =
1959 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1960 Invoke->getName(), NewBB);
1961 NewCall->setCallingConv(Invoke->getCallingConv());
1962 NewCall->setAttributes(Invoke->getAttributes());
1963 NewCall->setDebugLoc(Invoke->getDebugLoc());
1964 VMap[Invoke] = NewCall;
1965
Reid Kleckner6e48a822015-04-10 16:26:42 +00001966 // Remap the operands.
1967 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1968
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001969 // Insert an unconditional branch to the normal destination.
1970 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1971
1972 // The unwind destination won't be cloned into the new function, so
1973 // we don't need to clean up its phi nodes.
1974
1975 // We just added a terminator to the cloned block.
1976 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001977 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001978}
1979
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001980CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1981 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1982 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1983
1984 // We just added a terminator to the cloned block.
1985 // Tell the caller to stop processing the current basic block so that
1986 // the branch instruction will be skipped.
1987 return CloningDirector::StopCloningBB;
1988}
1989
Andrew Kaylorea8df612015-04-17 23:05:43 +00001990CloningDirector::CloningAction
1991WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1992 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001993 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1994 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1995 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1996 return CloningDirector::SkipInstruction;
1997 }
1998 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001999}
2000
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002001WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002002 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002003 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002004 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00002005
2006 // New allocas should be inserted in the entry block, but after the parent FP
2007 // is established if it is an instruction.
2008 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
2009 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
2010 InsertPoint = FPInst->getNextNode();
2011 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002012}
2013
2014Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002015 // If we're asked to materialize a static alloca, we temporarily create an
2016 // alloca in the outlined function and add this to the FrameVarInfo map. When
2017 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00002018 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002019 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002020 assert(AV->isStaticAlloca() &&
2021 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00002022 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2023 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00002024 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002025 return NewAlloca;
2026 }
2027
Andrew Kaylor72029c62015-03-03 00:41:03 +00002028 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00002029 Function *Parent = isa<Instruction>(V)
2030 ? cast<Instruction>(V)->getParent()->getParent()
2031 : cast<Argument>(V)->getParent();
2032 errs()
2033 << "Failed to demote instruction used in exception handler of function "
2034 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002035 errs() << " " << *V << '\n';
2036 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002037 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002038
Andrew Kaylor72029c62015-03-03 00:41:03 +00002039 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002040 return nullptr;
2041}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002042
Reid Kleckner3567d272015-04-02 21:13:31 +00002043void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2044 // Catch parameter objects have to live in the parent frame. When we see a use
2045 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2046 // used from another handler. This will prevent us from trying to sink the
2047 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002048 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002049 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2050}
2051
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002052// This function maps the catch and cleanup handlers that are reachable from the
2053// specified landing pad. The landing pad sequence will have this basic shape:
2054//
2055// <cleanup handler>
2056// <selector comparison>
2057// <catch handler>
2058// <cleanup handler>
2059// <selector comparison>
2060// <catch handler>
2061// <cleanup handler>
2062// ...
2063//
2064// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2065// any arbitrary control flow, but all paths through the cleanup code must
2066// eventually reach the next selector comparison and no path can skip to a
2067// different selector comparisons, though some paths may terminate abnormally.
2068// Therefore, we will use a depth first search from the start of any given
2069// cleanup block and stop searching when we find the next selector comparison.
2070//
2071// If the landingpad instruction does not have a catch clause, we will assume
2072// that any instructions other than selector comparisons and catch handlers can
2073// be ignored. In practice, these will only be the boilerplate instructions.
2074//
2075// The catch handlers may also have any control structure, but we are only
2076// interested in the start of the catch handlers, so we don't need to actually
2077// follow the flow of the catch handlers. The start of the catch handlers can
2078// be located from the compare instructions, but they can be skipped in the
2079// flow by following the contrary branch.
2080void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2081 LandingPadActions &Actions) {
2082 unsigned int NumClauses = LPad->getNumClauses();
2083 unsigned int HandlersFound = 0;
2084 BasicBlock *BB = LPad->getParent();
2085
2086 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2087
2088 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002089 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002090 return;
2091 }
2092
2093 VisitedBlockSet VisitedBlocks;
2094
2095 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002096 BasicBlock *NextBB = nullptr;
2097
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002098 // Skip over filter clauses.
2099 if (LPad->isFilter(HandlersFound)) {
2100 ++HandlersFound;
2101 continue;
2102 }
2103
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002104 // See if the clause we're looking for is a catch-all.
2105 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002106 Constant *ExpectedSelector =
2107 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002108 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002109 // The catch all must occur last.
2110 assert(HandlersFound == NumClauses - 1);
2111
Andrew Kaylorea8df612015-04-17 23:05:43 +00002112 // There can be additional selector dispatches in the call chain that we
2113 // need to ignore.
2114 BasicBlock *CatchBlock = nullptr;
2115 Constant *Selector;
2116 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2117 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002118 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002119 BB = NextBB;
2120 }
2121
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002122 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002123 CatchHandler *Action = nullptr;
2124 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2125 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2126 Action = CatchHandlerMap[BB];
2127 assert(Action->getSelector() == ExpectedSelector);
2128 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002129 // We don't expect a selector dispatch, but there may be a call to
2130 // llvm.eh.begincatch, which separates catch handling code from
2131 // cleanup code in the same control flow. This call looks for the
2132 // begincatch intrinsic.
2133 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2134 if (Action) {
2135 // For C++ EH, check if there is any interesting cleanup code before
2136 // we begin the catch. This is important because cleanups cannot
2137 // rethrow exceptions but code called from catches can. For SEH, it
2138 // isn't important if some finally code before a catch-all is executed
2139 // out of line or after recovering from the exception.
2140 if (Personality == EHPersonality::MSVC_CXX)
2141 findCleanupHandlers(Actions, BB, BB);
2142 } else {
2143 // If an action was not found, it means that the control flows
2144 // directly into the catch-all handler and there is no cleanup code.
2145 // That's an expected situation and we must create a catch action.
2146 // Since this is a catch-all handler, the selector won't actually
2147 // appear in the code anywhere. ExpectedSelector here is the constant
2148 // null ptr that we got from the landing pad instruction.
2149 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2150 CatchHandlerMap[BB] = Action;
2151 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002152 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002153 Actions.insertCatchHandler(Action);
2154 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2155 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002156
2157 // Once we reach a catch-all, don't expect to hit a resume instruction.
2158 BB = nullptr;
2159 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002160 }
2161
2162 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002163 assert(CatchAction);
2164
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002165 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002166 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002167
Andrew Kaylorea8df612015-04-17 23:05:43 +00002168 // When the source program contains multiple nested try blocks the catch
2169 // handlers can get strung together in such a way that we can encounter
2170 // a dispatch for a selector that we've already had a handler for.
2171 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2172 ++HandlersFound;
2173
2174 // Add the catch handler to the action list.
2175 DEBUG(dbgs() << " Found catch dispatch in block "
2176 << CatchAction->getStartBlock()->getName() << "\n");
2177 Actions.insertCatchHandler(CatchAction);
2178 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002179 // Under some circumstances optimized IR will flow unconditionally into a
2180 // handler block without checking the selector. This can only happen if
2181 // the landing pad has a catch-all handler and the handler for the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002182 // preceding catch clause is identical to the catch-call handler
Andrew Kaylor41758512015-04-20 22:04:09 +00002183 // (typically an empty catch). In this case, the handler must be shared
2184 // by all remaining clauses.
2185 if (isa<ConstantPointerNull>(
2186 CatchAction->getSelector()->stripPointerCasts())) {
2187 DEBUG(dbgs() << " Applying early catch-all handler in block "
2188 << CatchAction->getStartBlock()->getName()
2189 << " to all remaining clauses.\n");
2190 Actions.insertCatchHandler(CatchAction);
2191 return;
2192 }
2193
Andrew Kaylorea8df612015-04-17 23:05:43 +00002194 DEBUG(dbgs() << " Found extra catch dispatch in block "
2195 << CatchAction->getStartBlock()->getName() << "\n");
2196 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002197
2198 // Move on to the block after the catch handler.
2199 BB = NextBB;
2200 }
2201
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002202 // If we didn't wind up in a catch-all, see if there is any interesting code
2203 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002204 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002205
2206 // It's possible that some optimization moved code into a landingpad that
2207 // wasn't
2208 // previously being used for cleanup. If that happens, we need to execute
2209 // that
2210 // extra code from a cleanup handler.
2211 if (Actions.includesCleanup() && !LPad->isCleanup())
2212 LPad->setCleanup(true);
2213}
2214
2215// This function searches starting with the input block for the next
2216// block that terminates with a branch whose condition is based on a selector
2217// comparison. This may be the input block. See the mapLandingPadBlocks
2218// comments for a discussion of control flow assumptions.
2219//
2220CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2221 BasicBlock *&NextBB,
2222 VisitedBlockSet &VisitedBlocks) {
2223 // See if we've already found a catch handler use it.
2224 // Call count() first to avoid creating a null entry for blocks
2225 // we haven't seen before.
2226 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2227 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2228 NextBB = Action->getNextBB();
2229 return Action;
2230 }
2231
2232 // VisitedBlocks applies only to the current search. We still
2233 // need to consider blocks that we've visited while mapping other
2234 // landing pads.
2235 VisitedBlocks.insert(BB);
2236
2237 BasicBlock *CatchBlock = nullptr;
2238 Constant *Selector = nullptr;
2239
2240 // If this is the first time we've visited this block from any landing pad
2241 // look to see if it is a selector dispatch block.
2242 if (!CatchHandlerMap.count(BB)) {
2243 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2244 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2245 CatchHandlerMap[BB] = Action;
2246 return Action;
2247 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002248 // If we encounter a block containing an llvm.eh.begincatch before we
2249 // find a selector dispatch block, the handler is assumed to be
2250 // reached unconditionally. This happens for catch-all blocks, but
2251 // it can also happen for other catch handlers that have been combined
2252 // with the catch-all handler during optimization.
2253 if (isCatchBlock(BB)) {
2254 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2255 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2256 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2257 CatchHandlerMap[BB] = Action;
2258 return Action;
2259 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002260 }
2261
2262 // Visit each successor, looking for the dispatch.
2263 // FIXME: We expect to find the dispatch quickly, so this will probably
2264 // work better as a breadth first search.
2265 for (BasicBlock *Succ : successors(BB)) {
2266 if (VisitedBlocks.count(Succ))
2267 continue;
2268
2269 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2270 if (Action)
2271 return Action;
2272 }
2273 return nullptr;
2274}
2275
Reid Kleckner9405ef02015-04-10 23:12:29 +00002276// These are helper functions to combine repeated code from findCleanupHandlers.
2277static void createCleanupHandler(LandingPadActions &Actions,
2278 CleanupHandlerMapTy &CleanupHandlerMap,
2279 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002280 CleanupHandler *Action = new CleanupHandler(BB);
2281 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002282 Actions.insertCleanupHandler(Action);
2283 DEBUG(dbgs() << " Found cleanup code in block "
2284 << Action->getStartBlock()->getName() << "\n");
2285}
2286
Reid Kleckner9405ef02015-04-10 23:12:29 +00002287static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2288 Instruction *MaybeCall) {
2289 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002290 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002291 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002292 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002293 MaybeCall = MaybeCall->getNextNode();
2294 CallSite FinallyCall(MaybeCall);
2295 if (!FinallyCall || FinallyCall.arg_size() != 2)
2296 return CallSite();
2297 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2298 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002299 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002300 return CallSite();
2301 return FinallyCall;
2302}
2303
2304static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2305 // Skip single ubr blocks.
2306 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2307 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2308 if (Br && Br->isUnconditional())
2309 BB = Br->getSuccessor(0);
2310 else
2311 return BB;
2312 }
2313 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002314}
2315
2316// This function searches starting with the input block for the next block that
2317// contains code that is not part of a catch handler and would not be eliminated
2318// during handler outlining.
2319//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002320void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2321 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002322 // Here we will skip over the following:
2323 //
2324 // landing pad prolog:
2325 //
2326 // Unconditional branches
2327 //
2328 // Selector dispatch
2329 //
2330 // Resume pattern
2331 //
2332 // Anything else marks the start of an interesting block
2333
2334 BasicBlock *BB = StartBB;
2335 // Anything other than an unconditional branch will kick us out of this loop
2336 // one way or another.
2337 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002338 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002339 // If we've already scanned this block, don't scan it again. If it is
2340 // a cleanup block, there will be an action in the CleanupHandlerMap.
2341 // If we've scanned it and it is not a cleanup block, there will be a
2342 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2343 // be no entry in the CleanupHandlerMap. We must call count() first to
2344 // avoid creating a null entry for blocks we haven't scanned.
2345 if (CleanupHandlerMap.count(BB)) {
2346 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002347 Actions.insertCleanupHandler(Action);
2348 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002349 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002350 // FIXME: This cleanup might chain into another, and we need to discover
2351 // that.
2352 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002353 } else {
2354 // Here we handle the case where the cleanup handler map contains a
2355 // value for this block but the value is a nullptr. This means that
2356 // we have previously analyzed the block and determined that it did
2357 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002358 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002359 // resume or a conditional branch that is predicated on a comparison
2360 // with a selector. Either the resume or the selector dispatch
2361 // would terminate the search for cleanup code, so the unconditional
2362 // branch is the only case for which we might need to continue
2363 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002364 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2365 if (SuccBB == BB || SuccBB == EndBB)
2366 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002367 BB = SuccBB;
2368 continue;
2369 }
2370 }
2371
2372 // Create an entry in the cleanup handler map for this block. Initially
2373 // we create an entry that says this isn't a cleanup block. If we find
2374 // cleanup code, the caller will replace this entry.
2375 CleanupHandlerMap[BB] = nullptr;
2376
2377 TerminatorInst *Terminator = BB->getTerminator();
2378
2379 // Landing pad blocks have extra instructions we need to accept.
2380 LandingPadMap *LPadMap = nullptr;
2381 if (BB->isLandingPad()) {
2382 LandingPadInst *LPad = BB->getLandingPadInst();
2383 LPadMap = &LPadMaps[LPad];
2384 if (!LPadMap->isInitialized())
2385 LPadMap->mapLandingPad(LPad);
2386 }
2387
2388 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002389 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2390 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002391 // resume { i8*, i32 } %lpad.val2
2392 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2393 InsertValueInst *Insert1 = nullptr;
2394 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002395 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002396 // If the resume value isn't a phi or landingpad value, it should be a
2397 // series of insertions. Identify them so we can avoid them when scanning
2398 // for cleanups.
2399 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002400 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002401 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002402 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002403 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2404 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002405 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002406 }
2407 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2408 II != IE; ++II) {
2409 Instruction *Inst = II;
2410 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2411 continue;
2412 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2413 continue;
2414 if (!Inst->hasOneUse() ||
2415 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002416 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002417 }
2418 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002419 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002420 }
2421
2422 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002423 if (Branch && Branch->isConditional()) {
2424 // Look for the selector dispatch.
2425 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2426 // %matches = icmp eq i32 %sel, %2
2427 // br i1 %matches, label %catch14, label %eh.resume
2428 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2429 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002430 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002431 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2432 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002433 Instruction *Inst = II;
2434 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2435 continue;
2436 if (Inst == Compare || Inst == Branch)
2437 continue;
2438 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2439 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002440 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002441 }
2442 // The selector dispatch block should always terminate our search.
2443 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002444 return;
2445 }
2446
2447 if (isAsynchronousEHPersonality(Personality)) {
2448 // If this is a landingpad block, split the block at the first non-landing
2449 // pad instruction.
2450 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2451 if (LPadMap) {
2452 while (MaybeCall != BB->getTerminator() &&
2453 LPadMap->isLandingPadSpecificInst(MaybeCall))
2454 MaybeCall = MaybeCall->getNextNode();
2455 }
2456
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002457 // Look for outlined finally calls on x64, since those happen to match the
2458 // prototype provided by the runtime.
2459 if (TheTriple.getArch() == Triple::x86_64) {
2460 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2461 Function *Fin = FinallyCall.getCalledFunction();
2462 assert(Fin && "outlined finally call should be direct");
2463 auto *Action = new CleanupHandler(BB);
2464 Action->setHandlerBlockOrFunc(Fin);
2465 Actions.insertCleanupHandler(Action);
2466 CleanupHandlerMap[BB] = Action;
2467 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2468 << Fin->getName() << " in block "
2469 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002470
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002471 // Split the block if there were more interesting instructions and
2472 // look for finally calls in the normal successor block.
2473 BasicBlock *SuccBB = BB;
2474 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2475 FinallyCall.getInstruction()->getNextNode() !=
2476 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002477 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002478 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002479 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002480 if (FinallyCall.isInvoke()) {
2481 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2482 ->getNormalDest();
2483 } else {
2484 SuccBB = BB->getUniqueSuccessor();
2485 assert(SuccBB &&
2486 "splitOutlinedFinallyCalls didn't insert a branch");
2487 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002488 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002489 BB = SuccBB;
2490 if (BB == EndBB)
2491 return;
2492 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002493 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002494 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002495 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002496
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002497 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002498 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2499 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002500 Instruction *Inst = II;
2501 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2502 continue;
2503 // Unconditional branches fall through to this loop.
2504 if (Inst == Branch)
2505 continue;
2506 // If this is a catch block, there is no cleanup code to be found.
2507 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002508 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002509 // If this a nested landing pad, it may contain an endcatch call.
2510 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002511 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002512 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002513 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002514 }
2515
2516 // Only unconditional branches in empty blocks should get this far.
2517 assert(Branch && Branch->isUnconditional());
2518 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002519 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002520 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002521 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002522}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002523
2524// This is a public function, declared in WinEHFuncInfo.h and is also
2525// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002526void llvm::parseEHActions(
2527 const IntrinsicInst *II,
2528 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002529 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2530 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002531 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2532 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002533 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002534 if (ActionKind == /*catch=*/1) {
2535 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2536 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2537 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2538 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2539 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002540 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2541 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002542 CH->setHandlerBlockOrFunc(Handler);
2543 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002544 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002545 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002546 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2547 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002548 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002549 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002550 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002551 } else {
2552 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002553 }
2554 }
2555 std::reverse(Actions.begin(), Actions.end());
2556}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002557
2558namespace {
2559struct WinEHNumbering {
2560 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2561 CurrentBaseState(-1), NextState(0) {}
2562
2563 WinEHFuncInfo &FuncInfo;
2564 int CurrentBaseState;
2565 int NextState;
2566
2567 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2568 SmallPtrSet<const Function *, 4> VisitedHandlers;
2569
2570 int currentEHNumber() const {
2571 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2572 }
2573
2574 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2575 void createTryBlockMapEntry(int TryLow, int TryHigh,
2576 ArrayRef<CatchHandler *> Handlers);
2577 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2578 ImmutableCallSite CS);
2579 void popUnmatchedActions(int FirstMismatch);
2580 void calculateStateNumbers(const Function &F);
2581 void findActionRootLPads(const Function &F);
2582};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002583}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002584
David Majnemer0ad363e2015-08-18 19:07:12 +00002585static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
2586 const Value *V) {
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002587 WinEHUnwindMapEntry UME;
2588 UME.ToState = ToState;
David Majnemer0ad363e2015-08-18 19:07:12 +00002589 UME.Cleanup = V;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002590 FuncInfo.UnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +00002591 return FuncInfo.getLastStateNumber();
2592}
2593
2594static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
2595 int TryHigh, int CatchHigh,
2596 ArrayRef<const CatchPadInst *> Handlers) {
2597 WinEHTryBlockMapEntry TBME;
2598 TBME.TryLow = TryLow;
2599 TBME.TryHigh = TryHigh;
2600 TBME.CatchHigh = CatchHigh;
2601 assert(TBME.TryLow <= TBME.TryHigh);
2602 for (const CatchPadInst *CPI : Handlers) {
2603 WinEHHandlerType HT;
2604 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
2605 if (TypeInfo->isNullValue()) {
2606 HT.Adjectives = 0x40;
2607 HT.TypeDescriptor = nullptr;
2608 } else {
2609 auto *GV = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
2610 // Selectors are always pointers to GlobalVariables with 'struct' type.
2611 // The struct has two fields, adjectives and a type descriptor.
2612 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2613 HT.Adjectives =
2614 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2615 HT.TypeDescriptor =
2616 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2617 }
Reid Kleckner0e288232015-08-27 23:27:47 +00002618 HT.Handler = CPI->getNormalDest();
2619 HT.HandlerMBB = nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +00002620 // FIXME: Pass CPI->getArgOperand(1).
2621 HT.CatchObjRecoverIdx = -1;
2622 TBME.HandlerArray.push_back(HT);
2623 }
2624 FuncInfo.TryBlockMap.push_back(TBME);
2625}
2626
2627void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2628 Value *V = nullptr;
2629 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2630 V = cast<Function>(CH->getHandlerBlockOrFunc());
2631 addUnwindMapEntry(FuncInfo, ToState, V);
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002632}
2633
2634void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2635 ArrayRef<CatchHandler *> Handlers) {
2636 // See if we already have an entry for this set of handlers.
2637 // This is using iterators rather than a range-based for loop because
2638 // if we find the entry we're looking for we'll need the iterator to erase it.
2639 int NumHandlers = Handlers.size();
2640 auto I = FuncInfo.TryBlockMap.begin();
2641 auto E = FuncInfo.TryBlockMap.end();
2642 for ( ; I != E; ++I) {
2643 auto &Entry = *I;
2644 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2645 continue;
2646 int N;
2647 for (N = 0; N < NumHandlers; ++N) {
2648 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2649 break; // breaks out of inner loop
2650 }
2651 // If all the handlers match, this is what we were looking for.
2652 if (N == NumHandlers) {
2653 break;
2654 }
2655 }
2656
2657 // If we found an existing entry for this set of handlers, extend the range
2658 // but move the entry to the end of the map vector. The order of entries
2659 // in the map is critical to the way that the runtime finds handlers.
2660 // FIXME: Depending on what has happened with block ordering, this may
2661 // incorrectly combine entries that should remain separate.
2662 if (I != E) {
2663 // Copy the existing entry.
2664 WinEHTryBlockMapEntry Entry = *I;
2665 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2666 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2667 assert(Entry.TryLow <= Entry.TryHigh);
2668 // Erase the old entry and add this one to the back.
2669 FuncInfo.TryBlockMap.erase(I);
2670 FuncInfo.TryBlockMap.push_back(Entry);
2671 return;
2672 }
2673
2674 // If we didn't find an entry, create a new one.
2675 WinEHTryBlockMapEntry TBME;
2676 TBME.TryLow = TryLow;
2677 TBME.TryHigh = TryHigh;
2678 assert(TBME.TryLow <= TBME.TryHigh);
2679 for (CatchHandler *CH : Handlers) {
2680 WinEHHandlerType HT;
2681 if (CH->getSelector()->isNullValue()) {
2682 HT.Adjectives = 0x40;
2683 HT.TypeDescriptor = nullptr;
2684 } else {
2685 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2686 // Selectors are always pointers to GlobalVariables with 'struct' type.
2687 // The struct has two fields, adjectives and a type descriptor.
2688 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2689 HT.Adjectives =
2690 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2691 HT.TypeDescriptor =
2692 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2693 }
2694 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
Reid Kleckner0e288232015-08-27 23:27:47 +00002695 HT.HandlerMBB = nullptr;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002696 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2697 TBME.HandlerArray.push_back(HT);
2698 }
2699 FuncInfo.TryBlockMap.push_back(TBME);
2700}
2701
2702static void print_name(const Value *V) {
2703#ifndef NDEBUG
2704 if (!V) {
2705 DEBUG(dbgs() << "null");
2706 return;
2707 }
2708
2709 if (const auto *F = dyn_cast<Function>(V))
2710 DEBUG(dbgs() << F->getName());
2711 else
2712 DEBUG(V->dump());
2713#endif
2714}
2715
2716void WinEHNumbering::processCallSite(
2717 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2718 ImmutableCallSite CS) {
2719 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2720 << ") for: ");
2721 print_name(CS ? CS.getCalledValue() : nullptr);
2722 DEBUG(dbgs() << '\n');
2723
2724 DEBUG(dbgs() << "HandlerStack: \n");
2725 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2726 DEBUG(dbgs() << " ");
2727 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2728 DEBUG(dbgs() << '\n');
2729 }
2730 DEBUG(dbgs() << "Actions: \n");
2731 for (int I = 0, E = Actions.size(); I < E; ++I) {
2732 DEBUG(dbgs() << " ");
2733 print_name(Actions[I]->getHandlerBlockOrFunc());
2734 DEBUG(dbgs() << '\n');
2735 }
2736 int FirstMismatch = 0;
2737 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2738 ++FirstMismatch) {
2739 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2740 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2741 break;
2742 }
2743
2744 // Remove unmatched actions from the stack and process their EH states.
2745 popUnmatchedActions(FirstMismatch);
2746
2747 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2748 print_name(CS ? CS.getCalledValue() : nullptr);
2749 DEBUG(dbgs() << '\n');
2750
2751 bool LastActionWasCatch = false;
2752 const LandingPadInst *LastRootLPad = nullptr;
2753 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2754 // We can reuse eh states when pushing two catches for the same invoke.
2755 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2756 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2757 // Various conditions can lead to a handler being popped from the
2758 // stack and re-pushed later. That shouldn't create a new state.
2759 // FIXME: Can code optimization lead to re-used handlers?
2760 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2761 // If we already assigned the state enclosed by this handler re-use it.
2762 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2763 continue;
2764 }
2765 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2766 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2767 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2768 Actions[I]->setEHState(currentEHNumber());
2769 } else {
2770 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2771 print_name(Actions[I]->getHandlerBlockOrFunc());
2772 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2773 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2774 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2775 Actions[I]->setEHState(NextState);
2776 NextState++;
2777 }
2778 HandlerStack.push_back(std::move(Actions[I]));
2779 LastActionWasCatch = CurrActionIsCatch;
2780 LastRootLPad = RootLPad;
2781 }
2782
2783 // This is used to defer numbering states for a handler until after the
2784 // last time it appears in an invoke action list.
2785 if (CS.isInvoke()) {
2786 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2787 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2788 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2789 continue;
2790 FuncInfo.LastInvokeVisited[Handler] = true;
2791 DEBUG(dbgs() << "Last invoke of ");
2792 print_name(Handler);
2793 DEBUG(dbgs() << " has been visited.\n");
2794 }
2795 }
2796
2797 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2798 print_name(CS ? CS.getCalledValue() : nullptr);
2799 DEBUG(dbgs() << '\n');
2800}
2801
2802void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2803 // Don't recurse while we are looping over the handler stack. Instead, defer
2804 // the numbering of the catch handlers until we are done popping.
2805 SmallVector<CatchHandler *, 4> PoppedCatches;
2806 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2807 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2808 if (isa<CatchHandler>(Handler.get()))
2809 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2810 }
2811
2812 int TryHigh = NextState - 1;
2813 int LastTryLowIdx = 0;
2814 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2815 CatchHandler *CH = PoppedCatches[I];
2816 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2817 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2818 int TryLow = CH->getEHState();
2819 auto Handlers =
2820 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2821 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2822 for (size_t J = 0; J < Handlers.size(); ++J) {
2823 DEBUG(dbgs() << ", ");
2824 print_name(Handlers[J]->getHandlerBlockOrFunc());
2825 }
2826 DEBUG(dbgs() << ")\n");
2827 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2828 LastTryLowIdx = I + 1;
2829 }
2830 }
2831
2832 for (CatchHandler *CH : PoppedCatches) {
2833 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2834 if (FuncInfo.LastInvokeVisited[F]) {
2835 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2836 print_name(F);
2837 DEBUG(dbgs() << '\n');
2838 FuncInfo.HandlerBaseState[F] = NextState;
2839 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2840 << ", null)\n");
2841 createUnwindMapEntry(currentEHNumber(), nullptr);
2842 ++NextState;
2843 calculateStateNumbers(*F);
2844 }
2845 else {
2846 DEBUG(dbgs() << "Deferring handling of ");
2847 print_name(F);
2848 DEBUG(dbgs() << " until last invoke visited.\n");
2849 }
2850 }
2851 delete CH;
2852 }
2853}
2854
2855void WinEHNumbering::calculateStateNumbers(const Function &F) {
2856 auto I = VisitedHandlers.insert(&F);
2857 if (!I.second)
2858 return; // We've already visited this handler, don't renumber it.
2859
2860 int OldBaseState = CurrentBaseState;
2861 if (FuncInfo.HandlerBaseState.count(&F)) {
2862 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2863 }
2864
2865 size_t SavedHandlerStackSize = HandlerStack.size();
2866
2867 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2868 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2869 for (const BasicBlock &BB : F) {
2870 for (const Instruction &I : BB) {
2871 const auto *CI = dyn_cast<CallInst>(&I);
2872 if (!CI || CI->doesNotThrow())
2873 continue;
2874 processCallSite(None, CI);
2875 }
2876 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2877 if (!II)
2878 continue;
2879 const LandingPadInst *LPI = II->getLandingPadInst();
2880 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2881 if (!ActionsCall)
2882 continue;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002883 parseEHActions(ActionsCall, ActionList);
2884 if (ActionList.empty())
2885 continue;
2886 processCallSite(ActionList, II);
2887 ActionList.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00002888 FuncInfo.EHPadStateMap[LPI] = currentEHNumber();
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002889 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2890 << " to landing pad at " << LPI->getParent()->getName()
2891 << '\n');
2892 }
2893
2894 // Pop any actions that were pushed on the stack for this function.
2895 popUnmatchedActions(SavedHandlerStackSize);
2896
2897 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2898 << " to " << F.getName() << '\n');
2899 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2900
2901 CurrentBaseState = OldBaseState;
2902}
2903
2904// This function follows the same basic traversal as calculateStateNumbers
2905// but it is necessary to identify the root landing pad associated
2906// with each action before we start assigning state numbers.
2907void WinEHNumbering::findActionRootLPads(const Function &F) {
2908 auto I = VisitedHandlers.insert(&F);
2909 if (!I.second)
2910 return; // We've already visited this handler, don't revisit it.
2911
2912 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2913 for (const BasicBlock &BB : F) {
2914 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2915 if (!II)
2916 continue;
2917 const LandingPadInst *LPI = II->getLandingPadInst();
2918 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2919 if (!ActionsCall)
2920 continue;
2921
2922 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2923 parseEHActions(ActionsCall, ActionList);
2924 if (ActionList.empty())
2925 continue;
2926 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2927 if (auto *Handler
2928 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2929 FuncInfo.LastInvoke[Handler] = II;
2930 // Don't replace the root landing pad if we previously saw this
2931 // handler in a different function.
2932 if (FuncInfo.RootLPad.count(Handler) &&
2933 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2934 continue;
2935 DEBUG(dbgs() << "Setting root lpad for ");
2936 print_name(Handler);
2937 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2938 FuncInfo.RootLPad[Handler] = LPI;
2939 }
2940 }
2941 // Walk the actions again and look for nested handlers. This has to
2942 // happen after all of the actions have been processed in the current
2943 // function.
2944 for (int I = 0, E = ActionList.size(); I < E; ++I)
2945 if (auto *Handler
2946 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2947 findActionRootLPads(*Handler);
2948 ActionList.clear();
2949 }
2950}
2951
David Majnemer0ad363e2015-08-18 19:07:12 +00002952static const BasicBlock *getSingleCatchPadPredecessor(const BasicBlock &BB) {
2953 for (const BasicBlock *PredBlock : predecessors(&BB))
2954 if (isa<CatchPadInst>(PredBlock->getFirstNonPHI()))
2955 return PredBlock;
2956 return nullptr;
2957}
2958
2959// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
2960// to. If the unwind edge came from an invoke, return null.
2961static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB) {
2962 const TerminatorInst *TI = BB->getTerminator();
2963 if (isa<InvokeInst>(TI))
2964 return nullptr;
2965 if (isa<CatchPadInst>(TI) || isa<CatchEndPadInst>(TI) ||
2966 isa<TerminatePadInst>(TI))
2967 return BB;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002968 return cast<CleanupReturnInst>(TI)->getCleanupPad()->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +00002969}
2970
2971static void calculateExplicitStateNumbers(WinEHFuncInfo &FuncInfo,
2972 const BasicBlock &BB,
2973 int ParentState) {
2974 assert(BB.isEHPad());
2975 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
2976 // All catchpad instructions will be handled when we process their
2977 // respective catchendpad instruction.
2978 if (isa<CatchPadInst>(FirstNonPHI))
2979 return;
2980
2981 if (isa<CatchEndPadInst>(FirstNonPHI)) {
2982 const BasicBlock *TryPad = &BB;
2983 const BasicBlock *LastTryPad = nullptr;
2984 SmallVector<const CatchPadInst *, 2> Handlers;
2985 do {
2986 LastTryPad = TryPad;
2987 TryPad = getSingleCatchPadPredecessor(*TryPad);
2988 if (TryPad)
2989 Handlers.push_back(cast<CatchPadInst>(TryPad->getFirstNonPHI()));
2990 } while (TryPad);
2991 // We've pushed these back into reverse source order. Reverse them to get
2992 // the list back into source order.
2993 std::reverse(Handlers.begin(), Handlers.end());
2994 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
2995 FuncInfo.EHPadStateMap[Handlers.front()] = TryLow;
2996 for (const BasicBlock *PredBlock : predecessors(LastTryPad))
2997 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
2998 calculateExplicitStateNumbers(FuncInfo, *PredBlock, TryLow);
2999 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
3000 FuncInfo.EHPadStateMap[FirstNonPHI] = CatchLow;
3001 int TryHigh = CatchLow - 1;
3002 for (const BasicBlock *PredBlock : predecessors(&BB))
3003 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3004 calculateExplicitStateNumbers(FuncInfo, *PredBlock, CatchLow);
3005 int CatchHigh = FuncInfo.getLastStateNumber();
3006 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
3007 DEBUG(dbgs() << "TryLow[" << LastTryPad->getName() << "]: " << TryLow
3008 << '\n');
3009 DEBUG(dbgs() << "TryHigh[" << LastTryPad->getName() << "]: " << TryHigh
3010 << '\n');
3011 DEBUG(dbgs() << "CatchHigh[" << LastTryPad->getName() << "]: " << CatchHigh
3012 << '\n');
3013 } else if (isa<CleanupPadInst>(FirstNonPHI)) {
3014 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, &BB);
3015 FuncInfo.EHPadStateMap[FirstNonPHI] = CleanupState;
3016 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
3017 << BB.getName() << '\n');
3018 for (const BasicBlock *PredBlock : predecessors(&BB))
3019 if ((PredBlock = getEHPadFromPredecessor(PredBlock)))
3020 calculateExplicitStateNumbers(FuncInfo, *PredBlock, CleanupState);
3021 } else if (isa<TerminatePadInst>(FirstNonPHI)) {
3022 report_fatal_error("Not yet implemented!");
3023 } else {
3024 llvm_unreachable("unexpected EH Pad!");
3025 }
3026}
3027
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003028void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
3029 WinEHFuncInfo &FuncInfo) {
3030 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +00003031 if (!FuncInfo.EHPadStateMap.empty())
3032 return;
3033
3034 bool IsExplicit = false;
3035 for (const BasicBlock &BB : *ParentFn) {
3036 if (!BB.isEHPad())
3037 continue;
3038 // Check if the EH Pad has no exceptional successors (i.e. it unwinds to
3039 // caller). Cleanups are a little bit of a special case because their
3040 // control flow cannot be determined by looking at the pad but instead by
3041 // the pad's users.
3042 bool HasNoSuccessors = false;
3043 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
3044 if (FirstNonPHI->mayThrow()) {
3045 HasNoSuccessors = true;
3046 } else if (auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI)) {
3047 HasNoSuccessors =
3048 CPI->use_empty() ||
3049 cast<CleanupReturnInst>(CPI->user_back())->unwindsToCaller();
3050 }
3051
3052 if (!HasNoSuccessors)
3053 continue;
3054 calculateExplicitStateNumbers(FuncInfo, BB, -1);
3055 IsExplicit = true;
3056 }
3057
3058 if (IsExplicit)
Reid Klecknerfe4d4912015-05-28 22:00:24 +00003059 return;
3060
3061 WinEHNumbering Num(FuncInfo);
3062 Num.findActionRootLPads(*ParentFn);
3063 // The VisitedHandlers list is used by both findActionRootLPads and
3064 // calculateStateNumbers, but both functions need to visit all handlers.
3065 Num.VisitedHandlers.clear();
3066 Num.calculateStateNumbers(*ParentFn);
3067 // Pop everything on the handler stack.
3068 // It may be necessary to call this more than once because a handler can
3069 // be pushed on the stack as a result of clearing the stack.
3070 while (!Num.HandlerStack.empty())
3071 Num.processCallSite(None, ImmutableCallSite());
3072}
David Majnemerfd9f4772015-08-11 01:15:26 +00003073
Joseph Tremouletec182852015-08-28 01:12:35 +00003074void WinEHPrepare::colorFunclets(Function &F,
3075 SmallVectorImpl<BasicBlock *> &EntryBlocks) {
3076 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 16> Worklist;
3077 BasicBlock *EntryBlock = &F.getEntryBlock();
David Majnemerfd9f4772015-08-11 01:15:26 +00003078
Joseph Tremouletec182852015-08-28 01:12:35 +00003079 // Build up the color map, which maps each block to its set of 'colors'.
3080 // For any block B, the "colors" of B are the set of funclets F (possibly
3081 // including a root "funclet" representing the main function), such that
3082 // F will need to directly contain B or a copy of B (where the term "directly
3083 // contain" is used to distinguish from being "transitively contained" in
3084 // a nested funclet).
3085 // Use a CFG walk driven by a worklist of (block, color) pairs. The "color"
3086 // sets attached during this processing to a block which is the entry of some
3087 // funclet F is actually the set of F's parents -- i.e. the union of colors
3088 // of all predecessors of F's entry. For all other blocks, the color sets
3089 // are as defined above. A post-pass fixes up the block color map to reflect
3090 // the same sense of "color" for funclet entries as for other blocks.
3091
3092 Worklist.push_back({EntryBlock, EntryBlock});
David Majnemerfd9f4772015-08-11 01:15:26 +00003093
3094 while (!Worklist.empty()) {
Joseph Tremouletec182852015-08-28 01:12:35 +00003095 BasicBlock *Visiting;
3096 BasicBlock *Color;
3097 std::tie(Visiting, Color) = Worklist.pop_back_val();
3098 Instruction *VisitingHead = Visiting->getFirstNonPHI();
3099 if (VisitingHead->isEHPad() && !isa<CatchEndPadInst>(VisitingHead)) {
3100 // Mark this as a funclet head as a member of itself.
3101 FuncletBlocks[Visiting].insert(Visiting);
3102 // Queue exits with the parent color.
3103 for (User *Exit : VisitingHead->users()) {
3104 for (BasicBlock *Succ :
3105 successors(cast<Instruction>(Exit)->getParent())) {
3106 if (BlockColors[Succ].insert(Color).second) {
3107 Worklist.push_back({Succ, Color});
3108 }
3109 }
3110 }
3111 // Handle CatchPad specially since its successors need different colors.
3112 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(VisitingHead)) {
3113 // Visit the normal successor with the color of the new EH pad, and
3114 // visit the unwind successor with the color of the parent.
3115 BasicBlock *NormalSucc = CatchPad->getNormalDest();
3116 if (BlockColors[NormalSucc].insert(Visiting).second) {
3117 Worklist.push_back({NormalSucc, Visiting});
3118 }
3119 BasicBlock *UnwindSucc = CatchPad->getUnwindDest();
3120 if (BlockColors[UnwindSucc].insert(Color).second) {
3121 Worklist.push_back({UnwindSucc, Color});
3122 }
3123 continue;
3124 }
3125 // Switch color to the current node, except for terminate pads which
3126 // have no bodies and only unwind successors and so need their successors
3127 // visited with the color of the parent.
3128 if (!isa<TerminatePadInst>(VisitingHead))
3129 Color = Visiting;
3130 } else {
3131 // Note that this is a member of the given color.
3132 FuncletBlocks[Color].insert(Visiting);
3133 TerminatorInst *Terminator = Visiting->getTerminator();
3134 if (isa<CleanupReturnInst>(Terminator) ||
3135 isa<CatchReturnInst>(Terminator)) {
3136 // These block's successors have already been queued with the parent
3137 // color.
3138 continue;
3139 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003140 }
Joseph Tremouletec182852015-08-28 01:12:35 +00003141 for (BasicBlock *Succ : successors(Visiting)) {
3142 if (isa<CatchEndPadInst>(Succ->getFirstNonPHI())) {
3143 // The catchendpad needs to be visited with the parent's color, not
3144 // the current color. This will happen in the code above that visits
3145 // any catchpad unwind successor with the parent color, so we can
3146 // safely skip this successor here.
3147 continue;
3148 }
3149 if (BlockColors[Succ].insert(Color).second) {
3150 Worklist.push_back({Succ, Color});
3151 }
3152 }
3153 }
David Majnemerfd9f4772015-08-11 01:15:26 +00003154
Joseph Tremouletec182852015-08-28 01:12:35 +00003155 // The processing above actually accumulated the parent set for this
3156 // funclet into the color set for its entry; use the parent set to
3157 // populate the children map, and reset the color set to include just
3158 // the funclet itself (no instruction can target a funclet entry except on
3159 // that transitions to the child funclet).
3160 for (BasicBlock *FuncletEntry : EntryBlocks) {
3161 std::set<BasicBlock *> &ColorMapItem = BlockColors[FuncletEntry];
3162 for (BasicBlock *Parent : ColorMapItem)
3163 FuncletChildren[Parent].insert(FuncletEntry);
3164 ColorMapItem.clear();
3165 ColorMapItem.insert(FuncletEntry);
David Majnemerfd9f4772015-08-11 01:15:26 +00003166 }
3167}
3168
Joseph Tremouletec182852015-08-28 01:12:35 +00003169bool WinEHPrepare::prepareExplicitEH(
3170 Function &F, SmallVectorImpl<BasicBlock *> &EntryBlocks) {
David Majnemerfd9f4772015-08-11 01:15:26 +00003171 // Remove unreachable blocks. It is not valuable to assign them a color and
3172 // their existence can trick us into thinking values are alive when they are
3173 // not.
3174 removeUnreachableBlocks(F);
3175
Joseph Tremouletec182852015-08-28 01:12:35 +00003176 // Determine which blocks are reachable from which funclet entries.
3177 colorFunclets(F, EntryBlocks);
David Majnemerfd9f4772015-08-11 01:15:26 +00003178
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003179 // Strip PHI nodes off of EH pads.
3180 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +00003181 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3182 BasicBlock *BB = FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00003183 if (!BB->isEHPad())
3184 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +00003185 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3186 Instruction *I = BI++;
3187 auto *PN = dyn_cast<PHINode>(I);
3188 // Stop at the first non-PHI.
3189 if (!PN)
3190 break;
David Majnemerfd9f4772015-08-11 01:15:26 +00003191
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003192 AllocaInst *SpillSlot = insertPHILoads(PN, F);
3193 if (SpillSlot)
3194 insertPHIStores(PN, SpillSlot);
3195
3196 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +00003197 }
3198 }
3199
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003200 for (auto *PN : PHINodes) {
3201 // There may be lingering uses on other EH PHIs being removed
3202 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
3203 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +00003204 }
3205
3206 // Turn all inter-funclet uses of a Value into loads and stores.
3207 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3208 BasicBlock *BB = FI++;
3209 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3210 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3211 Instruction *I = BI++;
3212 // Funclets are permitted to use static allocas.
3213 if (auto *AI = dyn_cast<AllocaInst>(I))
3214 if (AI->isStaticAlloca())
3215 continue;
3216
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003217 demoteNonlocalUses(I, ColorsForBB, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003218 }
3219 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003220 // Also demote function parameters used in funclets.
3221 std::set<BasicBlock *> &ColorsForEntry = BlockColors[&F.getEntryBlock()];
3222 for (Argument &Arg : F.args())
3223 demoteNonlocalUses(&Arg, ColorsForEntry, F);
David Majnemerfd9f4772015-08-11 01:15:26 +00003224
3225 // We need to clone all blocks which belong to multiple funclets. Values are
3226 // remapped throughout the funclet to propogate both the new instructions
3227 // *and* the new basic blocks themselves.
Joseph Tremouletec182852015-08-28 01:12:35 +00003228 for (BasicBlock *FuncletPadBB : EntryBlocks) {
3229 std::set<BasicBlock *> &BlocksInFunclet = FuncletBlocks[FuncletPadBB];
David Majnemerfd9f4772015-08-11 01:15:26 +00003230
3231 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3232 ValueToValueMapTy VMap;
3233 for (BasicBlock *BB : BlocksInFunclet) {
3234 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3235 // We don't need to do anything if the block is monochromatic.
3236 size_t NumColorsForBB = ColorsForBB.size();
3237 if (NumColorsForBB == 1)
3238 continue;
3239
David Majnemerfd9f4772015-08-11 01:15:26 +00003240 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +00003241 BasicBlock *CBB =
3242 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
3243 // Insert the clone immediately after the original to ensure determinism
3244 // and to keep the same relative ordering of any funclet's blocks.
3245 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +00003246
3247 // Add basic block mapping.
3248 VMap[BB] = CBB;
3249
3250 // Record delta operations that we need to perform to our color mappings.
3251 Orig2Clone[BB] = CBB;
3252 }
3253
3254 // Update our color mappings to reflect that one block has lost a color and
3255 // another has gained a color.
3256 for (auto &BBMapping : Orig2Clone) {
3257 BasicBlock *OldBlock = BBMapping.first;
3258 BasicBlock *NewBlock = BBMapping.second;
3259
3260 BlocksInFunclet.insert(NewBlock);
3261 BlockColors[NewBlock].insert(FuncletPadBB);
3262
3263 BlocksInFunclet.erase(OldBlock);
3264 BlockColors[OldBlock].erase(FuncletPadBB);
3265 }
3266
3267 // Loop over all of the instructions in the function, fixing up operand
3268 // references as we go. This uses VMap to do all the hard work.
3269 for (BasicBlock *BB : BlocksInFunclet)
3270 // Loop over all instructions, fixing each one as we find it...
3271 for (Instruction &I : *BB)
3272 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3273 }
3274
David Majnemer83f4bb22015-08-17 20:56:39 +00003275 // Remove implausible terminators and replace them with UnreachableInst.
3276 for (auto &Funclet : FuncletBlocks) {
3277 BasicBlock *FuncletPadBB = Funclet.first;
3278 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3279 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
3280 auto *CatchPad = dyn_cast<CatchPadInst>(FirstNonPHI);
3281 auto *CleanupPad = dyn_cast<CleanupPadInst>(FirstNonPHI);
3282
3283 for (BasicBlock *BB : BlocksInFunclet) {
3284 TerminatorInst *TI = BB->getTerminator();
3285 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
3286 bool IsUnreachableRet = isa<ReturnInst>(TI) && (CatchPad || CleanupPad);
3287 // The token consumed by a CatchReturnInst must match the funclet token.
3288 bool IsUnreachableCatchret = false;
3289 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003290 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
David Majnemer83f4bb22015-08-17 20:56:39 +00003291 // The token consumed by a CleanupPadInst must match the funclet token.
3292 bool IsUnreachableCleanupret = false;
3293 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003294 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
David Majnemer83f4bb22015-08-17 20:56:39 +00003295 if (IsUnreachableRet || IsUnreachableCatchret || IsUnreachableCleanupret) {
3296 new UnreachableInst(BB->getContext(), TI);
3297 TI->eraseFromParent();
3298 }
3299 }
3300 }
3301
David Majnemerfd9f4772015-08-11 01:15:26 +00003302 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3303 // branches, etc.
3304 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3305 BasicBlock *BB = FI++;
3306 SimplifyInstructionsInBlock(BB);
3307 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3308 MergeBlockIntoPredecessor(BB);
3309 }
3310
David Majnemerfd9f4772015-08-11 01:15:26 +00003311 // We might have some unreachable blocks after cleaning up some impossible
3312 // control flow.
3313 removeUnreachableBlocks(F);
3314
3315 // Recolor the CFG to verify that all is well.
3316 for (BasicBlock &BB : F) {
3317 size_t NumColors = BlockColors[&BB].size();
3318 assert(NumColors == 1 && "Expected monochromatic BB!");
3319 if (NumColors == 0)
3320 report_fatal_error("Uncolored BB!");
3321 if (NumColors > 1)
3322 report_fatal_error("Multicolor BB!");
3323 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3324 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3325 if (EHPadHasPHI)
3326 report_fatal_error("EH Pad still has a PHI!");
3327 }
3328
3329 BlockColors.clear();
3330 FuncletBlocks.clear();
Joseph Tremouletec182852015-08-28 01:12:35 +00003331 FuncletChildren.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00003332
David Majnemerfd9f4772015-08-11 01:15:26 +00003333 return true;
3334}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003335
3336// TODO: Share loads when one use dominates another, or when a catchpad exit
3337// dominates uses (needs dominators).
3338AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
3339 BasicBlock *PHIBlock = PN->getParent();
3340 AllocaInst *SpillSlot = nullptr;
3341
3342 if (isa<CleanupPadInst>(PHIBlock->getFirstNonPHI())) {
3343 // Insert a load in place of the PHI and replace all uses.
3344 SpillSlot = new AllocaInst(PN->getType(), nullptr,
3345 Twine(PN->getName(), ".wineh.spillslot"),
3346 F.getEntryBlock().begin());
3347 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
3348 PHIBlock->getFirstInsertionPt());
3349 PN->replaceAllUsesWith(V);
3350 return SpillSlot;
3351 }
3352
3353 DenseMap<BasicBlock *, Value *> Loads;
3354 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
3355 UI != UE;) {
3356 Use &U = *UI++;
3357 auto *UsingInst = cast<Instruction>(U.getUser());
3358 BasicBlock *UsingBB = UsingInst->getParent();
3359 if (UsingBB->isEHPad()) {
3360 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
3361 // stores for it separately.
3362 assert(isa<PHINode>(UsingInst));
3363 continue;
3364 }
3365 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
3366 }
3367 return SpillSlot;
3368}
3369
3370// TODO: improve store placement. Inserting at def is probably good, but need
3371// to be careful not to introduce interfering stores (needs liveness analysis).
3372// TODO: identify related phi nodes that can share spill slots, and share them
3373// (also needs liveness).
3374void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
3375 AllocaInst *SpillSlot) {
3376 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
3377 // stored to the spill slot by the end of the given Block.
3378 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
3379
3380 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
3381
3382 while (!Worklist.empty()) {
3383 BasicBlock *EHBlock;
3384 Value *InVal;
3385 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
3386
3387 PHINode *PN = dyn_cast<PHINode>(InVal);
3388 if (PN && PN->getParent() == EHBlock) {
3389 // The value is defined by another PHI we need to remove, with no room to
3390 // insert a store after the PHI, so each predecessor needs to store its
3391 // incoming value.
3392 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
3393 Value *PredVal = PN->getIncomingValue(i);
3394
3395 // Undef can safely be skipped.
3396 if (isa<UndefValue>(PredVal))
3397 continue;
3398
3399 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
3400 }
3401 } else {
3402 // We need to store InVal, which dominates EHBlock, but can't put a store
3403 // in EHBlock, so need to put stores in each predecessor.
3404 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
3405 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
3406 }
3407 }
3408 }
3409}
3410
3411void WinEHPrepare::insertPHIStore(
3412 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
3413 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
3414
3415 if (PredBlock->isEHPad() &&
3416 !isa<CleanupPadInst>(PredBlock->getFirstNonPHI())) {
3417 // Pred is unsplittable, so we need to queue it on the worklist.
3418 Worklist.push_back({PredBlock, PredVal});
3419 return;
3420 }
3421
3422 // Otherwise, insert the store at the end of the basic block.
3423 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
3424}
3425
3426// TODO: Share loads for same-funclet uses (requires dominators if funclets
3427// aren't properly nested).
3428void WinEHPrepare::demoteNonlocalUses(Value *V,
3429 std::set<BasicBlock *> &ColorsForBB,
3430 Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +00003431 // Tokens can only be used non-locally due to control flow involving
3432 // unreachable edges. Don't try to demote the token usage, we'll simply
3433 // delete the cloned user later.
3434 if (isa<CatchPadInst>(V) || isa<CleanupPadInst>(V))
3435 return;
3436
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003437 DenseMap<BasicBlock *, Value *> Loads;
3438 AllocaInst *SpillSlot = nullptr;
3439 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;) {
3440 Use &U = *UI++;
3441 auto *UsingInst = cast<Instruction>(U.getUser());
3442 BasicBlock *UsingBB = UsingInst->getParent();
3443
Joseph Tremouletec182852015-08-28 01:12:35 +00003444 // Is the Use inside a block which is colored the same as the Def?
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003445 // If so, we don't need to escape the Def because we will clone
3446 // ourselves our own private copy.
3447 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
Joseph Tremouletec182852015-08-28 01:12:35 +00003448 if (ColorsForUsingBB == ColorsForBB)
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003449 continue;
3450
3451 replaceUseWithLoad(V, U, SpillSlot, Loads, F);
3452 }
3453 if (SpillSlot) {
3454 // Insert stores of the computed value into the stack slot.
3455 // We have to be careful if I is an invoke instruction,
3456 // because we can't insert the store AFTER the terminator instruction.
3457 BasicBlock::iterator InsertPt;
3458 if (isa<Argument>(V)) {
3459 InsertPt = F.getEntryBlock().getTerminator();
3460 } else if (isa<TerminatorInst>(V)) {
3461 auto *II = cast<InvokeInst>(V);
3462 // We cannot demote invoke instructions to the stack if their normal
3463 // edge is critical. Therefore, split the critical edge and create a
3464 // basic block into which the store can be inserted.
3465 if (!II->getNormalDest()->getSinglePredecessor()) {
3466 unsigned SuccNum =
3467 GetSuccessorNumber(II->getParent(), II->getNormalDest());
3468 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3469 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3470 assert(NewBlock && "Unable to split critical edge.");
3471 // Update the color mapping for the newly split edge.
3472 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[II->getParent()];
3473 BlockColors[NewBlock] = ColorsForUsingBB;
3474 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3475 FuncletBlocks[FuncletPad].insert(NewBlock);
3476 }
3477 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3478 } else {
3479 InsertPt = cast<Instruction>(V);
3480 ++InsertPt;
3481 // Don't insert before PHI nodes or EH pad instrs.
3482 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3483 ;
3484 }
3485 new StoreInst(V, SpillSlot, InsertPt);
3486 }
3487}
3488
3489void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
3490 DenseMap<BasicBlock *, Value *> &Loads,
3491 Function &F) {
3492 // Lazilly create the spill slot.
3493 if (!SpillSlot)
3494 SpillSlot = new AllocaInst(V->getType(), nullptr,
3495 Twine(V->getName(), ".wineh.spillslot"),
3496 F.getEntryBlock().begin());
3497
3498 auto *UsingInst = cast<Instruction>(U.getUser());
3499 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
3500 // If this is a PHI node, we can't insert a load of the value before
3501 // the use. Instead insert the load in the predecessor block
3502 // corresponding to the incoming value.
3503 //
3504 // Note that if there are multiple edges from a basic block to this
3505 // PHI node that we cannot have multiple loads. The problem is that
3506 // the resulting PHI node will have multiple values (from each load)
3507 // coming in from the same block, which is illegal SSA form.
3508 // For this reason, we keep track of and reuse loads we insert.
3509 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00003510 if (auto *CatchRet =
3511 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
3512 // Putting a load above a catchret and use on the phi would still leave
3513 // a cross-funclet def/use. We need to split the edge, change the
3514 // catchret to target the new block, and put the load there.
3515 BasicBlock *PHIBlock = UsingInst->getParent();
3516 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
3517 // SplitEdge gives us:
3518 // IncomingBlock:
3519 // ...
3520 // br label %NewBlock
3521 // NewBlock:
3522 // catchret label %PHIBlock
3523 // But we need:
3524 // IncomingBlock:
3525 // ...
3526 // catchret label %NewBlock
3527 // NewBlock:
3528 // br label %PHIBlock
3529 // So move the terminators to each others' blocks and swap their
3530 // successors.
3531 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
3532 Goto->removeFromParent();
3533 CatchRet->removeFromParent();
3534 IncomingBlock->getInstList().push_back(CatchRet);
3535 NewBlock->getInstList().push_back(Goto);
3536 Goto->setSuccessor(0, PHIBlock);
3537 CatchRet->setSuccessor(NewBlock);
3538 // Update the color mapping for the newly split edge.
3539 std::set<BasicBlock *> &ColorsForPHIBlock = BlockColors[PHIBlock];
3540 BlockColors[NewBlock] = ColorsForPHIBlock;
3541 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
3542 FuncletBlocks[FuncletPad].insert(NewBlock);
3543 // Treat the new block as incoming for load insertion.
3544 IncomingBlock = NewBlock;
3545 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00003546 Value *&Load = Loads[IncomingBlock];
3547 // Insert the load into the predecessor block
3548 if (!Load)
3549 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3550 /*Volatile=*/false, IncomingBlock->getTerminator());
3551
3552 U.set(Load);
3553 } else {
3554 // Reload right before the old use.
3555 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
3556 /*Volatile=*/false, UsingInst);
3557 U.set(Load);
3558 }
3559}