blob: 83ae82353aae06b77c98ba9687a3c361dcb44909 [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);
124
David Majnemerfd9f4772015-08-11 01:15:26 +0000125 bool prepareExplicitEH(Function &F);
126 void numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB);
127
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000128 Triple TheTriple;
129
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000130 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +0000131 DominatorTree *DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +0000132 const TargetLibraryInfo *LibInfo = nullptr;
Reid Kleckner582786b2015-04-30 18:17:12 +0000133 EHPersonality Personality = EHPersonality::Unknown;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000134 CatchHandlerMapTy CatchHandlerMap;
135 CleanupHandlerMapTy CleanupHandlerMap;
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000136 DenseMap<const LandingPadInst *, LandingPadMap> LPadMaps;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000137 SmallPtrSet<BasicBlock *, 4> NormalBlocks;
138 SmallPtrSet<BasicBlock *, 4> EHBlocks;
139 SetVector<BasicBlock *> EHReturnBlocks;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000140
141 // This maps landing pad instructions found in outlined handlers to
142 // the landing pad instruction in the parent function from which they
143 // were cloned. The cloned/nested landing pad is used as the key
144 // because the landing pad may be cloned into multiple handlers.
145 // This map will be used to add the llvm.eh.actions call to the nested
146 // landing pads after all handlers have been outlined.
147 DenseMap<LandingPadInst *, const LandingPadInst *> NestedLPtoOriginalLP;
148
149 // This maps blocks in the parent function which are destinations of
150 // catch handlers to cloned blocks in (other) outlined handlers. This
151 // handles the case where a nested landing pads has a catch handler that
152 // returns to a handler function rather than the parent function.
153 // The original block is used as the key here because there should only
154 // ever be one handler function from which the cloned block is not pruned.
155 // The original block will be pruned from the parent function after all
156 // handlers have been outlined. This map will be used to adjust the
157 // return instructions of handlers which return to the block that was
158 // outlined into a handler. This is done after all handlers have been
159 // outlined but before the outlined code is pruned from the parent function.
160 DenseMap<const BasicBlock *, BasicBlock *> LPadTargetBlocks;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000161
Reid Klecknerd5afc62f2015-07-07 23:23:03 +0000162 // Map from outlined handler to call to parent local address. Only used for
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000163 // 32-bit EH.
164 DenseMap<Function *, Value *> HandlerToParentFP;
165
Reid Kleckner582786b2015-04-30 18:17:12 +0000166 AllocaInst *SEHExceptionCodeSlot = nullptr;
David Majnemerfd9f4772015-08-11 01:15:26 +0000167
168 std::map<BasicBlock *, std::set<BasicBlock *>> BlockColors;
169 std::map<BasicBlock *, std::set<BasicBlock *>> FuncletBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000170};
171
172class WinEHFrameVariableMaterializer : public ValueMaterializer {
173public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000174 WinEHFrameVariableMaterializer(Function *OutlinedFn, Value *ParentFP,
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000175 FrameVarInfoMap &FrameVarInfo);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000176 ~WinEHFrameVariableMaterializer() override {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000177
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000178 Value *materializeValueFor(Value *V) override;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000179
Reid Kleckner3567d272015-04-02 21:13:31 +0000180 void escapeCatchObject(Value *V);
181
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000182private:
183 FrameVarInfoMap &FrameVarInfo;
184 IRBuilder<> Builder;
185};
186
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000187class LandingPadMap {
188public:
189 LandingPadMap() : OriginLPad(nullptr) {}
190 void mapLandingPad(const LandingPadInst *LPad);
191
192 bool isInitialized() { return OriginLPad != nullptr; }
193
Andrew Kaylorf7118ae2015-03-27 22:31:12 +0000194 bool isOriginLandingPadBlock(const BasicBlock *BB) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000195 bool isLandingPadSpecificInst(const Instruction *Inst) const;
196
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000197 void remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
198 Value *SelectorValue) const;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000199
200private:
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000201 const LandingPadInst *OriginLPad;
202 // We will normally only see one of each of these instructions, but
203 // if more than one occurs for some reason we can handle that.
204 TinyPtrVector<const ExtractValueInst *> ExtractedEHPtrs;
205 TinyPtrVector<const ExtractValueInst *> ExtractedSelectors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000206};
207
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000208class WinEHCloningDirectorBase : public CloningDirector {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000209public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000210 WinEHCloningDirectorBase(Function *HandlerFn, Value *ParentFP,
211 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
212 : Materializer(HandlerFn, ParentFP, VarInfo),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000213 SelectorIDType(Type::getInt32Ty(HandlerFn->getContext())),
214 Int8PtrType(Type::getInt8PtrTy(HandlerFn->getContext())),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000215 LPadMap(LPadMap), ParentFP(ParentFP) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000216
217 CloningAction handleInstruction(ValueToValueMapTy &VMap,
218 const Instruction *Inst,
219 BasicBlock *NewBB) override;
220
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000221 virtual CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
222 const Instruction *Inst,
223 BasicBlock *NewBB) = 0;
224 virtual CloningAction handleEndCatch(ValueToValueMapTy &VMap,
225 const Instruction *Inst,
226 BasicBlock *NewBB) = 0;
227 virtual CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
228 const Instruction *Inst,
229 BasicBlock *NewBB) = 0;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000230 virtual CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
231 const IndirectBrInst *IBr,
232 BasicBlock *NewBB) = 0;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000233 virtual CloningAction handleInvoke(ValueToValueMapTy &VMap,
234 const InvokeInst *Invoke,
235 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000236 virtual CloningAction handleResume(ValueToValueMapTy &VMap,
237 const ResumeInst *Resume,
238 BasicBlock *NewBB) = 0;
Andrew Kaylorea8df612015-04-17 23:05:43 +0000239 virtual CloningAction handleCompare(ValueToValueMapTy &VMap,
240 const CmpInst *Compare,
241 BasicBlock *NewBB) = 0;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000242 virtual CloningAction handleLandingPad(ValueToValueMapTy &VMap,
243 const LandingPadInst *LPad,
244 BasicBlock *NewBB) = 0;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000245
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000246 ValueMaterializer *getValueMaterializer() override { return &Materializer; }
247
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000248protected:
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000249 WinEHFrameVariableMaterializer Materializer;
250 Type *SelectorIDType;
251 Type *Int8PtrType;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000252 LandingPadMap &LPadMap;
Reid Klecknerf14787d2015-04-22 00:07:52 +0000253
254 /// The value representing the parent frame pointer.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000255 Value *ParentFP;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000256};
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000257
258class WinEHCatchDirector : public WinEHCloningDirectorBase {
259public:
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000260 WinEHCatchDirector(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000261 Function *CatchFn, Value *ParentFP, Value *Selector,
262 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap,
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000263 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPads,
264 DominatorTree *DT, SmallPtrSetImpl<BasicBlock *> &EHBlocks)
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000265 : WinEHCloningDirectorBase(CatchFn, ParentFP, VarInfo, LPadMap),
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000266 CurrentSelector(Selector->stripPointerCasts()),
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000267 ExceptionObjectVar(nullptr), NestedLPtoOriginalLP(NestedLPads),
268 DT(DT), EHBlocks(EHBlocks) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000269
270 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
271 const Instruction *Inst,
272 BasicBlock *NewBB) override;
273 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
274 BasicBlock *NewBB) override;
275 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
276 const Instruction *Inst,
277 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000278 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
279 const IndirectBrInst *IBr,
280 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000281 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
282 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000283 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
284 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000285 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
286 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000287 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
288 const LandingPadInst *LPad,
289 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000290
Reid Kleckner3567d272015-04-02 21:13:31 +0000291 Value *getExceptionVar() { return ExceptionObjectVar; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000292 TinyPtrVector<BasicBlock *> &getReturnTargets() { return ReturnTargets; }
293
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000294private:
295 Value *CurrentSelector;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000296
Reid Kleckner3567d272015-04-02 21:13:31 +0000297 Value *ExceptionObjectVar;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000298 TinyPtrVector<BasicBlock *> ReturnTargets;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000299
300 // This will be a reference to the field of the same name in the WinEHPrepare
301 // object which instantiates this WinEHCatchDirector object.
302 DenseMap<LandingPadInst *, const LandingPadInst *> &NestedLPtoOriginalLP;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000303 DominatorTree *DT;
304 SmallPtrSetImpl<BasicBlock *> &EHBlocks;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000305};
306
307class WinEHCleanupDirector : public WinEHCloningDirectorBase {
308public:
Reid Klecknerbcda1cd2015-04-29 22:49:54 +0000309 WinEHCleanupDirector(Function *CleanupFn, Value *ParentFP,
310 FrameVarInfoMap &VarInfo, LandingPadMap &LPadMap)
311 : WinEHCloningDirectorBase(CleanupFn, ParentFP, VarInfo,
312 LPadMap) {}
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000313
314 CloningAction handleBeginCatch(ValueToValueMapTy &VMap,
315 const Instruction *Inst,
316 BasicBlock *NewBB) override;
317 CloningAction handleEndCatch(ValueToValueMapTy &VMap, const Instruction *Inst,
318 BasicBlock *NewBB) override;
319 CloningAction handleTypeIdFor(ValueToValueMapTy &VMap,
320 const Instruction *Inst,
321 BasicBlock *NewBB) override;
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000322 CloningAction handleIndirectBr(ValueToValueMapTy &VMap,
323 const IndirectBrInst *IBr,
324 BasicBlock *NewBB) override;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000325 CloningAction handleInvoke(ValueToValueMapTy &VMap, const InvokeInst *Invoke,
326 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000327 CloningAction handleResume(ValueToValueMapTy &VMap, const ResumeInst *Resume,
328 BasicBlock *NewBB) override;
Andrew Kaylor91307432015-04-28 22:01:51 +0000329 CloningAction handleCompare(ValueToValueMapTy &VMap, const CmpInst *Compare,
330 BasicBlock *NewBB) override;
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000331 CloningAction handleLandingPad(ValueToValueMapTy &VMap,
332 const LandingPadInst *LPad,
333 BasicBlock *NewBB) override;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000334};
335
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000336class LandingPadActions {
337public:
338 LandingPadActions() : HasCleanupHandlers(false) {}
339
340 void insertCatchHandler(CatchHandler *Action) { Actions.push_back(Action); }
341 void insertCleanupHandler(CleanupHandler *Action) {
342 Actions.push_back(Action);
343 HasCleanupHandlers = true;
344 }
345
346 bool includesCleanup() const { return HasCleanupHandlers; }
347
David Majnemercde33032015-03-30 22:58:10 +0000348 SmallVectorImpl<ActionHandler *> &actions() { return Actions; }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000349 SmallVectorImpl<ActionHandler *>::iterator begin() { return Actions.begin(); }
350 SmallVectorImpl<ActionHandler *>::iterator end() { return Actions.end(); }
351
352private:
353 // Note that this class does not own the ActionHandler objects in this vector.
354 // The ActionHandlers are owned by the CatchHandlerMap and CleanupHandlerMap
355 // in the WinEHPrepare class.
356 SmallVector<ActionHandler *, 4> Actions;
357 bool HasCleanupHandlers;
358};
359
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000360} // end anonymous namespace
361
362char WinEHPrepare::ID = 0;
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000363INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions",
364 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000365
366FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) {
367 return new WinEHPrepare(TM);
368}
369
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000370bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000371 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000372 return false;
373
David Majnemerfd9f4772015-08-11 01:15:26 +0000374 // No need to prepare outlined handlers.
375 if (Fn.hasFnAttribute("wineh-parent"))
David Majnemer09e1fdb2015-08-06 21:13:51 +0000376 return false;
377
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000378 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000379 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000380
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000381 // Do nothing if this is not an MSVC personality.
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000382 if (!isMSVCEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000383 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000384
David Majnemerfd9f4772015-08-11 01:15:26 +0000385 SmallVector<LandingPadInst *, 4> LPads;
386 SmallVector<ResumeInst *, 4> Resumes;
387 bool ForExplicitEH = false;
388 for (BasicBlock &BB : Fn) {
389 if (auto *LP = BB.getLandingPadInst()) {
390 LPads.push_back(LP);
391 } else if (BB.getFirstNonPHI()->isEHPad()) {
392 ForExplicitEH = true;
393 break;
394 }
395 if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator()))
396 Resumes.push_back(Resume);
397 }
398
399 if (ForExplicitEH)
400 return prepareExplicitEH(Fn);
401
402 // No need to prepare functions that lack landing pads.
403 if (LPads.empty())
404 return false;
405
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000406 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000407 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000408
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000409 // If there were any landing pads, prepareExceptionHandlers will make changes.
410 prepareExceptionHandlers(Fn, LPads);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000411 return true;
412}
413
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000414bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000415
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000416void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {
417 AU.addRequired<DominatorTreeWrapperPass>();
Reid Klecknerf12c0302015-06-09 21:42:19 +0000418 AU.addRequired<TargetLibraryInfoWrapperPass>();
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000419}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000420
Reid Klecknerfd7df282015-04-22 21:05:21 +0000421static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
422 Constant *&Selector, BasicBlock *&NextBB);
423
424// Finds blocks reachable from the starting set Worklist. Does not follow unwind
425// edges or blocks listed in StopPoints.
426static void findReachableBlocks(SmallPtrSetImpl<BasicBlock *> &ReachableBBs,
427 SetVector<BasicBlock *> &Worklist,
428 const SetVector<BasicBlock *> *StopPoints) {
429 while (!Worklist.empty()) {
430 BasicBlock *BB = Worklist.pop_back_val();
431
432 // Don't cross blocks that we should stop at.
433 if (StopPoints && StopPoints->count(BB))
434 continue;
435
436 if (!ReachableBBs.insert(BB).second)
437 continue; // Already visited.
438
439 // Don't follow unwind edges of invokes.
440 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
441 Worklist.insert(II->getNormalDest());
442 continue;
443 }
444
445 // Otherwise, follow all successors.
446 Worklist.insert(succ_begin(BB), succ_end(BB));
447 }
448}
449
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000450// Attempt to find an instruction where a block can be split before
451// a call to llvm.eh.begincatch and its operands. If the block
452// begins with the begincatch call or one of its adjacent operands
453// the block will not be split.
454static Instruction *findBeginCatchSplitPoint(BasicBlock *BB,
455 IntrinsicInst *II) {
456 // If the begincatch call is already the first instruction in the block,
457 // don't split.
458 Instruction *FirstNonPHI = BB->getFirstNonPHI();
459 if (II == FirstNonPHI)
460 return nullptr;
461
462 // If either operand is in the same basic block as the instruction and
463 // isn't used by another instruction before the begincatch call, include it
464 // in the split block.
465 auto *Op0 = dyn_cast<Instruction>(II->getOperand(0));
466 auto *Op1 = dyn_cast<Instruction>(II->getOperand(1));
467
468 Instruction *I = II->getPrevNode();
469 Instruction *LastI = II;
470
471 while (I == Op0 || I == Op1) {
472 // If the block begins with one of the operands and there are no other
473 // instructions between the operand and the begincatch call, don't split.
474 if (I == FirstNonPHI)
475 return nullptr;
476
477 LastI = I;
478 I = I->getPrevNode();
479 }
480
481 // If there is at least one instruction in the block before the begincatch
482 // call and its operands, split the block at either the begincatch or
483 // its operand.
484 return LastI;
485}
486
Reid Klecknerfd7df282015-04-22 21:05:21 +0000487/// Find all points where exceptional control rejoins normal control flow via
488/// llvm.eh.endcatch. Add them to the normal bb reachability worklist.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000489void WinEHPrepare::findCXXEHReturnPoints(
490 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000491 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
492 BasicBlock *BB = BBI;
493 for (Instruction &I : *BB) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000494 if (match(&I, m_Intrinsic<Intrinsic::eh_begincatch>())) {
Andrew Kaylor91307432015-04-28 22:01:51 +0000495 Instruction *SplitPt =
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000496 findBeginCatchSplitPoint(BB, cast<IntrinsicInst>(&I));
497 if (SplitPt) {
498 // Split the block before the llvm.eh.begincatch call to allow
499 // cleanup and catch code to be distinguished later.
500 // Do not update BBI because we still need to process the
501 // portion of the block that we are splitting off.
Andrew Kaylora33f1592015-04-29 17:21:26 +0000502 SplitBlock(BB, SplitPt, DT);
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000503 break;
504 }
505 }
Reid Klecknerfd7df282015-04-22 21:05:21 +0000506 if (match(&I, m_Intrinsic<Intrinsic::eh_endcatch>())) {
507 // Split the block after the call to llvm.eh.endcatch if there is
508 // anything other than an unconditional branch, or if the successor
509 // starts with a phi.
510 auto *Br = dyn_cast<BranchInst>(I.getNextNode());
511 if (!Br || !Br->isUnconditional() ||
512 isa<PHINode>(Br->getSuccessor(0)->begin())) {
513 DEBUG(dbgs() << "splitting block " << BB->getName()
514 << " with llvm.eh.endcatch\n");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000515 BBI = SplitBlock(BB, I.getNextNode(), DT);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000516 }
517 // The next BB is normal control flow.
518 EHReturnBlocks.insert(BB->getTerminator()->getSuccessor(0));
519 break;
520 }
521 }
522 }
523}
524
525static bool isCatchAllLandingPad(const BasicBlock *BB) {
526 const LandingPadInst *LP = BB->getLandingPadInst();
527 if (!LP)
528 return false;
529 unsigned N = LP->getNumClauses();
530 return (N > 0 && LP->isCatch(N - 1) &&
531 isa<ConstantPointerNull>(LP->getClause(N - 1)));
532}
533
534/// Find all points where exceptions control rejoins normal control flow via
535/// selector dispatch.
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000536void WinEHPrepare::findSEHEHReturnPoints(
537 Function &F, SetVector<BasicBlock *> &EHReturnBlocks) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000538 for (auto BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
539 BasicBlock *BB = BBI;
540 // If the landingpad is a catch-all, treat the whole lpad as if it is
541 // reachable from normal control flow.
542 // FIXME: This is imprecise. We need a better way of identifying where a
543 // catch-all starts and cleanups stop. As far as LLVM is concerned, there
544 // is no difference.
545 if (isCatchAllLandingPad(BB)) {
546 EHReturnBlocks.insert(BB);
547 continue;
548 }
549
550 BasicBlock *CatchHandler;
551 BasicBlock *NextBB;
552 Constant *Selector;
553 if (isSelectorDispatch(BB, CatchHandler, Selector, NextBB)) {
Reid Klecknered012db2015-07-08 18:08:52 +0000554 // Split the edge if there are multiple predecessors. This creates a place
555 // where we can insert EH recovery code.
556 if (!CatchHandler->getSinglePredecessor()) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000557 DEBUG(dbgs() << "splitting EH return edge from " << BB->getName()
558 << " to " << CatchHandler->getName() << '\n');
559 BBI = CatchHandler = SplitCriticalEdge(
560 BB, std::find(succ_begin(BB), succ_end(BB), CatchHandler));
561 }
562 EHReturnBlocks.insert(CatchHandler);
563 }
564 }
565}
566
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000567void WinEHPrepare::identifyEHBlocks(Function &F,
568 SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000569 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
570 << F.getName() << '\n');
571
572 // Build a set of all non-exceptional blocks and exceptional blocks.
573 // - Non-exceptional blocks are blocks reachable from the entry block while
574 // not following invoke unwind edges.
575 // - Exceptional blocks are blocks reachable from landingpads. Analysis does
576 // not follow llvm.eh.endcatch blocks, which mark a transition from
577 // exceptional to normal control.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000578
579 if (Personality == EHPersonality::MSVC_CXX)
580 findCXXEHReturnPoints(F, EHReturnBlocks);
581 else
582 findSEHEHReturnPoints(F, EHReturnBlocks);
583
584 DEBUG({
585 dbgs() << "identified the following blocks as EH return points:\n";
586 for (BasicBlock *BB : EHReturnBlocks)
587 dbgs() << " " << BB->getName() << '\n';
588 });
589
Andrew Kaylor91307432015-04-28 22:01:51 +0000590// Join points should not have phis at this point, unless they are a
591// landingpad, in which case we will demote their phis later.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000592#ifndef NDEBUG
593 for (BasicBlock *BB : EHReturnBlocks)
594 assert((BB->isLandingPad() || !isa<PHINode>(BB->begin())) &&
595 "non-lpad EH return block has phi");
596#endif
597
598 // Normal blocks are the blocks reachable from the entry block and all EH
599 // return points.
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000600 SetVector<BasicBlock *> Worklist;
Reid Klecknerfd7df282015-04-22 21:05:21 +0000601 Worklist = EHReturnBlocks;
602 Worklist.insert(&F.getEntryBlock());
603 findReachableBlocks(NormalBlocks, Worklist, nullptr);
604 DEBUG({
605 dbgs() << "marked the following blocks as normal:\n";
606 for (BasicBlock *BB : NormalBlocks)
607 dbgs() << " " << BB->getName() << '\n';
608 });
609
610 // Exceptional blocks are the blocks reachable from landingpads that don't
611 // cross EH return points.
612 Worklist.clear();
613 for (auto *LPI : LPads)
614 Worklist.insert(LPI->getParent());
615 findReachableBlocks(EHBlocks, Worklist, &EHReturnBlocks);
616 DEBUG({
617 dbgs() << "marked the following blocks as exceptional:\n";
618 for (BasicBlock *BB : EHBlocks)
619 dbgs() << " " << BB->getName() << '\n';
620 });
621
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000622}
623
624/// Ensure that all values live into and out of exception handlers are stored
625/// in memory.
626/// FIXME: This falls down when values are defined in one handler and live into
627/// another handler. For example, a cleanup defines a value used only by a
628/// catch handler.
629void WinEHPrepare::demoteValuesLiveAcrossHandlers(
630 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
631 DEBUG(dbgs() << "Demoting values live across exception handlers in function "
632 << F.getName() << '\n');
633
634 // identifyEHBlocks() should have been called before this function.
635 assert(!NormalBlocks.empty());
636
Reid Kleckner7ea77082015-07-10 22:21:54 +0000637 // Try to avoid demoting EH pointer and selector values. They get in the way
638 // of our pattern matching.
639 SmallPtrSet<Instruction *, 10> EHVals;
640 for (BasicBlock &BB : F) {
641 LandingPadInst *LP = BB.getLandingPadInst();
642 if (!LP)
643 continue;
644 EHVals.insert(LP);
645 for (User *U : LP->users()) {
646 auto *EI = dyn_cast<ExtractValueInst>(U);
647 if (!EI)
648 continue;
649 EHVals.insert(EI);
650 for (User *U2 : EI->users()) {
651 if (auto *PN = dyn_cast<PHINode>(U2))
652 EHVals.insert(PN);
653 }
654 }
655 }
656
Reid Klecknerfd7df282015-04-22 21:05:21 +0000657 SetVector<Argument *> ArgsToDemote;
658 SetVector<Instruction *> InstrsToDemote;
659 for (BasicBlock &BB : F) {
660 bool IsNormalBB = NormalBlocks.count(&BB);
661 bool IsEHBB = EHBlocks.count(&BB);
662 if (!IsNormalBB && !IsEHBB)
663 continue; // Blocks that are neither normal nor EH are unreachable.
664 for (Instruction &I : BB) {
665 for (Value *Op : I.operands()) {
666 // Don't demote static allocas, constants, and labels.
667 if (isa<Constant>(Op) || isa<BasicBlock>(Op) || isa<InlineAsm>(Op))
668 continue;
669 auto *AI = dyn_cast<AllocaInst>(Op);
670 if (AI && AI->isStaticAlloca())
671 continue;
672
673 if (auto *Arg = dyn_cast<Argument>(Op)) {
674 if (IsEHBB) {
675 DEBUG(dbgs() << "Demoting argument " << *Arg
676 << " used by EH instr: " << I << "\n");
677 ArgsToDemote.insert(Arg);
678 }
679 continue;
680 }
681
Reid Kleckner7ea77082015-07-10 22:21:54 +0000682 // Don't demote EH values.
Reid Klecknerfd7df282015-04-22 21:05:21 +0000683 auto *OpI = cast<Instruction>(Op);
Reid Kleckner7ea77082015-07-10 22:21:54 +0000684 if (EHVals.count(OpI))
685 continue;
686
Reid Klecknerfd7df282015-04-22 21:05:21 +0000687 BasicBlock *OpBB = OpI->getParent();
688 // If a value is produced and consumed in the same BB, we don't need to
689 // demote it.
690 if (OpBB == &BB)
691 continue;
692 bool IsOpNormalBB = NormalBlocks.count(OpBB);
693 bool IsOpEHBB = EHBlocks.count(OpBB);
694 if (IsNormalBB != IsOpNormalBB || IsEHBB != IsOpEHBB) {
695 DEBUG({
696 dbgs() << "Demoting instruction live in-out from EH:\n";
697 dbgs() << "Instr: " << *OpI << '\n';
698 dbgs() << "User: " << I << '\n';
699 });
700 InstrsToDemote.insert(OpI);
701 }
702 }
703 }
704 }
705
706 // Demote values live into and out of handlers.
707 // FIXME: This demotion is inefficient. We should insert spills at the point
708 // of definition, insert one reload in each handler that uses the value, and
709 // insert reloads in the BB used to rejoin normal control flow.
710 Instruction *AllocaInsertPt = F.getEntryBlock().getFirstInsertionPt();
711 for (Instruction *I : InstrsToDemote)
712 DemoteRegToStack(*I, false, AllocaInsertPt);
713
714 // Demote arguments separately, and only for uses in EH blocks.
715 for (Argument *Arg : ArgsToDemote) {
716 auto *Slot = new AllocaInst(Arg->getType(), nullptr,
717 Arg->getName() + ".reg2mem", AllocaInsertPt);
718 SmallVector<User *, 4> Users(Arg->user_begin(), Arg->user_end());
719 for (User *U : Users) {
720 auto *I = dyn_cast<Instruction>(U);
721 if (I && EHBlocks.count(I->getParent())) {
722 auto *Reload = new LoadInst(Slot, Arg->getName() + ".reload", false, I);
723 U->replaceUsesOfWith(Arg, Reload);
724 }
725 }
726 new StoreInst(Arg, Slot, AllocaInsertPt);
727 }
728
729 // Demote landingpad phis, as the landingpad will be removed from the machine
730 // CFG.
731 for (LandingPadInst *LPI : LPads) {
732 BasicBlock *BB = LPI->getParent();
733 while (auto *Phi = dyn_cast<PHINode>(BB->begin()))
734 DemotePHIToStack(Phi, AllocaInsertPt);
735 }
736
737 DEBUG(dbgs() << "Demoted " << InstrsToDemote.size() << " instructions and "
738 << ArgsToDemote.size() << " arguments for WinEHPrepare\n\n");
739}
740
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000741bool WinEHPrepare::prepareExceptionHandlers(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000742 Function &F, SmallVectorImpl<LandingPadInst *> &LPads) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000743 // Don't run on functions that are already prepared.
744 for (LandingPadInst *LPad : LPads) {
745 BasicBlock *LPadBB = LPad->getParent();
746 for (Instruction &Inst : *LPadBB)
747 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>()))
748 return false;
749 }
750
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000751 identifyEHBlocks(F, LPads);
Reid Klecknerfd7df282015-04-22 21:05:21 +0000752 demoteValuesLiveAcrossHandlers(F, LPads);
753
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000754 // These containers are used to re-map frame variables that are used in
755 // outlined catch and cleanup handlers. They will be populated as the
756 // handlers are outlined.
757 FrameVarInfoMap FrameVarInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000758
759 bool HandlersOutlined = false;
760
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000761 Module *M = F.getParent();
762 LLVMContext &Context = M->getContext();
763
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000764 // Create a new function to receive the handler contents.
765 PointerType *Int8PtrType = Type::getInt8PtrTy(Context);
766 Type *Int32Type = Type::getInt32Ty(Context);
Reid Kleckner52b07792015-03-12 01:45:37 +0000767 Function *ActionIntrin = Intrinsic::getDeclaration(M, Intrinsic::eh_actions);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000768
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000769 if (isAsynchronousEHPersonality(Personality)) {
770 // FIXME: Switch the ehptr type to i32 and then switch this.
771 SEHExceptionCodeSlot =
772 new AllocaInst(Int8PtrType, nullptr, "seh_exception_code",
773 F.getEntryBlock().getFirstInsertionPt());
774 }
775
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000776 // In order to handle the case where one outlined catch handler returns
777 // to a block within another outlined catch handler that would otherwise
778 // be unreachable, we need to outline the nested landing pad before we
779 // outline the landing pad which encloses it.
Manuel Klimekb00d42c2015-05-21 15:38:25 +0000780 if (!isAsynchronousEHPersonality(Personality))
781 std::sort(LPads.begin(), LPads.end(),
782 [this](LandingPadInst *const &L, LandingPadInst *const &R) {
783 return DT->properlyDominates(R->getParent(), L->getParent());
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000784 });
785
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000786 // This container stores the llvm.eh.recover and IndirectBr instructions
787 // that make up the body of each landing pad after it has been outlined.
788 // We need to defer the population of the target list for the indirectbr
789 // until all landing pads have been outlined so that we can handle the
790 // case of blocks in the target that are reached only from nested
791 // landing pads.
792 SmallVector<std::pair<CallInst*, IndirectBrInst *>, 4> LPadImpls;
793
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000794 for (LandingPadInst *LPad : LPads) {
795 // Look for evidence that this landingpad has already been processed.
796 bool LPadHasActionList = false;
797 BasicBlock *LPadBB = LPad->getParent();
Reid Klecknerc759fe92015-03-19 22:31:02 +0000798 for (Instruction &Inst : *LPadBB) {
Reid Klecknerfd7df282015-04-22 21:05:21 +0000799 if (match(&Inst, m_Intrinsic<Intrinsic::eh_actions>())) {
800 LPadHasActionList = true;
801 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000802 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000803 }
804
805 // If we've already outlined the handlers for this landingpad,
806 // there's nothing more to do here.
807 if (LPadHasActionList)
808 continue;
809
Andrew Kaylor64622aa2015-04-01 17:21:25 +0000810 // If either of the values in the aggregate returned by the landing pad is
811 // extracted and stored to memory, promote the stored value to a register.
812 promoteLandingPadValues(LPad);
813
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000814 LandingPadActions Actions;
815 mapLandingPadBlocks(LPad, Actions);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000816
Reid Kleckner9405ef02015-04-10 23:12:29 +0000817 HandlersOutlined |= !Actions.actions().empty();
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000818 for (ActionHandler *Action : Actions) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000819 if (Action->hasBeenProcessed())
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000820 continue;
821 BasicBlock *StartBB = Action->getStartBlock();
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000822
823 // SEH doesn't do any outlining for catches. Instead, pass the handler
824 // basic block addr to llvm.eh.actions and list the block as a return
825 // target.
826 if (isAsynchronousEHPersonality(Personality)) {
827 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
828 processSEHCatchHandler(CatchAction, StartBB);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000829 continue;
830 }
831 }
832
Reid Kleckner9405ef02015-04-10 23:12:29 +0000833 outlineHandler(Action, &F, LPad, StartBB, FrameVarInfo);
834 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000835
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000836 // Split the block after the landingpad instruction so that it is just a
837 // call to llvm.eh.actions followed by indirectbr.
838 assert(!isa<PHINode>(LPadBB->begin()) && "lpad phi not removed");
Andrew Kaylor046f7b42015-04-28 21:54:14 +0000839 SplitBlock(LPadBB, LPad->getNextNode(), DT);
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000840 // Erase the branch inserted by the split so we can insert indirectbr.
841 LPadBB->getTerminator()->eraseFromParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000842
Reid Klecknere3af86e2015-04-23 21:22:30 +0000843 // Replace all extracted values with undef and ultimately replace the
844 // landingpad with undef.
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000845 SmallVector<Instruction *, 4> SEHCodeUses;
846 SmallVector<Instruction *, 4> EHUndefs;
Reid Klecknere3af86e2015-04-23 21:22:30 +0000847 for (User *U : LPad->users()) {
848 auto *E = dyn_cast<ExtractValueInst>(U);
849 if (!E)
850 continue;
851 assert(E->getNumIndices() == 1 &&
852 "Unexpected operation: extracting both landing pad values");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000853 unsigned Idx = *E->idx_begin();
854 assert((Idx == 0 || Idx == 1) && "unexpected index");
855 if (Idx == 0 && isAsynchronousEHPersonality(Personality))
856 SEHCodeUses.push_back(E);
857 else
858 EHUndefs.push_back(E);
Reid Klecknere3af86e2015-04-23 21:22:30 +0000859 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000860 for (Instruction *E : EHUndefs) {
Reid Klecknere3af86e2015-04-23 21:22:30 +0000861 E->replaceAllUsesWith(UndefValue::get(E->getType()));
862 E->eraseFromParent();
863 }
864 LPad->replaceAllUsesWith(UndefValue::get(LPad->getType()));
Reid Kleckner0f9e27a2015-03-18 20:26:53 +0000865
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000866 // Rewrite uses of the exception pointer to loads of an alloca.
Reid Kleckner7ea77082015-07-10 22:21:54 +0000867 while (!SEHCodeUses.empty()) {
868 Instruction *E = SEHCodeUses.pop_back_val();
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000869 SmallVector<Use *, 4> Uses;
870 for (Use &U : E->uses())
871 Uses.push_back(&U);
872 for (Use *U : Uses) {
873 auto *I = cast<Instruction>(U->getUser());
874 if (isa<ResumeInst>(I))
875 continue;
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000876 if (auto *Phi = dyn_cast<PHINode>(I))
Reid Kleckner7ea77082015-07-10 22:21:54 +0000877 SEHCodeUses.push_back(Phi);
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000878 else
Reid Kleckner7ea77082015-07-10 22:21:54 +0000879 U->set(new LoadInst(SEHExceptionCodeSlot, "sehcode", false, I));
Reid Klecknercfbfe6f2015-04-24 20:25:05 +0000880 }
881 E->replaceAllUsesWith(UndefValue::get(E->getType()));
882 E->eraseFromParent();
883 }
884
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000885 // Add a call to describe the actions for this landing pad.
886 std::vector<Value *> ActionArgs;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000887 for (ActionHandler *Action : Actions) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000888 // Action codes from docs are: 0 cleanup, 1 catch.
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000889 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000890 ActionArgs.push_back(ConstantInt::get(Int32Type, 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000891 ActionArgs.push_back(CatchAction->getSelector());
Reid Kleckner3567d272015-04-02 21:13:31 +0000892 // Find the frame escape index of the exception object alloca in the
893 // parent.
894 int FrameEscapeIdx = -1;
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000895 Value *EHObj = const_cast<Value *>(CatchAction->getExceptionVar());
Reid Kleckner3567d272015-04-02 21:13:31 +0000896 if (EHObj && !isa<ConstantPointerNull>(EHObj)) {
897 auto I = FrameVarInfo.find(EHObj);
898 assert(I != FrameVarInfo.end() &&
899 "failed to map llvm.eh.begincatch var");
900 FrameEscapeIdx = std::distance(FrameVarInfo.begin(), I);
901 }
902 ActionArgs.push_back(ConstantInt::get(Int32Type, FrameEscapeIdx));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000903 } else {
Reid Klecknerc759fe92015-03-19 22:31:02 +0000904 ActionArgs.push_back(ConstantInt::get(Int32Type, 0));
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000905 }
Reid Klecknerc759fe92015-03-19 22:31:02 +0000906 ActionArgs.push_back(Action->getHandlerBlockOrFunc());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000907 }
908 CallInst *Recover =
Reid Kleckner2c3ccaa2015-04-24 16:22:19 +0000909 CallInst::Create(ActionIntrin, ActionArgs, "recover", LPadBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000910
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000911 SetVector<BasicBlock *> ReturnTargets;
912 for (ActionHandler *Action : Actions) {
913 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
914 const auto &CatchTargets = CatchAction->getReturnTargets();
915 ReturnTargets.insert(CatchTargets.begin(), CatchTargets.end());
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000916 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000917 }
918 IndirectBrInst *Branch =
919 IndirectBrInst::Create(Recover, ReturnTargets.size(), LPadBB);
920 for (BasicBlock *Target : ReturnTargets)
921 Branch->addDestination(Target);
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000922
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000923 if (!isAsynchronousEHPersonality(Personality)) {
924 // C++ EH must repopulate the targets later to handle the case of
925 // targets that are reached indirectly through nested landing pads.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000926 LPadImpls.push_back(std::make_pair(Recover, Branch));
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000927 }
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000928
Andrew Kaylorf0f5e462015-03-03 20:00:16 +0000929 } // End for each landingpad
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000930
931 // If nothing got outlined, there is no more processing to be done.
932 if (!HandlersOutlined)
933 return false;
934
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000935 // Replace any nested landing pad stubs with the correct action handler.
936 // This must be done before we remove unreachable blocks because it
937 // cleans up references to outlined blocks that will be deleted.
938 for (auto &LPadPair : NestedLPtoOriginalLP)
939 completeNestedLandingPad(&F, LPadPair.first, LPadPair.second, FrameVarInfo);
Andrew Kaylor67d3c032015-04-08 20:57:22 +0000940 NestedLPtoOriginalLP.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000941
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000942 // Update the indirectbr instructions' target lists if necessary.
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000943 SetVector<BasicBlock*> CheckedTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000944 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000945 for (auto &LPadImplPair : LPadImpls) {
946 IntrinsicInst *Recover = cast<IntrinsicInst>(LPadImplPair.first);
947 IndirectBrInst *Branch = LPadImplPair.second;
948
949 // Get a list of handlers called by
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000950 parseEHActions(Recover, ActionList);
951
952 // Add an indirect branch listing possible successors of the catch handlers.
953 SetVector<BasicBlock *> ReturnTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +0000954 for (const auto &Action : ActionList) {
955 if (auto *CA = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000956 Function *Handler = cast<Function>(CA->getHandlerBlockOrFunc());
957 getPossibleReturnTargets(&F, Handler, ReturnTargets);
958 }
959 }
Andrew Kaylor0ddaf2b2015-05-12 00:13:51 +0000960 ActionList.clear();
Andrew Kaylora6c5b962015-05-20 23:22:24 +0000961 // Clear any targets we already knew about.
962 for (unsigned int I = 0, E = Branch->getNumDestinations(); I < E; ++I) {
963 BasicBlock *KnownTarget = Branch->getDestination(I);
964 if (ReturnTargets.count(KnownTarget))
965 ReturnTargets.remove(KnownTarget);
966 }
Andrew Kaylorcc14f382015-05-11 23:06:02 +0000967 for (BasicBlock *Target : ReturnTargets) {
968 Branch->addDestination(Target);
969 // The target may be a block that we excepted to get pruned.
970 // If it is, it may contain a call to llvm.eh.endcatch.
971 if (CheckedTargets.insert(Target)) {
972 // Earlier preparations guarantee that all calls to llvm.eh.endcatch
973 // will be followed by an unconditional branch.
974 auto *Br = dyn_cast<BranchInst>(Target->getTerminator());
975 if (Br && Br->isUnconditional() &&
976 Br != Target->getFirstNonPHIOrDbgOrLifetime()) {
977 Instruction *Prev = Br->getPrevNode();
978 if (match(cast<Value>(Prev), m_Intrinsic<Intrinsic::eh_endcatch>()))
979 Prev->eraseFromParent();
980 }
981 }
982 }
983 }
984 LPadImpls.clear();
985
David Majnemercde33032015-03-30 22:58:10 +0000986 F.addFnAttr("wineh-parent", F.getName());
987
Andrew Kaylor6b67d422015-03-11 23:22:06 +0000988 // Delete any blocks that were only used by handlers that were outlined above.
989 removeUnreachableBlocks(F);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000990
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000991 BasicBlock *Entry = &F.getEntryBlock();
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000992 IRBuilder<> Builder(F.getParent()->getContext());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000993 Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000994
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000995 Function *FrameEscapeFn =
Reid Kleckner60381792015-07-07 22:25:32 +0000996 Intrinsic::getDeclaration(M, Intrinsic::localescape);
Reid Klecknercfb9ce52015-03-05 18:26:34 +0000997 Function *RecoverFrameFn =
Reid Kleckner60381792015-07-07 22:25:32 +0000998 Intrinsic::getDeclaration(M, Intrinsic::localrecover);
Reid Klecknerf14787d2015-04-22 00:07:52 +0000999 SmallVector<Value *, 8> AllocasToEscape;
1000
Reid Kleckner60381792015-07-07 22:25:32 +00001001 // Scan the entry block for an existing call to llvm.localescape. We need to
Reid Klecknerf14787d2015-04-22 00:07:52 +00001002 // keep escaping those objects.
1003 for (Instruction &I : F.front()) {
1004 auto *II = dyn_cast<IntrinsicInst>(&I);
Reid Kleckner60381792015-07-07 22:25:32 +00001005 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
Reid Klecknerf14787d2015-04-22 00:07:52 +00001006 auto Args = II->arg_operands();
1007 AllocasToEscape.append(Args.begin(), Args.end());
1008 II->eraseFromParent();
1009 break;
1010 }
1011 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001012
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001013 // Finally, replace all of the temporary allocas for frame variables used in
Reid Kleckner60381792015-07-07 22:25:32 +00001014 // the outlined handlers with calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001015 for (auto &VarInfoEntry : FrameVarInfo) {
Andrew Kaylor72029c62015-03-03 00:41:03 +00001016 Value *ParentVal = VarInfoEntry.first;
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001017 TinyPtrVector<AllocaInst *> &Allocas = VarInfoEntry.second;
Reid Klecknerfd7df282015-04-22 21:05:21 +00001018 AllocaInst *ParentAlloca = cast<AllocaInst>(ParentVal);
Andrew Kaylor72029c62015-03-03 00:41:03 +00001019
Reid Klecknerb4019412015-04-06 18:50:38 +00001020 // FIXME: We should try to sink unescaped allocas from the parent frame into
1021 // the child frame. If the alloca is escaped, we have to use the lifetime
1022 // markers to ensure that the alloca is only live within the child frame.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001023
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001024 // Add this alloca to the list of things to escape.
1025 AllocasToEscape.push_back(ParentAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001026
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001027 // Next replace all outlined allocas that are mapped to it.
1028 for (AllocaInst *TempAlloca : Allocas) {
Reid Kleckner3567d272015-04-02 21:13:31 +00001029 if (TempAlloca == getCatchObjectSentinel())
1030 continue; // Skip catch parameter sentinels.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001031 Function *HandlerFn = TempAlloca->getParent()->getParent();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001032 llvm::Value *FP = HandlerToParentFP[HandlerFn];
1033 assert(FP);
1034
Reid Kleckner60381792015-07-07 22:25:32 +00001035 // FIXME: Sink this localrecover into the blocks where it is used.
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001036 Builder.SetInsertPoint(TempAlloca);
1037 Builder.SetCurrentDebugLocation(TempAlloca->getDebugLoc());
1038 Value *RecoverArgs[] = {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001039 Builder.CreateBitCast(&F, Int8PtrType, ""), FP,
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001040 llvm::ConstantInt::get(Int32Type, AllocasToEscape.size() - 1)};
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001041 Instruction *RecoveredAlloca =
1042 Builder.CreateCall(RecoverFrameFn, RecoverArgs);
1043
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001044 // Add a pointer bitcast if the alloca wasn't an i8.
1045 if (RecoveredAlloca->getType() != TempAlloca->getType()) {
1046 RecoveredAlloca->setName(Twine(TempAlloca->getName()) + ".i8");
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001047 RecoveredAlloca = cast<Instruction>(
1048 Builder.CreateBitCast(RecoveredAlloca, TempAlloca->getType()));
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001049 }
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001050 TempAlloca->replaceAllUsesWith(RecoveredAlloca);
1051 TempAlloca->removeFromParent();
1052 RecoveredAlloca->takeName(TempAlloca);
1053 delete TempAlloca;
1054 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001055 } // End for each FrameVarInfo entry.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001056
Reid Kleckner60381792015-07-07 22:25:32 +00001057 // Insert 'call void (...)* @llvm.localescape(...)' at the end of the entry
Reid Klecknercfb9ce52015-03-05 18:26:34 +00001058 // block.
1059 Builder.SetInsertPoint(&F.getEntryBlock().back());
1060 Builder.CreateCall(FrameEscapeFn, AllocasToEscape);
1061
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001062 if (SEHExceptionCodeSlot) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00001063 if (isAllocaPromotable(SEHExceptionCodeSlot)) {
1064 SmallPtrSet<BasicBlock *, 4> UserBlocks;
1065 for (User *U : SEHExceptionCodeSlot->users()) {
1066 if (auto *Inst = dyn_cast<Instruction>(U))
1067 UserBlocks.insert(Inst->getParent());
1068 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001069 PromoteMemToReg(SEHExceptionCodeSlot, *DT);
Reid Klecknerf12c0302015-06-09 21:42:19 +00001070 // After the promotion, kill off dead instructions.
1071 for (BasicBlock *BB : UserBlocks)
1072 SimplifyInstructionsInBlock(BB, LibInfo);
1073 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001074 }
1075
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001076 // Clean up the handler action maps we created for this function
1077 DeleteContainerSeconds(CatchHandlerMap);
1078 CatchHandlerMap.clear();
1079 DeleteContainerSeconds(CleanupHandlerMap);
1080 CleanupHandlerMap.clear();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001081 HandlerToParentFP.clear();
1082 DT = nullptr;
Reid Klecknerf12c0302015-06-09 21:42:19 +00001083 LibInfo = nullptr;
Ahmed Bougachaed363c52015-05-06 01:28:58 +00001084 SEHExceptionCodeSlot = nullptr;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001085 EHBlocks.clear();
1086 NormalBlocks.clear();
1087 EHReturnBlocks.clear();
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001088
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001089 return HandlersOutlined;
1090}
1091
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001092void WinEHPrepare::promoteLandingPadValues(LandingPadInst *LPad) {
1093 // If the return values of the landing pad instruction are extracted and
1094 // stored to memory, we want to promote the store locations to reg values.
1095 SmallVector<AllocaInst *, 2> EHAllocas;
1096
1097 // The landingpad instruction returns an aggregate value. Typically, its
1098 // value will be passed to a pair of extract value instructions and the
1099 // results of those extracts are often passed to store instructions.
1100 // In unoptimized code the stored value will often be loaded and then stored
1101 // again.
1102 for (auto *U : LPad->users()) {
1103 ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1104 if (!Extract)
1105 continue;
1106
1107 for (auto *EU : Extract->users()) {
1108 if (auto *Store = dyn_cast<StoreInst>(EU)) {
1109 auto *AV = cast<AllocaInst>(Store->getPointerOperand());
1110 EHAllocas.push_back(AV);
1111 }
1112 }
1113 }
1114
1115 // We can't do this without a dominator tree.
1116 assert(DT);
1117
1118 if (!EHAllocas.empty()) {
1119 PromoteMemToReg(EHAllocas, *DT);
1120 EHAllocas.clear();
1121 }
Reid Kleckner86762142015-04-16 00:02:04 +00001122
1123 // After promotion, some extracts may be trivially dead. Remove them.
1124 SmallVector<Value *, 4> Users(LPad->user_begin(), LPad->user_end());
1125 for (auto *U : Users)
1126 RecursivelyDeleteTriviallyDeadInstructions(U);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001127}
1128
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001129void WinEHPrepare::getPossibleReturnTargets(Function *ParentF,
1130 Function *HandlerF,
1131 SetVector<BasicBlock*> &Targets) {
1132 for (BasicBlock &BB : *HandlerF) {
1133 // If the handler contains landing pads, check for any
1134 // handlers that may return directly to a block in the
1135 // parent function.
1136 if (auto *LPI = BB.getLandingPadInst()) {
1137 IntrinsicInst *Recover = cast<IntrinsicInst>(LPI->getNextNode());
Benjamin Kramera48e0652015-05-16 15:40:03 +00001138 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001139 parseEHActions(Recover, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001140 for (const auto &Action : ActionList) {
1141 if (auto *CH = dyn_cast<CatchHandler>(Action.get())) {
Andrew Kaylorcc14f382015-05-11 23:06:02 +00001142 Function *NestedF = cast<Function>(CH->getHandlerBlockOrFunc());
1143 getPossibleReturnTargets(ParentF, NestedF, Targets);
1144 }
1145 }
1146 }
1147
1148 auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator());
1149 if (!Ret)
1150 continue;
1151
1152 // Handler functions must always return a block address.
1153 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1154
1155 // If this is the handler for a nested landing pad, the
1156 // return address may have been remapped to a block in the
1157 // parent handler. We're not interested in those.
1158 if (BA->getFunction() != ParentF)
1159 continue;
1160
1161 Targets.insert(BA->getBasicBlock());
1162 }
1163}
1164
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001165void WinEHPrepare::completeNestedLandingPad(Function *ParentFn,
1166 LandingPadInst *OutlinedLPad,
1167 const LandingPadInst *OriginalLPad,
1168 FrameVarInfoMap &FrameVarInfo) {
1169 // Get the nested block and erase the unreachable instruction that was
1170 // temporarily inserted as its terminator.
1171 LLVMContext &Context = ParentFn->getContext();
1172 BasicBlock *OutlinedBB = OutlinedLPad->getParent();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001173 // If the nested landing pad was outlined before the landing pad that enclosed
1174 // it, it will already be in outlined form. In that case, we just need to see
1175 // if the returns and the enclosing branch instruction need to be updated.
1176 IndirectBrInst *Branch =
1177 dyn_cast<IndirectBrInst>(OutlinedBB->getTerminator());
1178 if (!Branch) {
1179 // If the landing pad wasn't in outlined form, it should be a stub with
1180 // an unreachable terminator.
1181 assert(isa<UnreachableInst>(OutlinedBB->getTerminator()));
1182 OutlinedBB->getTerminator()->eraseFromParent();
1183 // That should leave OutlinedLPad as the last instruction in its block.
1184 assert(&OutlinedBB->back() == OutlinedLPad);
1185 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001186
1187 // The original landing pad will have already had its action intrinsic
1188 // built by the outlining loop. We need to clone that into the outlined
1189 // location. It may also be necessary to add references to the exception
1190 // variables to the outlined handler in which this landing pad is nested
1191 // and remap return instructions in the nested handlers that should return
1192 // to an address in the outlined handler.
1193 Function *OutlinedHandlerFn = OutlinedBB->getParent();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001194 BasicBlock::const_iterator II = OriginalLPad;
1195 ++II;
1196 // The instruction after the landing pad should now be a call to eh.actions.
1197 const Instruction *Recover = II;
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001198 const IntrinsicInst *EHActions = cast<IntrinsicInst>(Recover);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001199
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001200 // Remap the return target in the nested handler.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001201 SmallVector<BlockAddress *, 4> ActionTargets;
Benjamin Kramera48e0652015-05-16 15:40:03 +00001202 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001203 parseEHActions(EHActions, ActionList);
Benjamin Kramera48e0652015-05-16 15:40:03 +00001204 for (const auto &Action : ActionList) {
1205 auto *Catch = dyn_cast<CatchHandler>(Action.get());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001206 if (!Catch)
1207 continue;
1208 // The dyn_cast to function here selects C++ catch handlers and skips
1209 // SEH catch handlers.
1210 auto *Handler = dyn_cast<Function>(Catch->getHandlerBlockOrFunc());
1211 if (!Handler)
1212 continue;
1213 // Visit all the return instructions, looking for places that return
1214 // to a location within OutlinedHandlerFn.
1215 for (BasicBlock &NestedHandlerBB : *Handler) {
1216 auto *Ret = dyn_cast<ReturnInst>(NestedHandlerBB.getTerminator());
1217 if (!Ret)
1218 continue;
1219
1220 // Handler functions must always return a block address.
1221 BlockAddress *BA = cast<BlockAddress>(Ret->getReturnValue());
1222 // The original target will have been in the main parent function,
1223 // but if it is the address of a block that has been outlined, it
1224 // should be a block that was outlined into OutlinedHandlerFn.
1225 assert(BA->getFunction() == ParentFn);
1226
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001227 // Ignore targets that aren't part of an outlined handler function.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001228 if (!LPadTargetBlocks.count(BA->getBasicBlock()))
1229 continue;
1230
1231 // If the return value is the address ofF a block that we
1232 // previously outlined into the parent handler function, replace
1233 // the return instruction and add the mapped target to the list
1234 // of possible return addresses.
1235 BasicBlock *MappedBB = LPadTargetBlocks[BA->getBasicBlock()];
1236 assert(MappedBB->getParent() == OutlinedHandlerFn);
1237 BlockAddress *NewBA = BlockAddress::get(OutlinedHandlerFn, MappedBB);
1238 Ret->eraseFromParent();
1239 ReturnInst::Create(Context, NewBA, &NestedHandlerBB);
1240 ActionTargets.push_back(NewBA);
1241 }
1242 }
Andrew Kaylor7a0cec32015-04-03 21:44:17 +00001243 ActionList.clear();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001244
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001245 if (Branch) {
1246 // If the landing pad was already in outlined form, just update its targets.
1247 for (unsigned int I = Branch->getNumDestinations(); I > 0; --I)
1248 Branch->removeDestination(I);
1249 // Add the previously collected action targets.
1250 for (auto *Target : ActionTargets)
1251 Branch->addDestination(Target->getBasicBlock());
1252 } else {
1253 // If the landing pad was previously stubbed out, fill in its outlined form.
1254 IntrinsicInst *NewEHActions = cast<IntrinsicInst>(EHActions->clone());
1255 OutlinedBB->getInstList().push_back(NewEHActions);
1256
1257 // Insert an indirect branch into the outlined landing pad BB.
1258 IndirectBrInst *IBr = IndirectBrInst::Create(NewEHActions, 0, OutlinedBB);
1259 // Add the previously collected action targets.
1260 for (auto *Target : ActionTargets)
1261 IBr->addDestination(Target->getBasicBlock());
1262 }
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001263}
1264
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001265// This function examines a block to determine whether the block ends with a
1266// conditional branch to a catch handler based on a selector comparison.
1267// This function is used both by the WinEHPrepare::findSelectorComparison() and
1268// WinEHCleanupDirector::handleTypeIdFor().
1269static bool isSelectorDispatch(BasicBlock *BB, BasicBlock *&CatchHandler,
1270 Constant *&Selector, BasicBlock *&NextBB) {
1271 ICmpInst::Predicate Pred;
1272 BasicBlock *TBB, *FBB;
1273 Value *LHS, *RHS;
1274
1275 if (!match(BB->getTerminator(),
1276 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TBB, FBB)))
1277 return false;
1278
1279 if (!match(LHS,
1280 m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))) &&
1281 !match(RHS, m_Intrinsic<Intrinsic::eh_typeid_for>(m_Constant(Selector))))
1282 return false;
1283
1284 if (Pred == CmpInst::ICMP_EQ) {
1285 CatchHandler = TBB;
1286 NextBB = FBB;
1287 return true;
1288 }
1289
1290 if (Pred == CmpInst::ICMP_NE) {
1291 CatchHandler = FBB;
1292 NextBB = TBB;
1293 return true;
1294 }
1295
1296 return false;
1297}
1298
Andrew Kaylor41758512015-04-20 22:04:09 +00001299static bool isCatchBlock(BasicBlock *BB) {
1300 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
1301 II != IE; ++II) {
1302 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_begincatch>()))
1303 return true;
1304 }
1305 return false;
1306}
1307
David Majnemer7fddecc2015-06-17 20:52:32 +00001308static BasicBlock *createStubLandingPad(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001309 // FIXME: Finish this!
1310 LLVMContext &Context = Handler->getContext();
1311 BasicBlock *StubBB = BasicBlock::Create(Context, "stub");
1312 Handler->getBasicBlockList().push_back(StubBB);
1313 IRBuilder<> Builder(StubBB);
1314 LandingPadInst *LPad = Builder.CreateLandingPad(
1315 llvm::StructType::get(Type::getInt8PtrTy(Context),
1316 Type::getInt32Ty(Context), nullptr),
David Majnemer7fddecc2015-06-17 20:52:32 +00001317 0);
Andrew Kaylor43e1d762015-04-23 00:20:44 +00001318 // Insert a call to llvm.eh.actions so that we don't try to outline this lpad.
Andrew Kaylor91307432015-04-28 22:01:51 +00001319 Function *ActionIntrin =
1320 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::eh_actions);
David Blaikieff6409d2015-05-18 22:13:54 +00001321 Builder.CreateCall(ActionIntrin, {}, "recover");
Andrew Kaylorbb111322015-04-07 21:30:23 +00001322 LPad->setCleanup(true);
1323 Builder.CreateUnreachable();
1324 return StubBB;
1325}
1326
1327// Cycles through the blocks in an outlined handler function looking for an
1328// invoke instruction and inserts an invoke of llvm.donothing with an empty
1329// landing pad if none is found. The code that generates the .xdata tables for
1330// the handler needs at least one landing pad to identify the parent function's
1331// personality.
David Majnemer7fddecc2015-06-17 20:52:32 +00001332void WinEHPrepare::addStubInvokeToHandlerIfNeeded(Function *Handler) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001333 ReturnInst *Ret = nullptr;
Andrew Kaylor5f715522015-04-23 18:37:39 +00001334 UnreachableInst *Unreached = nullptr;
Andrew Kaylorbb111322015-04-07 21:30:23 +00001335 for (BasicBlock &BB : *Handler) {
1336 TerminatorInst *Terminator = BB.getTerminator();
1337 // If we find an invoke, there is nothing to be done.
1338 auto *II = dyn_cast<InvokeInst>(Terminator);
1339 if (II)
1340 return;
1341 // If we've already recorded a return instruction, keep looking for invokes.
Andrew Kaylor5f715522015-04-23 18:37:39 +00001342 if (!Ret)
1343 Ret = dyn_cast<ReturnInst>(Terminator);
1344 // If we haven't recorded an unreachable instruction, try this terminator.
1345 if (!Unreached)
1346 Unreached = dyn_cast<UnreachableInst>(Terminator);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001347 }
1348
1349 // If we got this far, the handler contains no invokes. We should have seen
Andrew Kaylor5f715522015-04-23 18:37:39 +00001350 // at least one return or unreachable instruction. We'll insert an invoke of
1351 // llvm.donothing ahead of that instruction.
1352 assert(Ret || Unreached);
1353 TerminatorInst *Term;
1354 if (Ret)
1355 Term = Ret;
1356 else
1357 Term = Unreached;
1358 BasicBlock *OldRetBB = Term->getParent();
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001359 BasicBlock *NewRetBB = SplitBlock(OldRetBB, Term, DT);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001360 // SplitBlock adds an unconditional branch instruction at the end of the
1361 // parent block. We want to replace that with an invoke call, so we can
1362 // erase it now.
1363 OldRetBB->getTerminator()->eraseFromParent();
David Majnemer7fddecc2015-06-17 20:52:32 +00001364 BasicBlock *StubLandingPad = createStubLandingPad(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001365 Function *F =
1366 Intrinsic::getDeclaration(Handler->getParent(), Intrinsic::donothing);
1367 InvokeInst::Create(F, NewRetBB, StubLandingPad, None, "", OldRetBB);
1368}
1369
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001370// FIXME: Consider sinking this into lib/Target/X86 somehow. TargetLowering
1371// usually doesn't build LLVM IR, so that's probably the wrong place.
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001372Function *WinEHPrepare::createHandlerFunc(Function *ParentFn, Type *RetTy,
1373 const Twine &Name, Module *M,
1374 Value *&ParentFP) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001375 // x64 uses a two-argument prototype where the parent FP is the second
1376 // argument. x86 uses no arguments, just the incoming EBP value.
1377 LLVMContext &Context = M->getContext();
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001378 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001379 FunctionType *FnType;
1380 if (TheTriple.getArch() == Triple::x86_64) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001381 Type *ArgTys[2] = {Int8PtrType, Int8PtrType};
1382 FnType = FunctionType::get(RetTy, ArgTys, false);
1383 } else {
1384 FnType = FunctionType::get(RetTy, None, false);
1385 }
1386
1387 Function *Handler =
1388 Function::Create(FnType, GlobalVariable::InternalLinkage, Name, M);
1389 BasicBlock *Entry = BasicBlock::Create(Context, "entry");
1390 Handler->getBasicBlockList().push_front(Entry);
1391 if (TheTriple.getArch() == Triple::x86_64) {
1392 ParentFP = &(Handler->getArgumentList().back());
1393 } else {
1394 assert(M);
1395 Function *FrameAddressFn =
1396 Intrinsic::getDeclaration(M, Intrinsic::frameaddress);
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001397 Function *RecoverFPFn =
1398 Intrinsic::getDeclaration(M, Intrinsic::x86_seh_recoverfp);
1399 IRBuilder<> Builder(&Handler->getEntryBlock());
1400 Value *EBP =
1401 Builder.CreateCall(FrameAddressFn, {Builder.getInt32(1)}, "ebp");
1402 Value *ParentI8Fn = Builder.CreateBitCast(ParentFn, Int8PtrType);
1403 ParentFP = Builder.CreateCall(RecoverFPFn, {ParentI8Fn, EBP});
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001404 }
1405 return Handler;
1406}
1407
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001408bool WinEHPrepare::outlineHandler(ActionHandler *Action, Function *SrcFn,
1409 LandingPadInst *LPad, BasicBlock *StartBB,
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001410 FrameVarInfoMap &VarInfo) {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001411 Module *M = SrcFn->getParent();
1412 LLVMContext &Context = M->getContext();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001413 Type *Int8PtrType = Type::getInt8PtrTy(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001414
1415 // Create a new function to receive the handler contents.
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001416 Value *ParentFP;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001417 Function *Handler;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001418 if (Action->getType() == Catch) {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001419 Handler = createHandlerFunc(SrcFn, Int8PtrType, SrcFn->getName() + ".catch", M,
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001420 ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001421 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00001422 Handler = createHandlerFunc(SrcFn, Type::getVoidTy(Context),
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001423 SrcFn->getName() + ".cleanup", M, ParentFP);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001424 }
David Majnemer7fddecc2015-06-17 20:52:32 +00001425 Handler->setPersonalityFn(SrcFn->getPersonalityFn());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001426 HandlerToParentFP[Handler] = ParentFP;
David Majnemercde33032015-03-30 22:58:10 +00001427 Handler->addFnAttr("wineh-parent", SrcFn->getName());
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001428 BasicBlock *Entry = &Handler->getEntryBlock();
David Majnemercde33032015-03-30 22:58:10 +00001429
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001430 // Generate a standard prolog to setup the frame recovery structure.
1431 IRBuilder<> Builder(Context);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001432 Builder.SetInsertPoint(Entry);
1433 Builder.SetCurrentDebugLocation(LPad->getDebugLoc());
1434
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001435 std::unique_ptr<WinEHCloningDirectorBase> Director;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001436
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001437 ValueToValueMapTy VMap;
1438
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001439 LandingPadMap &LPadMap = LPadMaps[LPad];
1440 if (!LPadMap.isInitialized())
1441 LPadMap.mapLandingPad(LPad);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001442 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1443 Constant *Sel = CatchAction->getSelector();
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001444 Director.reset(new WinEHCatchDirector(Handler, ParentFP, Sel, VarInfo,
1445 LPadMap, NestedLPtoOriginalLP, DT,
1446 EHBlocks));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001447 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1448 ConstantInt::get(Type::getInt32Ty(Context), 1));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001449 } else {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001450 Director.reset(
1451 new WinEHCleanupDirector(Handler, ParentFP, VarInfo, LPadMap));
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001452 LPadMap.remapEHValues(VMap, UndefValue::get(Int8PtrType),
1453 UndefValue::get(Type::getInt32Ty(Context)));
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001454 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001455
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001456 SmallVector<ReturnInst *, 8> Returns;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001457 ClonedCodeInfo OutlinedFunctionInfo;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001458
Andrew Kaylor3170e562015-03-20 21:42:54 +00001459 // If the start block contains PHI nodes, we need to map them.
1460 BasicBlock::iterator II = StartBB->begin();
1461 while (auto *PN = dyn_cast<PHINode>(II)) {
1462 bool Mapped = false;
1463 // Look for PHI values that we have already mapped (such as the selector).
1464 for (Value *Val : PN->incoming_values()) {
1465 if (VMap.count(Val)) {
1466 VMap[PN] = VMap[Val];
1467 Mapped = true;
1468 }
1469 }
1470 // If we didn't find a match for this value, map it as an undef.
1471 if (!Mapped) {
1472 VMap[PN] = UndefValue::get(PN->getType());
1473 }
1474 ++II;
1475 }
1476
Andrew Kaylor00e5d9e2015-04-20 22:53:42 +00001477 // The landing pad value may be used by PHI nodes. It will ultimately be
1478 // eliminated, but we need it in the map for intermediate handling.
1479 VMap[LPad] = UndefValue::get(LPad->getType());
1480
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001481 // Skip over PHIs and, if applicable, landingpad instructions.
Andrew Kaylor3170e562015-03-20 21:42:54 +00001482 II = StartBB->getFirstInsertionPt();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001483
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001484 CloneAndPruneIntoFromInst(Handler, SrcFn, II, VMap,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001485 /*ModuleLevelChanges=*/false, Returns, "",
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001486 &OutlinedFunctionInfo, Director.get());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001487
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001488 // Move all the instructions in the cloned "entry" block into our entry block.
1489 // Depending on how the parent function was laid out, the block that will
1490 // correspond to the outlined entry block may not be the first block in the
1491 // list. We can recognize it, however, as the cloned block which has no
1492 // predecessors. Any other block wouldn't have been cloned if it didn't
1493 // have a predecessor which was also cloned.
Andrew Kaylor91307432015-04-28 22:01:51 +00001494 Function::iterator ClonedIt = std::next(Function::iterator(Entry));
Andrew Kaylor5dacfd82015-04-24 23:10:38 +00001495 while (!pred_empty(ClonedIt))
1496 ++ClonedIt;
1497 BasicBlock *ClonedEntryBB = ClonedIt;
1498 assert(ClonedEntryBB);
1499 Entry->getInstList().splice(Entry->end(), ClonedEntryBB->getInstList());
1500 ClonedEntryBB->eraseFromParent();
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001501
Andrew Kaylorbb111322015-04-07 21:30:23 +00001502 // Make sure we can identify the handler's personality later.
David Majnemer7fddecc2015-06-17 20:52:32 +00001503 addStubInvokeToHandlerIfNeeded(Handler);
Andrew Kaylorbb111322015-04-07 21:30:23 +00001504
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001505 if (auto *CatchAction = dyn_cast<CatchHandler>(Action)) {
1506 WinEHCatchDirector *CatchDirector =
1507 reinterpret_cast<WinEHCatchDirector *>(Director.get());
1508 CatchAction->setExceptionVar(CatchDirector->getExceptionVar());
1509 CatchAction->setReturnTargets(CatchDirector->getReturnTargets());
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001510
1511 // Look for blocks that are not part of the landing pad that we just
1512 // outlined but terminate with a call to llvm.eh.endcatch and a
1513 // branch to a block that is in the handler we just outlined.
1514 // These blocks will be part of a nested landing pad that intends to
1515 // return to an address in this handler. This case is best handled
1516 // after both landing pads have been outlined, so for now we'll just
1517 // save the association of the blocks in LPadTargetBlocks. The
1518 // return instructions which are created from these branches will be
1519 // replaced after all landing pads have been outlined.
Richard Trieu6b1aa5f2015-04-15 01:21:15 +00001520 for (const auto MapEntry : VMap) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001521 // VMap maps all values and blocks that were just cloned, but dead
1522 // blocks which were pruned will map to nullptr.
1523 if (!isa<BasicBlock>(MapEntry.first) || MapEntry.second == nullptr)
1524 continue;
1525 const BasicBlock *MappedBB = cast<BasicBlock>(MapEntry.first);
1526 for (auto *Pred : predecessors(const_cast<BasicBlock *>(MappedBB))) {
1527 auto *Branch = dyn_cast<BranchInst>(Pred->getTerminator());
1528 if (!Branch || !Branch->isUnconditional() || Pred->size() <= 1)
1529 continue;
1530 BasicBlock::iterator II = const_cast<BranchInst *>(Branch);
1531 --II;
1532 if (match(cast<Value>(II), m_Intrinsic<Intrinsic::eh_endcatch>())) {
1533 // This would indicate that a nested landing pad wants to return
1534 // to a block that is outlined into two different handlers.
1535 assert(!LPadTargetBlocks.count(MappedBB));
1536 LPadTargetBlocks[MappedBB] = cast<BasicBlock>(MapEntry.second);
1537 }
1538 }
1539 }
1540 } // End if (CatchAction)
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001541
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001542 Action->setHandlerBlockOrFunc(Handler);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001543
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001544 return true;
1545}
1546
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001547/// This BB must end in a selector dispatch. All we need to do is pass the
1548/// handler block to llvm.eh.actions and list it as a possible indirectbr
1549/// target.
1550void WinEHPrepare::processSEHCatchHandler(CatchHandler *CatchAction,
1551 BasicBlock *StartBB) {
1552 BasicBlock *HandlerBB;
1553 BasicBlock *NextBB;
1554 Constant *Selector;
1555 bool Res = isSelectorDispatch(StartBB, HandlerBB, Selector, NextBB);
1556 if (Res) {
1557 // If this was EH dispatch, this must be a conditional branch to the handler
1558 // block.
1559 // FIXME: Handle instructions in the dispatch block. Currently we drop them,
1560 // leading to crashes if some optimization hoists stuff here.
1561 assert(CatchAction->getSelector() && HandlerBB &&
1562 "expected catch EH dispatch");
1563 } else {
1564 // This must be a catch-all. Split the block after the landingpad.
1565 assert(CatchAction->getSelector()->isNullValue() && "expected catch-all");
Andrew Kaylor046f7b42015-04-28 21:54:14 +00001566 HandlerBB = SplitBlock(StartBB, StartBB->getFirstInsertionPt(), DT);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001567 }
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001568 IRBuilder<> Builder(HandlerBB->getFirstInsertionPt());
1569 Function *EHCodeFn = Intrinsic::getDeclaration(
1570 StartBB->getParent()->getParent(), Intrinsic::eh_exceptioncode);
David Blaikieff6409d2015-05-18 22:13:54 +00001571 Value *Code = Builder.CreateCall(EHCodeFn, {}, "sehcode");
Reid Klecknercfbfe6f2015-04-24 20:25:05 +00001572 Code = Builder.CreateIntToPtr(Code, SEHExceptionCodeSlot->getAllocatedType());
1573 Builder.CreateStore(Code, SEHExceptionCodeSlot);
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00001574 CatchAction->setHandlerBlockOrFunc(BlockAddress::get(HandlerBB));
1575 TinyPtrVector<BasicBlock *> Targets(HandlerBB);
1576 CatchAction->setReturnTargets(Targets);
1577}
1578
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001579void LandingPadMap::mapLandingPad(const LandingPadInst *LPad) {
1580 // Each instance of this class should only ever be used to map a single
1581 // landing pad.
1582 assert(OriginLPad == nullptr || OriginLPad == LPad);
1583
1584 // If the landing pad has already been mapped, there's nothing more to do.
1585 if (OriginLPad == LPad)
1586 return;
1587
1588 OriginLPad = LPad;
1589
1590 // The landingpad instruction returns an aggregate value. Typically, its
1591 // value will be passed to a pair of extract value instructions and the
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001592 // results of those extracts will have been promoted to reg values before
1593 // this routine is called.
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001594 for (auto *U : LPad->users()) {
1595 const ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(U);
1596 if (!Extract)
1597 continue;
1598 assert(Extract->getNumIndices() == 1 &&
1599 "Unexpected operation: extracting both landing pad values");
1600 unsigned int Idx = *(Extract->idx_begin());
1601 assert((Idx == 0 || Idx == 1) &&
1602 "Unexpected operation: extracting an unknown landing pad element");
1603 if (Idx == 0) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001604 ExtractedEHPtrs.push_back(Extract);
1605 } else if (Idx == 1) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001606 ExtractedSelectors.push_back(Extract);
1607 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001608 }
1609}
1610
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001611bool LandingPadMap::isOriginLandingPadBlock(const BasicBlock *BB) const {
1612 return BB->getLandingPadInst() == OriginLPad;
1613}
1614
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001615bool LandingPadMap::isLandingPadSpecificInst(const Instruction *Inst) const {
1616 if (Inst == OriginLPad)
1617 return true;
1618 for (auto *Extract : ExtractedEHPtrs) {
1619 if (Inst == Extract)
1620 return true;
1621 }
1622 for (auto *Extract : ExtractedSelectors) {
1623 if (Inst == Extract)
1624 return true;
1625 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001626 return false;
1627}
1628
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001629void LandingPadMap::remapEHValues(ValueToValueMapTy &VMap, Value *EHPtrValue,
1630 Value *SelectorValue) const {
1631 // Remap all landing pad extract instructions to the specified values.
1632 for (auto *Extract : ExtractedEHPtrs)
1633 VMap[Extract] = EHPtrValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001634 for (auto *Extract : ExtractedSelectors)
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001635 VMap[Extract] = SelectorValue;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001636}
1637
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001638static bool isLocalAddressCall(const Value *V) {
1639 return match(const_cast<Value *>(V), m_Intrinsic<Intrinsic::localaddress>());
Reid Klecknerf14787d2015-04-22 00:07:52 +00001640}
1641
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001642CloningDirector::CloningAction WinEHCloningDirectorBase::handleInstruction(
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001643 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001644 // If this is one of the boilerplate landing pad instructions, skip it.
1645 // The instruction will have already been remapped in VMap.
1646 if (LPadMap.isLandingPadSpecificInst(Inst))
1647 return CloningDirector::SkipInstruction;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001648
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001649 // Nested landing pads that have not already been outlined will be cloned as
1650 // stubs, with just the landingpad instruction and an unreachable instruction.
1651 // When all landingpads have been outlined, we'll replace this with the
1652 // llvm.eh.actions call and indirect branch created when the landing pad was
1653 // outlined.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001654 if (auto *LPad = dyn_cast<LandingPadInst>(Inst)) {
1655 return handleLandingPad(VMap, LPad, NewBB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001656 }
1657
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001658 // Nested landing pads that have already been outlined will be cloned in their
1659 // outlined form, but we need to intercept the ibr instruction to filter out
1660 // targets that do not return to the handler we are outlining.
1661 if (auto *IBr = dyn_cast<IndirectBrInst>(Inst)) {
1662 return handleIndirectBr(VMap, IBr, NewBB);
1663 }
1664
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001665 if (auto *Invoke = dyn_cast<InvokeInst>(Inst))
1666 return handleInvoke(VMap, Invoke, NewBB);
1667
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001668 if (auto *Resume = dyn_cast<ResumeInst>(Inst))
1669 return handleResume(VMap, Resume, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001670
Andrew Kaylorea8df612015-04-17 23:05:43 +00001671 if (auto *Cmp = dyn_cast<CmpInst>(Inst))
1672 return handleCompare(VMap, Cmp, NewBB);
1673
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001674 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
1675 return handleBeginCatch(VMap, Inst, NewBB);
1676 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
1677 return handleEndCatch(VMap, Inst, NewBB);
1678 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
1679 return handleTypeIdFor(VMap, Inst, NewBB);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001680
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001681 // When outlining llvm.localaddress(), remap that to the second argument,
Reid Klecknerf14787d2015-04-22 00:07:52 +00001682 // which is the FP of the parent.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00001683 if (isLocalAddressCall(Inst)) {
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001684 VMap[Inst] = ParentFP;
Reid Klecknerf14787d2015-04-22 00:07:52 +00001685 return CloningDirector::SkipInstruction;
1686 }
1687
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001688 // Continue with the default cloning behavior.
1689 return CloningDirector::CloneInstruction;
1690}
1691
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001692CloningDirector::CloningAction WinEHCatchDirector::handleLandingPad(
1693 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001694 // If the instruction after the landing pad is a call to llvm.eh.actions
1695 // the landing pad has already been outlined. In this case, we should
1696 // clone it because it may return to a block in the handler we are
1697 // outlining now that would otherwise be unreachable. The landing pads
1698 // are sorted before outlining begins to enable this case to work
1699 // properly.
1700 const Instruction *NextI = LPad->getNextNode();
1701 if (match(NextI, m_Intrinsic<Intrinsic::eh_actions>()))
1702 return CloningDirector::CloneInstruction;
1703
1704 // If the landing pad hasn't been outlined yet, the landing pad we are
1705 // outlining now does not dominate it and so it cannot return to a block
1706 // in this handler. In that case, we can just insert a stub landing
1707 // pad now and patch it up later.
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001708 Instruction *NewInst = LPad->clone();
1709 if (LPad->hasName())
1710 NewInst->setName(LPad->getName());
1711 // Save this correlation for later processing.
1712 NestedLPtoOriginalLP[cast<LandingPadInst>(NewInst)] = LPad;
1713 VMap[LPad] = NewInst;
1714 BasicBlock::InstListType &InstList = NewBB->getInstList();
1715 InstList.push_back(NewInst);
1716 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1717 return CloningDirector::StopCloningBB;
1718}
1719
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001720CloningDirector::CloningAction WinEHCatchDirector::handleBeginCatch(
1721 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1722 // The argument to the call is some form of the first element of the
1723 // landingpad aggregate value, but that doesn't matter. It isn't used
1724 // here.
Reid Kleckner42366532015-03-03 23:20:30 +00001725 // The second argument is an outparameter where the exception object will be
1726 // stored. Typically the exception object is a scalar, but it can be an
1727 // aggregate when catching by value.
1728 // FIXME: Leave something behind to indicate where the exception object lives
1729 // for this handler. Should it be part of llvm.eh.actions?
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001730 assert(ExceptionObjectVar == nullptr && "Multiple calls to "
1731 "llvm.eh.begincatch found while "
1732 "outlining catch handler.");
1733 ExceptionObjectVar = Inst->getOperand(1)->stripPointerCasts();
Reid Kleckner3567d272015-04-02 21:13:31 +00001734 if (isa<ConstantPointerNull>(ExceptionObjectVar))
1735 return CloningDirector::SkipInstruction;
Reid Kleckneraab30e12015-04-03 18:18:06 +00001736 assert(cast<AllocaInst>(ExceptionObjectVar)->isStaticAlloca() &&
1737 "catch parameter is not static alloca");
Reid Kleckner3567d272015-04-02 21:13:31 +00001738 Materializer.escapeCatchObject(ExceptionObjectVar);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001739 return CloningDirector::SkipInstruction;
1740}
1741
1742CloningDirector::CloningAction
1743WinEHCatchDirector::handleEndCatch(ValueToValueMapTy &VMap,
1744 const Instruction *Inst, BasicBlock *NewBB) {
1745 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1746 // It might be interesting to track whether or not we are inside a catch
1747 // function, but that might make the algorithm more brittle than it needs
1748 // to be.
1749
1750 // The end catch call can occur in one of two places: either in a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001751 // landingpad block that is part of the catch handlers exception mechanism,
Andrew Kaylorf7118ae2015-03-27 22:31:12 +00001752 // or at the end of the catch block. However, a catch-all handler may call
1753 // end catch from the original landing pad. If the call occurs in a nested
1754 // landing pad block, we must skip it and continue so that the landing pad
1755 // gets cloned.
1756 auto *ParentBB = IntrinCall->getParent();
1757 if (ParentBB->isLandingPad() && !LPadMap.isOriginLandingPadBlock(ParentBB))
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001758 return CloningDirector::SkipInstruction;
1759
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001760 // If an end catch occurs anywhere else we want to terminate the handler
1761 // with a return to the code that follows the endcatch call. If the
1762 // next instruction is not an unconditional branch, we need to split the
1763 // block to provide a clear target for the return instruction.
1764 BasicBlock *ContinueBB;
1765 auto Next = std::next(BasicBlock::const_iterator(IntrinCall));
1766 const BranchInst *Branch = dyn_cast<BranchInst>(Next);
1767 if (!Branch || !Branch->isUnconditional()) {
1768 // We're interrupting the cloning process at this location, so the
1769 // const_cast we're doing here will not cause a problem.
1770 ContinueBB = SplitBlock(const_cast<BasicBlock *>(ParentBB),
1771 const_cast<Instruction *>(cast<Instruction>(Next)));
1772 } else {
1773 ContinueBB = Branch->getSuccessor(0);
1774 }
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001775
Andrew Kaylor64622aa2015-04-01 17:21:25 +00001776 ReturnInst::Create(NewBB->getContext(), BlockAddress::get(ContinueBB), NewBB);
1777 ReturnTargets.push_back(ContinueBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001778
1779 // We just added a terminator to the cloned block.
1780 // Tell the caller to stop processing the current basic block so that
1781 // the branch instruction will be skipped.
1782 return CloningDirector::StopCloningBB;
1783}
1784
1785CloningDirector::CloningAction WinEHCatchDirector::handleTypeIdFor(
1786 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
1787 auto *IntrinCall = dyn_cast<IntrinsicInst>(Inst);
1788 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1789 // This causes a replacement that will collapse the landing pad CFG based
1790 // on the filter function we intend to match.
1791 if (Selector == CurrentSelector)
1792 VMap[Inst] = ConstantInt::get(SelectorIDType, 1);
1793 else
1794 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
1795 // Tell the caller not to clone this instruction.
1796 return CloningDirector::SkipInstruction;
1797}
1798
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001799CloningDirector::CloningAction WinEHCatchDirector::handleIndirectBr(
1800 ValueToValueMapTy &VMap,
1801 const IndirectBrInst *IBr,
1802 BasicBlock *NewBB) {
1803 // If this indirect branch is not part of a landing pad block, just clone it.
1804 const BasicBlock *ParentBB = IBr->getParent();
1805 if (!ParentBB->isLandingPad())
1806 return CloningDirector::CloneInstruction;
1807
1808 // If it is part of a landing pad, we want to filter out target blocks
1809 // that are not part of the handler we are outlining.
1810 const LandingPadInst *LPad = ParentBB->getLandingPadInst();
1811
1812 // Save this correlation for later processing.
1813 NestedLPtoOriginalLP[cast<LandingPadInst>(VMap[LPad])] = LPad;
1814
1815 // We should only get here for landing pads that have already been outlined.
1816 assert(match(LPad->getNextNode(), m_Intrinsic<Intrinsic::eh_actions>()));
1817
1818 // Copy the indirectbr, but only include targets that were previously
1819 // identified as EH blocks and are dominated by the nested landing pad.
1820 SetVector<const BasicBlock *> ReturnTargets;
1821 for (int I = 0, E = IBr->getNumDestinations(); I < E; ++I) {
1822 auto *TargetBB = IBr->getDestination(I);
1823 if (EHBlocks.count(const_cast<BasicBlock*>(TargetBB)) &&
1824 DT->dominates(ParentBB, TargetBB)) {
1825 DEBUG(dbgs() << " Adding destination " << TargetBB->getName() << "\n");
1826 ReturnTargets.insert(TargetBB);
1827 }
1828 }
1829 IndirectBrInst *NewBranch =
1830 IndirectBrInst::Create(const_cast<Value *>(IBr->getAddress()),
1831 ReturnTargets.size(), NewBB);
1832 for (auto *Target : ReturnTargets)
1833 NewBranch->addDestination(const_cast<BasicBlock*>(Target));
1834
1835 // The operands and targets of the branch instruction are remapped later
1836 // because it is a terminator. Tell the cloning code to clone the
1837 // blocks we just added to the target list.
1838 return CloningDirector::CloneSuccessors;
1839}
1840
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001841CloningDirector::CloningAction
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001842WinEHCatchDirector::handleInvoke(ValueToValueMapTy &VMap,
1843 const InvokeInst *Invoke, BasicBlock *NewBB) {
1844 return CloningDirector::CloneInstruction;
1845}
1846
1847CloningDirector::CloningAction
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001848WinEHCatchDirector::handleResume(ValueToValueMapTy &VMap,
1849 const ResumeInst *Resume, BasicBlock *NewBB) {
1850 // Resume instructions shouldn't be reachable from catch handlers.
1851 // We still need to handle it, but it will be pruned.
1852 BasicBlock::InstListType &InstList = NewBB->getInstList();
1853 InstList.push_back(new UnreachableInst(NewBB->getContext()));
1854 return CloningDirector::StopCloningBB;
1855}
1856
Andrew Kaylorea8df612015-04-17 23:05:43 +00001857CloningDirector::CloningAction
1858WinEHCatchDirector::handleCompare(ValueToValueMapTy &VMap,
1859 const CmpInst *Compare, BasicBlock *NewBB) {
1860 const IntrinsicInst *IntrinCall = nullptr;
1861 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1862 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(0));
Andrew Kaylor91307432015-04-28 22:01:51 +00001863 } else if (match(Compare->getOperand(1),
1864 m_Intrinsic<Intrinsic::eh_typeid_for>())) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001865 IntrinCall = dyn_cast<IntrinsicInst>(Compare->getOperand(1));
1866 }
1867 if (IntrinCall) {
1868 Value *Selector = IntrinCall->getArgOperand(0)->stripPointerCasts();
1869 // This causes a replacement that will collapse the landing pad CFG based
1870 // on the filter function we intend to match.
1871 if (Selector == CurrentSelector->stripPointerCasts()) {
1872 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
Andrew Kaylor91307432015-04-28 22:01:51 +00001873 } else {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001874 VMap[Compare] = ConstantInt::get(SelectorIDType, 0);
1875 }
1876 return CloningDirector::SkipInstruction;
1877 }
1878 return CloningDirector::CloneInstruction;
1879}
1880
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001881CloningDirector::CloningAction WinEHCleanupDirector::handleLandingPad(
1882 ValueToValueMapTy &VMap, const LandingPadInst *LPad, BasicBlock *NewBB) {
1883 // The MS runtime will terminate the process if an exception occurs in a
1884 // cleanup handler, so we shouldn't encounter landing pads in the actual
1885 // cleanup code, but they may appear in catch blocks. Depending on where
1886 // we started cloning we may see one, but it will get dropped during dead
1887 // block pruning.
1888 Instruction *NewInst = new UnreachableInst(NewBB->getContext());
1889 VMap[LPad] = NewInst;
1890 BasicBlock::InstListType &InstList = NewBB->getInstList();
1891 InstList.push_back(NewInst);
1892 return CloningDirector::StopCloningBB;
1893}
1894
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001895CloningDirector::CloningAction WinEHCleanupDirector::handleBeginCatch(
1896 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001897 // Cleanup code may flow into catch blocks or the catch block may be part
1898 // of a branch that will be optimized away. We'll insert a return
1899 // instruction now, but it may be pruned before the cloning process is
1900 // complete.
1901 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001902 return CloningDirector::StopCloningBB;
1903}
1904
1905CloningDirector::CloningAction WinEHCleanupDirector::handleEndCatch(
1906 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylorbb111322015-04-07 21:30:23 +00001907 // Cleanup handlers nested within catch handlers may begin with a call to
1908 // eh.endcatch. We can just ignore that instruction.
1909 return CloningDirector::SkipInstruction;
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001910}
1911
1912CloningDirector::CloningAction WinEHCleanupDirector::handleTypeIdFor(
1913 ValueToValueMapTy &VMap, const Instruction *Inst, BasicBlock *NewBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001914 // If we encounter a selector comparison while cloning a cleanup handler,
1915 // we want to stop cloning immediately. Anything after the dispatch
1916 // will be outlined into a different handler.
1917 BasicBlock *CatchHandler;
1918 Constant *Selector;
1919 BasicBlock *NextBB;
1920 if (isSelectorDispatch(const_cast<BasicBlock *>(Inst->getParent()),
1921 CatchHandler, Selector, NextBB)) {
1922 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1923 return CloningDirector::StopCloningBB;
1924 }
1925 // If eg.typeid.for is called for any other reason, it can be ignored.
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001926 VMap[Inst] = ConstantInt::get(SelectorIDType, 0);
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001927 return CloningDirector::SkipInstruction;
1928}
1929
Andrew Kaylora6c5b962015-05-20 23:22:24 +00001930CloningDirector::CloningAction WinEHCleanupDirector::handleIndirectBr(
1931 ValueToValueMapTy &VMap,
1932 const IndirectBrInst *IBr,
1933 BasicBlock *NewBB) {
1934 // No special handling is required for cleanup cloning.
1935 return CloningDirector::CloneInstruction;
1936}
1937
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001938CloningDirector::CloningAction WinEHCleanupDirector::handleInvoke(
1939 ValueToValueMapTy &VMap, const InvokeInst *Invoke, BasicBlock *NewBB) {
1940 // All invokes in cleanup handlers can be replaced with calls.
1941 SmallVector<Value *, 16> CallArgs(Invoke->op_begin(), Invoke->op_end() - 3);
1942 // Insert a normal call instruction...
1943 CallInst *NewCall =
1944 CallInst::Create(const_cast<Value *>(Invoke->getCalledValue()), CallArgs,
1945 Invoke->getName(), NewBB);
1946 NewCall->setCallingConv(Invoke->getCallingConv());
1947 NewCall->setAttributes(Invoke->getAttributes());
1948 NewCall->setDebugLoc(Invoke->getDebugLoc());
1949 VMap[Invoke] = NewCall;
1950
Reid Kleckner6e48a822015-04-10 16:26:42 +00001951 // Remap the operands.
1952 llvm::RemapInstruction(NewCall, VMap, RF_None, nullptr, &Materializer);
1953
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001954 // Insert an unconditional branch to the normal destination.
1955 BranchInst::Create(Invoke->getNormalDest(), NewBB);
1956
1957 // The unwind destination won't be cloned into the new function, so
1958 // we don't need to clean up its phi nodes.
1959
1960 // We just added a terminator to the cloned block.
1961 // Tell the caller to stop processing the current basic block.
Reid Kleckner6e48a822015-04-10 16:26:42 +00001962 return CloningDirector::CloneSuccessors;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00001963}
1964
Andrew Kaylorf0f5e462015-03-03 20:00:16 +00001965CloningDirector::CloningAction WinEHCleanupDirector::handleResume(
1966 ValueToValueMapTy &VMap, const ResumeInst *Resume, BasicBlock *NewBB) {
1967 ReturnInst::Create(NewBB->getContext(), nullptr, NewBB);
1968
1969 // We just added a terminator to the cloned block.
1970 // Tell the caller to stop processing the current basic block so that
1971 // the branch instruction will be skipped.
1972 return CloningDirector::StopCloningBB;
1973}
1974
Andrew Kaylorea8df612015-04-17 23:05:43 +00001975CloningDirector::CloningAction
1976WinEHCleanupDirector::handleCompare(ValueToValueMapTy &VMap,
1977 const CmpInst *Compare, BasicBlock *NewBB) {
Andrew Kaylorea8df612015-04-17 23:05:43 +00001978 if (match(Compare->getOperand(0), m_Intrinsic<Intrinsic::eh_typeid_for>()) ||
1979 match(Compare->getOperand(1), m_Intrinsic<Intrinsic::eh_typeid_for>())) {
1980 VMap[Compare] = ConstantInt::get(SelectorIDType, 1);
1981 return CloningDirector::SkipInstruction;
1982 }
1983 return CloningDirector::CloneInstruction;
Andrew Kaylorea8df612015-04-17 23:05:43 +00001984}
1985
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001986WinEHFrameVariableMaterializer::WinEHFrameVariableMaterializer(
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001987 Function *OutlinedFn, Value *ParentFP, FrameVarInfoMap &FrameVarInfo)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001988 : FrameVarInfo(FrameVarInfo), Builder(OutlinedFn->getContext()) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00001989 BasicBlock *EntryBB = &OutlinedFn->getEntryBlock();
Reid Klecknerbcda1cd2015-04-29 22:49:54 +00001990
1991 // New allocas should be inserted in the entry block, but after the parent FP
1992 // is established if it is an instruction.
1993 Instruction *InsertPoint = EntryBB->getFirstInsertionPt();
1994 if (auto *FPInst = dyn_cast<Instruction>(ParentFP))
1995 InsertPoint = FPInst->getNextNode();
1996 Builder.SetInsertPoint(EntryBB, InsertPoint);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001997}
1998
1999Value *WinEHFrameVariableMaterializer::materializeValueFor(Value *V) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002000 // If we're asked to materialize a static alloca, we temporarily create an
2001 // alloca in the outlined function and add this to the FrameVarInfo map. When
2002 // all the outlining is complete, we'll replace these temporary allocas with
Reid Kleckner60381792015-07-07 22:25:32 +00002003 // calls to llvm.localrecover.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002004 if (auto *AV = dyn_cast<AllocaInst>(V)) {
Reid Klecknerfd7df282015-04-22 21:05:21 +00002005 assert(AV->isStaticAlloca() &&
2006 "cannot materialize un-demoted dynamic alloca");
Andrew Kaylor72029c62015-03-03 00:41:03 +00002007 AllocaInst *NewAlloca = dyn_cast<AllocaInst>(AV->clone());
2008 Builder.Insert(NewAlloca, AV->getName());
Reid Klecknercfb9ce52015-03-05 18:26:34 +00002009 FrameVarInfo[AV].push_back(NewAlloca);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002010 return NewAlloca;
2011 }
2012
Andrew Kaylor72029c62015-03-03 00:41:03 +00002013 if (isa<Instruction>(V) || isa<Argument>(V)) {
Reid Klecknerd1b38c42015-05-06 18:45:24 +00002014 Function *Parent = isa<Instruction>(V)
2015 ? cast<Instruction>(V)->getParent()->getParent()
2016 : cast<Argument>(V)->getParent();
2017 errs()
2018 << "Failed to demote instruction used in exception handler of function "
2019 << GlobalValue::getRealLinkageName(Parent->getName()) << ":\n";
Reid Klecknerfd7df282015-04-22 21:05:21 +00002020 errs() << " " << *V << '\n';
2021 report_fatal_error("WinEHPrepare failed to demote instruction");
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002022 }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002023
Andrew Kaylor72029c62015-03-03 00:41:03 +00002024 // Don't materialize other values.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00002025 return nullptr;
2026}
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002027
Reid Kleckner3567d272015-04-02 21:13:31 +00002028void WinEHFrameVariableMaterializer::escapeCatchObject(Value *V) {
2029 // Catch parameter objects have to live in the parent frame. When we see a use
2030 // of a catch parameter, add a sentinel to the multimap to indicate that it's
2031 // used from another handler. This will prevent us from trying to sink the
2032 // alloca into the handler and ensure that the catch parameter is present in
Reid Kleckner60381792015-07-07 22:25:32 +00002033 // the call to llvm.localescape.
Reid Kleckner3567d272015-04-02 21:13:31 +00002034 FrameVarInfo[V].push_back(getCatchObjectSentinel());
2035}
2036
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002037// This function maps the catch and cleanup handlers that are reachable from the
2038// specified landing pad. The landing pad sequence will have this basic shape:
2039//
2040// <cleanup handler>
2041// <selector comparison>
2042// <catch handler>
2043// <cleanup handler>
2044// <selector comparison>
2045// <catch handler>
2046// <cleanup handler>
2047// ...
2048//
2049// Any of the cleanup slots may be absent. The cleanup slots may be occupied by
2050// any arbitrary control flow, but all paths through the cleanup code must
2051// eventually reach the next selector comparison and no path can skip to a
2052// different selector comparisons, though some paths may terminate abnormally.
2053// Therefore, we will use a depth first search from the start of any given
2054// cleanup block and stop searching when we find the next selector comparison.
2055//
2056// If the landingpad instruction does not have a catch clause, we will assume
2057// that any instructions other than selector comparisons and catch handlers can
2058// be ignored. In practice, these will only be the boilerplate instructions.
2059//
2060// The catch handlers may also have any control structure, but we are only
2061// interested in the start of the catch handlers, so we don't need to actually
2062// follow the flow of the catch handlers. The start of the catch handlers can
2063// be located from the compare instructions, but they can be skipped in the
2064// flow by following the contrary branch.
2065void WinEHPrepare::mapLandingPadBlocks(LandingPadInst *LPad,
2066 LandingPadActions &Actions) {
2067 unsigned int NumClauses = LPad->getNumClauses();
2068 unsigned int HandlersFound = 0;
2069 BasicBlock *BB = LPad->getParent();
2070
2071 DEBUG(dbgs() << "Mapping landing pad: " << BB->getName() << "\n");
2072
2073 if (NumClauses == 0) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002074 findCleanupHandlers(Actions, BB, nullptr);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002075 return;
2076 }
2077
2078 VisitedBlockSet VisitedBlocks;
2079
2080 while (HandlersFound != NumClauses) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002081 BasicBlock *NextBB = nullptr;
2082
Andrew Kaylor20ae2a32015-04-23 22:38:36 +00002083 // Skip over filter clauses.
2084 if (LPad->isFilter(HandlersFound)) {
2085 ++HandlersFound;
2086 continue;
2087 }
2088
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002089 // See if the clause we're looking for is a catch-all.
2090 // If so, the catch begins immediately.
Andrew Kaylor91307432015-04-28 22:01:51 +00002091 Constant *ExpectedSelector =
2092 LPad->getClause(HandlersFound)->stripPointerCasts();
Andrew Kaylorea8df612015-04-17 23:05:43 +00002093 if (isa<ConstantPointerNull>(ExpectedSelector)) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002094 // The catch all must occur last.
2095 assert(HandlersFound == NumClauses - 1);
2096
Andrew Kaylorea8df612015-04-17 23:05:43 +00002097 // There can be additional selector dispatches in the call chain that we
2098 // need to ignore.
2099 BasicBlock *CatchBlock = nullptr;
2100 Constant *Selector;
2101 while (BB && isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2102 DEBUG(dbgs() << " Found extra catch dispatch in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002103 << CatchBlock->getName() << "\n");
Andrew Kaylorea8df612015-04-17 23:05:43 +00002104 BB = NextBB;
2105 }
2106
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002107 // Add the catch handler to the action list.
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002108 CatchHandler *Action = nullptr;
2109 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2110 // If the CatchHandlerMap already has an entry for this BB, re-use it.
2111 Action = CatchHandlerMap[BB];
2112 assert(Action->getSelector() == ExpectedSelector);
2113 } else {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002114 // We don't expect a selector dispatch, but there may be a call to
2115 // llvm.eh.begincatch, which separates catch handling code from
2116 // cleanup code in the same control flow. This call looks for the
2117 // begincatch intrinsic.
2118 Action = findCatchHandler(BB, NextBB, VisitedBlocks);
2119 if (Action) {
2120 // For C++ EH, check if there is any interesting cleanup code before
2121 // we begin the catch. This is important because cleanups cannot
2122 // rethrow exceptions but code called from catches can. For SEH, it
2123 // isn't important if some finally code before a catch-all is executed
2124 // out of line or after recovering from the exception.
2125 if (Personality == EHPersonality::MSVC_CXX)
2126 findCleanupHandlers(Actions, BB, BB);
2127 } else {
2128 // If an action was not found, it means that the control flows
2129 // directly into the catch-all handler and there is no cleanup code.
2130 // That's an expected situation and we must create a catch action.
2131 // Since this is a catch-all handler, the selector won't actually
2132 // appear in the code anywhere. ExpectedSelector here is the constant
2133 // null ptr that we got from the landing pad instruction.
2134 Action = new CatchHandler(BB, ExpectedSelector, nullptr);
2135 CatchHandlerMap[BB] = Action;
2136 }
Andrew Kaylorf18771b2015-04-20 18:48:45 +00002137 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002138 Actions.insertCatchHandler(Action);
2139 DEBUG(dbgs() << " Catch all handler at block " << BB->getName() << "\n");
2140 ++HandlersFound;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002141
2142 // Once we reach a catch-all, don't expect to hit a resume instruction.
2143 BB = nullptr;
2144 break;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002145 }
2146
2147 CatchHandler *CatchAction = findCatchHandler(BB, NextBB, VisitedBlocks);
Andrew Kaylor41758512015-04-20 22:04:09 +00002148 assert(CatchAction);
2149
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002150 // See if there is any interesting code executed before the dispatch.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002151 findCleanupHandlers(Actions, BB, CatchAction->getStartBlock());
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002152
Andrew Kaylorea8df612015-04-17 23:05:43 +00002153 // When the source program contains multiple nested try blocks the catch
2154 // handlers can get strung together in such a way that we can encounter
2155 // a dispatch for a selector that we've already had a handler for.
2156 if (CatchAction->getSelector()->stripPointerCasts() == ExpectedSelector) {
2157 ++HandlersFound;
2158
2159 // Add the catch handler to the action list.
2160 DEBUG(dbgs() << " Found catch dispatch in block "
2161 << CatchAction->getStartBlock()->getName() << "\n");
2162 Actions.insertCatchHandler(CatchAction);
2163 } else {
Andrew Kaylor41758512015-04-20 22:04:09 +00002164 // Under some circumstances optimized IR will flow unconditionally into a
2165 // handler block without checking the selector. This can only happen if
2166 // the landing pad has a catch-all handler and the handler for the
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002167 // preceding catch clause is identical to the catch-call handler
Andrew Kaylor41758512015-04-20 22:04:09 +00002168 // (typically an empty catch). In this case, the handler must be shared
2169 // by all remaining clauses.
2170 if (isa<ConstantPointerNull>(
2171 CatchAction->getSelector()->stripPointerCasts())) {
2172 DEBUG(dbgs() << " Applying early catch-all handler in block "
2173 << CatchAction->getStartBlock()->getName()
2174 << " to all remaining clauses.\n");
2175 Actions.insertCatchHandler(CatchAction);
2176 return;
2177 }
2178
Andrew Kaylorea8df612015-04-17 23:05:43 +00002179 DEBUG(dbgs() << " Found extra catch dispatch in block "
2180 << CatchAction->getStartBlock()->getName() << "\n");
2181 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002182
2183 // Move on to the block after the catch handler.
2184 BB = NextBB;
2185 }
2186
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002187 // If we didn't wind up in a catch-all, see if there is any interesting code
2188 // executed before the resume.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002189 findCleanupHandlers(Actions, BB, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002190
2191 // It's possible that some optimization moved code into a landingpad that
2192 // wasn't
2193 // previously being used for cleanup. If that happens, we need to execute
2194 // that
2195 // extra code from a cleanup handler.
2196 if (Actions.includesCleanup() && !LPad->isCleanup())
2197 LPad->setCleanup(true);
2198}
2199
2200// This function searches starting with the input block for the next
2201// block that terminates with a branch whose condition is based on a selector
2202// comparison. This may be the input block. See the mapLandingPadBlocks
2203// comments for a discussion of control flow assumptions.
2204//
2205CatchHandler *WinEHPrepare::findCatchHandler(BasicBlock *BB,
2206 BasicBlock *&NextBB,
2207 VisitedBlockSet &VisitedBlocks) {
2208 // See if we've already found a catch handler use it.
2209 // Call count() first to avoid creating a null entry for blocks
2210 // we haven't seen before.
2211 if (CatchHandlerMap.count(BB) && CatchHandlerMap[BB] != nullptr) {
2212 CatchHandler *Action = cast<CatchHandler>(CatchHandlerMap[BB]);
2213 NextBB = Action->getNextBB();
2214 return Action;
2215 }
2216
2217 // VisitedBlocks applies only to the current search. We still
2218 // need to consider blocks that we've visited while mapping other
2219 // landing pads.
2220 VisitedBlocks.insert(BB);
2221
2222 BasicBlock *CatchBlock = nullptr;
2223 Constant *Selector = nullptr;
2224
2225 // If this is the first time we've visited this block from any landing pad
2226 // look to see if it is a selector dispatch block.
2227 if (!CatchHandlerMap.count(BB)) {
2228 if (isSelectorDispatch(BB, CatchBlock, Selector, NextBB)) {
2229 CatchHandler *Action = new CatchHandler(BB, Selector, NextBB);
2230 CatchHandlerMap[BB] = Action;
2231 return Action;
2232 }
Andrew Kaylor41758512015-04-20 22:04:09 +00002233 // If we encounter a block containing an llvm.eh.begincatch before we
2234 // find a selector dispatch block, the handler is assumed to be
2235 // reached unconditionally. This happens for catch-all blocks, but
2236 // it can also happen for other catch handlers that have been combined
2237 // with the catch-all handler during optimization.
2238 if (isCatchBlock(BB)) {
2239 PointerType *Int8PtrTy = Type::getInt8PtrTy(BB->getContext());
2240 Constant *NullSelector = ConstantPointerNull::get(Int8PtrTy);
2241 CatchHandler *Action = new CatchHandler(BB, NullSelector, nullptr);
2242 CatchHandlerMap[BB] = Action;
2243 return Action;
2244 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002245 }
2246
2247 // Visit each successor, looking for the dispatch.
2248 // FIXME: We expect to find the dispatch quickly, so this will probably
2249 // work better as a breadth first search.
2250 for (BasicBlock *Succ : successors(BB)) {
2251 if (VisitedBlocks.count(Succ))
2252 continue;
2253
2254 CatchHandler *Action = findCatchHandler(Succ, NextBB, VisitedBlocks);
2255 if (Action)
2256 return Action;
2257 }
2258 return nullptr;
2259}
2260
Reid Kleckner9405ef02015-04-10 23:12:29 +00002261// These are helper functions to combine repeated code from findCleanupHandlers.
2262static void createCleanupHandler(LandingPadActions &Actions,
2263 CleanupHandlerMapTy &CleanupHandlerMap,
2264 BasicBlock *BB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002265 CleanupHandler *Action = new CleanupHandler(BB);
2266 CleanupHandlerMap[BB] = Action;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002267 Actions.insertCleanupHandler(Action);
2268 DEBUG(dbgs() << " Found cleanup code in block "
2269 << Action->getStartBlock()->getName() << "\n");
2270}
2271
Reid Kleckner9405ef02015-04-10 23:12:29 +00002272static CallSite matchOutlinedFinallyCall(BasicBlock *BB,
2273 Instruction *MaybeCall) {
2274 // Look for finally blocks that Clang has already outlined for us.
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002275 // %fp = call i8* @llvm.localaddress()
Reid Kleckner9405ef02015-04-10 23:12:29 +00002276 // call void @"fin$parent"(iN 1, i8* %fp)
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002277 if (isLocalAddressCall(MaybeCall) && MaybeCall != BB->getTerminator())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002278 MaybeCall = MaybeCall->getNextNode();
2279 CallSite FinallyCall(MaybeCall);
2280 if (!FinallyCall || FinallyCall.arg_size() != 2)
2281 return CallSite();
2282 if (!match(FinallyCall.getArgument(0), m_SpecificInt(1)))
2283 return CallSite();
Reid Klecknerd5afc62f2015-07-07 23:23:03 +00002284 if (!isLocalAddressCall(FinallyCall.getArgument(1)))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002285 return CallSite();
2286 return FinallyCall;
2287}
2288
2289static BasicBlock *followSingleUnconditionalBranches(BasicBlock *BB) {
2290 // Skip single ubr blocks.
2291 while (BB->getFirstNonPHIOrDbg() == BB->getTerminator()) {
2292 auto *Br = dyn_cast<BranchInst>(BB->getTerminator());
2293 if (Br && Br->isUnconditional())
2294 BB = Br->getSuccessor(0);
2295 else
2296 return BB;
2297 }
2298 return BB;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002299}
2300
2301// This function searches starting with the input block for the next block that
2302// contains code that is not part of a catch handler and would not be eliminated
2303// during handler outlining.
2304//
Reid Kleckner9405ef02015-04-10 23:12:29 +00002305void WinEHPrepare::findCleanupHandlers(LandingPadActions &Actions,
2306 BasicBlock *StartBB, BasicBlock *EndBB) {
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002307 // Here we will skip over the following:
2308 //
2309 // landing pad prolog:
2310 //
2311 // Unconditional branches
2312 //
2313 // Selector dispatch
2314 //
2315 // Resume pattern
2316 //
2317 // Anything else marks the start of an interesting block
2318
2319 BasicBlock *BB = StartBB;
2320 // Anything other than an unconditional branch will kick us out of this loop
2321 // one way or another.
2322 while (BB) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002323 BB = followSingleUnconditionalBranches(BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002324 // If we've already scanned this block, don't scan it again. If it is
2325 // a cleanup block, there will be an action in the CleanupHandlerMap.
2326 // If we've scanned it and it is not a cleanup block, there will be a
2327 // nullptr in the CleanupHandlerMap. If we have not scanned it, there will
2328 // be no entry in the CleanupHandlerMap. We must call count() first to
2329 // avoid creating a null entry for blocks we haven't scanned.
2330 if (CleanupHandlerMap.count(BB)) {
2331 if (auto *Action = CleanupHandlerMap[BB]) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002332 Actions.insertCleanupHandler(Action);
2333 DEBUG(dbgs() << " Found cleanup code in block "
Andrew Kaylor91307432015-04-28 22:01:51 +00002334 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002335 // FIXME: This cleanup might chain into another, and we need to discover
2336 // that.
2337 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002338 } else {
2339 // Here we handle the case where the cleanup handler map contains a
2340 // value for this block but the value is a nullptr. This means that
2341 // we have previously analyzed the block and determined that it did
2342 // not contain any cleanup code. Based on the earlier analysis, we
Eric Christopher572e03a2015-06-19 01:53:21 +00002343 // know the block must end in either an unconditional branch, a
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002344 // resume or a conditional branch that is predicated on a comparison
2345 // with a selector. Either the resume or the selector dispatch
2346 // would terminate the search for cleanup code, so the unconditional
2347 // branch is the only case for which we might need to continue
2348 // searching.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002349 BasicBlock *SuccBB = followSingleUnconditionalBranches(BB);
2350 if (SuccBB == BB || SuccBB == EndBB)
2351 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002352 BB = SuccBB;
2353 continue;
2354 }
2355 }
2356
2357 // Create an entry in the cleanup handler map for this block. Initially
2358 // we create an entry that says this isn't a cleanup block. If we find
2359 // cleanup code, the caller will replace this entry.
2360 CleanupHandlerMap[BB] = nullptr;
2361
2362 TerminatorInst *Terminator = BB->getTerminator();
2363
2364 // Landing pad blocks have extra instructions we need to accept.
2365 LandingPadMap *LPadMap = nullptr;
2366 if (BB->isLandingPad()) {
2367 LandingPadInst *LPad = BB->getLandingPadInst();
2368 LPadMap = &LPadMaps[LPad];
2369 if (!LPadMap->isInitialized())
2370 LPadMap->mapLandingPad(LPad);
2371 }
2372
2373 // Look for the bare resume pattern:
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002374 // %lpad.val1 = insertvalue { i8*, i32 } undef, i8* %exn, 0
2375 // %lpad.val2 = insertvalue { i8*, i32 } %lpad.val1, i32 %sel, 1
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002376 // resume { i8*, i32 } %lpad.val2
2377 if (auto *Resume = dyn_cast<ResumeInst>(Terminator)) {
2378 InsertValueInst *Insert1 = nullptr;
2379 InsertValueInst *Insert2 = nullptr;
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002380 Value *ResumeVal = Resume->getOperand(0);
Reid Kleckner1c130bb2015-04-16 17:02:23 +00002381 // If the resume value isn't a phi or landingpad value, it should be a
2382 // series of insertions. Identify them so we can avoid them when scanning
2383 // for cleanups.
2384 if (!isa<PHINode>(ResumeVal) && !isa<LandingPadInst>(ResumeVal)) {
Reid Kleckner0f9e27a2015-03-18 20:26:53 +00002385 Insert2 = dyn_cast<InsertValueInst>(ResumeVal);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002386 if (!Insert2)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002387 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002388 Insert1 = dyn_cast<InsertValueInst>(Insert2->getAggregateOperand());
2389 if (!Insert1)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002390 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002391 }
2392 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2393 II != IE; ++II) {
2394 Instruction *Inst = II;
2395 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2396 continue;
2397 if (Inst == Insert1 || Inst == Insert2 || Inst == Resume)
2398 continue;
2399 if (!Inst->hasOneUse() ||
2400 (Inst->user_back() != Insert1 && Inst->user_back() != Insert2)) {
Reid Kleckner9405ef02015-04-10 23:12:29 +00002401 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002402 }
2403 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002404 return;
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002405 }
2406
2407 BranchInst *Branch = dyn_cast<BranchInst>(Terminator);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002408 if (Branch && Branch->isConditional()) {
2409 // Look for the selector dispatch.
2410 // %2 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIf to i8*))
2411 // %matches = icmp eq i32 %sel, %2
2412 // br i1 %matches, label %catch14, label %eh.resume
2413 CmpInst *Compare = dyn_cast<CmpInst>(Branch->getCondition());
2414 if (!Compare || !Compare->isEquality())
Reid Kleckner9405ef02015-04-10 23:12:29 +00002415 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylorbb111322015-04-07 21:30:23 +00002416 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2417 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002418 Instruction *Inst = II;
2419 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2420 continue;
2421 if (Inst == Compare || Inst == Branch)
2422 continue;
2423 if (match(Inst, m_Intrinsic<Intrinsic::eh_typeid_for>()))
2424 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002425 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002426 }
2427 // The selector dispatch block should always terminate our search.
2428 assert(BB == EndBB);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002429 return;
2430 }
2431
2432 if (isAsynchronousEHPersonality(Personality)) {
2433 // If this is a landingpad block, split the block at the first non-landing
2434 // pad instruction.
2435 Instruction *MaybeCall = BB->getFirstNonPHIOrDbg();
2436 if (LPadMap) {
2437 while (MaybeCall != BB->getTerminator() &&
2438 LPadMap->isLandingPadSpecificInst(MaybeCall))
2439 MaybeCall = MaybeCall->getNextNode();
2440 }
2441
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002442 // Look for outlined finally calls on x64, since those happen to match the
2443 // prototype provided by the runtime.
2444 if (TheTriple.getArch() == Triple::x86_64) {
2445 if (CallSite FinallyCall = matchOutlinedFinallyCall(BB, MaybeCall)) {
2446 Function *Fin = FinallyCall.getCalledFunction();
2447 assert(Fin && "outlined finally call should be direct");
2448 auto *Action = new CleanupHandler(BB);
2449 Action->setHandlerBlockOrFunc(Fin);
2450 Actions.insertCleanupHandler(Action);
2451 CleanupHandlerMap[BB] = Action;
2452 DEBUG(dbgs() << " Found frontend-outlined finally call to "
2453 << Fin->getName() << " in block "
2454 << Action->getStartBlock()->getName() << "\n");
Reid Kleckner9405ef02015-04-10 23:12:29 +00002455
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002456 // Split the block if there were more interesting instructions and
2457 // look for finally calls in the normal successor block.
2458 BasicBlock *SuccBB = BB;
2459 if (FinallyCall.getInstruction() != BB->getTerminator() &&
2460 FinallyCall.getInstruction()->getNextNode() !=
2461 BB->getTerminator()) {
Andrew Kaylor046f7b42015-04-28 21:54:14 +00002462 SuccBB =
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002463 SplitBlock(BB, FinallyCall.getInstruction()->getNextNode(), DT);
Reid Kleckner9405ef02015-04-10 23:12:29 +00002464 } else {
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002465 if (FinallyCall.isInvoke()) {
2466 SuccBB = cast<InvokeInst>(FinallyCall.getInstruction())
2467 ->getNormalDest();
2468 } else {
2469 SuccBB = BB->getUniqueSuccessor();
2470 assert(SuccBB &&
2471 "splitOutlinedFinallyCalls didn't insert a branch");
2472 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002473 }
Reid Kleckner6511c8b2015-07-01 20:59:25 +00002474 BB = SuccBB;
2475 if (BB == EndBB)
2476 return;
2477 continue;
Reid Kleckner9405ef02015-04-10 23:12:29 +00002478 }
Reid Kleckner9405ef02015-04-10 23:12:29 +00002479 }
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002480 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002481
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002482 // Anything else is either a catch block or interesting cleanup code.
Andrew Kaylorbb111322015-04-07 21:30:23 +00002483 for (BasicBlock::iterator II = BB->getFirstNonPHIOrDbg(), IE = BB->end();
2484 II != IE; ++II) {
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002485 Instruction *Inst = II;
2486 if (LPadMap && LPadMap->isLandingPadSpecificInst(Inst))
2487 continue;
2488 // Unconditional branches fall through to this loop.
2489 if (Inst == Branch)
2490 continue;
2491 // If this is a catch block, there is no cleanup code to be found.
2492 if (match(Inst, m_Intrinsic<Intrinsic::eh_begincatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002493 return;
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002494 // If this a nested landing pad, it may contain an endcatch call.
2495 if (match(Inst, m_Intrinsic<Intrinsic::eh_endcatch>()))
Reid Kleckner9405ef02015-04-10 23:12:29 +00002496 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002497 // Anything else makes this interesting cleanup code.
Reid Kleckner9405ef02015-04-10 23:12:29 +00002498 return createCleanupHandler(Actions, CleanupHandlerMap, BB);
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002499 }
2500
2501 // Only unconditional branches in empty blocks should get this far.
2502 assert(Branch && Branch->isUnconditional());
2503 if (BB == EndBB)
Reid Kleckner9405ef02015-04-10 23:12:29 +00002504 return;
Andrew Kaylor64622aa2015-04-01 17:21:25 +00002505 BB = Branch->getSuccessor(0);
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002506 }
Andrew Kaylor6b67d422015-03-11 23:22:06 +00002507}
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002508
2509// This is a public function, declared in WinEHFuncInfo.h and is also
2510// referenced by WinEHNumbering in FunctionLoweringInfo.cpp.
Benjamin Kramera48e0652015-05-16 15:40:03 +00002511void llvm::parseEHActions(
2512 const IntrinsicInst *II,
2513 SmallVectorImpl<std::unique_ptr<ActionHandler>> &Actions) {
Reid Klecknerf12c0302015-06-09 21:42:19 +00002514 assert(II->getIntrinsicID() == Intrinsic::eh_actions &&
2515 "attempted to parse non eh.actions intrinsic");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002516 for (unsigned I = 0, E = II->getNumArgOperands(); I != E;) {
2517 uint64_t ActionKind =
Andrew Kaylorbb111322015-04-07 21:30:23 +00002518 cast<ConstantInt>(II->getArgOperand(I))->getZExtValue();
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002519 if (ActionKind == /*catch=*/1) {
2520 auto *Selector = cast<Constant>(II->getArgOperand(I + 1));
2521 ConstantInt *EHObjIndex = cast<ConstantInt>(II->getArgOperand(I + 2));
2522 int64_t EHObjIndexVal = EHObjIndex->getSExtValue();
2523 Constant *Handler = cast<Constant>(II->getArgOperand(I + 3));
2524 I += 4;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002525 auto CH = make_unique<CatchHandler>(/*BB=*/nullptr, Selector,
2526 /*NextBB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002527 CH->setHandlerBlockOrFunc(Handler);
2528 CH->setExceptionVarIndex(EHObjIndexVal);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002529 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002530 } else if (ActionKind == 0) {
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002531 Constant *Handler = cast<Constant>(II->getArgOperand(I + 1));
2532 I += 2;
Benjamin Kramera48e0652015-05-16 15:40:03 +00002533 auto CH = make_unique<CleanupHandler>(/*BB=*/nullptr);
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002534 CH->setHandlerBlockOrFunc(Handler);
Benjamin Kramera48e0652015-05-16 15:40:03 +00002535 Actions.push_back(std::move(CH));
David Majnemer69132a72015-04-03 22:49:05 +00002536 } else {
2537 llvm_unreachable("Expected either a catch or cleanup handler!");
Andrew Kayloraa92ab02015-04-03 19:37:50 +00002538 }
2539 }
2540 std::reverse(Actions.begin(), Actions.end());
2541}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002542
2543namespace {
2544struct WinEHNumbering {
2545 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
2546 CurrentBaseState(-1), NextState(0) {}
2547
2548 WinEHFuncInfo &FuncInfo;
2549 int CurrentBaseState;
2550 int NextState;
2551
2552 SmallVector<std::unique_ptr<ActionHandler>, 4> HandlerStack;
2553 SmallPtrSet<const Function *, 4> VisitedHandlers;
2554
2555 int currentEHNumber() const {
2556 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
2557 }
2558
2559 void createUnwindMapEntry(int ToState, ActionHandler *AH);
2560 void createTryBlockMapEntry(int TryLow, int TryHigh,
2561 ArrayRef<CatchHandler *> Handlers);
2562 void processCallSite(MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2563 ImmutableCallSite CS);
2564 void popUnmatchedActions(int FirstMismatch);
2565 void calculateStateNumbers(const Function &F);
2566 void findActionRootLPads(const Function &F);
2567};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002568}
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002569
2570void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
2571 WinEHUnwindMapEntry UME;
2572 UME.ToState = ToState;
2573 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
2574 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
2575 else
2576 UME.Cleanup = nullptr;
2577 FuncInfo.UnwindMap.push_back(UME);
2578}
2579
2580void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
2581 ArrayRef<CatchHandler *> Handlers) {
2582 // See if we already have an entry for this set of handlers.
2583 // This is using iterators rather than a range-based for loop because
2584 // if we find the entry we're looking for we'll need the iterator to erase it.
2585 int NumHandlers = Handlers.size();
2586 auto I = FuncInfo.TryBlockMap.begin();
2587 auto E = FuncInfo.TryBlockMap.end();
2588 for ( ; I != E; ++I) {
2589 auto &Entry = *I;
2590 if (Entry.HandlerArray.size() != (size_t)NumHandlers)
2591 continue;
2592 int N;
2593 for (N = 0; N < NumHandlers; ++N) {
2594 if (Entry.HandlerArray[N].Handler != Handlers[N]->getHandlerBlockOrFunc())
2595 break; // breaks out of inner loop
2596 }
2597 // If all the handlers match, this is what we were looking for.
2598 if (N == NumHandlers) {
2599 break;
2600 }
2601 }
2602
2603 // If we found an existing entry for this set of handlers, extend the range
2604 // but move the entry to the end of the map vector. The order of entries
2605 // in the map is critical to the way that the runtime finds handlers.
2606 // FIXME: Depending on what has happened with block ordering, this may
2607 // incorrectly combine entries that should remain separate.
2608 if (I != E) {
2609 // Copy the existing entry.
2610 WinEHTryBlockMapEntry Entry = *I;
2611 Entry.TryLow = std::min(TryLow, Entry.TryLow);
2612 Entry.TryHigh = std::max(TryHigh, Entry.TryHigh);
2613 assert(Entry.TryLow <= Entry.TryHigh);
2614 // Erase the old entry and add this one to the back.
2615 FuncInfo.TryBlockMap.erase(I);
2616 FuncInfo.TryBlockMap.push_back(Entry);
2617 return;
2618 }
2619
2620 // If we didn't find an entry, create a new one.
2621 WinEHTryBlockMapEntry TBME;
2622 TBME.TryLow = TryLow;
2623 TBME.TryHigh = TryHigh;
2624 assert(TBME.TryLow <= TBME.TryHigh);
2625 for (CatchHandler *CH : Handlers) {
2626 WinEHHandlerType HT;
2627 if (CH->getSelector()->isNullValue()) {
2628 HT.Adjectives = 0x40;
2629 HT.TypeDescriptor = nullptr;
2630 } else {
2631 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
2632 // Selectors are always pointers to GlobalVariables with 'struct' type.
2633 // The struct has two fields, adjectives and a type descriptor.
2634 auto *CS = cast<ConstantStruct>(GV->getInitializer());
2635 HT.Adjectives =
2636 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
2637 HT.TypeDescriptor =
2638 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
2639 }
2640 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
2641 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
2642 TBME.HandlerArray.push_back(HT);
2643 }
2644 FuncInfo.TryBlockMap.push_back(TBME);
2645}
2646
2647static void print_name(const Value *V) {
2648#ifndef NDEBUG
2649 if (!V) {
2650 DEBUG(dbgs() << "null");
2651 return;
2652 }
2653
2654 if (const auto *F = dyn_cast<Function>(V))
2655 DEBUG(dbgs() << F->getName());
2656 else
2657 DEBUG(V->dump());
2658#endif
2659}
2660
2661void WinEHNumbering::processCallSite(
2662 MutableArrayRef<std::unique_ptr<ActionHandler>> Actions,
2663 ImmutableCallSite CS) {
2664 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
2665 << ") for: ");
2666 print_name(CS ? CS.getCalledValue() : nullptr);
2667 DEBUG(dbgs() << '\n');
2668
2669 DEBUG(dbgs() << "HandlerStack: \n");
2670 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2671 DEBUG(dbgs() << " ");
2672 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
2673 DEBUG(dbgs() << '\n');
2674 }
2675 DEBUG(dbgs() << "Actions: \n");
2676 for (int I = 0, E = Actions.size(); I < E; ++I) {
2677 DEBUG(dbgs() << " ");
2678 print_name(Actions[I]->getHandlerBlockOrFunc());
2679 DEBUG(dbgs() << '\n');
2680 }
2681 int FirstMismatch = 0;
2682 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
2683 ++FirstMismatch) {
2684 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
2685 Actions[FirstMismatch]->getHandlerBlockOrFunc())
2686 break;
2687 }
2688
2689 // Remove unmatched actions from the stack and process their EH states.
2690 popUnmatchedActions(FirstMismatch);
2691
2692 DEBUG(dbgs() << "Pushing actions for CallSite: ");
2693 print_name(CS ? CS.getCalledValue() : nullptr);
2694 DEBUG(dbgs() << '\n');
2695
2696 bool LastActionWasCatch = false;
2697 const LandingPadInst *LastRootLPad = nullptr;
2698 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
2699 // We can reuse eh states when pushing two catches for the same invoke.
2700 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I].get());
2701 auto *Handler = cast<Function>(Actions[I]->getHandlerBlockOrFunc());
2702 // Various conditions can lead to a handler being popped from the
2703 // stack and re-pushed later. That shouldn't create a new state.
2704 // FIXME: Can code optimization lead to re-used handlers?
2705 if (FuncInfo.HandlerEnclosedState.count(Handler)) {
2706 // If we already assigned the state enclosed by this handler re-use it.
2707 Actions[I]->setEHState(FuncInfo.HandlerEnclosedState[Handler]);
2708 continue;
2709 }
2710 const LandingPadInst* RootLPad = FuncInfo.RootLPad[Handler];
2711 if (CurrActionIsCatch && LastActionWasCatch && RootLPad == LastRootLPad) {
2712 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber() << "\n");
2713 Actions[I]->setEHState(currentEHNumber());
2714 } else {
2715 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
2716 print_name(Actions[I]->getHandlerBlockOrFunc());
2717 DEBUG(dbgs() << ") with EH state " << NextState << "\n");
2718 createUnwindMapEntry(currentEHNumber(), Actions[I].get());
2719 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
2720 Actions[I]->setEHState(NextState);
2721 NextState++;
2722 }
2723 HandlerStack.push_back(std::move(Actions[I]));
2724 LastActionWasCatch = CurrActionIsCatch;
2725 LastRootLPad = RootLPad;
2726 }
2727
2728 // This is used to defer numbering states for a handler until after the
2729 // last time it appears in an invoke action list.
2730 if (CS.isInvoke()) {
2731 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
2732 auto *Handler = cast<Function>(HandlerStack[I]->getHandlerBlockOrFunc());
2733 if (FuncInfo.LastInvoke[Handler] != cast<InvokeInst>(CS.getInstruction()))
2734 continue;
2735 FuncInfo.LastInvokeVisited[Handler] = true;
2736 DEBUG(dbgs() << "Last invoke of ");
2737 print_name(Handler);
2738 DEBUG(dbgs() << " has been visited.\n");
2739 }
2740 }
2741
2742 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
2743 print_name(CS ? CS.getCalledValue() : nullptr);
2744 DEBUG(dbgs() << '\n');
2745}
2746
2747void WinEHNumbering::popUnmatchedActions(int FirstMismatch) {
2748 // Don't recurse while we are looping over the handler stack. Instead, defer
2749 // the numbering of the catch handlers until we are done popping.
2750 SmallVector<CatchHandler *, 4> PoppedCatches;
2751 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
2752 std::unique_ptr<ActionHandler> Handler = HandlerStack.pop_back_val();
2753 if (isa<CatchHandler>(Handler.get()))
2754 PoppedCatches.push_back(cast<CatchHandler>(Handler.release()));
2755 }
2756
2757 int TryHigh = NextState - 1;
2758 int LastTryLowIdx = 0;
2759 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
2760 CatchHandler *CH = PoppedCatches[I];
2761 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
2762 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
2763 int TryLow = CH->getEHState();
2764 auto Handlers =
2765 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
2766 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
2767 for (size_t J = 0; J < Handlers.size(); ++J) {
2768 DEBUG(dbgs() << ", ");
2769 print_name(Handlers[J]->getHandlerBlockOrFunc());
2770 }
2771 DEBUG(dbgs() << ")\n");
2772 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
2773 LastTryLowIdx = I + 1;
2774 }
2775 }
2776
2777 for (CatchHandler *CH : PoppedCatches) {
2778 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
2779 if (FuncInfo.LastInvokeVisited[F]) {
2780 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
2781 print_name(F);
2782 DEBUG(dbgs() << '\n');
2783 FuncInfo.HandlerBaseState[F] = NextState;
2784 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
2785 << ", null)\n");
2786 createUnwindMapEntry(currentEHNumber(), nullptr);
2787 ++NextState;
2788 calculateStateNumbers(*F);
2789 }
2790 else {
2791 DEBUG(dbgs() << "Deferring handling of ");
2792 print_name(F);
2793 DEBUG(dbgs() << " until last invoke visited.\n");
2794 }
2795 }
2796 delete CH;
2797 }
2798}
2799
2800void WinEHNumbering::calculateStateNumbers(const Function &F) {
2801 auto I = VisitedHandlers.insert(&F);
2802 if (!I.second)
2803 return; // We've already visited this handler, don't renumber it.
2804
2805 int OldBaseState = CurrentBaseState;
2806 if (FuncInfo.HandlerBaseState.count(&F)) {
2807 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
2808 }
2809
2810 size_t SavedHandlerStackSize = HandlerStack.size();
2811
2812 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
2813 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2814 for (const BasicBlock &BB : F) {
2815 for (const Instruction &I : BB) {
2816 const auto *CI = dyn_cast<CallInst>(&I);
2817 if (!CI || CI->doesNotThrow())
2818 continue;
2819 processCallSite(None, CI);
2820 }
2821 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2822 if (!II)
2823 continue;
2824 const LandingPadInst *LPI = II->getLandingPadInst();
2825 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2826 if (!ActionsCall)
2827 continue;
Reid Klecknerfe4d4912015-05-28 22:00:24 +00002828 parseEHActions(ActionsCall, ActionList);
2829 if (ActionList.empty())
2830 continue;
2831 processCallSite(ActionList, II);
2832 ActionList.clear();
2833 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
2834 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
2835 << " to landing pad at " << LPI->getParent()->getName()
2836 << '\n');
2837 }
2838
2839 // Pop any actions that were pushed on the stack for this function.
2840 popUnmatchedActions(SavedHandlerStackSize);
2841
2842 DEBUG(dbgs() << "Assigning max state " << NextState - 1
2843 << " to " << F.getName() << '\n');
2844 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
2845
2846 CurrentBaseState = OldBaseState;
2847}
2848
2849// This function follows the same basic traversal as calculateStateNumbers
2850// but it is necessary to identify the root landing pad associated
2851// with each action before we start assigning state numbers.
2852void WinEHNumbering::findActionRootLPads(const Function &F) {
2853 auto I = VisitedHandlers.insert(&F);
2854 if (!I.second)
2855 return; // We've already visited this handler, don't revisit it.
2856
2857 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
2858 for (const BasicBlock &BB : F) {
2859 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
2860 if (!II)
2861 continue;
2862 const LandingPadInst *LPI = II->getLandingPadInst();
2863 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
2864 if (!ActionsCall)
2865 continue;
2866
2867 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
2868 parseEHActions(ActionsCall, ActionList);
2869 if (ActionList.empty())
2870 continue;
2871 for (int I = 0, E = ActionList.size(); I < E; ++I) {
2872 if (auto *Handler
2873 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc())) {
2874 FuncInfo.LastInvoke[Handler] = II;
2875 // Don't replace the root landing pad if we previously saw this
2876 // handler in a different function.
2877 if (FuncInfo.RootLPad.count(Handler) &&
2878 FuncInfo.RootLPad[Handler]->getParent()->getParent() != &F)
2879 continue;
2880 DEBUG(dbgs() << "Setting root lpad for ");
2881 print_name(Handler);
2882 DEBUG(dbgs() << " to " << LPI->getParent()->getName() << '\n');
2883 FuncInfo.RootLPad[Handler] = LPI;
2884 }
2885 }
2886 // Walk the actions again and look for nested handlers. This has to
2887 // happen after all of the actions have been processed in the current
2888 // function.
2889 for (int I = 0, E = ActionList.size(); I < E; ++I)
2890 if (auto *Handler
2891 = dyn_cast<Function>(ActionList[I]->getHandlerBlockOrFunc()))
2892 findActionRootLPads(*Handler);
2893 ActionList.clear();
2894 }
2895}
2896
2897void llvm::calculateWinCXXEHStateNumbers(const Function *ParentFn,
2898 WinEHFuncInfo &FuncInfo) {
2899 // Return if it's already been done.
2900 if (!FuncInfo.LandingPadStateMap.empty())
2901 return;
2902
2903 WinEHNumbering Num(FuncInfo);
2904 Num.findActionRootLPads(*ParentFn);
2905 // The VisitedHandlers list is used by both findActionRootLPads and
2906 // calculateStateNumbers, but both functions need to visit all handlers.
2907 Num.VisitedHandlers.clear();
2908 Num.calculateStateNumbers(*ParentFn);
2909 // Pop everything on the handler stack.
2910 // It may be necessary to call this more than once because a handler can
2911 // be pushed on the stack as a result of clearing the stack.
2912 while (!Num.HandlerStack.empty())
2913 Num.processCallSite(None, ImmutableCallSite());
2914}
David Majnemerfd9f4772015-08-11 01:15:26 +00002915
2916void WinEHPrepare::numberFunclet(BasicBlock *InitialBB, BasicBlock *FuncletBB) {
2917 Instruction *FirstNonPHI = FuncletBB->getFirstNonPHI();
2918 bool IsCatch = isa<CatchPadInst>(FirstNonPHI);
2919 bool IsCleanup = isa<CleanupPadInst>(FirstNonPHI);
2920
2921 // Initialize the worklist with the funclet's entry point.
2922 std::vector<BasicBlock *> Worklist;
2923 Worklist.push_back(InitialBB);
2924
2925 while (!Worklist.empty()) {
2926 BasicBlock *BB = Worklist.back();
2927 Worklist.pop_back();
2928
2929 // There can be only one "pad" basic block in the funclet: the initial one.
2930 if (BB != FuncletBB && BB->isEHPad())
2931 continue;
2932
2933 // Add 'FuncletBB' as a possible color for 'BB'.
2934 if (BlockColors[BB].insert(FuncletBB).second == false) {
2935 // Skip basic blocks which we have already visited.
2936 continue;
2937 }
2938
2939 FuncletBlocks[FuncletBB].insert(BB);
2940
2941 Instruction *Terminator = BB->getTerminator();
2942 // The catchret's successors cannot be part of the funclet.
2943 if (IsCatch && isa<CatchReturnInst>(Terminator))
2944 continue;
2945 // The cleanupret's successors cannot be part of the funclet.
2946 if (IsCleanup && isa<CleanupReturnInst>(Terminator))
2947 continue;
2948
2949 Worklist.insert(Worklist.end(), succ_begin(BB), succ_end(BB));
2950 }
2951}
2952
2953bool WinEHPrepare::prepareExplicitEH(Function &F) {
2954 LLVMContext &Context = F.getContext();
2955 // Remove unreachable blocks. It is not valuable to assign them a color and
2956 // their existence can trick us into thinking values are alive when they are
2957 // not.
2958 removeUnreachableBlocks(F);
2959
2960 BasicBlock *EntryBlock = &F.getEntryBlock();
2961
2962 // Number everything starting from the entry block.
2963 numberFunclet(EntryBlock, EntryBlock);
2964
2965 for (BasicBlock &BB : F) {
2966 // Remove single entry PHIs to simplify preparation.
2967 if (auto *PN = dyn_cast<PHINode>(BB.begin()))
2968 if (PN->getNumIncomingValues() == 1)
2969 FoldSingleEntryPHINodes(&BB);
2970
2971 // EH pad instructions are always the first non-PHI nodes in a block if they
2972 // are at all present.
2973 Instruction *I = BB.getFirstNonPHI();
2974 if (I->isEHPad())
2975 numberFunclet(&BB, &BB);
2976
2977 // It is possible for a normal basic block to only be reachable via an
2978 // exceptional basic block. The successor of a catchret is the only case
2979 // where this is possible.
2980 if (auto *CRI = dyn_cast<CatchReturnInst>(BB.getTerminator()))
2981 numberFunclet(CRI->getSuccessor(), EntryBlock);
2982 }
2983
2984 // Insert cleanuppads before EH blocks with PHI nodes.
2985 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
2986 BasicBlock *BB = FI++;
2987 // Skip any BBs which aren't EH pads.
2988 if (!BB->isEHPad())
2989 continue;
2990 // Skip any cleanuppads, they can hold non-PHI instructions.
2991 if (isa<CleanupPadInst>(BB->getFirstNonPHI()))
2992 continue;
2993 // Skip any EH pads without PHIs, we don't need to worry about demoting into
2994 // them.
2995 if (!isa<PHINode>(BB->begin()))
2996 continue;
2997
2998 // Create our new cleanuppad BB, terminate it with a cleanupret.
2999 auto *NewCleanupBB = BasicBlock::Create(
3000 Context, Twine(BB->getName(), ".wineh.phibb"), &F, BB);
3001 auto *CPI = CleanupPadInst::Create(Type::getVoidTy(Context), {BB}, "",
3002 NewCleanupBB);
3003 CleanupReturnInst::Create(Context, /*RetVal=*/nullptr, BB, NewCleanupBB);
3004
3005 // Update the funclet data structures to keep them in the loop.
3006 BlockColors[NewCleanupBB].insert(NewCleanupBB);
3007 FuncletBlocks[NewCleanupBB].insert(NewCleanupBB);
3008
3009 // Reparent PHIs from the old EH BB into the cleanuppad.
3010 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3011 Instruction *I = BI++;
3012 auto *PN = dyn_cast<PHINode>(I);
3013 // Stop at the first non-PHI.
3014 if (!PN)
3015 break;
3016 PN->removeFromParent();
3017 PN->insertBefore(CPI);
3018 }
3019
3020 // Redirect predecessors from the old EH BB to the cleanuppad.
3021 std::set<BasicBlock *> Preds;
3022 Preds.insert(pred_begin(BB), pred_end(BB));
3023 for (BasicBlock *Pred : Preds) {
3024 // Don't redirect the new cleanuppad to itself!
3025 if (Pred == NewCleanupBB)
3026 continue;
3027 TerminatorInst *TI = Pred->getTerminator();
3028 for (unsigned TII = 0, TIE = TI->getNumSuccessors(); TII != TIE; ++TII) {
3029 BasicBlock *Successor = TI->getSuccessor(TII);
3030 if (Successor == BB)
3031 TI->setSuccessor(TII, NewCleanupBB);
3032 }
3033 }
3034 }
3035
3036 // Get rid of polychromatic PHI nodes.
3037 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3038 BasicBlock *BB = FI++;
3039 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3040 bool IsEHPad = BB->isEHPad();
3041 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3042 Instruction *I = BI++;
3043 auto *PN = dyn_cast<PHINode>(I);
3044 // Stop at the first non-PHI node.
3045 if (!PN)
3046 break;
3047
3048 // EH pads cannot be lowered with PHI nodes prefacing them.
3049 if (IsEHPad) {
3050 // We should have removed PHIs from all non-cleanuppad blocks.
3051 if (!isa<CleanupPadInst>(BB->getFirstNonPHI()))
3052 report_fatal_error("Unexpected PHI on EH Pad");
3053 DemotePHIToStack(PN);
3054 continue;
3055 }
3056
3057 // See if *all* the basic blocks involved in this PHI node are in the
3058 // same, lone, color. If so, demotion is not needed.
3059 bool SameColor = ColorsForBB.size() == 1;
3060 if (SameColor) {
3061 for (unsigned PNI = 0, PNE = PN->getNumIncomingValues(); PNI != PNE;
3062 ++PNI) {
3063 BasicBlock *IncomingBB = PN->getIncomingBlock(PNI);
3064 std::set<BasicBlock *> &ColorsForIncomingBB = BlockColors[IncomingBB];
3065 // If the colors differ, bail out early and demote.
3066 if (ColorsForIncomingBB != ColorsForBB) {
3067 SameColor = false;
3068 break;
3069 }
3070 }
3071 }
3072
3073 if (!SameColor)
3074 DemotePHIToStack(PN);
3075 }
3076 }
3077
3078 // Turn all inter-funclet uses of a Value into loads and stores.
3079 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3080 BasicBlock *BB = FI++;
3081 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3082 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
3083 Instruction *I = BI++;
3084 // Funclets are permitted to use static allocas.
3085 if (auto *AI = dyn_cast<AllocaInst>(I))
3086 if (AI->isStaticAlloca())
3087 continue;
3088
3089 // FIXME: Our spill-placement algorithm is incredibly naive. We should
3090 // try to sink+hoist as much as possible to avoid redundant stores and reloads.
3091 DenseMap<BasicBlock *, Value *> Loads;
3092 AllocaInst *SpillSlot = nullptr;
3093 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
3094 UI != UE;) {
3095 Use &U = *UI++;
3096 auto *UsingInst = cast<Instruction>(U.getUser());
3097 BasicBlock *UsingBB = UsingInst->getParent();
3098
3099 // Is the Use inside a block which is colored with a subset of the Def?
3100 // If so, we don't need to escape the Def because we will clone
3101 // ourselves our own private copy.
3102 std::set<BasicBlock *> &ColorsForUsingBB = BlockColors[UsingBB];
3103 if (std::includes(ColorsForBB.begin(), ColorsForBB.end(),
3104 ColorsForUsingBB.begin(), ColorsForUsingBB.end()))
3105 continue;
3106
3107 // Lazilly create the spill slot. We spill immediately after the value
3108 // in the BasicBlock.
3109 // FIXME: This can be improved to spill at the block exit points.
3110 if (!SpillSlot)
3111 SpillSlot = new AllocaInst(I->getType(), nullptr,
3112 Twine(I->getName(), ".wineh.spillslot"),
3113 EntryBlock->begin());
3114
3115 if (auto *PN = dyn_cast<PHINode>(UsingInst)) {
3116 // If this is a PHI node, we can't insert a load of the value before
3117 // the use. Instead insert the load in the predecessor block
3118 // corresponding to the incoming value.
3119 //
3120 // Note that if there are multiple edges from a basic block to this
3121 // PHI node that we cannot have multiple loads. The problem is that
3122 // the resulting PHI node will have multiple values (from each load)
3123 // coming in from the same block, which is illegal SSA form.
3124 // For this reason, we keep track of and reuse loads we insert.
3125 BasicBlock *IncomingBlock = PN->getIncomingBlock(U);
3126 Value *&V = Loads[IncomingBlock];
3127 // Insert the load into the predecessor block
3128 if (!V)
3129 V = new LoadInst(SpillSlot, Twine(I->getName(), ".wineh.reload"),
3130 /*Volatile=*/false,
3131 IncomingBlock->getTerminator());
3132 U.set(V);
3133 } else {
3134 // Reload right before the old use.
3135 // FIXME: This can be improved to reload at a block entry point.
3136 Value *V =
3137 new LoadInst(SpillSlot, Twine(I->getName(), ".wineh.reload"),
3138 /*Volatile=*/false, UsingInst);
3139 U.set(V);
3140 }
3141 }
3142 if (SpillSlot) {
3143 // Insert stores of the computed value into the stack slot.
3144 // We have to be careful if I is an invoke instruction,
3145 // because we can't insert the store AFTER the terminator instruction.
3146 BasicBlock::iterator InsertPt;
3147 if (!isa<TerminatorInst>(I)) {
3148 InsertPt = I;
3149 ++InsertPt;
3150 // Don't insert before PHI nodes or EH pad instrs.
3151 for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
3152 ;
3153 } else {
3154 auto *II = cast<InvokeInst>(I);
3155 // We cannot demote invoke instructions to the stack if their normal
3156 // edge is critical. Therefore, split the critical edge and create a
3157 // basic block into which the store can be inserted.
3158 if (!II->getNormalDest()->getSinglePredecessor()) {
3159 unsigned SuccNum = GetSuccessorNumber(BB, II->getNormalDest());
3160 assert(isCriticalEdge(II, SuccNum) && "Expected a critical edge!");
3161 BasicBlock *NewBlock = SplitCriticalEdge(II, SuccNum);
3162 assert(NewBlock && "Unable to split critical edge.");
3163 // Update the color mapping for the newly split edge.
3164 std::set<BasicBlock *> &ColorsForUsingBB =
3165 BlockColors[II->getParent()];
3166 BlockColors[NewBlock] = ColorsForUsingBB;
3167 for (BasicBlock *FuncletPad : ColorsForUsingBB)
3168 FuncletBlocks[FuncletPad].insert(NewBlock);
3169 }
3170 InsertPt = II->getNormalDest()->getFirstInsertionPt();
3171 }
3172 new StoreInst(I, SpillSlot, InsertPt);
3173 }
3174 }
3175 }
3176
3177 // We need to clone all blocks which belong to multiple funclets. Values are
3178 // remapped throughout the funclet to propogate both the new instructions
3179 // *and* the new basic blocks themselves.
3180 for (auto &Funclet : FuncletBlocks) {
3181 BasicBlock *FuncletPadBB = Funclet.first;
3182 std::set<BasicBlock *> &BlocksInFunclet = Funclet.second;
3183
3184 std::map<BasicBlock *, BasicBlock *> Orig2Clone;
3185 ValueToValueMapTy VMap;
3186 for (BasicBlock *BB : BlocksInFunclet) {
3187 std::set<BasicBlock *> &ColorsForBB = BlockColors[BB];
3188 // We don't need to do anything if the block is monochromatic.
3189 size_t NumColorsForBB = ColorsForBB.size();
3190 if (NumColorsForBB == 1)
3191 continue;
3192
3193 assert(!isa<PHINode>(BB->front()) &&
3194 "Polychromatic PHI nodes should have been demoted!");
3195
3196 // Create a new basic block and copy instructions into it!
3197 BasicBlock *CBB = CloneBasicBlock(
3198 BB, VMap, Twine(".for.", FuncletPadBB->getName()), &F);
3199
3200 // Add basic block mapping.
3201 VMap[BB] = CBB;
3202
3203 // Record delta operations that we need to perform to our color mappings.
3204 Orig2Clone[BB] = CBB;
3205 }
3206
3207 // Update our color mappings to reflect that one block has lost a color and
3208 // another has gained a color.
3209 for (auto &BBMapping : Orig2Clone) {
3210 BasicBlock *OldBlock = BBMapping.first;
3211 BasicBlock *NewBlock = BBMapping.second;
3212
3213 BlocksInFunclet.insert(NewBlock);
3214 BlockColors[NewBlock].insert(FuncletPadBB);
3215
3216 BlocksInFunclet.erase(OldBlock);
3217 BlockColors[OldBlock].erase(FuncletPadBB);
3218 }
3219
3220 // Loop over all of the instructions in the function, fixing up operand
3221 // references as we go. This uses VMap to do all the hard work.
3222 for (BasicBlock *BB : BlocksInFunclet)
3223 // Loop over all instructions, fixing each one as we find it...
3224 for (Instruction &I : *BB)
3225 RemapInstruction(&I, VMap, RF_IgnoreMissingEntries);
3226 }
3227
3228 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
3229 // branches, etc.
3230 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
3231 BasicBlock *BB = FI++;
3232 SimplifyInstructionsInBlock(BB);
3233 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
3234 MergeBlockIntoPredecessor(BB);
3235 }
3236
3237 // TODO: Do something about cleanupblocks which branch to implausible
3238 // cleanuprets.
3239
3240 // We might have some unreachable blocks after cleaning up some impossible
3241 // control flow.
3242 removeUnreachableBlocks(F);
3243
3244 // Recolor the CFG to verify that all is well.
3245 for (BasicBlock &BB : F) {
3246 size_t NumColors = BlockColors[&BB].size();
3247 assert(NumColors == 1 && "Expected monochromatic BB!");
3248 if (NumColors == 0)
3249 report_fatal_error("Uncolored BB!");
3250 if (NumColors > 1)
3251 report_fatal_error("Multicolor BB!");
3252 bool EHPadHasPHI = BB.isEHPad() && isa<PHINode>(BB.begin());
3253 assert(!EHPadHasPHI && "EH Pad still has a PHI!");
3254 if (EHPadHasPHI)
3255 report_fatal_error("EH Pad still has a PHI!");
3256 }
3257
3258 BlockColors.clear();
3259 FuncletBlocks.clear();
3260 return true;
3261}