blob: 199e7228a8a4d476fcc1aad63ede5ae7a5e2738b [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"
David Blaikie2be39222018-03-21 22:34:23 +000024#include "llvm/Analysis/Utils/Local.h"
Chandler Carruthe0115342015-12-29 09:24:39 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/CodeGen/Passes.h"
David Majnemercde33032015-03-30 22:58:10 +000027#include "llvm/CodeGen/WinEHFuncInfo.h"
David Majnemerdbdc9c22016-01-02 09:26:36 +000028#include "llvm/IR/Verifier.h"
Chandler Carruthe0115342015-12-29 09:24:39 +000029#include "llvm/MC/MCSymbol.h"
Andrew Kaylor1476e6d2015-02-24 20:49:35 +000030#include "llvm/Pass.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"
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
Andrew Kaylor1476e6d2015-02-24 20:49:35 +0000106 // 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);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000274 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
275 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
276 << '\n');
277 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
278 << '\n');
David Majnemer0ad363e2015-08-18 19:07:12 +0000279 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000280 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
281
282 // It's possible for a cleanup to be visited twice: it might have multiple
283 // cleanupret instructions.
284 if (FuncInfo.EHPadStateMap.count(CleanupPad))
285 return;
286
287 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
288 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000289 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
290 << BB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000291 for (const BasicBlock *PredBlock : predecessors(BB)) {
292 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
293 CleanupPad->getParentPad()))) {
294 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
295 CleanupState);
296 }
297 }
298 for (const User *U : CleanupPad->users()) {
299 const auto *UserI = cast<Instruction>(U);
300 if (UserI->isEHPad())
301 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
302 "contain exceptional actions");
303 }
David Majnemer0ad363e2015-08-18 19:07:12 +0000304 }
305}
306
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000307static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
308 const Function *Filter, const BasicBlock *Handler) {
Reid Kleckner94b704c2015-09-09 21:10:03 +0000309 SEHUnwindMapEntry Entry;
310 Entry.ToState = ParentState;
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000311 Entry.IsFinally = false;
Reid Kleckner94b704c2015-09-09 21:10:03 +0000312 Entry.Filter = Filter;
313 Entry.Handler = Handler;
314 FuncInfo.SEHUnwindMap.push_back(Entry);
315 return FuncInfo.SEHUnwindMap.size() - 1;
316}
317
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000318static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
319 const BasicBlock *Handler) {
320 SEHUnwindMapEntry Entry;
321 Entry.ToState = ParentState;
322 Entry.IsFinally = true;
323 Entry.Filter = nullptr;
324 Entry.Handler = Handler;
325 FuncInfo.SEHUnwindMap.push_back(Entry);
326 return FuncInfo.SEHUnwindMap.size() - 1;
327}
328
David Majnemer8a1c45d2015-12-12 05:38:55 +0000329static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
330 const Instruction *FirstNonPHI,
331 int ParentState) {
332 const BasicBlock *BB = FirstNonPHI->getParent();
333 assert(BB->isEHPad() && "no a funclet!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000334
David Majnemer8a1c45d2015-12-12 05:38:55 +0000335 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
336 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
337 "shouldn't revist catch funclets!");
338
Reid Kleckner94b704c2015-09-09 21:10:03 +0000339 // Extract the filter function and the __except basic block and create a
340 // state for them.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000341 assert(CatchSwitch->getNumHandlers() == 1 &&
Reid Kleckner94b704c2015-09-09 21:10:03 +0000342 "SEH doesn't have multiple handlers per __try");
David Majnemer8a1c45d2015-12-12 05:38:55 +0000343 const auto *CatchPad =
344 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
345 const BasicBlock *CatchPadBB = CatchPad->getParent();
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000346 const Constant *FilterOrNull =
David Majnemer8a1c45d2015-12-12 05:38:55 +0000347 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
Reid Klecknerfc64fae2015-10-01 21:38:24 +0000348 const Function *Filter = dyn_cast<Function>(FilterOrNull);
349 assert((Filter || FilterOrNull->isNullValue()) &&
350 "unexpected filter value");
David Majnemer7735a6d2015-10-06 23:31:59 +0000351 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000352
353 // Everything in the __try block uses TryState as its parent state.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000354 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000355 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
356 << CatchPadBB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000357 for (const BasicBlock *PredBlock : predecessors(BB))
358 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
359 CatchSwitch->getParentPad())))
360 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
361 TryState);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000362
363 // Everything in the __except block unwinds to ParentState, just like code
364 // outside the __try.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000365 for (const User *U : CatchPad->users()) {
366 const auto *UserI = cast<Instruction>(U);
David Majnemer17525ab2016-02-23 07:18:15 +0000367 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
368 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
369 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000370 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
David Majnemer17525ab2016-02-23 07:18:15 +0000371 }
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000372 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
373 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
374 // If a nested cleanup pad reports a null unwind destination and the
375 // enclosing catch pad doesn't it must be post-dominated by an
376 // unreachable instruction.
377 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
David Majnemerc640f862015-12-23 03:59:04 +0000378 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
Andrew Kaylord1188dd2016-02-12 21:10:16 +0000379 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000380 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000381 } else {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000382 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
383
384 // It's possible for a cleanup to be visited twice: it might have multiple
385 // cleanupret instructions.
386 if (FuncInfo.EHPadStateMap.count(CleanupPad))
387 return;
388
389 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
390 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000391 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
392 << BB->getName() << '\n');
David Majnemer8a1c45d2015-12-12 05:38:55 +0000393 for (const BasicBlock *PredBlock : predecessors(BB))
394 if ((PredBlock =
395 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
396 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
397 CleanupState);
398 for (const User *U : CleanupPad->users()) {
399 const auto *UserI = cast<Instruction>(U);
400 if (UserI->isEHPad())
401 report_fatal_error("Cleanup funclets for the SEH personality cannot "
402 "contain exceptional actions");
403 }
Reid Kleckner94b704c2015-09-09 21:10:03 +0000404 }
405}
406
David Majnemer8a1c45d2015-12-12 05:38:55 +0000407static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
408 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
409 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
410 CatchSwitch->unwindsToCaller();
411 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
412 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
413 getCleanupRetUnwindDest(CleanupPad) == nullptr;
414 if (isa<CatchPadInst>(EHPad))
415 return false;
416 llvm_unreachable("unexpected EHPad!");
Reid Kleckner94b704c2015-09-09 21:10:03 +0000417}
418
Reid Kleckner813f1b62015-09-16 22:14:46 +0000419void llvm::calculateSEHStateNumbers(const Function *Fn,
Reid Kleckner94b704c2015-09-09 21:10:03 +0000420 WinEHFuncInfo &FuncInfo) {
421 // Don't compute state numbers twice.
422 if (!FuncInfo.SEHUnwindMap.empty())
423 return;
424
Reid Kleckner813f1b62015-09-16 22:14:46 +0000425 for (const BasicBlock &BB : *Fn) {
David Majnemer8a1c45d2015-12-12 05:38:55 +0000426 if (!BB.isEHPad())
Reid Kleckner94b704c2015-09-09 21:10:03 +0000427 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000428 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
429 if (!isTopLevelPadForMSVC(FirstNonPHI))
430 continue;
431 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000432 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000433
434 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Kleckner94b704c2015-09-09 21:10:03 +0000435}
436
Reid Kleckner813f1b62015-09-16 22:14:46 +0000437void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000438 WinEHFuncInfo &FuncInfo) {
439 // Return if it's already been done.
David Majnemer0ad363e2015-08-18 19:07:12 +0000440 if (!FuncInfo.EHPadStateMap.empty())
441 return;
442
Reid Kleckner813f1b62015-09-16 22:14:46 +0000443 for (const BasicBlock &BB : *Fn) {
David Majnemer0ad363e2015-08-18 19:07:12 +0000444 if (!BB.isEHPad())
445 continue;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000446 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000447 if (!isTopLevelPadForMSVC(FirstNonPHI))
David Majnemer0ad363e2015-08-18 19:07:12 +0000448 continue;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000449 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
David Majnemer0ad363e2015-08-18 19:07:12 +0000450 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000451
452 calculateStateNumbersForInvokes(Fn, FuncInfo);
Reid Klecknerfe4d4912015-05-28 22:00:24 +0000453}
David Majnemerfd9f4772015-08-11 01:15:26 +0000454
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000455static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
456 int TryParentState, ClrHandlerType HandlerType,
457 uint32_t TypeToken, const BasicBlock *Handler) {
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000458 ClrEHUnwindMapEntry Entry;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000459 Entry.HandlerParentState = HandlerParentState;
460 Entry.TryParentState = TryParentState;
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000461 Entry.Handler = Handler;
462 Entry.HandlerType = HandlerType;
463 Entry.TypeToken = TypeToken;
464 FuncInfo.ClrEHUnwindMap.push_back(Entry);
465 return FuncInfo.ClrEHUnwindMap.size() - 1;
466}
467
468void llvm::calculateClrEHStateNumbers(const Function *Fn,
469 WinEHFuncInfo &FuncInfo) {
470 // Return if it's already been done.
471 if (!FuncInfo.EHPadStateMap.empty())
472 return;
473
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000474 // This numbering assigns one state number to each catchpad and cleanuppad.
475 // It also computes two tree-like relations over states:
476 // 1) Each state has a "HandlerParentState", which is the state of the next
477 // outer handler enclosing this state's handler (same as nearest ancestor
478 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
479 // 2) Each state has a "TryParentState", which:
480 // a) for a catchpad that's not the last handler on its catchswitch, is
481 // the state of the next catchpad on that catchswitch
482 // b) for all other pads, is the state of the pad whose try region is the
483 // next outer try region enclosing this state's try region. The "try
484 // regions are not present as such in the IR, but will be inferred
485 // based on the placement of invokes and pads which reach each other
486 // by exceptional exits
487 // Catchswitches do not get their own states, but each gets mapped to the
488 // state of its first catchpad.
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000489
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000490 // Step one: walk down from outermost to innermost funclets, assigning each
491 // catchpad and cleanuppad a state number. Add an entry to the
492 // ClrEHUnwindMap for each state, recording its HandlerParentState and
493 // handler attributes. Record the TryParentState as well for each catchpad
494 // that's not the last on its catchswitch, but initialize all other entries'
495 // TryParentStates to a sentinel -1 value that the next pass will update.
496
497 // Seed a worklist with pads that have no parent.
498 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000499 for (const BasicBlock &BB : *Fn) {
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000500 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000501 const Value *ParentPad;
502 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
503 ParentPad = CPI->getParentPad();
504 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
505 ParentPad = CSI->getParentPad();
506 else
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000507 continue;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000508 if (isa<ConstantTokenNone>(ParentPad))
509 Worklist.emplace_back(FirstNonPHI, -1);
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000510 }
511
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000512 // Use the worklist to visit all pads, from outer to inner. Record
513 // HandlerParentState for all pads. Record TryParentState only for catchpads
514 // that aren't the last on their catchswitch (setting all other entries'
515 // TryParentStates to an initial value of -1). This loop is also responsible
516 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
517 // catchswitches.
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000518 while (!Worklist.empty()) {
519 const Instruction *Pad;
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000520 int HandlerParentState;
521 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000522
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000523 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
524 // Create the entry for this cleanup with the appropriate handler
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000525 // properties. Finally and fault handlers are distinguished by arity.
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000526 ClrHandlerType HandlerType =
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000527 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
528 : ClrHandlerType::Finally);
529 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
530 HandlerType, 0, Pad->getParent());
531 // Queue any child EH pads on the worklist.
532 for (const User *U : Cleanup->users())
533 if (const auto *I = dyn_cast<Instruction>(U))
534 if (I->isEHPad())
535 Worklist.emplace_back(I, CleanupState);
536 // Remember this pad's state.
537 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
538 } else {
539 // Walk the handlers of this catchswitch in reverse order since all but
540 // the last need to set the following one as its TryParentState.
541 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
542 int CatchState = -1, FollowerState = -1;
543 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
544 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
545 CBI != CBE; ++CBI, FollowerState = CatchState) {
546 const BasicBlock *CatchBlock = *CBI;
547 // Create the entry for this catch with the appropriate handler
548 // properties.
549 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
David Majnemer8a1c45d2015-12-12 05:38:55 +0000550 uint32_t TypeToken = static_cast<uint32_t>(
551 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000552 CatchState =
553 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
554 ClrHandlerType::Catch, TypeToken, CatchBlock);
555 // Queue any child EH pads on the worklist.
556 for (const User *U : Catch->users())
557 if (const auto *I = dyn_cast<Instruction>(U))
558 if (I->isEHPad())
559 Worklist.emplace_back(I, CatchState);
560 // Remember this catch's state.
561 FuncInfo.EHPadStateMap[Catch] = CatchState;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000562 }
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000563 // Associate the catchswitch with the state of its first catch.
564 assert(CatchSwitch->getNumHandlers());
565 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000566 }
567 }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000568
Joseph Tremoulet52f729a2016-01-04 16:16:01 +0000569 // Step two: record the TryParentState of each state. For cleanuppads that
570 // don't have cleanuprets, we may need to infer this from their child pads,
571 // so visit pads in descendant-most to ancestor-most order.
572 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
573 End = FuncInfo.ClrEHUnwindMap.rend();
574 Entry != End; ++Entry) {
575 const Instruction *Pad =
576 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
577 // For most pads, the TryParentState is the state associated with the
578 // unwind dest of exceptional exits from it.
579 const BasicBlock *UnwindDest;
580 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
581 // If a catch is not the last in its catchswitch, its TryParentState is
582 // the state associated with the next catch in the switch, even though
583 // that's not the unwind dest of exceptions escaping the catch. Those
584 // cases were already assigned a TryParentState in the first pass, so
585 // skip them.
586 if (Entry->TryParentState != -1)
587 continue;
588 // Otherwise, get the unwind dest from the catchswitch.
589 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
590 } else {
591 const auto *Cleanup = cast<CleanupPadInst>(Pad);
592 UnwindDest = nullptr;
593 for (const User *U : Cleanup->users()) {
594 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
595 // Common and unambiguous case -- cleanupret indicates cleanup's
596 // unwind dest.
597 UnwindDest = CleanupRet->getUnwindDest();
598 break;
599 }
600
601 // Get an unwind dest for the user
602 const BasicBlock *UserUnwindDest = nullptr;
603 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
604 UserUnwindDest = Invoke->getUnwindDest();
605 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
606 UserUnwindDest = CatchSwitch->getUnwindDest();
607 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
608 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
609 int UserUnwindState =
610 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
611 if (UserUnwindState != -1)
612 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
613 .Handler.get<const BasicBlock *>();
614 }
615
616 // Not having an unwind dest for this user might indicate that it
617 // doesn't unwind, so can't be taken as proof that the cleanup itself
618 // may unwind to caller (see e.g. SimplifyUnreachable and
619 // RemoveUnwindEdge).
620 if (!UserUnwindDest)
621 continue;
622
623 // Now we have an unwind dest for the user, but we need to see if it
624 // unwinds all the way out of the cleanup or if it stays within it.
625 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
626 const Value *UserUnwindParent;
627 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
628 UserUnwindParent = CSI->getParentPad();
629 else
630 UserUnwindParent =
631 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
632
633 // The unwind stays within the cleanup iff it targets a child of the
634 // cleanup.
635 if (UserUnwindParent == Cleanup)
636 continue;
637
638 // This unwind exits the cleanup, so its dest is the cleanup's dest.
639 UnwindDest = UserUnwindDest;
640 break;
641 }
642 }
643
644 // Record the state of the unwind dest as the TryParentState.
645 int UnwindDestState;
646
647 // If UnwindDest is null at this point, either the pad in question can
648 // be exited by unwind to caller, or it cannot be exited by unwind. In
649 // either case, reporting such cases as unwinding to caller is correct.
650 // This can lead to EH tables that "look strange" -- if this pad's is in
651 // a parent funclet which has other children that do unwind to an enclosing
652 // pad, the try region for this pad will be missing the "duplicate" EH
653 // clause entries that you'd expect to see covering the whole parent. That
654 // should be benign, since the unwind never actually happens. If it were
655 // an issue, we could add a subsequent pass that pushes unwind dests down
656 // from parents that have them to children that appear to unwind to caller.
657 if (!UnwindDest) {
658 UnwindDestState = -1;
659 } else {
660 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
661 }
662
663 Entry->TryParentState = UnwindDestState;
664 }
665
666 // Step three: transfer information from pads to invokes.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000667 calculateStateNumbersForInvokes(Fn, FuncInfo);
Joseph Tremoulet7f8c11652015-10-06 20:30:33 +0000668}
669
David Majnemer8a1c45d2015-12-12 05:38:55 +0000670void WinEHPrepare::colorFunclets(Function &F) {
671 BlockColors = colorEHFunclets(F);
David Majnemerfd9f4772015-08-11 01:15:26 +0000672
David Majnemer8a1c45d2015-12-12 05:38:55 +0000673 // Invert the map from BB to colors to color to BBs.
674 for (BasicBlock &BB : F) {
675 ColorVector &Colors = BlockColors[&BB];
676 for (BasicBlock *Color : Colors)
677 FuncletBlocks[Color].push_back(&BB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000678 }
679}
680
David Majnemerb3d9b962015-09-16 18:40:24 +0000681void WinEHPrepare::demotePHIsOnFunclets(Function &F) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000682 // Strip PHI nodes off of EH pads.
683 SmallVector<PHINode *, 16> PHINodes;
David Majnemerfd9f4772015-08-11 01:15:26 +0000684 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000685 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000686 if (!BB->isEHPad())
687 continue;
David Majnemerfd9f4772015-08-11 01:15:26 +0000688 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000689 Instruction *I = &*BI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000690 auto *PN = dyn_cast<PHINode>(I);
691 // Stop at the first non-PHI.
692 if (!PN)
693 break;
David Majnemerfd9f4772015-08-11 01:15:26 +0000694
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000695 AllocaInst *SpillSlot = insertPHILoads(PN, F);
696 if (SpillSlot)
697 insertPHIStores(PN, SpillSlot);
698
699 PHINodes.push_back(PN);
David Majnemerfd9f4772015-08-11 01:15:26 +0000700 }
701 }
702
Joseph Tremouletc9ff9142015-08-13 14:30:10 +0000703 for (auto *PN : PHINodes) {
704 // There may be lingering uses on other EH PHIs being removed
705 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
706 PN->eraseFromParent();
David Majnemerfd9f4772015-08-11 01:15:26 +0000707 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000708}
David Majnemerfd9f4772015-08-11 01:15:26 +0000709
David Majnemer8a1c45d2015-12-12 05:38:55 +0000710void WinEHPrepare::cloneCommonBlocks(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000711 // We need to clone all blocks which belong to multiple funclets. Values are
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000712 // remapped throughout the funclet to propagate both the new instructions
David Majnemerfd9f4772015-08-11 01:15:26 +0000713 // *and* the new basic blocks themselves.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000714 for (auto &Funclets : FuncletBlocks) {
715 BasicBlock *FuncletPadBB = Funclets.first;
716 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000717 Value *FuncletToken;
718 if (FuncletPadBB == &F.getEntryBlock())
719 FuncletToken = ConstantTokenNone::get(F.getContext());
720 else
721 FuncletToken = FuncletPadBB->getFirstNonPHI();
David Majnemerfd9f4772015-08-11 01:15:26 +0000722
David Majnemer8a1c45d2015-12-12 05:38:55 +0000723 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
David Majnemerfd9f4772015-08-11 01:15:26 +0000724 ValueToValueMapTy VMap;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000725 for (BasicBlock *BB : BlocksInFunclet) {
726 ColorVector &ColorsForBB = BlockColors[BB];
David Majnemerfd9f4772015-08-11 01:15:26 +0000727 // We don't need to do anything if the block is monochromatic.
728 size_t NumColorsForBB = ColorsForBB.size();
729 if (NumColorsForBB == 1)
730 continue;
731
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000732 DEBUG_WITH_TYPE("winehprepare-coloring",
733 dbgs() << " Cloning block \'" << BB->getName()
734 << "\' for funclet \'" << FuncletPadBB->getName()
735 << "\'.\n");
736
David Majnemerfd9f4772015-08-11 01:15:26 +0000737 // Create a new basic block and copy instructions into it!
Joseph Tremouletec182852015-08-28 01:12:35 +0000738 BasicBlock *CBB =
739 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
740 // Insert the clone immediately after the original to ensure determinism
741 // and to keep the same relative ordering of any funclet's blocks.
742 CBB->insertInto(&F, BB->getNextNode());
David Majnemerfd9f4772015-08-11 01:15:26 +0000743
744 // Add basic block mapping.
745 VMap[BB] = CBB;
746
747 // Record delta operations that we need to perform to our color mappings.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000748 Orig2Clone.emplace_back(BB, CBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000749 }
750
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000751 // If nothing was cloned, we're done cloning in this funclet.
752 if (Orig2Clone.empty())
753 continue;
754
David Majnemerfd9f4772015-08-11 01:15:26 +0000755 // Update our color mappings to reflect that one block has lost a color and
756 // another has gained a color.
757 for (auto &BBMapping : Orig2Clone) {
758 BasicBlock *OldBlock = BBMapping.first;
759 BasicBlock *NewBlock = BBMapping.second;
760
David Majnemer8a1c45d2015-12-12 05:38:55 +0000761 BlocksInFunclet.push_back(NewBlock);
762 ColorVector &NewColors = BlockColors[NewBlock];
763 assert(NewColors.empty() && "A new block should only have one color!");
764 NewColors.push_back(FuncletPadBB);
David Majnemerfd9f4772015-08-11 01:15:26 +0000765
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000766 DEBUG_WITH_TYPE("winehprepare-coloring",
767 dbgs() << " Assigned color \'" << FuncletPadBB->getName()
768 << "\' to block \'" << NewBlock->getName()
769 << "\'.\n");
770
David Majnemer8a1c45d2015-12-12 05:38:55 +0000771 BlocksInFunclet.erase(
772 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
773 BlocksInFunclet.end());
774 ColorVector &OldColors = BlockColors[OldBlock];
775 OldColors.erase(
776 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
777 OldColors.end());
Andrew Kaylorfdd48fa2015-11-09 19:59:02 +0000778
779 DEBUG_WITH_TYPE("winehprepare-coloring",
780 dbgs() << " Removed color \'" << FuncletPadBB->getName()
781 << "\' from block \'" << OldBlock->getName()
782 << "\'.\n");
David Majnemerfd9f4772015-08-11 01:15:26 +0000783 }
784
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000785 // Loop over all of the instructions in this funclet, fixing up operand
David Majnemerfd9f4772015-08-11 01:15:26 +0000786 // references as we go. This uses VMap to do all the hard work.
787 for (BasicBlock *BB : BlocksInFunclet)
788 // Loop over all instructions, fixing each one as we find it...
789 for (Instruction &I : *BB)
Joseph Tremoulet39234fc2015-10-07 19:29:56 +0000790 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000791 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
David Majnemer459a64a2015-09-16 18:40:37 +0000792
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000793 // Catchrets targeting cloned blocks need to be updated separately from
794 // the loop above because they are not in the current funclet.
795 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
796 for (auto &BBMapping : Orig2Clone) {
797 BasicBlock *OldBlock = BBMapping.first;
798 BasicBlock *NewBlock = BBMapping.second;
799
800 FixupCatchrets.clear();
801 for (BasicBlock *Pred : predecessors(OldBlock))
802 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000803 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000804 FixupCatchrets.push_back(CatchRet);
805
806 for (CatchReturnInst *CatchRet : FixupCatchrets)
807 CatchRet->setSuccessor(NewBlock);
808 }
809
David Majnemer8a1c45d2015-12-12 05:38:55 +0000810 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
811 unsigned NumPreds = PN->getNumIncomingValues();
812 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
813 ++PredIdx) {
814 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000815 bool EdgeTargetsFunclet;
816 if (auto *CRI =
817 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
Joseph Tremoulet44b3f962016-01-15 21:16:19 +0000818 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
Joseph Tremoulet71e56762016-01-02 15:22:36 +0000819 } else {
820 ColorVector &IncomingColors = BlockColors[IncomingBlock];
821 assert(!IncomingColors.empty() && "Block not colored!");
822 assert((IncomingColors.size() == 1 ||
823 llvm::all_of(IncomingColors,
824 [&](BasicBlock *Color) {
825 return Color != FuncletPadBB;
826 })) &&
827 "Cloning should leave this funclet's blocks monochromatic");
828 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
829 }
830 if (IsForOldBlock != EdgeTargetsFunclet)
David Majnemer8a1c45d2015-12-12 05:38:55 +0000831 continue;
832 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
833 // Revisit the next entry.
834 --PredIdx;
835 --PredEnd;
836 }
837 };
838
839 for (auto &BBMapping : Orig2Clone) {
840 BasicBlock *OldBlock = BBMapping.first;
841 BasicBlock *NewBlock = BBMapping.second;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000842 for (PHINode &OldPN : OldBlock->phis()) {
843 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000844 }
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000845 for (PHINode &NewPN : NewBlock->phis()) {
846 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000847 }
848 }
849
David Majnemer459a64a2015-09-16 18:40:37 +0000850 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
851 // the PHI nodes for NewBB now.
852 for (auto &BBMapping : Orig2Clone) {
853 BasicBlock *OldBlock = BBMapping.first;
854 BasicBlock *NewBlock = BBMapping.second;
855 for (BasicBlock *SuccBB : successors(NewBlock)) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000856 for (PHINode &SuccPN : SuccBB->phis()) {
David Majnemer459a64a2015-09-16 18:40:37 +0000857 // Ok, we have a PHI node. Figure out what the incoming value was for
858 // the OldBlock.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000859 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
David Majnemer459a64a2015-09-16 18:40:37 +0000860 if (OldBlockIdx == -1)
861 break;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000862 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
David Majnemer459a64a2015-09-16 18:40:37 +0000863
864 // Remap the value if necessary.
865 if (auto *Inst = dyn_cast<Instruction>(IV)) {
866 ValueToValueMapTy::iterator I = VMap.find(Inst);
867 if (I != VMap.end())
868 IV = I->second;
869 }
870
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000871 SuccPN.addIncoming(IV, NewBlock);
David Majnemer459a64a2015-09-16 18:40:37 +0000872 }
873 }
874 }
875
876 for (ValueToValueMapTy::value_type VT : VMap) {
877 // If there were values defined in BB that are used outside the funclet,
878 // then we now have to update all uses of the value to use either the
879 // original value, the cloned value, or some PHI derived value. This can
880 // require arbitrary PHI insertion, of which we are prepared to do, clean
881 // these up now.
882 SmallVector<Use *, 16> UsesToRename;
883
884 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
885 if (!OldI)
886 continue;
887 auto *NewI = cast<Instruction>(VT.second);
888 // Scan all uses of this instruction to see if it is used outside of its
889 // funclet, and if so, record them in UsesToRename.
890 for (Use &U : OldI->uses()) {
891 Instruction *UserI = cast<Instruction>(U.getUser());
892 BasicBlock *UserBB = UserI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +0000893 ColorVector &ColorsForUserBB = BlockColors[UserBB];
David Majnemer459a64a2015-09-16 18:40:37 +0000894 assert(!ColorsForUserBB.empty());
895 if (ColorsForUserBB.size() > 1 ||
896 *ColorsForUserBB.begin() != FuncletPadBB)
897 UsesToRename.push_back(&U);
898 }
899
900 // If there are no uses outside the block, we're done with this
901 // instruction.
902 if (UsesToRename.empty())
903 continue;
904
905 // We found a use of OldI outside of the funclet. Rename all uses of OldI
906 // that are outside its funclet to be uses of the appropriate PHI node
907 // etc.
908 SSAUpdater SSAUpdate;
909 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
910 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
911 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
912
913 while (!UsesToRename.empty())
914 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
915 }
David Majnemerfd9f4772015-08-11 01:15:26 +0000916 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000917}
David Majnemerfd9f4772015-08-11 01:15:26 +0000918
David Majnemer3bb88c02015-12-15 21:27:27 +0000919void WinEHPrepare::removeImplausibleInstructions(Function &F) {
David Majnemer83f4bb22015-08-17 20:56:39 +0000920 // Remove implausible terminators and replace them with UnreachableInst.
921 for (auto &Funclet : FuncletBlocks) {
922 BasicBlock *FuncletPadBB = Funclet.first;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000923 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
David Majnemer3bb88c02015-12-15 21:27:27 +0000924 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
925 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
926 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
927 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
David Majnemer83f4bb22015-08-17 20:56:39 +0000928
929 for (BasicBlock *BB : BlocksInFunclet) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000930 for (Instruction &I : *BB) {
931 CallSite CS(&I);
932 if (!CS)
933 continue;
934
935 Value *FuncletBundleOperand = nullptr;
936 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
937 FuncletBundleOperand = BU->Inputs.front();
938
939 if (FuncletBundleOperand == FuncletPad)
940 continue;
941
David Majnemer08dd52dc2016-02-26 00:04:25 +0000942 // Skip call sites which are nounwind intrinsics or inline asm.
David Majnemer3bb88c02015-12-15 21:27:27 +0000943 auto *CalledFn =
944 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Justin Lebar9cbc3012016-07-28 23:58:15 +0000945 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
946 CS.isInlineAsm()))
David Majnemer3bb88c02015-12-15 21:27:27 +0000947 continue;
948
949 // This call site was not part of this funclet, remove it.
950 if (CS.isInvoke()) {
951 // Remove the unwind edge if it was an invoke.
952 removeUnwindEdge(BB);
953 // Get a pointer to the new call.
954 BasicBlock::iterator CallI =
955 std::prev(BB->getTerminator()->getIterator());
956 auto *CI = cast<CallInst>(&*CallI);
David Majnemere14e7bc2016-06-25 08:19:55 +0000957 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000958 } else {
David Majnemere14e7bc2016-06-25 08:19:55 +0000959 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
David Majnemer3bb88c02015-12-15 21:27:27 +0000960 }
961
962 // There are no more instructions in the block (except for unreachable),
963 // we are done.
964 break;
965 }
966
David Majnemer83f4bb22015-08-17 20:56:39 +0000967 TerminatorInst *TI = BB->getTerminator();
968 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
David Majnemer3bb88c02015-12-15 21:27:27 +0000969 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
David Majnemer83f4bb22015-08-17 20:56:39 +0000970 // The token consumed by a CatchReturnInst must match the funclet token.
971 bool IsUnreachableCatchret = false;
972 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000973 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000974 // The token consumed by a CleanupReturnInst must match the funclet token.
David Majnemer83f4bb22015-08-17 20:56:39 +0000975 bool IsUnreachableCleanupret = false;
976 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000977 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +0000978 if (IsUnreachableRet || IsUnreachableCatchret ||
David Majnemer8a1c45d2015-12-12 05:38:55 +0000979 IsUnreachableCleanupret) {
David Majnemere14e7bc2016-06-25 08:19:55 +0000980 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000981 } else if (isa<InvokeInst>(TI)) {
David Majnemer3bb88c02015-12-15 21:27:27 +0000982 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
983 // Invokes within a cleanuppad for the MSVC++ personality never
984 // transfer control to their unwind edge: the personality will
985 // terminate the program.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000986 removeUnwindEdge(BB);
David Majnemer3bb88c02015-12-15 21:27:27 +0000987 }
David Majnemer83f4bb22015-08-17 20:56:39 +0000988 }
989 }
990 }
David Majnemerb3d9b962015-09-16 18:40:24 +0000991}
David Majnemer83f4bb22015-08-17 20:56:39 +0000992
David Majnemerb3d9b962015-09-16 18:40:24 +0000993void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +0000994 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
995 // branches, etc.
996 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000997 BasicBlock *BB = &*FI++;
David Majnemerfd9f4772015-08-11 01:15:26 +0000998 SimplifyInstructionsInBlock(BB);
999 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1000 MergeBlockIntoPredecessor(BB);
1001 }
1002
David Majnemerfd9f4772015-08-11 01:15:26 +00001003 // We might have some unreachable blocks after cleaning up some impossible
1004 // control flow.
1005 removeUnreachableBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001006}
David Majnemerfd9f4772015-08-11 01:15:26 +00001007
Florian Hahn6b3216a2017-07-31 10:07:49 +00001008#ifndef NDEBUG
David Majnemerb3d9b962015-09-16 18:40:24 +00001009void WinEHPrepare::verifyPreparedFunclets(Function &F) {
David Majnemerfd9f4772015-08-11 01:15:26 +00001010 for (BasicBlock &BB : F) {
1011 size_t NumColors = BlockColors[&BB].size();
1012 assert(NumColors == 1 && "Expected monochromatic BB!");
1013 if (NumColors == 0)
1014 report_fatal_error("Uncolored BB!");
1015 if (NumColors > 1)
1016 report_fatal_error("Multicolor BB!");
NAKAMURA Takumided575e2016-01-03 01:41:00 +00001017 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
1018 "EH Pad still has a PHI!");
David Majnemerfd9f4772015-08-11 01:15:26 +00001019 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001020}
Florian Hahn6b3216a2017-07-31 10:07:49 +00001021#endif
David Majnemerb3d9b962015-09-16 18:40:24 +00001022
David Majnemer8a1c45d2015-12-12 05:38:55 +00001023bool WinEHPrepare::prepareExplicitEH(Function &F) {
1024 // Remove unreachable blocks. It is not valuable to assign them a color and
1025 // their existence can trick us into thinking values are alive when they are
1026 // not.
1027 removeUnreachableBlocks(F);
1028
David Majnemerb3d9b962015-09-16 18:40:24 +00001029 // Determine which blocks are reachable from which funclet entries.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001030 colorFunclets(F);
1031
1032 cloneCommonBlocks(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001033
Reid Klecknercc2f6c32015-11-19 23:23:33 +00001034 if (!DisableDemotion)
David Majnemer459a64a2015-09-16 18:40:37 +00001035 demotePHIsOnFunclets(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001036
David Majnemer459a64a2015-09-16 18:40:37 +00001037 if (!DisableCleanups) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001038 LLVM_DEBUG(verifyFunction(F));
David Majnemer3bb88c02015-12-15 21:27:27 +00001039 removeImplausibleInstructions(F);
David Majnemerb3d9b962015-09-16 18:40:24 +00001040
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001041 LLVM_DEBUG(verifyFunction(F));
David Majnemer459a64a2015-09-16 18:40:37 +00001042 cleanupPreparedFunclets(F);
1043 }
David Majnemerb3d9b962015-09-16 18:40:24 +00001044
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001045 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemerdbdc9c22016-01-02 09:26:36 +00001046 // Recolor the CFG to verify that all is well.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001047 LLVM_DEBUG(colorFunclets(F));
1048 LLVM_DEBUG(verifyPreparedFunclets(F));
David Majnemerfd9f4772015-08-11 01:15:26 +00001049
1050 BlockColors.clear();
1051 FuncletBlocks.clear();
David Majnemer0ad363e2015-08-18 19:07:12 +00001052
David Majnemerfd9f4772015-08-11 01:15:26 +00001053 return true;
1054}
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001055
1056// TODO: Share loads when one use dominates another, or when a catchpad exit
1057// dominates uses (needs dominators).
1058AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1059 BasicBlock *PHIBlock = PN->getParent();
1060 AllocaInst *SpillSlot = nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +00001061 Instruction *EHPad = PHIBlock->getFirstNonPHI();
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001062
David Majnemer8a1c45d2015-12-12 05:38:55 +00001063 if (!isa<TerminatorInst>(EHPad)) {
1064 // If the EHPad isn't a terminator, then we can insert a load in this block
1065 // that will dominate all uses.
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001066 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001067 Twine(PN->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001068 &F.getEntryBlock().front());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001069 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001070 &*PHIBlock->getFirstInsertionPt());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001071 PN->replaceAllUsesWith(V);
1072 return SpillSlot;
1073 }
1074
David Majnemer8a1c45d2015-12-12 05:38:55 +00001075 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1076 // loads of the slot before every use.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001077 DenseMap<BasicBlock *, Value *> Loads;
1078 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1079 UI != UE;) {
1080 Use &U = *UI++;
1081 auto *UsingInst = cast<Instruction>(U.getUser());
David Majnemer8a1c45d2015-12-12 05:38:55 +00001082 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001083 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1084 // stores for it separately.
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001085 continue;
1086 }
1087 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1088 }
1089 return SpillSlot;
1090}
1091
1092// TODO: improve store placement. Inserting at def is probably good, but need
1093// to be careful not to introduce interfering stores (needs liveness analysis).
1094// TODO: identify related phi nodes that can share spill slots, and share them
1095// (also needs liveness).
1096void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1097 AllocaInst *SpillSlot) {
1098 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1099 // stored to the spill slot by the end of the given Block.
1100 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1101
1102 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1103
1104 while (!Worklist.empty()) {
1105 BasicBlock *EHBlock;
1106 Value *InVal;
1107 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1108
1109 PHINode *PN = dyn_cast<PHINode>(InVal);
1110 if (PN && PN->getParent() == EHBlock) {
1111 // The value is defined by another PHI we need to remove, with no room to
1112 // insert a store after the PHI, so each predecessor needs to store its
1113 // incoming value.
1114 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1115 Value *PredVal = PN->getIncomingValue(i);
1116
1117 // Undef can safely be skipped.
1118 if (isa<UndefValue>(PredVal))
1119 continue;
1120
1121 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1122 }
1123 } else {
1124 // We need to store InVal, which dominates EHBlock, but can't put a store
1125 // in EHBlock, so need to put stores in each predecessor.
1126 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1127 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1128 }
1129 }
1130 }
1131}
1132
1133void WinEHPrepare::insertPHIStore(
1134 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1135 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1136
1137 if (PredBlock->isEHPad() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +00001138 isa<TerminatorInst>(PredBlock->getFirstNonPHI())) {
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001139 // Pred is unsplittable, so we need to queue it on the worklist.
1140 Worklist.push_back({PredBlock, PredVal});
1141 return;
1142 }
1143
1144 // Otherwise, insert the store at the end of the basic block.
1145 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1146}
1147
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001148void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1149 DenseMap<BasicBlock *, Value *> &Loads,
1150 Function &F) {
1151 // Lazilly create the spill slot.
1152 if (!SpillSlot)
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001153 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001154 Twine(V->getName(), ".wineh.spillslot"),
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001155 &F.getEntryBlock().front());
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001156
1157 auto *UsingInst = cast<Instruction>(U.getUser());
1158 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1159 // If this is a PHI node, we can't insert a load of the value before
1160 // the use. Instead insert the load in the predecessor block
1161 // corresponding to the incoming value.
1162 //
1163 // Note that if there are multiple edges from a basic block to this
1164 // PHI node that we cannot have multiple loads. The problem is that
1165 // the resulting PHI node will have multiple values (from each load)
1166 // coming in from the same block, which is illegal SSA form.
1167 // For this reason, we keep track of and reuse loads we insert.
1168 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001169 if (auto *CatchRet =
1170 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1171 // Putting a load above a catchret and use on the phi would still leave
1172 // a cross-funclet def/use. We need to split the edge, change the
1173 // catchret to target the new block, and put the load there.
1174 BasicBlock *PHIBlock = UsingInst->getParent();
1175 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1176 // SplitEdge gives us:
1177 // IncomingBlock:
1178 // ...
1179 // br label %NewBlock
1180 // NewBlock:
1181 // catchret label %PHIBlock
1182 // But we need:
1183 // IncomingBlock:
1184 // ...
1185 // catchret label %NewBlock
1186 // NewBlock:
1187 // br label %PHIBlock
1188 // So move the terminators to each others' blocks and swap their
1189 // successors.
1190 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1191 Goto->removeFromParent();
1192 CatchRet->removeFromParent();
1193 IncomingBlock->getInstList().push_back(CatchRet);
1194 NewBlock->getInstList().push_back(Goto);
1195 Goto->setSuccessor(0, PHIBlock);
1196 CatchRet->setSuccessor(NewBlock);
1197 // Update the color mapping for the newly split edge.
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001198 // Grab a reference to the ColorVector to be inserted before getting the
1199 // reference to the vector we are copying because inserting the new
1200 // element in BlockColors might cause the map to be reallocated.
1201 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
David Majnemer8a1c45d2015-12-12 05:38:55 +00001202 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
Andrew Kaylorce3bcae2016-12-14 19:30:18 +00001203 ColorsForNewBlock = ColorsForPHIBlock;
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001204 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
David Majnemer8a1c45d2015-12-12 05:38:55 +00001205 FuncletBlocks[FuncletPad].push_back(NewBlock);
Joseph Tremoulet7031c9f2015-08-17 13:51:37 +00001206 // Treat the new block as incoming for load insertion.
1207 IncomingBlock = NewBlock;
1208 }
Joseph Tremouletc9ff9142015-08-13 14:30:10 +00001209 Value *&Load = Loads[IncomingBlock];
1210 // Insert the load into the predecessor block
1211 if (!Load)
1212 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1213 /*Volatile=*/false, IncomingBlock->getTerminator());
1214
1215 U.set(Load);
1216 } else {
1217 // Reload right before the old use.
1218 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1219 /*Volatile=*/false, UsingInst);
1220 U.set(Load);
1221 }
1222}
Reid Klecknerc71d6272015-09-28 23:56:30 +00001223
David Majnemer8a1c45d2015-12-12 05:38:55 +00001224void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
Reid Klecknerc71d6272015-09-28 23:56:30 +00001225 MCSymbol *InvokeBegin,
1226 MCSymbol *InvokeEnd) {
David Majnemer8a1c45d2015-12-12 05:38:55 +00001227 assert(InvokeStateMap.count(II) &&
1228 "should get invoke with precomputed state");
1229 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
Reid Klecknerc71d6272015-09-28 23:56:30 +00001230}
Chandler Carruthe0115342015-12-29 09:24:39 +00001231
1232WinEHFuncInfo::WinEHFuncInfo() {}