blob: 87958a738c67e250ccb7d9b2e89b8aa53cc7819b [file] [log] [blame]
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00001//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Kaylor1476e6d2015-02-24 20:49:35 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass lowers LLVM IR exception handling into something closer to what the
Reid Kleckner0738a9c2015-05-05 17:44:16 +000010// backend wants for functions using a personality function from a runtime
11// provided by MSVC. Functions with other personality functions are left alone
12// and may be prepared by other passes. In particular, all supported MSVC
13// personality functions require cleanup code to be outlined, and the C++
14// personality requires catch handler code to be outlined.
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000015//
16//===----------------------------------------------------------------------===//
17
Joseph Tremoulet52f729a2016-01-04 16:16:01 +000018#include "llvm/ADT/DenseMap.h"
David Majnemer8a1c45d2015-12-12 05:38:55 +000019#include "llvm/ADT/MapVector.h"
Joseph Tremoulet52f729a2016-01-04 16:16:01 +000020#include "llvm/ADT/STLExtras.h"
David Majnemerfd9f4772015-08-11 01:15:26 +000021#include "llvm/Analysis/CFG.h"
David Majnemer70497c62015-12-02 23:06:39 +000022#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthe0115342015-12-29 09:24:39 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/CodeGen/Passes.h"
David Majnemercde33032015-03-30 22:58:10 +000025#include "llvm/CodeGen/WinEHFuncInfo.h"
David Majnemerdbdc9c22016-01-02 09:26:36 +000026#include "llvm/IR/Verifier.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080027#include "llvm/InitializePasses.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"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080030#include "llvm/Support/CommandLine.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000031#include "llvm/Support/Debug.h"
Benjamin Kramera8d61b12015-03-23 18:57:17 +000032#include "llvm/Support/raw_ostream.h"
Andrew Kaylor6b67d422015-03-11 23:22:06 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000034#include "llvm/Transforms/Utils/Cloning.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080035#include "llvm/Transforms/Utils/Local.h"
David Majnemer459a64a2015-09-16 18:40:37 +000036#include "llvm/Transforms/Utils/SSAUpdater.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000037
38using namespace llvm;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000039
40#define DEBUG_TYPE "winehprepare"
41
David Majnemer459a64a2015-09-16 18:40:37 +000042static cl::opt<bool> DisableDemotion(
43 "disable-demotion", cl::Hidden,
44 cl::desc(
Heejin Ahnb4be38f2018-05-17 20:52:03 +000045 "Clone multicolor basic blocks but do not demote cross scopes"),
David Majnemer459a64a2015-09-16 18:40:37 +000046 cl::init(false));
47
48static cl::opt<bool> DisableCleanups(
49 "disable-cleanups", cl::Hidden,
50 cl::desc("Do not remove implausible terminators or other similar cleanups"),
51 cl::init(false));
52
Heejin Ahn99d60e02018-05-31 22:02:34 +000053static cl::opt<bool> DemoteCatchSwitchPHIOnlyOpt(
54 "demote-catchswitch-only", cl::Hidden,
55 cl::desc("Demote catchswitch BBs only (for wasm EH)"), cl::init(false));
56
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000057namespace {
Fangrui Songf78650a2018-07-30 19:41:25 +000058
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000059class WinEHPrepare : public FunctionPass {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000060public:
61 static char ID; // Pass identification, replacement for typeid.
Heejin Ahn99d60e02018-05-31 22:02:34 +000062 WinEHPrepare(bool DemoteCatchSwitchPHIOnly = false)
63 : FunctionPass(ID), DemoteCatchSwitchPHIOnly(DemoteCatchSwitchPHIOnly) {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000064
65 bool runOnFunction(Function &Fn) override;
66
67 bool doFinalization(Module &M) override;
68
69 void getAnalysisUsage(AnalysisUsage &AU) const override;
70
Mehdi Amini117296c2016-10-01 02:56:57 +000071 StringRef getPassName() const override {
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000072 return "Windows exception handling preparation";
73 }
74
75private:
Joseph Tremouletc9ff9142015-08-13 14:30:10 +000076 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
77 void
78 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
79 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
80 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
81 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
82 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
David Majnemer8a1c45d2015-12-12 05:38:55 +000083 bool prepareExplicitEH(Function &F);
David Majnemer8a1c45d2015-12-12 05:38:55 +000084 void colorFunclets(Function &F);
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +000085
Heejin Ahn99d60e02018-05-31 22:02:34 +000086 void demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
David Majnemer8a1c45d2015-12-12 05:38:55 +000087 void cloneCommonBlocks(Function &F);
David Majnemer3bb88c02015-12-15 21:27:27 +000088 void removeImplausibleInstructions(Function &F);
David Majnemerb3d9b962015-09-16 18:40:24 +000089 void cleanupPreparedFunclets(Function &F);
90 void verifyPreparedFunclets(Function &F);
David Majnemerfd9f4772015-08-11 01:15:26 +000091
Heejin Ahn99d60e02018-05-31 22:02:34 +000092 bool DemoteCatchSwitchPHIOnly;
93
Reid Kleckner0f9e27a2015-03-18 20:26:53 +000094 // All fields are reset by runOnFunction.
Reid Kleckner582786b2015-04-30 18:17:12 +000095 EHPersonality Personality = EHPersonality::Unknown;
David Majnemerfd9f4772015-08-11 01:15:26 +000096
Matt Arsenault3c1fc762017-04-10 22:27:50 +000097 const DataLayout *DL = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +000098 DenseMap<BasicBlock *, ColorVector> BlockColors;
99 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000100};
101
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000102} // end anonymous namespace
103
104char WinEHPrepare::ID = 0;
Matthias Braun1527baa2017-05-25 21:26:32 +0000105INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000106 false, false)
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000107
Heejin Ahn99d60e02018-05-31 22:02:34 +0000108FunctionPass *llvm::createWinEHPass(bool DemoteCatchSwitchPHIOnly) {
109 return new WinEHPrepare(DemoteCatchSwitchPHIOnly);
110}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000111
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000112bool WinEHPrepare::runOnFunction(Function &Fn) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000113 if (!Fn.hasPersonalityFn())
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000114 return false;
115
116 // Classify the personality to see what kind of preparation we need.
David Majnemer7fddecc2015-06-17 20:52:32 +0000117 Personality = classifyEHPersonality(Fn.getPersonalityFn());
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000118
Heejin Ahnb4be38f2018-05-17 20:52:03 +0000119 // Do nothing if this is not a scope-based personality.
120 if (!isScopedEHPersonality(Personality))
Reid Kleckner47c8e7a2015-03-12 00:36:20 +0000121 return false;
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000122
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000123 DL = &Fn.getParent()->getDataLayout();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000124 return prepareExplicitEH(Fn);
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000125}
126
Andrew Kayloraa92ab02015-04-03 19:37:50 +0000127bool WinEHPrepare::doFinalization(Module &M) { return false; }
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000128
David Majnemere6965832015-10-16 19:59:52 +0000129void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000130
David Majnemer0ad363e2015-08-18 19:07:12 +0000131static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
David Majnemerbfa5b982015-10-10 00:04:29 +0000132 const BasicBlock *BB) {
Reid Kleckner14e77352015-10-09 23:34:53 +0000133 CxxUnwindMapEntry UME;
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000134 UME.ToState = ToState;
David Majnemerbfa5b982015-10-10 00:04:29 +0000135 UME.Cleanup = BB;
Reid Kleckner14e77352015-10-09 23:34:53 +0000136 FuncInfo.CxxUnwindMap.push_back(UME);
David Majnemer0ad363e2015-08-18 19:07:12 +0000137 return FuncInfo.getLastStateNumber();
138}
139
140static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
141 int TryHigh, int CatchHigh,
142 ArrayRef<const CatchPadInst *> Handlers) {
143 WinEHTryBlockMapEntry TBME;
144 TBME.TryLow = TryLow;
145 TBME.TryHigh = TryHigh;
146 TBME.CatchHigh = CatchHigh;
147 assert(TBME.TryLow <= TBME.TryHigh);
148 for (const CatchPadInst *CPI : Handlers) {
149 WinEHHandlerType HT;
150 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
Reid Klecknerb005d282015-09-16 20:16:27 +0000151 if (TypeInfo->isNullValue())
David Majnemer0ad363e2015-08-18 19:07:12 +0000152 HT.TypeDescriptor = nullptr;
Reid Klecknerb005d282015-09-16 20:16:27 +0000153 else
154 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
155 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
David Majnemer7735a6d2015-10-06 23:31:59 +0000156 HT.Handler = CPI->getParent();
David Majnemer086fec22016-01-08 08:03:55 +0000157 if (auto *AI =
158 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
159 HT.CatchObj.Alloca = AI;
Reid Klecknerb005d282015-09-16 20:16:27 +0000160 else
David Majnemer086fec22016-01-08 08:03:55 +0000161 HT.CatchObj.Alloca = nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +0000162 TBME.HandlerArray.push_back(HT);
163 }
164 FuncInfo.TryBlockMap.push_back(TBME);
165}
166
David Majnemer8a1c45d2015-12-12 05:38:55 +0000167static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
168 for (const User *U : CleanupPad->users())
169 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
170 return CRI->getUnwindDest();
David Majnemer0ad363e2015-08-18 19:07:12 +0000171 return nullptr;
172}
173
David Majnemer8a1c45d2015-12-12 05:38:55 +0000174static void calculateStateNumbersForInvokes(const Function *Fn,
175 WinEHFuncInfo &FuncInfo) {
176 auto *F = const_cast<Function *>(Fn);
177 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
178 for (BasicBlock &BB : *F) {
179 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
180 if (!II)
181 continue;
182
183 auto &BBColors = BlockColors[&BB];
David Majnemerc640f862015-12-23 03:59:04 +0000184 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
David Majnemer8a1c45d2015-12-12 05:38:55 +0000185 BasicBlock *FuncletEntryBB = BBColors.front();
186
187 BasicBlock *FuncletUnwindDest;
188 auto *FuncletPad =
189 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
190 assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
191 if (!FuncletPad)
192 FuncletUnwindDest = nullptr;
193 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
194 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
195 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
196 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
197 else
198 llvm_unreachable("unexpected funclet pad!");
199
200 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
201 int BaseState = -1;
202 if (FuncletUnwindDest == InvokeUnwindDest) {
203 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
204 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
205 BaseState = BaseStateI->second;
206 }
207
208 if (BaseState != -1) {
209 FuncInfo.InvokeStateMap[II] = BaseState;
210 } else {
211 Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
212 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
213 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
214 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000215 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000216}
217
David Majnemer0ad363e2015-08-18 19:07:12 +0000218// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
219// to. If the unwind edge came from an invoke, return null.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000220static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
221 Value *ParentPad) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000222 const Instruction *TI = BB->getTerminator();
David Majnemer0ad363e2015-08-18 19:07:12 +0000223 if (isa<InvokeInst>(TI))
224 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000225 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
226 if (CatchSwitch->getParentPad() != ParentPad)
227 return nullptr;
David Majnemer0ad363e2015-08-18 19:07:12 +0000228 return BB;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000229 }
230 assert(!TI->isEHPad() && "unexpected EHPad!");
231 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
232 if (CleanupPad->getParentPad() != ParentPad)
233 return nullptr;
234 return CleanupPad->getParent();
David Majnemer0ad363e2015-08-18 19:07:12 +0000235}
236
David Majnemer8a1c45d2015-12-12 05:38:55 +0000237static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
238 const Instruction *FirstNonPHI,
239 int ParentState) {
240 const BasicBlock *BB = FirstNonPHI->getParent();
241 assert(BB->isEHPad() && "not a funclet!");
David Majnemer0ad363e2015-08-18 19:07:12 +0000242
David Majnemer8a1c45d2015-12-12 05:38:55 +0000243 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
244 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
245 "shouldn't revist catch funclets!");
246
David Majnemer0ad363e2015-08-18 19:07:12 +0000247 SmallVector<const CatchPadInst *, 2> Handlers;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000248 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
249 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
250 Handlers.push_back(CatchPad);
251 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000252 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000253 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
254 for (const BasicBlock *PredBlock : predecessors(BB))
255 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
256 CatchSwitch->getParentPad())))
257 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
258 TryLow);
David Majnemer0ad363e2015-08-18 19:07:12 +0000259 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000260
261 // catchpads are separate funclets in C++ EH due to the way rethrow works.
David Majnemer0ad363e2015-08-18 19:07:12 +0000262 int TryHigh = CatchLow - 1;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000263 for (const auto *CatchPad : Handlers) {
264 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
265 for (const User *U : CatchPad->users()) {
266 const auto *UserI = cast<Instruction>(U);
David Majnemer17525ab2016-02-23 07:18:15 +0000267 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
268 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
269 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000270 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
David Majnemer17525ab2016-02-23 07:18:15 +0000271 }
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000272 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
273 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
274 // If a nested cleanup pad reports a null unwind destination and the
275 // enclosing catch pad doesn't it must be post-dominated by an
276 // unreachable instruction.
277 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000278 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000279 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000280 }
281 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000282 int CatchHigh = FuncInfo.getLastStateNumber();
283 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000284 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
285 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
286 << '\n');
287 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
288 << '\n');
David Majnemer0ad363e2015-08-18 19:07:12 +0000289 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000290 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
291
292 // It's possible for a cleanup to be visited twice: it might have multiple
293 // cleanupret instructions.
294 if (FuncInfo.EHPadStateMap.count(CleanupPad))
295 return;
296
297 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
298 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000299 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
300 << BB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000301 for (const BasicBlock *PredBlock : predecessors(BB)) {
302 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
303 CleanupPad->getParentPad()))) {
304 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
305 CleanupState);
306 }
307 }
308 for (const User *U : CleanupPad->users()) {
309 const auto *UserI = cast<Instruction>(U);
310 if (UserI->isEHPad())
311 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
312 "contain exceptional actions");
313 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000314 }
315}
316
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000317static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
318 const Function *Filter, const BasicBlock *Handler) {
Reid Kleckner94b704c2015-09-09 21:10:03 +0000319 SEHUnwindMapEntry Entry;
320 Entry.ToState = ParentState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000321 Entry.IsFinally = false;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000322 Entry.Filter = Filter;
323 Entry.Handler = Handler;
324 FuncInfo.SEHUnwindMap.push_back(Entry);
325 return FuncInfo.SEHUnwindMap.size() - 1;
326}
327
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000328static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
329 const BasicBlock *Handler) {
330 SEHUnwindMapEntry Entry;
331 Entry.ToState = ParentState;
332 Entry.IsFinally = true;
333 Entry.Filter = nullptr;
334 Entry.Handler = Handler;
335 FuncInfo.SEHUnwindMap.push_back(Entry);
336 return FuncInfo.SEHUnwindMap.size() - 1;
337}
338
David Majnemer8a1c45d2015-12-12 05:38:55 +0000339static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
340 const Instruction *FirstNonPHI,
341 int ParentState) {
342 const BasicBlock *BB = FirstNonPHI->getParent();
343 assert(BB->isEHPad() && "no a funclet!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000344
David Majnemer8a1c45d2015-12-12 05:38:55 +0000345 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
346 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
347 "shouldn't revist catch funclets!");
348
Reid Kleckner94b704c2015-09-09 21:10:03 +0000349 // Extract the filter function and the __except basic block and create a
350 // state for them.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000351 assert(CatchSwitch->getNumHandlers() == 1 &&
Reid Kleckner94b704c2015-09-09 21:10:03 +0000352 "SEH doesn't have multiple handlers per __try");
David Majnemer8a1c45d2015-12-12 05:38:55 +0000353 const auto *CatchPad =
354 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
355 const BasicBlock *CatchPadBB = CatchPad->getParent();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000356 const Constant *FilterOrNull =
David Majnemer8a1c45d2015-12-12 05:38:55 +0000357 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000358 const Function *Filter = dyn_cast<Function>(FilterOrNull);
359 assert((Filter || FilterOrNull->isNullValue()) &&
360 "unexpected filter value");
David Majnemer7735a6d2015-10-06 23:31:59 +0000361 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000362
363 // Everything in the __try block uses TryState as its parent state.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000364 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000365 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
366 << CatchPadBB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000367 for (const BasicBlock *PredBlock : predecessors(BB))
368 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
369 CatchSwitch->getParentPad())))
370 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
371 TryState);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000372
373 // Everything in the __except block unwinds to ParentState, just like code
374 // outside the __try.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000375 for (const User *U : CatchPad->users()) {
376 const auto *UserI = cast<Instruction>(U);
David Majnemer17525ab2016-02-23 07:18:15 +0000377 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
378 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
379 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000380 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
David Majnemer17525ab2016-02-23 07:18:15 +0000381 }
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000382 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
383 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
384 // If a nested cleanup pad reports a null unwind destination and the
385 // enclosing catch pad doesn't it must be post-dominated by an
386 // unreachable instruction.
387 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000388 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000389 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000390 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000391 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000392 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
393
394 // It's possible for a cleanup to be visited twice: it might have multiple
395 // cleanupret instructions.
396 if (FuncInfo.EHPadStateMap.count(CleanupPad))
397 return;
398
399 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
400 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000401 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
402 << BB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000403 for (const BasicBlock *PredBlock : predecessors(BB))
404 if ((PredBlock =
405 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
406 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
407 CleanupState);
408 for (const User *U : CleanupPad->users()) {
409 const auto *UserI = cast<Instruction>(U);
410 if (UserI->isEHPad())
411 report_fatal_error("Cleanup funclets for the SEH personality cannot "
412 "contain exceptional actions");
413 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000414 }
415}
416
David Majnemer8a1c45d2015-12-12 05:38:55 +0000417static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
418 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
419 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
420 CatchSwitch->unwindsToCaller();
421 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
422 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
423 getCleanupRetUnwindDest(CleanupPad) == nullptr;
424 if (isa<CatchPadInst>(EHPad))
425 return false;
426 llvm_unreachable("unexpected EHPad!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000427}
428
Reid Kleckner813f1b62015-09-16 22:14:46 +0000429void llvm::calculateSEHStateNumbers(const Function *Fn,
Reid Kleckner94b704c2015-09-09 21:10:03 +0000430 WinEHFuncInfo &FuncInfo) {
431 // Don't compute state numbers twice.
432 if (!FuncInfo.SEHUnwindMap.empty())
433 return;
434
Reid Kleckner813f1b62015-09-16 22:14:46 +0000435 for (const BasicBlock &BB : *Fn) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000436 if (!BB.isEHPad())
Reid Kleckner94b704c2015-09-09 21:10:03 +0000437 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000438 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
439 if (!isTopLevelPadForMSVC(FirstNonPHI))
440 continue;
441 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000442 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000443
444 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000445}
446
Reid Kleckner813f1b62015-09-16 22:14:46 +0000447void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000448 WinEHFuncInfo &FuncInfo) {
449 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +0000450 if (!FuncInfo.EHPadStateMap.empty())
451 return;
452
Reid Kleckner813f1b62015-09-16 22:14:46 +0000453 for (const BasicBlock &BB : *Fn) {
David Majnemer0ad363e2015-08-18 19:07:12 +0000454 if (!BB.isEHPad())
455 continue;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000456 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000457 if (!isTopLevelPadForMSVC(FirstNonPHI))
David Majnemer0ad363e2015-08-18 19:07:12 +0000458 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000459 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
David Majnemer0ad363e2015-08-18 19:07:12 +0000460 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000461
462 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000463}
David Majnemerfd9f4772015-08-11 01:15:26 +0000464
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000465static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
466 int TryParentState, ClrHandlerType HandlerType,
467 uint32_t TypeToken, const BasicBlock *Handler) {
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000468 ClrEHUnwindMapEntry Entry;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000469 Entry.HandlerParentState = HandlerParentState;
470 Entry.TryParentState = TryParentState;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000471 Entry.Handler = Handler;
472 Entry.HandlerType = HandlerType;
473 Entry.TypeToken = TypeToken;
474 FuncInfo.ClrEHUnwindMap.push_back(Entry);
475 return FuncInfo.ClrEHUnwindMap.size() - 1;
476}
477
478void llvm::calculateClrEHStateNumbers(const Function *Fn,
479 WinEHFuncInfo &FuncInfo) {
480 // Return if it's already been done.
481 if (!FuncInfo.EHPadStateMap.empty())
482 return;
483
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000484 // This numbering assigns one state number to each catchpad and cleanuppad.
485 // It also computes two tree-like relations over states:
486 // 1) Each state has a "HandlerParentState", which is the state of the next
487 // outer handler enclosing this state's handler (same as nearest ancestor
488 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
489 // 2) Each state has a "TryParentState", which:
490 // a) for a catchpad that's not the last handler on its catchswitch, is
491 // the state of the next catchpad on that catchswitch
492 // b) for all other pads, is the state of the pad whose try region is the
493 // next outer try region enclosing this state's try region. The "try
494 // regions are not present as such in the IR, but will be inferred
495 // based on the placement of invokes and pads which reach each other
496 // by exceptional exits
497 // Catchswitches do not get their own states, but each gets mapped to the
498 // state of its first catchpad.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000499
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000500 // Step one: walk down from outermost to innermost funclets, assigning each
501 // catchpad and cleanuppad a state number. Add an entry to the
502 // ClrEHUnwindMap for each state, recording its HandlerParentState and
503 // handler attributes. Record the TryParentState as well for each catchpad
504 // that's not the last on its catchswitch, but initialize all other entries'
505 // TryParentStates to a sentinel -1 value that the next pass will update.
506
507 // Seed a worklist with pads that have no parent.
508 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000509 for (const BasicBlock &BB : *Fn) {
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000510 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000511 const Value *ParentPad;
512 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
513 ParentPad = CPI->getParentPad();
514 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
515 ParentPad = CSI->getParentPad();
516 else
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000517 continue;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000518 if (isa<ConstantTokenNone>(ParentPad))
519 Worklist.emplace_back(FirstNonPHI, -1);
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000520 }
521
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000522 // Use the worklist to visit all pads, from outer to inner. Record
523 // HandlerParentState for all pads. Record TryParentState only for catchpads
524 // that aren't the last on their catchswitch (setting all other entries'
525 // TryParentStates to an initial value of -1). This loop is also responsible
526 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
527 // catchswitches.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000528 while (!Worklist.empty()) {
529 const Instruction *Pad;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000530 int HandlerParentState;
531 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000532
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000533 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
534 // Create the entry for this cleanup with the appropriate handler
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000535 // properties. Finally and fault handlers are distinguished by arity.
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000536 ClrHandlerType HandlerType =
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000537 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
538 : ClrHandlerType::Finally);
539 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
540 HandlerType, 0, Pad->getParent());
541 // Queue any child EH pads on the worklist.
542 for (const User *U : Cleanup->users())
543 if (const auto *I = dyn_cast<Instruction>(U))
544 if (I->isEHPad())
545 Worklist.emplace_back(I, CleanupState);
546 // Remember this pad's state.
547 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
548 } else {
549 // Walk the handlers of this catchswitch in reverse order since all but
550 // the last need to set the following one as its TryParentState.
551 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
552 int CatchState = -1, FollowerState = -1;
553 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
554 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
555 CBI != CBE; ++CBI, FollowerState = CatchState) {
556 const BasicBlock *CatchBlock = *CBI;
557 // Create the entry for this catch with the appropriate handler
558 // properties.
559 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
David Majnemer8a1c45d2015-12-12 05:38:55 +0000560 uint32_t TypeToken = static_cast<uint32_t>(
561 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000562 CatchState =
563 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
564 ClrHandlerType::Catch, TypeToken, CatchBlock);
565 // Queue any child EH pads on the worklist.
566 for (const User *U : Catch->users())
567 if (const auto *I = dyn_cast<Instruction>(U))
568 if (I->isEHPad())
569 Worklist.emplace_back(I, CatchState);
570 // Remember this catch's state.
571 FuncInfo.EHPadStateMap[Catch] = CatchState;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000572 }
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000573 // Associate the catchswitch with the state of its first catch.
574 assert(CatchSwitch->getNumHandlers());
575 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000576 }
577 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000578
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000579 // Step two: record the TryParentState of each state. For cleanuppads that
580 // don't have cleanuprets, we may need to infer this from their child pads,
581 // so visit pads in descendant-most to ancestor-most order.
582 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
583 End = FuncInfo.ClrEHUnwindMap.rend();
584 Entry != End; ++Entry) {
585 const Instruction *Pad =
586 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
587 // For most pads, the TryParentState is the state associated with the
588 // unwind dest of exceptional exits from it.
589 const BasicBlock *UnwindDest;
590 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
591 // If a catch is not the last in its catchswitch, its TryParentState is
592 // the state associated with the next catch in the switch, even though
593 // that's not the unwind dest of exceptions escaping the catch. Those
594 // cases were already assigned a TryParentState in the first pass, so
595 // skip them.
596 if (Entry->TryParentState != -1)
597 continue;
598 // Otherwise, get the unwind dest from the catchswitch.
599 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
600 } else {
601 const auto *Cleanup = cast<CleanupPadInst>(Pad);
602 UnwindDest = nullptr;
603 for (const User *U : Cleanup->users()) {
604 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
605 // Common and unambiguous case -- cleanupret indicates cleanup's
606 // unwind dest.
607 UnwindDest = CleanupRet->getUnwindDest();
608 break;
609 }
610
611 // Get an unwind dest for the user
612 const BasicBlock *UserUnwindDest = nullptr;
613 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
614 UserUnwindDest = Invoke->getUnwindDest();
615 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
616 UserUnwindDest = CatchSwitch->getUnwindDest();
617 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
618 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
619 int UserUnwindState =
620 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
621 if (UserUnwindState != -1)
622 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
623 .Handler.get<const BasicBlock *>();
624 }
625
626 // Not having an unwind dest for this user might indicate that it
627 // doesn't unwind, so can't be taken as proof that the cleanup itself
628 // may unwind to caller (see e.g. SimplifyUnreachable and
629 // RemoveUnwindEdge).
630 if (!UserUnwindDest)
631 continue;
632
633 // Now we have an unwind dest for the user, but we need to see if it
634 // unwinds all the way out of the cleanup or if it stays within it.
635 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
636 const Value *UserUnwindParent;
637 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
638 UserUnwindParent = CSI->getParentPad();
639 else
640 UserUnwindParent =
641 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
642
643 // The unwind stays within the cleanup iff it targets a child of the
644 // cleanup.
645 if (UserUnwindParent == Cleanup)
646 continue;
647
648 // This unwind exits the cleanup, so its dest is the cleanup's dest.
649 UnwindDest = UserUnwindDest;
650 break;
651 }
652 }
653
654 // Record the state of the unwind dest as the TryParentState.
655 int UnwindDestState;
656
657 // If UnwindDest is null at this point, either the pad in question can
658 // be exited by unwind to caller, or it cannot be exited by unwind. In
659 // either case, reporting such cases as unwinding to caller is correct.
660 // This can lead to EH tables that "look strange" -- if this pad's is in
661 // a parent funclet which has other children that do unwind to an enclosing
662 // pad, the try region for this pad will be missing the "duplicate" EH
663 // clause entries that you'd expect to see covering the whole parent. That
664 // should be benign, since the unwind never actually happens. If it were
665 // an issue, we could add a subsequent pass that pushes unwind dests down
666 // from parents that have them to children that appear to unwind to caller.
667 if (!UnwindDest) {
668 UnwindDestState = -1;
669 } else {
670 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
671 }
672
673 Entry->TryParentState = UnwindDestState;
674 }
675
676 // Step three: transfer information from pads to invokes.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000677 calculateStateNumbersForInvokes(Fn, FuncInfo);
Joseph Tremoulet7f8c1162015-10-06 20:30:33 +0000678}
679
David Majnemer8a1c45d2015-12-12 05:38:55 +0000680void WinEHPrepare::colorFunclets(Function &F) {
681 BlockColors = colorEHFunclets(F);
David Majnemerfd9f4772015-08-11 01:15:26 +0000682
David Majnemer8a1c45d2015-12-12 05:38:55 +0000683 // Invert the map from BB to colors to color to BBs.
684 for (BasicBlock &BB : F) {
685 ColorVector &Colors = BlockColors[&BB];
686 for (BasicBlock *Color : Colors)
687 FuncletBlocks[Color].push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000688 }
689}
690
Heejin Ahn99d60e02018-05-31 22:02:34 +0000691void WinEHPrepare::demotePHIsOnFunclets(Function &F,
692 bool DemoteCatchSwitchPHIOnly) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000693 // Strip PHI nodes off of EH pads.
694 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +0000695 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000696 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000697 if (!BB->isEHPad())
698 continue;
Heejin Ahn99d60e02018-05-31 22:02:34 +0000699 if (DemoteCatchSwitchPHIOnly && !isa<CatchSwitchInst>(BB->getFirstNonPHI()))
700 continue;
701
David Majnemerfd9f4772015-08-11 01:15:26 +0000702 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000703 Instruction *I = &*BI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000704 auto *PN = dyn_cast<PHINode>(I);
705 // Stop at the first non-PHI.
706 if (!PN)
707 break;
David Majnemerfd9f4772015-08-11 01:15:26 +0000708
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000709 AllocaInst *SpillSlot = insertPHILoads(PN, F);
710 if (SpillSlot)
711 insertPHIStores(PN, SpillSlot);
712
713 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +0000714 }
715 }
716
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000717 for (auto *PN : PHINodes) {
718 // There may be lingering uses on other EH PHIs being removed
719 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
720 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +0000721 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000722}
David Majnemerfd9f4772015-08-11 01:15:26 +0000723
David Majnemer8a1c45d2015-12-12 05:38:55 +0000724void WinEHPrepare::cloneCommonBlocks(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000725 // We need to clone all blocks which belong to multiple funclets. Values are
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000726 // remapped throughout the funclet to propagate both the new instructions
David Majnemerfd9f4772015-08-11 01:15:26 +0000727 // *and* the new basic blocks themselves.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000728 for (auto &Funclets : FuncletBlocks) {
729 BasicBlock *FuncletPadBB = Funclets.first;
730 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000731 Value *FuncletToken;
732 if (FuncletPadBB == &F.getEntryBlock())
733 FuncletToken = ConstantTokenNone::get(F.getContext());
734 else
735 FuncletToken = FuncletPadBB->getFirstNonPHI();
David Majnemerfd9f4772015-08-11 01:15:26 +0000736
David Majnemer8a1c45d2015-12-12 05:38:55 +0000737 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
David Majnemerfd9f4772015-08-11 01:15:26 +0000738 ValueToValueMapTy VMap;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000739 for (BasicBlock *BB : BlocksInFunclet) {
740 ColorVector &ColorsForBB = BlockColors[BB];
David Majnemerfd9f4772015-08-11 01:15:26 +0000741 // We don't need to do anything if the block is monochromatic.
742 size_t NumColorsForBB = ColorsForBB.size();
743 if (NumColorsForBB == 1)
744 continue;
745
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000746 DEBUG_WITH_TYPE("winehprepare-coloring",
747 dbgs() << " Cloning block \'" << BB->getName()
748 << "\' for funclet \'" << FuncletPadBB->getName()
749 << "\'.\n");
750
David Majnemerfd9f4772015-08-11 01:15:26 +0000751 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +0000752 BasicBlock *CBB =
753 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
754 // Insert the clone immediately after the original to ensure determinism
755 // and to keep the same relative ordering of any funclet's blocks.
756 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +0000757
758 // Add basic block mapping.
759 VMap[BB] = CBB;
760
761 // Record delta operations that we need to perform to our color mappings.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000762 Orig2Clone.emplace_back(BB, CBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000763 }
764
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000765 // If nothing was cloned, we're done cloning in this funclet.
766 if (Orig2Clone.empty())
767 continue;
768
David Majnemerfd9f4772015-08-11 01:15:26 +0000769 // Update our color mappings to reflect that one block has lost a color and
770 // another has gained a color.
771 for (auto &BBMapping : Orig2Clone) {
772 BasicBlock *OldBlock = BBMapping.first;
773 BasicBlock *NewBlock = BBMapping.second;
774
David Majnemer8a1c45d2015-12-12 05:38:55 +0000775 BlocksInFunclet.push_back(NewBlock);
776 ColorVector &NewColors = BlockColors[NewBlock];
777 assert(NewColors.empty() && "A new block should only have one color!");
778 NewColors.push_back(FuncletPadBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000779
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000780 DEBUG_WITH_TYPE("winehprepare-coloring",
781 dbgs() << " Assigned color \'" << FuncletPadBB->getName()
782 << "\' to block \'" << NewBlock->getName()
783 << "\'.\n");
784
David Majnemer8a1c45d2015-12-12 05:38:55 +0000785 BlocksInFunclet.erase(
786 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
787 BlocksInFunclet.end());
788 ColorVector &OldColors = BlockColors[OldBlock];
789 OldColors.erase(
790 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
791 OldColors.end());
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000792
793 DEBUG_WITH_TYPE("winehprepare-coloring",
794 dbgs() << " Removed color \'" << FuncletPadBB->getName()
795 << "\' from block \'" << OldBlock->getName()
796 << "\'.\n");
David Majnemerfd9f4772015-08-11 01:15:26 +0000797 }
798
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000799 // Loop over all of the instructions in this funclet, fixing up operand
David Majnemerfd9f4772015-08-11 01:15:26 +0000800 // references as we go. This uses VMap to do all the hard work.
801 for (BasicBlock *BB : BlocksInFunclet)
802 // Loop over all instructions, fixing each one as we find it...
803 for (Instruction &I : *BB)
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000804 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000805 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
David Majnemer459a64a2015-09-16 18:40:37 +0000806
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000807 // Catchrets targeting cloned blocks need to be updated separately from
808 // the loop above because they are not in the current funclet.
809 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
810 for (auto &BBMapping : Orig2Clone) {
811 BasicBlock *OldBlock = BBMapping.first;
812 BasicBlock *NewBlock = BBMapping.second;
813
814 FixupCatchrets.clear();
815 for (BasicBlock *Pred : predecessors(OldBlock))
816 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000817 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000818 FixupCatchrets.push_back(CatchRet);
819
820 for (CatchReturnInst *CatchRet : FixupCatchrets)
821 CatchRet->setSuccessor(NewBlock);
822 }
823
David Majnemer8a1c45d2015-12-12 05:38:55 +0000824 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
825 unsigned NumPreds = PN->getNumIncomingValues();
826 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
827 ++PredIdx) {
828 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000829 bool EdgeTargetsFunclet;
830 if (auto *CRI =
831 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000832 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000833 } else {
834 ColorVector &IncomingColors = BlockColors[IncomingBlock];
835 assert(!IncomingColors.empty() && "Block not colored!");
836 assert((IncomingColors.size() == 1 ||
837 llvm::all_of(IncomingColors,
838 [&](BasicBlock *Color) {
839 return Color != FuncletPadBB;
840 })) &&
841 "Cloning should leave this funclet's blocks monochromatic");
842 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
843 }
844 if (IsForOldBlock != EdgeTargetsFunclet)
David Majnemer8a1c45d2015-12-12 05:38:55 +0000845 continue;
846 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
847 // Revisit the next entry.
848 --PredIdx;
849 --PredEnd;
850 }
851 };
852
853 for (auto &BBMapping : Orig2Clone) {
854 BasicBlock *OldBlock = BBMapping.first;
855 BasicBlock *NewBlock = BBMapping.second;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000856 for (PHINode &OldPN : OldBlock->phis()) {
857 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000858 }
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000859 for (PHINode &NewPN : NewBlock->phis()) {
860 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000861 }
862 }
863
David Majnemer459a64a2015-09-16 18:40:37 +0000864 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
865 // the PHI nodes for NewBB now.
866 for (auto &BBMapping : Orig2Clone) {
867 BasicBlock *OldBlock = BBMapping.first;
868 BasicBlock *NewBlock = BBMapping.second;
869 for (BasicBlock *SuccBB : successors(NewBlock)) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000870 for (PHINode &SuccPN : SuccBB->phis()) {
David Majnemer459a64a2015-09-16 18:40:37 +0000871 // Ok, we have a PHI node. Figure out what the incoming value was for
872 // the OldBlock.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000873 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
David Majnemer459a64a2015-09-16 18:40:37 +0000874 if (OldBlockIdx == -1)
875 break;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000876 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
David Majnemer459a64a2015-09-16 18:40:37 +0000877
878 // Remap the value if necessary.
879 if (auto *Inst = dyn_cast<Instruction>(IV)) {
880 ValueToValueMapTy::iterator I = VMap.find(Inst);
881 if (I != VMap.end())
882 IV = I->second;
883 }
884
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000885 SuccPN.addIncoming(IV, NewBlock);
David Majnemer459a64a2015-09-16 18:40:37 +0000886 }
887 }
888 }
889
890 for (ValueToValueMapTy::value_type VT : VMap) {
891 // If there were values defined in BB that are used outside the funclet,
892 // then we now have to update all uses of the value to use either the
893 // original value, the cloned value, or some PHI derived value. This can
894 // require arbitrary PHI insertion, of which we are prepared to do, clean
895 // these up now.
896 SmallVector<Use *, 16> UsesToRename;
897
898 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
899 if (!OldI)
900 continue;
901 auto *NewI = cast<Instruction>(VT.second);
902 // Scan all uses of this instruction to see if it is used outside of its
903 // funclet, and if so, record them in UsesToRename.
904 for (Use &U : OldI->uses()) {
905 Instruction *UserI = cast<Instruction>(U.getUser());
906 BasicBlock *UserBB = UserI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000907 ColorVector &ColorsForUserBB = BlockColors[UserBB];
David Majnemer459a64a2015-09-16 18:40:37 +0000908 assert(!ColorsForUserBB.empty());
909 if (ColorsForUserBB.size() > 1 ||
910 *ColorsForUserBB.begin() != FuncletPadBB)
911 UsesToRename.push_back(&U);
912 }
913
914 // If there are no uses outside the block, we're done with this
915 // instruction.
916 if (UsesToRename.empty())
917 continue;
918
919 // We found a use of OldI outside of the funclet. Rename all uses of OldI
920 // that are outside its funclet to be uses of the appropriate PHI node
921 // etc.
922 SSAUpdater SSAUpdate;
923 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
924 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
925 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
926
927 while (!UsesToRename.empty())
928 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
929 }
David Majnemerfd9f4772015-08-11 01:15:26 +0000930 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000931}
David Majnemerfd9f4772015-08-11 01:15:26 +0000932
David Majnemer3bb88c02015-12-15 21:27:27 +0000933void WinEHPrepare::removeImplausibleInstructions(Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +0000934 // Remove implausible terminators and replace them with UnreachableInst.
935 for (auto &Funclet : FuncletBlocks) {
936 BasicBlock *FuncletPadBB = Funclet.first;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000937 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
David Majnemer3bb88c02015-12-15 21:27:27 +0000938 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
939 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
940 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
941 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
David Majnemer83f4bb22015-08-17 20:56:39 +0000942
943 for (BasicBlock *BB : BlocksInFunclet) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000944 for (Instruction &I : *BB) {
945 CallSite CS(&I);
946 if (!CS)
947 continue;
948
949 Value *FuncletBundleOperand = nullptr;
950 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
951 FuncletBundleOperand = BU->Inputs.front();
952
953 if (FuncletBundleOperand == FuncletPad)
954 continue;
955
David Majnemer08dd52dc2016-02-26 00:04:25 +0000956 // Skip call sites which are nounwind intrinsics or inline asm.
David Majnemer3bb88c02015-12-15 21:27:27 +0000957 auto *CalledFn =
958 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Justin Lebar9cbc3012016-07-28 23:58:15 +0000959 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
960 CS.isInlineAsm()))
David Majnemer3bb88c02015-12-15 21:27:27 +0000961 continue;
962
963 // This call site was not part of this funclet, remove it.
964 if (CS.isInvoke()) {
965 // Remove the unwind edge if it was an invoke.
966 removeUnwindEdge(BB);
967 // Get a pointer to the new call.
968 BasicBlock::iterator CallI =
969 std::prev(BB->getTerminator()->getIterator());
970 auto *CI = cast<CallInst>(&*CallI);
David Majnemere14e7bc2016-06-25 08:19:55 +0000971 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000972 } else {
David Majnemere14e7bc2016-06-25 08:19:55 +0000973 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000974 }
975
976 // There are no more instructions in the block (except for unreachable),
977 // we are done.
978 break;
979 }
980
Chandler Carruthedb12a82018-10-15 10:04:59 +0000981 Instruction *TI = BB->getTerminator();
David Majnemer83f4bb22015-08-17 20:56:39 +0000982 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
David Majnemer3bb88c02015-12-15 21:27:27 +0000983 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
David Majnemer83f4bb22015-08-17 20:56:39 +0000984 // The token consumed by a CatchReturnInst must match the funclet token.
985 bool IsUnreachableCatchret = false;
986 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000987 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000988 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemer83f4bb22015-08-17 20:56:39 +0000989 bool IsUnreachableCleanupret = false;
990 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000991 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000992 if (IsUnreachableRet || IsUnreachableCatchret ||
David Majnemer8a1c45d2015-12-12 05:38:55 +0000993 IsUnreachableCleanupret) {
David Majnemere14e7bc2016-06-25 08:19:55 +0000994 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000995 } else if (isa<InvokeInst>(TI)) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000996 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
997 // Invokes within a cleanuppad for the MSVC++ personality never
998 // transfer control to their unwind edge: the personality will
999 // terminate the program.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001000 removeUnwindEdge(BB);
David Majnemer3bb88c02015-12-15 21:27:27 +00001001 }
David Majnemer83f4bb22015-08-17 20:56:39 +00001002 }
1003 }
1004 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001005}
David Majnemer83f4bb22015-08-17 20:56:39 +00001006
David Majnemerb3d9b962015-09-16 18:40:24 +00001007void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00001008 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1009 // branches, etc.
1010 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001011 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +00001012 SimplifyInstructionsInBlock(BB);
1013 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1014 MergeBlockIntoPredecessor(BB);
1015 }
1016
David Majnemerfd9f4772015-08-11 01:15:26 +00001017 // We might have some unreachable blocks after cleaning up some impossible
1018 // control flow.
1019 removeUnreachableBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001020}
David Majnemerfd9f4772015-08-11 01:15:26 +00001021
Florian Hahn6b3216a2017-07-31 10:07:49 +00001022#ifndef NDEBUG
David Majnemerb3d9b962015-09-16 18:40:24 +00001023void WinEHPrepare::verifyPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00001024 for (BasicBlock &BB : F) {
1025 size_t NumColors = BlockColors[&BB].size();
1026 assert(NumColors == 1 && "Expected monochromatic BB!");
1027 if (NumColors == 0)
1028 report_fatal_error("Uncolored BB!");
1029 if (NumColors > 1)
1030 report_fatal_error("Multicolor BB!");
NAKAMURA Takumided575e2016-01-03 01:41:00 +00001031 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1032 "EH Pad still has a PHI!");
David Majnemerfd9f4772015-08-11 01:15:26 +00001033 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001034}
Florian Hahn6b3216a2017-07-31 10:07:49 +00001035#endif
David Majnemerb3d9b962015-09-16 18:40:24 +00001036
David Majnemer8a1c45d2015-12-12 05:38:55 +00001037bool WinEHPrepare::prepareExplicitEH(Function &F) {
1038 // Remove unreachable blocks. It is not valuable to assign them a color and
1039 // their existence can trick us into thinking values are alive when they are
1040 // not.
1041 removeUnreachableBlocks(F);
1042
David Majnemerb3d9b962015-09-16 18:40:24 +00001043 // Determine which blocks are reachable from which funclet entries.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001044 colorFunclets(F);
1045
1046 cloneCommonBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001047
Reid Klecknercc2f6c32015-11-19 23:23:33 +00001048 if (!DisableDemotion)
Heejin Ahn99d60e02018-05-31 22:02:34 +00001049 demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly ||
1050 DemoteCatchSwitchPHIOnlyOpt);
David Majnemerb3d9b962015-09-16 18:40:24 +00001051
David Majnemer459a64a2015-09-16 18:40:37 +00001052 if (!DisableCleanups) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001053 LLVM_DEBUG(verifyFunction(F));
David Majnemer3bb88c02015-12-15 21:27:27 +00001054 removeImplausibleInstructions(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001055
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001056 LLVM_DEBUG(verifyFunction(F));
David Majnemer459a64a2015-09-16 18:40:37 +00001057 cleanupPreparedFunclets(F);
1058 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001059
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001060 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemerdbdc9c22016-01-02 09:26:36 +00001061 // Recolor the CFG to verify that all is well.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001062 LLVM_DEBUG(colorFunclets(F));
1063 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemerfd9f4772015-08-11 01:15:26 +00001064
1065 BlockColors.clear();
1066 FuncletBlocks.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00001067
David Majnemerfd9f4772015-08-11 01:15:26 +00001068 return true;
1069}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001070
1071// TODO: Share loads when one use dominates another, or when a catchpad exit
1072// dominates uses (needs dominators).
1073AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1074 BasicBlock *PHIBlock = PN->getParent();
1075 AllocaInst *SpillSlot = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +00001076 Instruction *EHPad = PHIBlock->getFirstNonPHI();
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001077
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001078 if (!EHPad->isTerminator()) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001079 // If the EHPad isn't a terminator, then we can insert a load in this block
1080 // that will dominate all uses.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001081 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001082 Twine(PN->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001083 &F.getEntryBlock().front());
James Y Knight14359ef2019-02-01 20:44:24 +00001084 Value *V = new LoadInst(PN->getType(), SpillSlot,
1085 Twine(PN->getName(), ".wineh.reload"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001086 &*PHIBlock->getFirstInsertionPt());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001087 PN->replaceAllUsesWith(V);
1088 return SpillSlot;
1089 }
1090
David Majnemer8a1c45d2015-12-12 05:38:55 +00001091 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1092 // loads of the slot before every use.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001093 DenseMap<BasicBlock *, Value *> Loads;
1094 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1095 UI != UE;) {
1096 Use &U = *UI++;
1097 auto *UsingInst = cast<Instruction>(U.getUser());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001098 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001099 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1100 // stores for it separately.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001101 continue;
1102 }
1103 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1104 }
1105 return SpillSlot;
1106}
1107
1108// TODO: improve store placement. Inserting at def is probably good, but need
1109// to be careful not to introduce interfering stores (needs liveness analysis).
1110// TODO: identify related phi nodes that can share spill slots, and share them
1111// (also needs liveness).
1112void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1113 AllocaInst *SpillSlot) {
1114 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1115 // stored to the spill slot by the end of the given Block.
1116 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1117
1118 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1119
1120 while (!Worklist.empty()) {
1121 BasicBlock *EHBlock;
1122 Value *InVal;
1123 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1124
1125 PHINode *PN = dyn_cast<PHINode>(InVal);
1126 if (PN && PN->getParent() == EHBlock) {
1127 // The value is defined by another PHI we need to remove, with no room to
1128 // insert a store after the PHI, so each predecessor needs to store its
1129 // incoming value.
1130 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1131 Value *PredVal = PN->getIncomingValue(i);
1132
1133 // Undef can safely be skipped.
1134 if (isa<UndefValue>(PredVal))
1135 continue;
1136
1137 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1138 }
1139 } else {
1140 // We need to store InVal, which dominates EHBlock, but can't put a store
1141 // in EHBlock, so need to put stores in each predecessor.
1142 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1143 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1144 }
1145 }
1146 }
1147}
1148
1149void WinEHPrepare::insertPHIStore(
1150 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1151 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1152
Chandler Carruth9ae926b2018-08-26 09:51:22 +00001153 if (PredBlock->isEHPad() && PredBlock->getFirstNonPHI()->isTerminator()) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001154 // Pred is unsplittable, so we need to queue it on the worklist.
1155 Worklist.push_back({PredBlock, PredVal});
1156 return;
1157 }
1158
1159 // Otherwise, insert the store at the end of the basic block.
1160 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1161}
1162
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001163void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1164 DenseMap<BasicBlock *, Value *> &Loads,
1165 Function &F) {
1166 // Lazilly create the spill slot.
1167 if (!SpillSlot)
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001168 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001169 Twine(V->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001170 &F.getEntryBlock().front());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001171
1172 auto *UsingInst = cast<Instruction>(U.getUser());
1173 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1174 // If this is a PHI node, we can't insert a load of the value before
1175 // the use. Instead insert the load in the predecessor block
1176 // corresponding to the incoming value.
1177 //
1178 // Note that if there are multiple edges from a basic block to this
1179 // PHI node that we cannot have multiple loads. The problem is that
1180 // the resulting PHI node will have multiple values (from each load)
1181 // coming in from the same block, which is illegal SSA form.
1182 // For this reason, we keep track of and reuse loads we insert.
1183 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001184 if (auto *CatchRet =
1185 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1186 // Putting a load above a catchret and use on the phi would still leave
1187 // a cross-funclet def/use. We need to split the edge, change the
1188 // catchret to target the new block, and put the load there.
1189 BasicBlock *PHIBlock = UsingInst->getParent();
1190 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1191 // SplitEdge gives us:
1192 // IncomingBlock:
1193 // ...
1194 // br label %NewBlock
1195 // NewBlock:
1196 // catchret label %PHIBlock
1197 // But we need:
1198 // IncomingBlock:
1199 // ...
1200 // catchret label %NewBlock
1201 // NewBlock:
1202 // br label %PHIBlock
1203 // So move the terminators to each others' blocks and swap their
1204 // successors.
1205 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1206 Goto->removeFromParent();
1207 CatchRet->removeFromParent();
1208 IncomingBlock->getInstList().push_back(CatchRet);
1209 NewBlock->getInstList().push_back(Goto);
1210 Goto->setSuccessor(0, PHIBlock);
1211 CatchRet->setSuccessor(NewBlock);
1212 // Update the color mapping for the newly split edge.
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001213 // Grab a reference to the ColorVector to be inserted before getting the
1214 // reference to the vector we are copying because inserting the new
1215 // element in BlockColors might cause the map to be reallocated.
1216 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
David Majnemer8a1c45d2015-12-12 05:38:55 +00001217 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001218 ColorsForNewBlock = ColorsForPHIBlock;
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001219 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
David Majnemer8a1c45d2015-12-12 05:38:55 +00001220 FuncletBlocks[FuncletPad].push_back(NewBlock);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001221 // Treat the new block as incoming for load insertion.
1222 IncomingBlock = NewBlock;
1223 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001224 Value *&Load = Loads[IncomingBlock];
1225 // Insert the load into the predecessor block
1226 if (!Load)
James Y Knight14359ef2019-02-01 20:44:24 +00001227 Load = new LoadInst(V->getType(), SpillSlot,
1228 Twine(V->getName(), ".wineh.reload"),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001229 /*isVolatile=*/false, IncomingBlock->getTerminator());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001230
1231 U.set(Load);
1232 } else {
1233 // Reload right before the old use.
James Y Knight14359ef2019-02-01 20:44:24 +00001234 auto *Load = new LoadInst(V->getType(), SpillSlot,
1235 Twine(V->getName(), ".wineh.reload"),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001236 /*isVolatile=*/false, UsingInst);
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001237 U.set(Load);
1238 }
1239}
Reid Klecknerc71d6272015-09-28 23:56:30 +00001240
David Majnemer8a1c45d2015-12-12 05:38:55 +00001241void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
Reid Klecknerc71d6272015-09-28 23:56:30 +00001242 MCSymbol *InvokeBegin,
1243 MCSymbol *InvokeEnd) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001244 assert(InvokeStateMap.count(II) &&
1245 "should get invoke with precomputed state");
1246 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
Reid Klecknerc71d6272015-09-28 23:56:30 +00001247}
Chandler Carruthe0115342015-12-29 09:24:39 +00001248
1249WinEHFuncInfo::WinEHFuncInfo() {}