blob: 7ad84734203d91a7fa1492ea13be517daf42141e [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
Joseph Tremoulet52f729a2016-01-04 16:16:01 +000019#include "llvm/ADT/DenseMap.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000020#include "llvm/ADT/MapVector.h"
Joseph Tremoulet52f729a2016-01-04 16:16:01 +000021#include "llvm/ADT/STLExtras.h"
David Majnemerfd9f4772015-08-11 01:15:26 +000022#include "llvm/Analysis/CFG.h"
David Majnemer70497c62015-12-02 23:06:39 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthe0115342015-12-29 09:24:39 +000024#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/CodeGen/Passes.h"
David Majnemercde33032015-03-30 22:58:10 +000026#include "llvm/CodeGen/WinEHFuncInfo.h"
David Majnemerdbdc9c22016-01-02 09:26:36 +000027#include "llvm/IR/Verifier.h"
Chandler Carruthe0115342015-12-29 09:24:39 +000028#include "llvm/MC/MCSymbol.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000029#include "llvm/Pass.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000030#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000031#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000033#include "llvm/Transforms/Utils/Cloning.h"
34#include "llvm/Transforms/Utils/Local.h"
David Majnemer459a64a2015-09-16 18:40:37 +000035#include "llvm/Transforms/Utils/SSAUpdater.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000036
37using namespace llvm;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000038
39#define DEBUG_TYPE "winehprepare"
40
David Majnemer459a64a2015-09-16 18:40:37 +000041static cl::opt<bool> DisableDemotion(
42 "disable-demotion", cl::Hidden,
43 cl::desc(
44 "Clone multicolor basic blocks but do not demote cross funclet values"),
45 cl::init(false));
46
47static cl::opt<bool> DisableCleanups(
48 "disable-cleanups", cl::Hidden,
49 cl::desc("Do not remove implausible terminators or other similar cleanups"),
50 cl::init(false));
51
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000052namespace {
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +000053
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000054class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000055public:
56 static char ID; // Pass identification, replacement for typeid.
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000057 WinEHPrepare() : FunctionPass(ID) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000058
59 bool runOnFunction(Function &Fn) override;
60
61 bool doFinalization(Module &M) override;
62
63 void getAnalysisUsage(AnalysisUsage &AU) const override;
64
Mehdi Amini117296c2016-10-01 02:56:57 +000065 StringRef getPassName() const override {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000066 return "Windows exception handling preparation";
67 }
68
69private:
Joseph Tremouletc9ff9142015-08-13 14:30:10 +000070 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
71 void
72 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
73 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
74 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
75 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
76 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
David Majnemer8a1c45d2015-12-12 05:38:55 +000077 bool prepareExplicitEH(Function &F);
David Majnemer8a1c45d2015-12-12 05:38:55 +000078 void colorFunclets(Function &F);
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +000079
David Majnemerb3d9b962015-09-16 18:40:24 +000080 void demotePHIsOnFunclets(Function &F);
David Majnemer8a1c45d2015-12-12 05:38:55 +000081 void cloneCommonBlocks(Function &F);
David Majnemer3bb88c02015-12-15 21:27:27 +000082 void removeImplausibleInstructions(Function &F);
David Majnemerb3d9b962015-09-16 18:40:24 +000083 void cleanupPreparedFunclets(Function &F);
84 void verifyPreparedFunclets(Function &F);
David Majnemerfd9f4772015-08-11 01:15:26 +000085
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000086 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +000087 EHPersonality Personality = EHPersonality::Unknown;
David Majnemerfd9f4772015-08-11 01:15:26 +000088
Matt Arsenault3c1fc762017-04-10 22:27:50 +000089 const DataLayout *DL = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +000090 DenseMap<BasicBlock *, ColorVector> BlockColors;
91 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000092};
93
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000094} // end anonymous namespace
95
96char WinEHPrepare::ID = 0;
Matthias Braun1527baa2017-05-25 21:26:32 +000097INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +000098 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000099
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000100FunctionPass *llvm::createWinEHPass() { return new WinEHPrepare(); }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000101
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000102bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000103 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000104 return false;
105
106 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000107 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000108
Joseph Tremoulet2afea542015-10-06 20:28:16 +0000109 // Do nothing if this is not a funclet-based personality.
110 if (!isFuncletEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000111 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000112
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000113 DL = &Fn.getParent()->getDataLayout();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000114 return prepareExplicitEH(Fn);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000115}
116
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000117bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000118
David Majnemere6965832015-10-16 19:59:52 +0000119void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000120
David Majnemer0ad363e2015-08-18 19:07:12 +0000121static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
David Majnemerbfa5b982015-10-10 00:04:29 +0000122 const BasicBlock *BB) {
Reid Kleckner14e77352015-10-09 23:34:53 +0000123 CxxUnwindMapEntry UME;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000124 UME.ToState = ToState;
David Majnemerbfa5b982015-10-10 00:04:29 +0000125 UME.Cleanup = BB;
Reid Kleckner14e77352015-10-09 23:34:53 +0000126 FuncInfo.CxxUnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +0000127 return FuncInfo.getLastStateNumber();
128}
129
130static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
131 int TryHigh, int CatchHigh,
132 ArrayRef<const CatchPadInst *> Handlers) {
133 WinEHTryBlockMapEntry TBME;
134 TBME.TryLow = TryLow;
135 TBME.TryHigh = TryHigh;
136 TBME.CatchHigh = CatchHigh;
137 assert(TBME.TryLow <= TBME.TryHigh);
138 for (const CatchPadInst *CPI : Handlers) {
139 WinEHHandlerType HT;
140 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
Reid Klecknerb005d282015-09-16 20:16:27 +0000141 if (TypeInfo->isNullValue())
David Majnemer0ad363e2015-08-18 19:07:12 +0000142 HT.TypeDescriptor = nullptr;
Reid Klecknerb005d282015-09-16 20:16:27 +0000143 else
144 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
145 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
David Majnemer7735a6d2015-10-06 23:31:59 +0000146 HT.Handler = CPI->getParent();
David Majnemer086fec22016-01-08 08:03:55 +0000147 if (auto *AI =
148 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
149 HT.CatchObj.Alloca = AI;
Reid Klecknerb005d282015-09-16 20:16:27 +0000150 else
David Majnemer086fec22016-01-08 08:03:55 +0000151 HT.CatchObj.Alloca = nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +0000152 TBME.HandlerArray.push_back(HT);
153 }
154 FuncInfo.TryBlockMap.push_back(TBME);
155}
156
David Majnemer8a1c45d2015-12-12 05:38:55 +0000157static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
158 for (const User *U : CleanupPad->users())
159 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
160 return CRI->getUnwindDest();
David Majnemer0ad363e2015-08-18 19:07:12 +0000161 return nullptr;
162}
163
David Majnemer8a1c45d2015-12-12 05:38:55 +0000164static void calculateStateNumbersForInvokes(const Function *Fn,
165 WinEHFuncInfo &FuncInfo) {
166 auto *F = const_cast<Function *>(Fn);
167 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
168 for (BasicBlock &BB : *F) {
169 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
170 if (!II)
171 continue;
172
173 auto &BBColors = BlockColors[&BB];
David Majnemerc640f862015-12-23 03:59:04 +0000174 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
David Majnemer8a1c45d2015-12-12 05:38:55 +0000175 BasicBlock *FuncletEntryBB = BBColors.front();
176
177 BasicBlock *FuncletUnwindDest;
178 auto *FuncletPad =
179 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
180 assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
181 if (!FuncletPad)
182 FuncletUnwindDest = nullptr;
183 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
184 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
185 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
186 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
187 else
188 llvm_unreachable("unexpected funclet pad!");
189
190 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
191 int BaseState = -1;
192 if (FuncletUnwindDest == InvokeUnwindDest) {
193 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
194 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
195 BaseState = BaseStateI->second;
196 }
197
198 if (BaseState != -1) {
199 FuncInfo.InvokeStateMap[II] = BaseState;
200 } else {
201 Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
202 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
203 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
204 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000205 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000206}
207
David Majnemer0ad363e2015-08-18 19:07:12 +0000208// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
209// to. If the unwind edge came from an invoke, return null.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000210static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
211 Value *ParentPad) {
David Majnemer0ad363e2015-08-18 19:07:12 +0000212 const TerminatorInst *TI = BB->getTerminator();
213 if (isa<InvokeInst>(TI))
214 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000215 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
216 if (CatchSwitch->getParentPad() != ParentPad)
217 return nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +0000218 return BB;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000219 }
220 assert(!TI->isEHPad() && "unexpected EHPad!");
221 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
222 if (CleanupPad->getParentPad() != ParentPad)
223 return nullptr;
224 return CleanupPad->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +0000225}
226
David Majnemer8a1c45d2015-12-12 05:38:55 +0000227static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
228 const Instruction *FirstNonPHI,
229 int ParentState) {
230 const BasicBlock *BB = FirstNonPHI->getParent();
231 assert(BB->isEHPad() && "not a funclet!");
David Majnemer0ad363e2015-08-18 19:07:12 +0000232
David Majnemer8a1c45d2015-12-12 05:38:55 +0000233 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
234 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
235 "shouldn't revist catch funclets!");
236
David Majnemer0ad363e2015-08-18 19:07:12 +0000237 SmallVector<const CatchPadInst *, 2> Handlers;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000238 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
239 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
240 Handlers.push_back(CatchPad);
241 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000242 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000243 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
244 for (const BasicBlock *PredBlock : predecessors(BB))
245 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
246 CatchSwitch->getParentPad())))
247 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
248 TryLow);
David Majnemer0ad363e2015-08-18 19:07:12 +0000249 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000250
251 // catchpads are separate funclets in C++ EH due to the way rethrow works.
David Majnemer0ad363e2015-08-18 19:07:12 +0000252 int TryHigh = CatchLow - 1;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000253 for (const auto *CatchPad : Handlers) {
254 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
255 for (const User *U : CatchPad->users()) {
256 const auto *UserI = cast<Instruction>(U);
David Majnemer17525ab2016-02-23 07:18:15 +0000257 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
258 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
259 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000260 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
David Majnemer17525ab2016-02-23 07:18:15 +0000261 }
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000262 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
263 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
264 // If a nested cleanup pad reports a null unwind destination and the
265 // enclosing catch pad doesn't it must be post-dominated by an
266 // unreachable instruction.
267 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000268 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000269 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000270 }
271 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000272 int CatchHigh = FuncInfo.getLastStateNumber();
273 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000274 DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
275 DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh << '\n');
276 DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
David Majnemer0ad363e2015-08-18 19:07:12 +0000277 << '\n');
David Majnemer0ad363e2015-08-18 19:07:12 +0000278 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000279 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
280
281 // It's possible for a cleanup to be visited twice: it might have multiple
282 // cleanupret instructions.
283 if (FuncInfo.EHPadStateMap.count(CleanupPad))
284 return;
285
286 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
287 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
288 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
289 << BB->getName() << '\n');
290 for (const BasicBlock *PredBlock : predecessors(BB)) {
291 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
292 CleanupPad->getParentPad()))) {
293 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
294 CleanupState);
295 }
296 }
297 for (const User *U : CleanupPad->users()) {
298 const auto *UserI = cast<Instruction>(U);
299 if (UserI->isEHPad())
300 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
301 "contain exceptional actions");
302 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000303 }
304}
305
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000306static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
307 const Function *Filter, const BasicBlock *Handler) {
Reid Kleckner94b704c2015-09-09 21:10:03 +0000308 SEHUnwindMapEntry Entry;
309 Entry.ToState = ParentState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000310 Entry.IsFinally = false;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000311 Entry.Filter = Filter;
312 Entry.Handler = Handler;
313 FuncInfo.SEHUnwindMap.push_back(Entry);
314 return FuncInfo.SEHUnwindMap.size() - 1;
315}
316
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000317static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
318 const BasicBlock *Handler) {
319 SEHUnwindMapEntry Entry;
320 Entry.ToState = ParentState;
321 Entry.IsFinally = true;
322 Entry.Filter = nullptr;
323 Entry.Handler = Handler;
324 FuncInfo.SEHUnwindMap.push_back(Entry);
325 return FuncInfo.SEHUnwindMap.size() - 1;
326}
327
David Majnemer8a1c45d2015-12-12 05:38:55 +0000328static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
329 const Instruction *FirstNonPHI,
330 int ParentState) {
331 const BasicBlock *BB = FirstNonPHI->getParent();
332 assert(BB->isEHPad() && "no a funclet!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000333
David Majnemer8a1c45d2015-12-12 05:38:55 +0000334 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
335 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
336 "shouldn't revist catch funclets!");
337
Reid Kleckner94b704c2015-09-09 21:10:03 +0000338 // Extract the filter function and the __except basic block and create a
339 // state for them.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000340 assert(CatchSwitch->getNumHandlers() == 1 &&
Reid Kleckner94b704c2015-09-09 21:10:03 +0000341 "SEH doesn't have multiple handlers per __try");
David Majnemer8a1c45d2015-12-12 05:38:55 +0000342 const auto *CatchPad =
343 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
344 const BasicBlock *CatchPadBB = CatchPad->getParent();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000345 const Constant *FilterOrNull =
David Majnemer8a1c45d2015-12-12 05:38:55 +0000346 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000347 const Function *Filter = dyn_cast<Function>(FilterOrNull);
348 assert((Filter || FilterOrNull->isNullValue()) &&
349 "unexpected filter value");
David Majnemer7735a6d2015-10-06 23:31:59 +0000350 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000351
352 // Everything in the __try block uses TryState as its parent state.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000353 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000354 DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
355 << CatchPadBB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000356 for (const BasicBlock *PredBlock : predecessors(BB))
357 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
358 CatchSwitch->getParentPad())))
359 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
360 TryState);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000361
362 // Everything in the __except block unwinds to ParentState, just like code
363 // outside the __try.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000364 for (const User *U : CatchPad->users()) {
365 const auto *UserI = cast<Instruction>(U);
David Majnemer17525ab2016-02-23 07:18:15 +0000366 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
367 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
368 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000369 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
David Majnemer17525ab2016-02-23 07:18:15 +0000370 }
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000371 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
372 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
373 // If a nested cleanup pad reports a null unwind destination and the
374 // enclosing catch pad doesn't it must be post-dominated by an
375 // unreachable instruction.
376 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000377 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000378 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000379 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000380 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000381 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
382
383 // It's possible for a cleanup to be visited twice: it might have multiple
384 // cleanupret instructions.
385 if (FuncInfo.EHPadStateMap.count(CleanupPad))
386 return;
387
388 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
389 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
390 DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
391 << BB->getName() << '\n');
392 for (const BasicBlock *PredBlock : predecessors(BB))
393 if ((PredBlock =
394 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
395 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
396 CleanupState);
397 for (const User *U : CleanupPad->users()) {
398 const auto *UserI = cast<Instruction>(U);
399 if (UserI->isEHPad())
400 report_fatal_error("Cleanup funclets for the SEH personality cannot "
401 "contain exceptional actions");
402 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000403 }
404}
405
David Majnemer8a1c45d2015-12-12 05:38:55 +0000406static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
407 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
408 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
409 CatchSwitch->unwindsToCaller();
410 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
411 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
412 getCleanupRetUnwindDest(CleanupPad) == nullptr;
413 if (isa<CatchPadInst>(EHPad))
414 return false;
415 llvm_unreachable("unexpected EHPad!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000416}
417
Reid Kleckner813f1b62015-09-16 22:14:46 +0000418void llvm::calculateSEHStateNumbers(const Function *Fn,
Reid Kleckner94b704c2015-09-09 21:10:03 +0000419 WinEHFuncInfo &FuncInfo) {
420 // Don't compute state numbers twice.
421 if (!FuncInfo.SEHUnwindMap.empty())
422 return;
423
Reid Kleckner813f1b62015-09-16 22:14:46 +0000424 for (const BasicBlock &BB : *Fn) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000425 if (!BB.isEHPad())
Reid Kleckner94b704c2015-09-09 21:10:03 +0000426 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000427 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
428 if (!isTopLevelPadForMSVC(FirstNonPHI))
429 continue;
430 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000431 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000432
433 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000434}
435
Reid Kleckner813f1b62015-09-16 22:14:46 +0000436void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000437 WinEHFuncInfo &FuncInfo) {
438 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +0000439 if (!FuncInfo.EHPadStateMap.empty())
440 return;
441
Reid Kleckner813f1b62015-09-16 22:14:46 +0000442 for (const BasicBlock &BB : *Fn) {
David Majnemer0ad363e2015-08-18 19:07:12 +0000443 if (!BB.isEHPad())
444 continue;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000445 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000446 if (!isTopLevelPadForMSVC(FirstNonPHI))
David Majnemer0ad363e2015-08-18 19:07:12 +0000447 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000448 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
David Majnemer0ad363e2015-08-18 19:07:12 +0000449 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000450
451 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000452}
David Majnemerfd9f4772015-08-11 01:15:26 +0000453
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000454static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
455 int TryParentState, ClrHandlerType HandlerType,
456 uint32_t TypeToken, const BasicBlock *Handler) {
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000457 ClrEHUnwindMapEntry Entry;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000458 Entry.HandlerParentState = HandlerParentState;
459 Entry.TryParentState = TryParentState;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000460 Entry.Handler = Handler;
461 Entry.HandlerType = HandlerType;
462 Entry.TypeToken = TypeToken;
463 FuncInfo.ClrEHUnwindMap.push_back(Entry);
464 return FuncInfo.ClrEHUnwindMap.size() - 1;
465}
466
467void llvm::calculateClrEHStateNumbers(const Function *Fn,
468 WinEHFuncInfo &FuncInfo) {
469 // Return if it's already been done.
470 if (!FuncInfo.EHPadStateMap.empty())
471 return;
472
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000473 // This numbering assigns one state number to each catchpad and cleanuppad.
474 // It also computes two tree-like relations over states:
475 // 1) Each state has a "HandlerParentState", which is the state of the next
476 // outer handler enclosing this state's handler (same as nearest ancestor
477 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
478 // 2) Each state has a "TryParentState", which:
479 // a) for a catchpad that's not the last handler on its catchswitch, is
480 // the state of the next catchpad on that catchswitch
481 // b) for all other pads, is the state of the pad whose try region is the
482 // next outer try region enclosing this state's try region. The "try
483 // regions are not present as such in the IR, but will be inferred
484 // based on the placement of invokes and pads which reach each other
485 // by exceptional exits
486 // Catchswitches do not get their own states, but each gets mapped to the
487 // state of its first catchpad.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000488
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000489 // Step one: walk down from outermost to innermost funclets, assigning each
490 // catchpad and cleanuppad a state number. Add an entry to the
491 // ClrEHUnwindMap for each state, recording its HandlerParentState and
492 // handler attributes. Record the TryParentState as well for each catchpad
493 // that's not the last on its catchswitch, but initialize all other entries'
494 // TryParentStates to a sentinel -1 value that the next pass will update.
495
496 // Seed a worklist with pads that have no parent.
497 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000498 for (const BasicBlock &BB : *Fn) {
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000499 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000500 const Value *ParentPad;
501 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
502 ParentPad = CPI->getParentPad();
503 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
504 ParentPad = CSI->getParentPad();
505 else
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000506 continue;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000507 if (isa<ConstantTokenNone>(ParentPad))
508 Worklist.emplace_back(FirstNonPHI, -1);
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000509 }
510
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000511 // Use the worklist to visit all pads, from outer to inner. Record
512 // HandlerParentState for all pads. Record TryParentState only for catchpads
513 // that aren't the last on their catchswitch (setting all other entries'
514 // TryParentStates to an initial value of -1). This loop is also responsible
515 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
516 // catchswitches.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000517 while (!Worklist.empty()) {
518 const Instruction *Pad;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000519 int HandlerParentState;
520 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000521
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000522 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
523 // Create the entry for this cleanup with the appropriate handler
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000524 // properties. Finally and fault handlers are distinguished by arity.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000525 ClrHandlerType HandlerType =
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000526 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
527 : ClrHandlerType::Finally);
528 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
529 HandlerType, 0, Pad->getParent());
530 // Queue any child EH pads on the worklist.
531 for (const User *U : Cleanup->users())
532 if (const auto *I = dyn_cast<Instruction>(U))
533 if (I->isEHPad())
534 Worklist.emplace_back(I, CleanupState);
535 // Remember this pad's state.
536 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
537 } else {
538 // Walk the handlers of this catchswitch in reverse order since all but
539 // the last need to set the following one as its TryParentState.
540 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
541 int CatchState = -1, FollowerState = -1;
542 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
543 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
544 CBI != CBE; ++CBI, FollowerState = CatchState) {
545 const BasicBlock *CatchBlock = *CBI;
546 // Create the entry for this catch with the appropriate handler
547 // properties.
548 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
David Majnemer8a1c45d2015-12-12 05:38:55 +0000549 uint32_t TypeToken = static_cast<uint32_t>(
550 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000551 CatchState =
552 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
553 ClrHandlerType::Catch, TypeToken, CatchBlock);
554 // Queue any child EH pads on the worklist.
555 for (const User *U : Catch->users())
556 if (const auto *I = dyn_cast<Instruction>(U))
557 if (I->isEHPad())
558 Worklist.emplace_back(I, CatchState);
559 // Remember this catch's state.
560 FuncInfo.EHPadStateMap[Catch] = CatchState;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000561 }
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000562 // Associate the catchswitch with the state of its first catch.
563 assert(CatchSwitch->getNumHandlers());
564 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000565 }
566 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000567
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000568 // Step two: record the TryParentState of each state. For cleanuppads that
569 // don't have cleanuprets, we may need to infer this from their child pads,
570 // so visit pads in descendant-most to ancestor-most order.
571 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
572 End = FuncInfo.ClrEHUnwindMap.rend();
573 Entry != End; ++Entry) {
574 const Instruction *Pad =
575 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
576 // For most pads, the TryParentState is the state associated with the
577 // unwind dest of exceptional exits from it.
578 const BasicBlock *UnwindDest;
579 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
580 // If a catch is not the last in its catchswitch, its TryParentState is
581 // the state associated with the next catch in the switch, even though
582 // that's not the unwind dest of exceptions escaping the catch. Those
583 // cases were already assigned a TryParentState in the first pass, so
584 // skip them.
585 if (Entry->TryParentState != -1)
586 continue;
587 // Otherwise, get the unwind dest from the catchswitch.
588 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
589 } else {
590 const auto *Cleanup = cast<CleanupPadInst>(Pad);
591 UnwindDest = nullptr;
592 for (const User *U : Cleanup->users()) {
593 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
594 // Common and unambiguous case -- cleanupret indicates cleanup's
595 // unwind dest.
596 UnwindDest = CleanupRet->getUnwindDest();
597 break;
598 }
599
600 // Get an unwind dest for the user
601 const BasicBlock *UserUnwindDest = nullptr;
602 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
603 UserUnwindDest = Invoke->getUnwindDest();
604 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
605 UserUnwindDest = CatchSwitch->getUnwindDest();
606 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
607 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
608 int UserUnwindState =
609 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
610 if (UserUnwindState != -1)
611 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
612 .Handler.get<const BasicBlock *>();
613 }
614
615 // Not having an unwind dest for this user might indicate that it
616 // doesn't unwind, so can't be taken as proof that the cleanup itself
617 // may unwind to caller (see e.g. SimplifyUnreachable and
618 // RemoveUnwindEdge).
619 if (!UserUnwindDest)
620 continue;
621
622 // Now we have an unwind dest for the user, but we need to see if it
623 // unwinds all the way out of the cleanup or if it stays within it.
624 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
625 const Value *UserUnwindParent;
626 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
627 UserUnwindParent = CSI->getParentPad();
628 else
629 UserUnwindParent =
630 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
631
632 // The unwind stays within the cleanup iff it targets a child of the
633 // cleanup.
634 if (UserUnwindParent == Cleanup)
635 continue;
636
637 // This unwind exits the cleanup, so its dest is the cleanup's dest.
638 UnwindDest = UserUnwindDest;
639 break;
640 }
641 }
642
643 // Record the state of the unwind dest as the TryParentState.
644 int UnwindDestState;
645
646 // If UnwindDest is null at this point, either the pad in question can
647 // be exited by unwind to caller, or it cannot be exited by unwind. In
648 // either case, reporting such cases as unwinding to caller is correct.
649 // This can lead to EH tables that "look strange" -- if this pad's is in
650 // a parent funclet which has other children that do unwind to an enclosing
651 // pad, the try region for this pad will be missing the "duplicate" EH
652 // clause entries that you'd expect to see covering the whole parent. That
653 // should be benign, since the unwind never actually happens. If it were
654 // an issue, we could add a subsequent pass that pushes unwind dests down
655 // from parents that have them to children that appear to unwind to caller.
656 if (!UnwindDest) {
657 UnwindDestState = -1;
658 } else {
659 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
660 }
661
662 Entry->TryParentState = UnwindDestState;
663 }
664
665 // Step three: transfer information from pads to invokes.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000666 calculateStateNumbersForInvokes(Fn, FuncInfo);
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000667}
668
David Majnemer8a1c45d2015-12-12 05:38:55 +0000669void WinEHPrepare::colorFunclets(Function &F) {
670 BlockColors = colorEHFunclets(F);
David Majnemerfd9f4772015-08-11 01:15:26 +0000671
David Majnemer8a1c45d2015-12-12 05:38:55 +0000672 // Invert the map from BB to colors to color to BBs.
673 for (BasicBlock &BB : F) {
674 ColorVector &Colors = BlockColors[&BB];
675 for (BasicBlock *Color : Colors)
676 FuncletBlocks[Color].push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000677 }
678}
679
David Majnemerb3d9b962015-09-16 18:40:24 +0000680void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000681 // Strip PHI nodes off of EH pads.
682 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +0000683 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000684 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000685 if (!BB->isEHPad())
686 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +0000687 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000688 Instruction *I = &*BI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000689 auto *PN = dyn_cast<PHINode>(I);
690 // Stop at the first non-PHI.
691 if (!PN)
692 break;
David Majnemerfd9f4772015-08-11 01:15:26 +0000693
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000694 AllocaInst *SpillSlot = insertPHILoads(PN, F);
695 if (SpillSlot)
696 insertPHIStores(PN, SpillSlot);
697
698 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +0000699 }
700 }
701
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000702 for (auto *PN : PHINodes) {
703 // There may be lingering uses on other EH PHIs being removed
704 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
705 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +0000706 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000707}
David Majnemerfd9f4772015-08-11 01:15:26 +0000708
David Majnemer8a1c45d2015-12-12 05:38:55 +0000709void WinEHPrepare::cloneCommonBlocks(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000710 // We need to clone all blocks which belong to multiple funclets. Values are
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000711 // remapped throughout the funclet to propagate both the new instructions
David Majnemerfd9f4772015-08-11 01:15:26 +0000712 // *and* the new basic blocks themselves.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000713 for (auto &Funclets : FuncletBlocks) {
714 BasicBlock *FuncletPadBB = Funclets.first;
715 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000716 Value *FuncletToken;
717 if (FuncletPadBB == &F.getEntryBlock())
718 FuncletToken = ConstantTokenNone::get(F.getContext());
719 else
720 FuncletToken = FuncletPadBB->getFirstNonPHI();
David Majnemerfd9f4772015-08-11 01:15:26 +0000721
David Majnemer8a1c45d2015-12-12 05:38:55 +0000722 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
David Majnemerfd9f4772015-08-11 01:15:26 +0000723 ValueToValueMapTy VMap;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000724 for (BasicBlock *BB : BlocksInFunclet) {
725 ColorVector &ColorsForBB = BlockColors[BB];
David Majnemerfd9f4772015-08-11 01:15:26 +0000726 // We don't need to do anything if the block is monochromatic.
727 size_t NumColorsForBB = ColorsForBB.size();
728 if (NumColorsForBB == 1)
729 continue;
730
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000731 DEBUG_WITH_TYPE("winehprepare-coloring",
732 dbgs() << " Cloning block \'" << BB->getName()
733 << "\' for funclet \'" << FuncletPadBB->getName()
734 << "\'.\n");
735
David Majnemerfd9f4772015-08-11 01:15:26 +0000736 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +0000737 BasicBlock *CBB =
738 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
739 // Insert the clone immediately after the original to ensure determinism
740 // and to keep the same relative ordering of any funclet's blocks.
741 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +0000742
743 // Add basic block mapping.
744 VMap[BB] = CBB;
745
746 // Record delta operations that we need to perform to our color mappings.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000747 Orig2Clone.emplace_back(BB, CBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000748 }
749
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000750 // If nothing was cloned, we're done cloning in this funclet.
751 if (Orig2Clone.empty())
752 continue;
753
David Majnemerfd9f4772015-08-11 01:15:26 +0000754 // Update our color mappings to reflect that one block has lost a color and
755 // another has gained a color.
756 for (auto &BBMapping : Orig2Clone) {
757 BasicBlock *OldBlock = BBMapping.first;
758 BasicBlock *NewBlock = BBMapping.second;
759
David Majnemer8a1c45d2015-12-12 05:38:55 +0000760 BlocksInFunclet.push_back(NewBlock);
761 ColorVector &NewColors = BlockColors[NewBlock];
762 assert(NewColors.empty() && "A new block should only have one color!");
763 NewColors.push_back(FuncletPadBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000764
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000765 DEBUG_WITH_TYPE("winehprepare-coloring",
766 dbgs() << " Assigned color \'" << FuncletPadBB->getName()
767 << "\' to block \'" << NewBlock->getName()
768 << "\'.\n");
769
David Majnemer8a1c45d2015-12-12 05:38:55 +0000770 BlocksInFunclet.erase(
771 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
772 BlocksInFunclet.end());
773 ColorVector &OldColors = BlockColors[OldBlock];
774 OldColors.erase(
775 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
776 OldColors.end());
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000777
778 DEBUG_WITH_TYPE("winehprepare-coloring",
779 dbgs() << " Removed color \'" << FuncletPadBB->getName()
780 << "\' from block \'" << OldBlock->getName()
781 << "\'.\n");
David Majnemerfd9f4772015-08-11 01:15:26 +0000782 }
783
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000784 // Loop over all of the instructions in this funclet, fixing up operand
David Majnemerfd9f4772015-08-11 01:15:26 +0000785 // references as we go. This uses VMap to do all the hard work.
786 for (BasicBlock *BB : BlocksInFunclet)
787 // Loop over all instructions, fixing each one as we find it...
788 for (Instruction &I : *BB)
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000789 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000790 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
David Majnemer459a64a2015-09-16 18:40:37 +0000791
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000792 // Catchrets targeting cloned blocks need to be updated separately from
793 // the loop above because they are not in the current funclet.
794 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
795 for (auto &BBMapping : Orig2Clone) {
796 BasicBlock *OldBlock = BBMapping.first;
797 BasicBlock *NewBlock = BBMapping.second;
798
799 FixupCatchrets.clear();
800 for (BasicBlock *Pred : predecessors(OldBlock))
801 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000802 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000803 FixupCatchrets.push_back(CatchRet);
804
805 for (CatchReturnInst *CatchRet : FixupCatchrets)
806 CatchRet->setSuccessor(NewBlock);
807 }
808
David Majnemer8a1c45d2015-12-12 05:38:55 +0000809 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
810 unsigned NumPreds = PN->getNumIncomingValues();
811 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
812 ++PredIdx) {
813 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000814 bool EdgeTargetsFunclet;
815 if (auto *CRI =
816 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000817 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000818 } else {
819 ColorVector &IncomingColors = BlockColors[IncomingBlock];
820 assert(!IncomingColors.empty() && "Block not colored!");
821 assert((IncomingColors.size() == 1 ||
822 llvm::all_of(IncomingColors,
823 [&](BasicBlock *Color) {
824 return Color != FuncletPadBB;
825 })) &&
826 "Cloning should leave this funclet's blocks monochromatic");
827 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
828 }
829 if (IsForOldBlock != EdgeTargetsFunclet)
David Majnemer8a1c45d2015-12-12 05:38:55 +0000830 continue;
831 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
832 // Revisit the next entry.
833 --PredIdx;
834 --PredEnd;
835 }
836 };
837
838 for (auto &BBMapping : Orig2Clone) {
839 BasicBlock *OldBlock = BBMapping.first;
840 BasicBlock *NewBlock = BBMapping.second;
841 for (Instruction &OldI : *OldBlock) {
842 auto *OldPN = dyn_cast<PHINode>(&OldI);
843 if (!OldPN)
844 break;
845 UpdatePHIOnClonedBlock(OldPN, /*IsForOldBlock=*/true);
846 }
847 for (Instruction &NewI : *NewBlock) {
848 auto *NewPN = dyn_cast<PHINode>(&NewI);
849 if (!NewPN)
850 break;
851 UpdatePHIOnClonedBlock(NewPN, /*IsForOldBlock=*/false);
852 }
853 }
854
David Majnemer459a64a2015-09-16 18:40:37 +0000855 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
856 // the PHI nodes for NewBB now.
857 for (auto &BBMapping : Orig2Clone) {
858 BasicBlock *OldBlock = BBMapping.first;
859 BasicBlock *NewBlock = BBMapping.second;
860 for (BasicBlock *SuccBB : successors(NewBlock)) {
861 for (Instruction &SuccI : *SuccBB) {
862 auto *SuccPN = dyn_cast<PHINode>(&SuccI);
863 if (!SuccPN)
864 break;
865
866 // Ok, we have a PHI node. Figure out what the incoming value was for
867 // the OldBlock.
868 int OldBlockIdx = SuccPN->getBasicBlockIndex(OldBlock);
869 if (OldBlockIdx == -1)
870 break;
871 Value *IV = SuccPN->getIncomingValue(OldBlockIdx);
872
873 // Remap the value if necessary.
874 if (auto *Inst = dyn_cast<Instruction>(IV)) {
875 ValueToValueMapTy::iterator I = VMap.find(Inst);
876 if (I != VMap.end())
877 IV = I->second;
878 }
879
880 SuccPN->addIncoming(IV, NewBlock);
881 }
882 }
883 }
884
885 for (ValueToValueMapTy::value_type VT : VMap) {
886 // If there were values defined in BB that are used outside the funclet,
887 // then we now have to update all uses of the value to use either the
888 // original value, the cloned value, or some PHI derived value. This can
889 // require arbitrary PHI insertion, of which we are prepared to do, clean
890 // these up now.
891 SmallVector<Use *, 16> UsesToRename;
892
893 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
894 if (!OldI)
895 continue;
896 auto *NewI = cast<Instruction>(VT.second);
897 // Scan all uses of this instruction to see if it is used outside of its
898 // funclet, and if so, record them in UsesToRename.
899 for (Use &U : OldI->uses()) {
900 Instruction *UserI = cast<Instruction>(U.getUser());
901 BasicBlock *UserBB = UserI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000902 ColorVector &ColorsForUserBB = BlockColors[UserBB];
David Majnemer459a64a2015-09-16 18:40:37 +0000903 assert(!ColorsForUserBB.empty());
904 if (ColorsForUserBB.size() > 1 ||
905 *ColorsForUserBB.begin() != FuncletPadBB)
906 UsesToRename.push_back(&U);
907 }
908
909 // If there are no uses outside the block, we're done with this
910 // instruction.
911 if (UsesToRename.empty())
912 continue;
913
914 // We found a use of OldI outside of the funclet. Rename all uses of OldI
915 // that are outside its funclet to be uses of the appropriate PHI node
916 // etc.
917 SSAUpdater SSAUpdate;
918 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
919 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
920 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
921
922 while (!UsesToRename.empty())
923 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
924 }
David Majnemerfd9f4772015-08-11 01:15:26 +0000925 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000926}
David Majnemerfd9f4772015-08-11 01:15:26 +0000927
David Majnemer3bb88c02015-12-15 21:27:27 +0000928void WinEHPrepare::removeImplausibleInstructions(Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +0000929 // Remove implausible terminators and replace them with UnreachableInst.
930 for (auto &Funclet : FuncletBlocks) {
931 BasicBlock *FuncletPadBB = Funclet.first;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000932 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
David Majnemer3bb88c02015-12-15 21:27:27 +0000933 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
934 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
935 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
936 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
David Majnemer83f4bb22015-08-17 20:56:39 +0000937
938 for (BasicBlock *BB : BlocksInFunclet) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000939 for (Instruction &I : *BB) {
940 CallSite CS(&I);
941 if (!CS)
942 continue;
943
944 Value *FuncletBundleOperand = nullptr;
945 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
946 FuncletBundleOperand = BU->Inputs.front();
947
948 if (FuncletBundleOperand == FuncletPad)
949 continue;
950
David Majnemer08dd52dc2016-02-26 00:04:25 +0000951 // Skip call sites which are nounwind intrinsics or inline asm.
David Majnemer3bb88c02015-12-15 21:27:27 +0000952 auto *CalledFn =
953 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Justin Lebar9cbc3012016-07-28 23:58:15 +0000954 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
955 CS.isInlineAsm()))
David Majnemer3bb88c02015-12-15 21:27:27 +0000956 continue;
957
958 // This call site was not part of this funclet, remove it.
959 if (CS.isInvoke()) {
960 // Remove the unwind edge if it was an invoke.
961 removeUnwindEdge(BB);
962 // Get a pointer to the new call.
963 BasicBlock::iterator CallI =
964 std::prev(BB->getTerminator()->getIterator());
965 auto *CI = cast<CallInst>(&*CallI);
David Majnemere14e7bc2016-06-25 08:19:55 +0000966 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000967 } else {
David Majnemere14e7bc2016-06-25 08:19:55 +0000968 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000969 }
970
971 // There are no more instructions in the block (except for unreachable),
972 // we are done.
973 break;
974 }
975
David Majnemer83f4bb22015-08-17 20:56:39 +0000976 TerminatorInst *TI = BB->getTerminator();
977 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
David Majnemer3bb88c02015-12-15 21:27:27 +0000978 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
David Majnemer83f4bb22015-08-17 20:56:39 +0000979 // The token consumed by a CatchReturnInst must match the funclet token.
980 bool IsUnreachableCatchret = false;
981 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000982 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000983 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemer83f4bb22015-08-17 20:56:39 +0000984 bool IsUnreachableCleanupret = false;
985 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000986 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000987 if (IsUnreachableRet || IsUnreachableCatchret ||
David Majnemer8a1c45d2015-12-12 05:38:55 +0000988 IsUnreachableCleanupret) {
David Majnemere14e7bc2016-06-25 08:19:55 +0000989 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000990 } else if (isa<InvokeInst>(TI)) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000991 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
992 // Invokes within a cleanuppad for the MSVC++ personality never
993 // transfer control to their unwind edge: the personality will
994 // terminate the program.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000995 removeUnwindEdge(BB);
David Majnemer3bb88c02015-12-15 21:27:27 +0000996 }
David Majnemer83f4bb22015-08-17 20:56:39 +0000997 }
998 }
999 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001000}
David Majnemer83f4bb22015-08-17 20:56:39 +00001001
David Majnemerb3d9b962015-09-16 18:40:24 +00001002void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00001003 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1004 // branches, etc.
1005 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001006 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00001007 SimplifyInstructionsInBlock(BB);
1008 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1009 MergeBlockIntoPredecessor(BB);
1010 }
1011
David Majnemerfd9f4772015-08-11 01:15:26 +00001012 // We might have some unreachable blocks after cleaning up some impossible
1013 // control flow.
1014 removeUnreachableBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001015}
David Majnemerfd9f4772015-08-11 01:15:26 +00001016
Florian Hahn6b3216a2017-07-31 10:07:49 +00001017#ifndef NDEBUG
David Majnemerb3d9b962015-09-16 18:40:24 +00001018void WinEHPrepare::verifyPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00001019 for (BasicBlock &BB : F) {
1020 size_t NumColors = BlockColors[&BB].size();
1021 assert(NumColors == 1 && "Expected monochromatic BB!");
1022 if (NumColors == 0)
1023 report_fatal_error("Uncolored BB!");
1024 if (NumColors > 1)
1025 report_fatal_error("Multicolor BB!");
NAKAMURA Takumided575e2016-01-03 01:41:00 +00001026 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1027 "EH Pad still has a PHI!");
David Majnemerfd9f4772015-08-11 01:15:26 +00001028 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001029}
Florian Hahn6b3216a2017-07-31 10:07:49 +00001030#endif
David Majnemerb3d9b962015-09-16 18:40:24 +00001031
David Majnemer8a1c45d2015-12-12 05:38:55 +00001032bool WinEHPrepare::prepareExplicitEH(Function &F) {
1033 // Remove unreachable blocks. It is not valuable to assign them a color and
1034 // their existence can trick us into thinking values are alive when they are
1035 // not.
1036 removeUnreachableBlocks(F);
1037
David Majnemerb3d9b962015-09-16 18:40:24 +00001038 // Determine which blocks are reachable from which funclet entries.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001039 colorFunclets(F);
1040
1041 cloneCommonBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001042
Reid Klecknercc2f6c32015-11-19 23:23:33 +00001043 if (!DisableDemotion)
David Majnemer459a64a2015-09-16 18:40:37 +00001044 demotePHIsOnFunclets(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001045
David Majnemer459a64a2015-09-16 18:40:37 +00001046 if (!DisableCleanups) {
David Majnemerdbdc9c22016-01-02 09:26:36 +00001047 DEBUG(verifyFunction(F));
David Majnemer3bb88c02015-12-15 21:27:27 +00001048 removeImplausibleInstructions(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001049
David Majnemerdbdc9c22016-01-02 09:26:36 +00001050 DEBUG(verifyFunction(F));
David Majnemer459a64a2015-09-16 18:40:37 +00001051 cleanupPreparedFunclets(F);
1052 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001053
David Majnemerdbdc9c22016-01-02 09:26:36 +00001054 DEBUG(verifyPreparedFunclets(F));
1055 // Recolor the CFG to verify that all is well.
1056 DEBUG(colorFunclets(F));
1057 DEBUG(verifyPreparedFunclets(F));
David Majnemerfd9f4772015-08-11 01:15:26 +00001058
1059 BlockColors.clear();
1060 FuncletBlocks.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00001061
David Majnemerfd9f4772015-08-11 01:15:26 +00001062 return true;
1063}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001064
1065// TODO: Share loads when one use dominates another, or when a catchpad exit
1066// dominates uses (needs dominators).
1067AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1068 BasicBlock *PHIBlock = PN->getParent();
1069 AllocaInst *SpillSlot = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +00001070 Instruction *EHPad = PHIBlock->getFirstNonPHI();
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001071
David Majnemer8a1c45d2015-12-12 05:38:55 +00001072 if (!isa<TerminatorInst>(EHPad)) {
1073 // If the EHPad isn't a terminator, then we can insert a load in this block
1074 // that will dominate all uses.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001075 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001076 Twine(PN->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001077 &F.getEntryBlock().front());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001078 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001079 &*PHIBlock->getFirstInsertionPt());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001080 PN->replaceAllUsesWith(V);
1081 return SpillSlot;
1082 }
1083
David Majnemer8a1c45d2015-12-12 05:38:55 +00001084 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1085 // loads of the slot before every use.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001086 DenseMap<BasicBlock *, Value *> Loads;
1087 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1088 UI != UE;) {
1089 Use &U = *UI++;
1090 auto *UsingInst = cast<Instruction>(U.getUser());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001091 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001092 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1093 // stores for it separately.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001094 continue;
1095 }
1096 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1097 }
1098 return SpillSlot;
1099}
1100
1101// TODO: improve store placement. Inserting at def is probably good, but need
1102// to be careful not to introduce interfering stores (needs liveness analysis).
1103// TODO: identify related phi nodes that can share spill slots, and share them
1104// (also needs liveness).
1105void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1106 AllocaInst *SpillSlot) {
1107 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1108 // stored to the spill slot by the end of the given Block.
1109 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1110
1111 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1112
1113 while (!Worklist.empty()) {
1114 BasicBlock *EHBlock;
1115 Value *InVal;
1116 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1117
1118 PHINode *PN = dyn_cast<PHINode>(InVal);
1119 if (PN && PN->getParent() == EHBlock) {
1120 // The value is defined by another PHI we need to remove, with no room to
1121 // insert a store after the PHI, so each predecessor needs to store its
1122 // incoming value.
1123 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1124 Value *PredVal = PN->getIncomingValue(i);
1125
1126 // Undef can safely be skipped.
1127 if (isa<UndefValue>(PredVal))
1128 continue;
1129
1130 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1131 }
1132 } else {
1133 // We need to store InVal, which dominates EHBlock, but can't put a store
1134 // in EHBlock, so need to put stores in each predecessor.
1135 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1136 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1137 }
1138 }
1139 }
1140}
1141
1142void WinEHPrepare::insertPHIStore(
1143 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1144 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1145
1146 if (PredBlock->isEHPad() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +00001147 isa<TerminatorInst>(PredBlock->getFirstNonPHI())) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001148 // Pred is unsplittable, so we need to queue it on the worklist.
1149 Worklist.push_back({PredBlock, PredVal});
1150 return;
1151 }
1152
1153 // Otherwise, insert the store at the end of the basic block.
1154 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1155}
1156
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001157void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1158 DenseMap<BasicBlock *, Value *> &Loads,
1159 Function &F) {
1160 // Lazilly create the spill slot.
1161 if (!SpillSlot)
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001162 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001163 Twine(V->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001164 &F.getEntryBlock().front());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001165
1166 auto *UsingInst = cast<Instruction>(U.getUser());
1167 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1168 // If this is a PHI node, we can't insert a load of the value before
1169 // the use. Instead insert the load in the predecessor block
1170 // corresponding to the incoming value.
1171 //
1172 // Note that if there are multiple edges from a basic block to this
1173 // PHI node that we cannot have multiple loads. The problem is that
1174 // the resulting PHI node will have multiple values (from each load)
1175 // coming in from the same block, which is illegal SSA form.
1176 // For this reason, we keep track of and reuse loads we insert.
1177 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001178 if (auto *CatchRet =
1179 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1180 // Putting a load above a catchret and use on the phi would still leave
1181 // a cross-funclet def/use. We need to split the edge, change the
1182 // catchret to target the new block, and put the load there.
1183 BasicBlock *PHIBlock = UsingInst->getParent();
1184 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1185 // SplitEdge gives us:
1186 // IncomingBlock:
1187 // ...
1188 // br label %NewBlock
1189 // NewBlock:
1190 // catchret label %PHIBlock
1191 // But we need:
1192 // IncomingBlock:
1193 // ...
1194 // catchret label %NewBlock
1195 // NewBlock:
1196 // br label %PHIBlock
1197 // So move the terminators to each others' blocks and swap their
1198 // successors.
1199 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1200 Goto->removeFromParent();
1201 CatchRet->removeFromParent();
1202 IncomingBlock->getInstList().push_back(CatchRet);
1203 NewBlock->getInstList().push_back(Goto);
1204 Goto->setSuccessor(0, PHIBlock);
1205 CatchRet->setSuccessor(NewBlock);
1206 // Update the color mapping for the newly split edge.
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001207 // Grab a reference to the ColorVector to be inserted before getting the
1208 // reference to the vector we are copying because inserting the new
1209 // element in BlockColors might cause the map to be reallocated.
1210 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
David Majnemer8a1c45d2015-12-12 05:38:55 +00001211 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001212 ColorsForNewBlock = ColorsForPHIBlock;
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001213 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
David Majnemer8a1c45d2015-12-12 05:38:55 +00001214 FuncletBlocks[FuncletPad].push_back(NewBlock);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001215 // Treat the new block as incoming for load insertion.
1216 IncomingBlock = NewBlock;
1217 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001218 Value *&Load = Loads[IncomingBlock];
1219 // Insert the load into the predecessor block
1220 if (!Load)
1221 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1222 /*Volatile=*/false, IncomingBlock->getTerminator());
1223
1224 U.set(Load);
1225 } else {
1226 // Reload right before the old use.
1227 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1228 /*Volatile=*/false, UsingInst);
1229 U.set(Load);
1230 }
1231}
Reid Klecknerc71d6272015-09-28 23:56:30 +00001232
David Majnemer8a1c45d2015-12-12 05:38:55 +00001233void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
Reid Klecknerc71d6272015-09-28 23:56:30 +00001234 MCSymbol *InvokeBegin,
1235 MCSymbol *InvokeEnd) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001236 assert(InvokeStateMap.count(II) &&
1237 "should get invoke with precomputed state");
1238 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
Reid Klecknerc71d6272015-09-28 23:56:30 +00001239}
Chandler Carruthe0115342015-12-29 09:24:39 +00001240
1241WinEHFuncInfo::WinEHFuncInfo() {}