WinEHPrepare.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. //===-- WinEHPrepare - Prepare exception handling for code generation ---===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass lowers LLVM IR exception handling into something closer to what the
  10. // 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.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/MapVector.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/EHPersonalities.h"
  23. #include "llvm/CodeGen/MachineBasicBlock.h"
  24. #include "llvm/CodeGen/Passes.h"
  25. #include "llvm/CodeGen/WinEHFuncInfo.h"
  26. #include "llvm/IR/Verifier.h"
  27. #include "llvm/InitializePasses.h"
  28. #include "llvm/MC/MCSymbol.h"
  29. #include "llvm/Pass.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  34. #include "llvm/Transforms/Utils/Cloning.h"
  35. #include "llvm/Transforms/Utils/Local.h"
  36. #include "llvm/Transforms/Utils/SSAUpdater.h"
  37. using namespace llvm;
  38. #define DEBUG_TYPE "winehprepare"
  39. static cl::opt<bool> DisableDemotion(
  40. "disable-demotion", cl::Hidden,
  41. cl::desc(
  42. "Clone multicolor basic blocks but do not demote cross scopes"),
  43. cl::init(false));
  44. static cl::opt<bool> DisableCleanups(
  45. "disable-cleanups", cl::Hidden,
  46. cl::desc("Do not remove implausible terminators or other similar cleanups"),
  47. cl::init(false));
  48. static cl::opt<bool> DemoteCatchSwitchPHIOnlyOpt(
  49. "demote-catchswitch-only", cl::Hidden,
  50. cl::desc("Demote catchswitch BBs only (for wasm EH)"), cl::init(false));
  51. namespace {
  52. class WinEHPrepare : public FunctionPass {
  53. public:
  54. static char ID; // Pass identification, replacement for typeid.
  55. WinEHPrepare(bool DemoteCatchSwitchPHIOnly = false)
  56. : FunctionPass(ID), DemoteCatchSwitchPHIOnly(DemoteCatchSwitchPHIOnly) {}
  57. bool runOnFunction(Function &Fn) override;
  58. bool doFinalization(Module &M) override;
  59. void getAnalysisUsage(AnalysisUsage &AU) const override;
  60. StringRef getPassName() const override {
  61. return "Windows exception handling preparation";
  62. }
  63. private:
  64. void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
  65. void
  66. insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
  67. SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
  68. AllocaInst *insertPHILoads(PHINode *PN, Function &F);
  69. void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
  70. DenseMap<BasicBlock *, Value *> &Loads, Function &F);
  71. bool prepareExplicitEH(Function &F);
  72. void colorFunclets(Function &F);
  73. void demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
  74. void cloneCommonBlocks(Function &F);
  75. void removeImplausibleInstructions(Function &F);
  76. void cleanupPreparedFunclets(Function &F);
  77. void verifyPreparedFunclets(Function &F);
  78. bool DemoteCatchSwitchPHIOnly;
  79. // All fields are reset by runOnFunction.
  80. EHPersonality Personality = EHPersonality::Unknown;
  81. const DataLayout *DL = nullptr;
  82. DenseMap<BasicBlock *, ColorVector> BlockColors;
  83. MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
  84. };
  85. } // end anonymous namespace
  86. char WinEHPrepare::ID = 0;
  87. INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",
  88. false, false)
  89. FunctionPass *llvm::createWinEHPass(bool DemoteCatchSwitchPHIOnly) {
  90. return new WinEHPrepare(DemoteCatchSwitchPHIOnly);
  91. }
  92. bool WinEHPrepare::runOnFunction(Function &Fn) {
  93. if (!Fn.hasPersonalityFn())
  94. return false;
  95. // Classify the personality to see what kind of preparation we need.
  96. Personality = classifyEHPersonality(Fn.getPersonalityFn());
  97. // Do nothing if this is not a scope-based personality.
  98. if (!isScopedEHPersonality(Personality))
  99. return false;
  100. DL = &Fn.getParent()->getDataLayout();
  101. return prepareExplicitEH(Fn);
  102. }
  103. bool WinEHPrepare::doFinalization(Module &M) { return false; }
  104. void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
  105. static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
  106. const BasicBlock *BB) {
  107. CxxUnwindMapEntry UME;
  108. UME.ToState = ToState;
  109. UME.Cleanup = BB;
  110. FuncInfo.CxxUnwindMap.push_back(UME);
  111. return FuncInfo.getLastStateNumber();
  112. }
  113. static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
  114. int TryHigh, int CatchHigh,
  115. ArrayRef<const CatchPadInst *> Handlers) {
  116. WinEHTryBlockMapEntry TBME;
  117. TBME.TryLow = TryLow;
  118. TBME.TryHigh = TryHigh;
  119. TBME.CatchHigh = CatchHigh;
  120. assert(TBME.TryLow <= TBME.TryHigh);
  121. for (const CatchPadInst *CPI : Handlers) {
  122. WinEHHandlerType HT;
  123. Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
  124. if (TypeInfo->isNullValue())
  125. HT.TypeDescriptor = nullptr;
  126. else
  127. HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
  128. HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
  129. HT.Handler = CPI->getParent();
  130. if (auto *AI =
  131. dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
  132. HT.CatchObj.Alloca = AI;
  133. else
  134. HT.CatchObj.Alloca = nullptr;
  135. TBME.HandlerArray.push_back(HT);
  136. }
  137. FuncInfo.TryBlockMap.push_back(TBME);
  138. }
  139. static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
  140. for (const User *U : CleanupPad->users())
  141. if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
  142. return CRI->getUnwindDest();
  143. return nullptr;
  144. }
  145. static void calculateStateNumbersForInvokes(const Function *Fn,
  146. WinEHFuncInfo &FuncInfo) {
  147. auto *F = const_cast<Function *>(Fn);
  148. DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
  149. for (BasicBlock &BB : *F) {
  150. auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
  151. if (!II)
  152. continue;
  153. auto &BBColors = BlockColors[&BB];
  154. assert(BBColors.size() == 1 && "multi-color BB not removed by preparation");
  155. BasicBlock *FuncletEntryBB = BBColors.front();
  156. BasicBlock *FuncletUnwindDest;
  157. auto *FuncletPad =
  158. dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
  159. assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock());
  160. if (!FuncletPad)
  161. FuncletUnwindDest = nullptr;
  162. else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
  163. FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
  164. else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
  165. FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
  166. else
  167. llvm_unreachable("unexpected funclet pad!");
  168. BasicBlock *InvokeUnwindDest = II->getUnwindDest();
  169. int BaseState = -1;
  170. if (FuncletUnwindDest == InvokeUnwindDest) {
  171. auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
  172. if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
  173. BaseState = BaseStateI->second;
  174. }
  175. if (BaseState != -1) {
  176. FuncInfo.InvokeStateMap[II] = BaseState;
  177. } else {
  178. Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
  179. assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
  180. FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
  181. }
  182. }
  183. }
  184. // Given BB which ends in an unwind edge, return the EHPad that this BB belongs
  185. // to. If the unwind edge came from an invoke, return null.
  186. static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
  187. Value *ParentPad) {
  188. const Instruction *TI = BB->getTerminator();
  189. if (isa<InvokeInst>(TI))
  190. return nullptr;
  191. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
  192. if (CatchSwitch->getParentPad() != ParentPad)
  193. return nullptr;
  194. return BB;
  195. }
  196. assert(!TI->isEHPad() && "unexpected EHPad!");
  197. auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
  198. if (CleanupPad->getParentPad() != ParentPad)
  199. return nullptr;
  200. return CleanupPad->getParent();
  201. }
  202. // Starting from a EHPad, Backward walk through control-flow graph
  203. // to produce two primary outputs:
  204. // FuncInfo.EHPadStateMap[] and FuncInfo.CxxUnwindMap[]
  205. static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
  206. const Instruction *FirstNonPHI,
  207. int ParentState) {
  208. const BasicBlock *BB = FirstNonPHI->getParent();
  209. assert(BB->isEHPad() && "not a funclet!");
  210. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
  211. assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
  212. "shouldn't revist catch funclets!");
  213. SmallVector<const CatchPadInst *, 2> Handlers;
  214. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  215. auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
  216. Handlers.push_back(CatchPad);
  217. }
  218. int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
  219. FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
  220. for (const BasicBlock *PredBlock : predecessors(BB))
  221. if ((PredBlock = getEHPadFromPredecessor(PredBlock,
  222. CatchSwitch->getParentPad())))
  223. calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
  224. TryLow);
  225. int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
  226. // catchpads are separate funclets in C++ EH due to the way rethrow works.
  227. int TryHigh = CatchLow - 1;
  228. // MSVC FrameHandler3/4 on x64&Arm64 expect Catch Handlers in $tryMap$
  229. // stored in pre-order (outer first, inner next), not post-order
  230. // Add to map here. Fix the CatchHigh after children are processed
  231. const Module *Mod = BB->getParent()->getParent();
  232. bool IsPreOrder = Triple(Mod->getTargetTriple()).isArch64Bit();
  233. if (IsPreOrder)
  234. addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchLow, Handlers);
  235. unsigned TBMEIdx = FuncInfo.TryBlockMap.size() - 1;
  236. for (const auto *CatchPad : Handlers) {
  237. FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
  238. for (const User *U : CatchPad->users()) {
  239. const auto *UserI = cast<Instruction>(U);
  240. if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
  241. BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
  242. if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
  243. calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
  244. }
  245. if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
  246. BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
  247. // If a nested cleanup pad reports a null unwind destination and the
  248. // enclosing catch pad doesn't it must be post-dominated by an
  249. // unreachable instruction.
  250. if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
  251. calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
  252. }
  253. }
  254. }
  255. int CatchHigh = FuncInfo.getLastStateNumber();
  256. // Now child Catches are processed, update CatchHigh
  257. if (IsPreOrder)
  258. FuncInfo.TryBlockMap[TBMEIdx].CatchHigh = CatchHigh;
  259. else // PostOrder
  260. addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
  261. LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n');
  262. LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHigh
  263. << '\n');
  264. LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHigh
  265. << '\n');
  266. } else {
  267. auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
  268. // It's possible for a cleanup to be visited twice: it might have multiple
  269. // cleanupret instructions.
  270. if (FuncInfo.EHPadStateMap.count(CleanupPad))
  271. return;
  272. int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
  273. FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
  274. LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
  275. << BB->getName() << '\n');
  276. for (const BasicBlock *PredBlock : predecessors(BB)) {
  277. if ((PredBlock = getEHPadFromPredecessor(PredBlock,
  278. CleanupPad->getParentPad()))) {
  279. calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
  280. CleanupState);
  281. }
  282. }
  283. for (const User *U : CleanupPad->users()) {
  284. const auto *UserI = cast<Instruction>(U);
  285. if (UserI->isEHPad())
  286. report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
  287. "contain exceptional actions");
  288. }
  289. }
  290. }
  291. static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
  292. const Function *Filter, const BasicBlock *Handler) {
  293. SEHUnwindMapEntry Entry;
  294. Entry.ToState = ParentState;
  295. Entry.IsFinally = false;
  296. Entry.Filter = Filter;
  297. Entry.Handler = Handler;
  298. FuncInfo.SEHUnwindMap.push_back(Entry);
  299. return FuncInfo.SEHUnwindMap.size() - 1;
  300. }
  301. static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
  302. const BasicBlock *Handler) {
  303. SEHUnwindMapEntry Entry;
  304. Entry.ToState = ParentState;
  305. Entry.IsFinally = true;
  306. Entry.Filter = nullptr;
  307. Entry.Handler = Handler;
  308. FuncInfo.SEHUnwindMap.push_back(Entry);
  309. return FuncInfo.SEHUnwindMap.size() - 1;
  310. }
  311. // Starting from a EHPad, Backward walk through control-flow graph
  312. // to produce two primary outputs:
  313. // FuncInfo.EHPadStateMap[] and FuncInfo.SEHUnwindMap[]
  314. static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
  315. const Instruction *FirstNonPHI,
  316. int ParentState) {
  317. const BasicBlock *BB = FirstNonPHI->getParent();
  318. assert(BB->isEHPad() && "no a funclet!");
  319. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
  320. assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&
  321. "shouldn't revist catch funclets!");
  322. // Extract the filter function and the __except basic block and create a
  323. // state for them.
  324. assert(CatchSwitch->getNumHandlers() == 1 &&
  325. "SEH doesn't have multiple handlers per __try");
  326. const auto *CatchPad =
  327. cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
  328. const BasicBlock *CatchPadBB = CatchPad->getParent();
  329. const Constant *FilterOrNull =
  330. cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
  331. const Function *Filter = dyn_cast<Function>(FilterOrNull);
  332. assert((Filter || FilterOrNull->isNullValue()) &&
  333. "unexpected filter value");
  334. int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
  335. // Everything in the __try block uses TryState as its parent state.
  336. FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
  337. LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "
  338. << CatchPadBB->getName() << '\n');
  339. for (const BasicBlock *PredBlock : predecessors(BB))
  340. if ((PredBlock = getEHPadFromPredecessor(PredBlock,
  341. CatchSwitch->getParentPad())))
  342. calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
  343. TryState);
  344. // Everything in the __except block unwinds to ParentState, just like code
  345. // outside the __try.
  346. for (const User *U : CatchPad->users()) {
  347. const auto *UserI = cast<Instruction>(U);
  348. if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
  349. BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
  350. if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
  351. calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
  352. }
  353. if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
  354. BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
  355. // If a nested cleanup pad reports a null unwind destination and the
  356. // enclosing catch pad doesn't it must be post-dominated by an
  357. // unreachable instruction.
  358. if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
  359. calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
  360. }
  361. }
  362. } else {
  363. auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
  364. // It's possible for a cleanup to be visited twice: it might have multiple
  365. // cleanupret instructions.
  366. if (FuncInfo.EHPadStateMap.count(CleanupPad))
  367. return;
  368. int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
  369. FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
  370. LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "
  371. << BB->getName() << '\n');
  372. for (const BasicBlock *PredBlock : predecessors(BB))
  373. if ((PredBlock =
  374. getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
  375. calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
  376. CleanupState);
  377. for (const User *U : CleanupPad->users()) {
  378. const auto *UserI = cast<Instruction>(U);
  379. if (UserI->isEHPad())
  380. report_fatal_error("Cleanup funclets for the SEH personality cannot "
  381. "contain exceptional actions");
  382. }
  383. }
  384. }
  385. static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
  386. if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
  387. return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
  388. CatchSwitch->unwindsToCaller();
  389. if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
  390. return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
  391. getCleanupRetUnwindDest(CleanupPad) == nullptr;
  392. if (isa<CatchPadInst>(EHPad))
  393. return false;
  394. llvm_unreachable("unexpected EHPad!");
  395. }
  396. void llvm::calculateSEHStateNumbers(const Function *Fn,
  397. WinEHFuncInfo &FuncInfo) {
  398. // Don't compute state numbers twice.
  399. if (!FuncInfo.SEHUnwindMap.empty())
  400. return;
  401. for (const BasicBlock &BB : *Fn) {
  402. if (!BB.isEHPad())
  403. continue;
  404. const Instruction *FirstNonPHI = BB.getFirstNonPHI();
  405. if (!isTopLevelPadForMSVC(FirstNonPHI))
  406. continue;
  407. ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
  408. }
  409. calculateStateNumbersForInvokes(Fn, FuncInfo);
  410. }
  411. void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
  412. WinEHFuncInfo &FuncInfo) {
  413. // Return if it's already been done.
  414. if (!FuncInfo.EHPadStateMap.empty())
  415. return;
  416. for (const BasicBlock &BB : *Fn) {
  417. if (!BB.isEHPad())
  418. continue;
  419. const Instruction *FirstNonPHI = BB.getFirstNonPHI();
  420. if (!isTopLevelPadForMSVC(FirstNonPHI))
  421. continue;
  422. calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
  423. }
  424. calculateStateNumbersForInvokes(Fn, FuncInfo);
  425. }
  426. static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
  427. int TryParentState, ClrHandlerType HandlerType,
  428. uint32_t TypeToken, const BasicBlock *Handler) {
  429. ClrEHUnwindMapEntry Entry;
  430. Entry.HandlerParentState = HandlerParentState;
  431. Entry.TryParentState = TryParentState;
  432. Entry.Handler = Handler;
  433. Entry.HandlerType = HandlerType;
  434. Entry.TypeToken = TypeToken;
  435. FuncInfo.ClrEHUnwindMap.push_back(Entry);
  436. return FuncInfo.ClrEHUnwindMap.size() - 1;
  437. }
  438. void llvm::calculateClrEHStateNumbers(const Function *Fn,
  439. WinEHFuncInfo &FuncInfo) {
  440. // Return if it's already been done.
  441. if (!FuncInfo.EHPadStateMap.empty())
  442. return;
  443. // This numbering assigns one state number to each catchpad and cleanuppad.
  444. // It also computes two tree-like relations over states:
  445. // 1) Each state has a "HandlerParentState", which is the state of the next
  446. // outer handler enclosing this state's handler (same as nearest ancestor
  447. // per the ParentPad linkage on EH pads, but skipping over catchswitches).
  448. // 2) Each state has a "TryParentState", which:
  449. // a) for a catchpad that's not the last handler on its catchswitch, is
  450. // the state of the next catchpad on that catchswitch
  451. // b) for all other pads, is the state of the pad whose try region is the
  452. // next outer try region enclosing this state's try region. The "try
  453. // regions are not present as such in the IR, but will be inferred
  454. // based on the placement of invokes and pads which reach each other
  455. // by exceptional exits
  456. // Catchswitches do not get their own states, but each gets mapped to the
  457. // state of its first catchpad.
  458. // Step one: walk down from outermost to innermost funclets, assigning each
  459. // catchpad and cleanuppad a state number. Add an entry to the
  460. // ClrEHUnwindMap for each state, recording its HandlerParentState and
  461. // handler attributes. Record the TryParentState as well for each catchpad
  462. // that's not the last on its catchswitch, but initialize all other entries'
  463. // TryParentStates to a sentinel -1 value that the next pass will update.
  464. // Seed a worklist with pads that have no parent.
  465. SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
  466. for (const BasicBlock &BB : *Fn) {
  467. const Instruction *FirstNonPHI = BB.getFirstNonPHI();
  468. const Value *ParentPad;
  469. if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
  470. ParentPad = CPI->getParentPad();
  471. else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
  472. ParentPad = CSI->getParentPad();
  473. else
  474. continue;
  475. if (isa<ConstantTokenNone>(ParentPad))
  476. Worklist.emplace_back(FirstNonPHI, -1);
  477. }
  478. // Use the worklist to visit all pads, from outer to inner. Record
  479. // HandlerParentState for all pads. Record TryParentState only for catchpads
  480. // that aren't the last on their catchswitch (setting all other entries'
  481. // TryParentStates to an initial value of -1). This loop is also responsible
  482. // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
  483. // catchswitches.
  484. while (!Worklist.empty()) {
  485. const Instruction *Pad;
  486. int HandlerParentState;
  487. std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
  488. if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
  489. // Create the entry for this cleanup with the appropriate handler
  490. // properties. Finally and fault handlers are distinguished by arity.
  491. ClrHandlerType HandlerType =
  492. (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
  493. : ClrHandlerType::Finally);
  494. int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
  495. HandlerType, 0, Pad->getParent());
  496. // Queue any child EH pads on the worklist.
  497. for (const User *U : Cleanup->users())
  498. if (const auto *I = dyn_cast<Instruction>(U))
  499. if (I->isEHPad())
  500. Worklist.emplace_back(I, CleanupState);
  501. // Remember this pad's state.
  502. FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
  503. } else {
  504. // Walk the handlers of this catchswitch in reverse order since all but
  505. // the last need to set the following one as its TryParentState.
  506. const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
  507. int CatchState = -1, FollowerState = -1;
  508. SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
  509. for (const BasicBlock *CatchBlock : llvm::reverse(CatchBlocks)) {
  510. // Create the entry for this catch with the appropriate handler
  511. // properties.
  512. const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
  513. uint32_t TypeToken = static_cast<uint32_t>(
  514. cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
  515. CatchState =
  516. addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
  517. ClrHandlerType::Catch, TypeToken, CatchBlock);
  518. // Queue any child EH pads on the worklist.
  519. for (const User *U : Catch->users())
  520. if (const auto *I = dyn_cast<Instruction>(U))
  521. if (I->isEHPad())
  522. Worklist.emplace_back(I, CatchState);
  523. // Remember this catch's state.
  524. FuncInfo.EHPadStateMap[Catch] = CatchState;
  525. FollowerState = CatchState;
  526. }
  527. // Associate the catchswitch with the state of its first catch.
  528. assert(CatchSwitch->getNumHandlers());
  529. FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
  530. }
  531. }
  532. // Step two: record the TryParentState of each state. For cleanuppads that
  533. // don't have cleanuprets, we may need to infer this from their child pads,
  534. // so visit pads in descendant-most to ancestor-most order.
  535. for (ClrEHUnwindMapEntry &Entry : llvm::reverse(FuncInfo.ClrEHUnwindMap)) {
  536. const Instruction *Pad =
  537. Entry.Handler.get<const BasicBlock *>()->getFirstNonPHI();
  538. // For most pads, the TryParentState is the state associated with the
  539. // unwind dest of exceptional exits from it.
  540. const BasicBlock *UnwindDest;
  541. if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
  542. // If a catch is not the last in its catchswitch, its TryParentState is
  543. // the state associated with the next catch in the switch, even though
  544. // that's not the unwind dest of exceptions escaping the catch. Those
  545. // cases were already assigned a TryParentState in the first pass, so
  546. // skip them.
  547. if (Entry.TryParentState != -1)
  548. continue;
  549. // Otherwise, get the unwind dest from the catchswitch.
  550. UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
  551. } else {
  552. const auto *Cleanup = cast<CleanupPadInst>(Pad);
  553. UnwindDest = nullptr;
  554. for (const User *U : Cleanup->users()) {
  555. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
  556. // Common and unambiguous case -- cleanupret indicates cleanup's
  557. // unwind dest.
  558. UnwindDest = CleanupRet->getUnwindDest();
  559. break;
  560. }
  561. // Get an unwind dest for the user
  562. const BasicBlock *UserUnwindDest = nullptr;
  563. if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
  564. UserUnwindDest = Invoke->getUnwindDest();
  565. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
  566. UserUnwindDest = CatchSwitch->getUnwindDest();
  567. } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
  568. int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
  569. int UserUnwindState =
  570. FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
  571. if (UserUnwindState != -1)
  572. UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
  573. .Handler.get<const BasicBlock *>();
  574. }
  575. // Not having an unwind dest for this user might indicate that it
  576. // doesn't unwind, so can't be taken as proof that the cleanup itself
  577. // may unwind to caller (see e.g. SimplifyUnreachable and
  578. // RemoveUnwindEdge).
  579. if (!UserUnwindDest)
  580. continue;
  581. // Now we have an unwind dest for the user, but we need to see if it
  582. // unwinds all the way out of the cleanup or if it stays within it.
  583. const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
  584. const Value *UserUnwindParent;
  585. if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
  586. UserUnwindParent = CSI->getParentPad();
  587. else
  588. UserUnwindParent =
  589. cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
  590. // The unwind stays within the cleanup iff it targets a child of the
  591. // cleanup.
  592. if (UserUnwindParent == Cleanup)
  593. continue;
  594. // This unwind exits the cleanup, so its dest is the cleanup's dest.
  595. UnwindDest = UserUnwindDest;
  596. break;
  597. }
  598. }
  599. // Record the state of the unwind dest as the TryParentState.
  600. int UnwindDestState;
  601. // If UnwindDest is null at this point, either the pad in question can
  602. // be exited by unwind to caller, or it cannot be exited by unwind. In
  603. // either case, reporting such cases as unwinding to caller is correct.
  604. // This can lead to EH tables that "look strange" -- if this pad's is in
  605. // a parent funclet which has other children that do unwind to an enclosing
  606. // pad, the try region for this pad will be missing the "duplicate" EH
  607. // clause entries that you'd expect to see covering the whole parent. That
  608. // should be benign, since the unwind never actually happens. If it were
  609. // an issue, we could add a subsequent pass that pushes unwind dests down
  610. // from parents that have them to children that appear to unwind to caller.
  611. if (!UnwindDest) {
  612. UnwindDestState = -1;
  613. } else {
  614. UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
  615. }
  616. Entry.TryParentState = UnwindDestState;
  617. }
  618. // Step three: transfer information from pads to invokes.
  619. calculateStateNumbersForInvokes(Fn, FuncInfo);
  620. }
  621. void WinEHPrepare::colorFunclets(Function &F) {
  622. BlockColors = colorEHFunclets(F);
  623. // Invert the map from BB to colors to color to BBs.
  624. for (BasicBlock &BB : F) {
  625. ColorVector &Colors = BlockColors[&BB];
  626. for (BasicBlock *Color : Colors)
  627. FuncletBlocks[Color].push_back(&BB);
  628. }
  629. }
  630. void WinEHPrepare::demotePHIsOnFunclets(Function &F,
  631. bool DemoteCatchSwitchPHIOnly) {
  632. // Strip PHI nodes off of EH pads.
  633. SmallVector<PHINode *, 16> PHINodes;
  634. for (BasicBlock &BB : make_early_inc_range(F)) {
  635. if (!BB.isEHPad())
  636. continue;
  637. if (DemoteCatchSwitchPHIOnly && !isa<CatchSwitchInst>(BB.getFirstNonPHI()))
  638. continue;
  639. for (Instruction &I : make_early_inc_range(BB)) {
  640. auto *PN = dyn_cast<PHINode>(&I);
  641. // Stop at the first non-PHI.
  642. if (!PN)
  643. break;
  644. AllocaInst *SpillSlot = insertPHILoads(PN, F);
  645. if (SpillSlot)
  646. insertPHIStores(PN, SpillSlot);
  647. PHINodes.push_back(PN);
  648. }
  649. }
  650. for (auto *PN : PHINodes) {
  651. // There may be lingering uses on other EH PHIs being removed
  652. PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
  653. PN->eraseFromParent();
  654. }
  655. }
  656. void WinEHPrepare::cloneCommonBlocks(Function &F) {
  657. // We need to clone all blocks which belong to multiple funclets. Values are
  658. // remapped throughout the funclet to propagate both the new instructions
  659. // *and* the new basic blocks themselves.
  660. for (auto &Funclets : FuncletBlocks) {
  661. BasicBlock *FuncletPadBB = Funclets.first;
  662. std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
  663. Value *FuncletToken;
  664. if (FuncletPadBB == &F.getEntryBlock())
  665. FuncletToken = ConstantTokenNone::get(F.getContext());
  666. else
  667. FuncletToken = FuncletPadBB->getFirstNonPHI();
  668. std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
  669. ValueToValueMapTy VMap;
  670. for (BasicBlock *BB : BlocksInFunclet) {
  671. ColorVector &ColorsForBB = BlockColors[BB];
  672. // We don't need to do anything if the block is monochromatic.
  673. size_t NumColorsForBB = ColorsForBB.size();
  674. if (NumColorsForBB == 1)
  675. continue;
  676. DEBUG_WITH_TYPE("winehprepare-coloring",
  677. dbgs() << " Cloning block \'" << BB->getName()
  678. << "\' for funclet \'" << FuncletPadBB->getName()
  679. << "\'.\n");
  680. // Create a new basic block and copy instructions into it!
  681. BasicBlock *CBB =
  682. CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
  683. // Insert the clone immediately after the original to ensure determinism
  684. // and to keep the same relative ordering of any funclet's blocks.
  685. CBB->insertInto(&F, BB->getNextNode());
  686. // Add basic block mapping.
  687. VMap[BB] = CBB;
  688. // Record delta operations that we need to perform to our color mappings.
  689. Orig2Clone.emplace_back(BB, CBB);
  690. }
  691. // If nothing was cloned, we're done cloning in this funclet.
  692. if (Orig2Clone.empty())
  693. continue;
  694. // Update our color mappings to reflect that one block has lost a color and
  695. // another has gained a color.
  696. for (auto &BBMapping : Orig2Clone) {
  697. BasicBlock *OldBlock = BBMapping.first;
  698. BasicBlock *NewBlock = BBMapping.second;
  699. BlocksInFunclet.push_back(NewBlock);
  700. ColorVector &NewColors = BlockColors[NewBlock];
  701. assert(NewColors.empty() && "A new block should only have one color!");
  702. NewColors.push_back(FuncletPadBB);
  703. DEBUG_WITH_TYPE("winehprepare-coloring",
  704. dbgs() << " Assigned color \'" << FuncletPadBB->getName()
  705. << "\' to block \'" << NewBlock->getName()
  706. << "\'.\n");
  707. llvm::erase_value(BlocksInFunclet, OldBlock);
  708. ColorVector &OldColors = BlockColors[OldBlock];
  709. llvm::erase_value(OldColors, FuncletPadBB);
  710. DEBUG_WITH_TYPE("winehprepare-coloring",
  711. dbgs() << " Removed color \'" << FuncletPadBB->getName()
  712. << "\' from block \'" << OldBlock->getName()
  713. << "\'.\n");
  714. }
  715. // Loop over all of the instructions in this funclet, fixing up operand
  716. // references as we go. This uses VMap to do all the hard work.
  717. for (BasicBlock *BB : BlocksInFunclet)
  718. // Loop over all instructions, fixing each one as we find it...
  719. for (Instruction &I : *BB)
  720. RemapInstruction(&I, VMap,
  721. RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
  722. // Catchrets targeting cloned blocks need to be updated separately from
  723. // the loop above because they are not in the current funclet.
  724. SmallVector<CatchReturnInst *, 2> FixupCatchrets;
  725. for (auto &BBMapping : Orig2Clone) {
  726. BasicBlock *OldBlock = BBMapping.first;
  727. BasicBlock *NewBlock = BBMapping.second;
  728. FixupCatchrets.clear();
  729. for (BasicBlock *Pred : predecessors(OldBlock))
  730. if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
  731. if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
  732. FixupCatchrets.push_back(CatchRet);
  733. for (CatchReturnInst *CatchRet : FixupCatchrets)
  734. CatchRet->setSuccessor(NewBlock);
  735. }
  736. auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
  737. unsigned NumPreds = PN->getNumIncomingValues();
  738. for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
  739. ++PredIdx) {
  740. BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
  741. bool EdgeTargetsFunclet;
  742. if (auto *CRI =
  743. dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
  744. EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
  745. } else {
  746. ColorVector &IncomingColors = BlockColors[IncomingBlock];
  747. assert(!IncomingColors.empty() && "Block not colored!");
  748. assert((IncomingColors.size() == 1 ||
  749. llvm::all_of(IncomingColors,
  750. [&](BasicBlock *Color) {
  751. return Color != FuncletPadBB;
  752. })) &&
  753. "Cloning should leave this funclet's blocks monochromatic");
  754. EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
  755. }
  756. if (IsForOldBlock != EdgeTargetsFunclet)
  757. continue;
  758. PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
  759. // Revisit the next entry.
  760. --PredIdx;
  761. --PredEnd;
  762. }
  763. };
  764. for (auto &BBMapping : Orig2Clone) {
  765. BasicBlock *OldBlock = BBMapping.first;
  766. BasicBlock *NewBlock = BBMapping.second;
  767. for (PHINode &OldPN : OldBlock->phis()) {
  768. UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
  769. }
  770. for (PHINode &NewPN : NewBlock->phis()) {
  771. UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
  772. }
  773. }
  774. // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
  775. // the PHI nodes for NewBB now.
  776. for (auto &BBMapping : Orig2Clone) {
  777. BasicBlock *OldBlock = BBMapping.first;
  778. BasicBlock *NewBlock = BBMapping.second;
  779. for (BasicBlock *SuccBB : successors(NewBlock)) {
  780. for (PHINode &SuccPN : SuccBB->phis()) {
  781. // Ok, we have a PHI node. Figure out what the incoming value was for
  782. // the OldBlock.
  783. int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
  784. if (OldBlockIdx == -1)
  785. break;
  786. Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
  787. // Remap the value if necessary.
  788. if (auto *Inst = dyn_cast<Instruction>(IV)) {
  789. ValueToValueMapTy::iterator I = VMap.find(Inst);
  790. if (I != VMap.end())
  791. IV = I->second;
  792. }
  793. SuccPN.addIncoming(IV, NewBlock);
  794. }
  795. }
  796. }
  797. for (ValueToValueMapTy::value_type VT : VMap) {
  798. // If there were values defined in BB that are used outside the funclet,
  799. // then we now have to update all uses of the value to use either the
  800. // original value, the cloned value, or some PHI derived value. This can
  801. // require arbitrary PHI insertion, of which we are prepared to do, clean
  802. // these up now.
  803. SmallVector<Use *, 16> UsesToRename;
  804. auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
  805. if (!OldI)
  806. continue;
  807. auto *NewI = cast<Instruction>(VT.second);
  808. // Scan all uses of this instruction to see if it is used outside of its
  809. // funclet, and if so, record them in UsesToRename.
  810. for (Use &U : OldI->uses()) {
  811. Instruction *UserI = cast<Instruction>(U.getUser());
  812. BasicBlock *UserBB = UserI->getParent();
  813. ColorVector &ColorsForUserBB = BlockColors[UserBB];
  814. assert(!ColorsForUserBB.empty());
  815. if (ColorsForUserBB.size() > 1 ||
  816. *ColorsForUserBB.begin() != FuncletPadBB)
  817. UsesToRename.push_back(&U);
  818. }
  819. // If there are no uses outside the block, we're done with this
  820. // instruction.
  821. if (UsesToRename.empty())
  822. continue;
  823. // We found a use of OldI outside of the funclet. Rename all uses of OldI
  824. // that are outside its funclet to be uses of the appropriate PHI node
  825. // etc.
  826. SSAUpdater SSAUpdate;
  827. SSAUpdate.Initialize(OldI->getType(), OldI->getName());
  828. SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
  829. SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
  830. while (!UsesToRename.empty())
  831. SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
  832. }
  833. }
  834. }
  835. void WinEHPrepare::removeImplausibleInstructions(Function &F) {
  836. // Remove implausible terminators and replace them with UnreachableInst.
  837. for (auto &Funclet : FuncletBlocks) {
  838. BasicBlock *FuncletPadBB = Funclet.first;
  839. std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
  840. Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
  841. auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
  842. auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
  843. auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
  844. for (BasicBlock *BB : BlocksInFunclet) {
  845. for (Instruction &I : *BB) {
  846. auto *CB = dyn_cast<CallBase>(&I);
  847. if (!CB)
  848. continue;
  849. Value *FuncletBundleOperand = nullptr;
  850. if (auto BU = CB->getOperandBundle(LLVMContext::OB_funclet))
  851. FuncletBundleOperand = BU->Inputs.front();
  852. if (FuncletBundleOperand == FuncletPad)
  853. continue;
  854. // Skip call sites which are nounwind intrinsics or inline asm.
  855. auto *CalledFn =
  856. dyn_cast<Function>(CB->getCalledOperand()->stripPointerCasts());
  857. if (CalledFn && ((CalledFn->isIntrinsic() && CB->doesNotThrow()) ||
  858. CB->isInlineAsm()))
  859. continue;
  860. // This call site was not part of this funclet, remove it.
  861. if (isa<InvokeInst>(CB)) {
  862. // Remove the unwind edge if it was an invoke.
  863. removeUnwindEdge(BB);
  864. // Get a pointer to the new call.
  865. BasicBlock::iterator CallI =
  866. std::prev(BB->getTerminator()->getIterator());
  867. auto *CI = cast<CallInst>(&*CallI);
  868. changeToUnreachable(CI);
  869. } else {
  870. changeToUnreachable(&I);
  871. }
  872. // There are no more instructions in the block (except for unreachable),
  873. // we are done.
  874. break;
  875. }
  876. Instruction *TI = BB->getTerminator();
  877. // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
  878. bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
  879. // The token consumed by a CatchReturnInst must match the funclet token.
  880. bool IsUnreachableCatchret = false;
  881. if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
  882. IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
  883. // The token consumed by a CleanupReturnInst must match the funclet token.
  884. bool IsUnreachableCleanupret = false;
  885. if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
  886. IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
  887. if (IsUnreachableRet || IsUnreachableCatchret ||
  888. IsUnreachableCleanupret) {
  889. changeToUnreachable(TI);
  890. } else if (isa<InvokeInst>(TI)) {
  891. if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
  892. // Invokes within a cleanuppad for the MSVC++ personality never
  893. // transfer control to their unwind edge: the personality will
  894. // terminate the program.
  895. removeUnwindEdge(BB);
  896. }
  897. }
  898. }
  899. }
  900. }
  901. void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
  902. // Clean-up some of the mess we made by removing useles PHI nodes, trivial
  903. // branches, etc.
  904. for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
  905. SimplifyInstructionsInBlock(&BB);
  906. ConstantFoldTerminator(&BB, /*DeleteDeadConditions=*/true);
  907. MergeBlockIntoPredecessor(&BB);
  908. }
  909. // We might have some unreachable blocks after cleaning up some impossible
  910. // control flow.
  911. removeUnreachableBlocks(F);
  912. }
  913. #ifndef NDEBUG
  914. void WinEHPrepare::verifyPreparedFunclets(Function &F) {
  915. for (BasicBlock &BB : F) {
  916. size_t NumColors = BlockColors[&BB].size();
  917. assert(NumColors == 1 && "Expected monochromatic BB!");
  918. if (NumColors == 0)
  919. report_fatal_error("Uncolored BB!");
  920. if (NumColors > 1)
  921. report_fatal_error("Multicolor BB!");
  922. assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&
  923. "EH Pad still has a PHI!");
  924. }
  925. }
  926. #endif
  927. bool WinEHPrepare::prepareExplicitEH(Function &F) {
  928. // Remove unreachable blocks. It is not valuable to assign them a color and
  929. // their existence can trick us into thinking values are alive when they are
  930. // not.
  931. removeUnreachableBlocks(F);
  932. // Determine which blocks are reachable from which funclet entries.
  933. colorFunclets(F);
  934. cloneCommonBlocks(F);
  935. if (!DisableDemotion)
  936. demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly ||
  937. DemoteCatchSwitchPHIOnlyOpt);
  938. if (!DisableCleanups) {
  939. assert(!verifyFunction(F, &dbgs()));
  940. removeImplausibleInstructions(F);
  941. assert(!verifyFunction(F, &dbgs()));
  942. cleanupPreparedFunclets(F);
  943. }
  944. LLVM_DEBUG(verifyPreparedFunclets(F));
  945. // Recolor the CFG to verify that all is well.
  946. LLVM_DEBUG(colorFunclets(F));
  947. LLVM_DEBUG(verifyPreparedFunclets(F));
  948. BlockColors.clear();
  949. FuncletBlocks.clear();
  950. return true;
  951. }
  952. // TODO: Share loads when one use dominates another, or when a catchpad exit
  953. // dominates uses (needs dominators).
  954. AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
  955. BasicBlock *PHIBlock = PN->getParent();
  956. AllocaInst *SpillSlot = nullptr;
  957. Instruction *EHPad = PHIBlock->getFirstNonPHI();
  958. if (!EHPad->isTerminator()) {
  959. // If the EHPad isn't a terminator, then we can insert a load in this block
  960. // that will dominate all uses.
  961. SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
  962. Twine(PN->getName(), ".wineh.spillslot"),
  963. &F.getEntryBlock().front());
  964. Value *V = new LoadInst(PN->getType(), SpillSlot,
  965. Twine(PN->getName(), ".wineh.reload"),
  966. &*PHIBlock->getFirstInsertionPt());
  967. PN->replaceAllUsesWith(V);
  968. return SpillSlot;
  969. }
  970. // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
  971. // loads of the slot before every use.
  972. DenseMap<BasicBlock *, Value *> Loads;
  973. for (Use &U : llvm::make_early_inc_range(PN->uses())) {
  974. auto *UsingInst = cast<Instruction>(U.getUser());
  975. if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
  976. // Use is on an EH pad phi. Leave it alone; we'll insert loads and
  977. // stores for it separately.
  978. continue;
  979. }
  980. replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
  981. }
  982. return SpillSlot;
  983. }
  984. // TODO: improve store placement. Inserting at def is probably good, but need
  985. // to be careful not to introduce interfering stores (needs liveness analysis).
  986. // TODO: identify related phi nodes that can share spill slots, and share them
  987. // (also needs liveness).
  988. void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
  989. AllocaInst *SpillSlot) {
  990. // Use a worklist of (Block, Value) pairs -- the given Value needs to be
  991. // stored to the spill slot by the end of the given Block.
  992. SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
  993. Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
  994. while (!Worklist.empty()) {
  995. BasicBlock *EHBlock;
  996. Value *InVal;
  997. std::tie(EHBlock, InVal) = Worklist.pop_back_val();
  998. PHINode *PN = dyn_cast<PHINode>(InVal);
  999. if (PN && PN->getParent() == EHBlock) {
  1000. // The value is defined by another PHI we need to remove, with no room to
  1001. // insert a store after the PHI, so each predecessor needs to store its
  1002. // incoming value.
  1003. for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
  1004. Value *PredVal = PN->getIncomingValue(i);
  1005. // Undef can safely be skipped.
  1006. if (isa<UndefValue>(PredVal))
  1007. continue;
  1008. insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
  1009. }
  1010. } else {
  1011. // We need to store InVal, which dominates EHBlock, but can't put a store
  1012. // in EHBlock, so need to put stores in each predecessor.
  1013. for (BasicBlock *PredBlock : predecessors(EHBlock)) {
  1014. insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
  1015. }
  1016. }
  1017. }
  1018. }
  1019. void WinEHPrepare::insertPHIStore(
  1020. BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
  1021. SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
  1022. if (PredBlock->isEHPad() && PredBlock->getFirstNonPHI()->isTerminator()) {
  1023. // Pred is unsplittable, so we need to queue it on the worklist.
  1024. Worklist.push_back({PredBlock, PredVal});
  1025. return;
  1026. }
  1027. // Otherwise, insert the store at the end of the basic block.
  1028. new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
  1029. }
  1030. void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
  1031. DenseMap<BasicBlock *, Value *> &Loads,
  1032. Function &F) {
  1033. // Lazilly create the spill slot.
  1034. if (!SpillSlot)
  1035. SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
  1036. Twine(V->getName(), ".wineh.spillslot"),
  1037. &F.getEntryBlock().front());
  1038. auto *UsingInst = cast<Instruction>(U.getUser());
  1039. if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
  1040. // If this is a PHI node, we can't insert a load of the value before
  1041. // the use. Instead insert the load in the predecessor block
  1042. // corresponding to the incoming value.
  1043. //
  1044. // Note that if there are multiple edges from a basic block to this
  1045. // PHI node that we cannot have multiple loads. The problem is that
  1046. // the resulting PHI node will have multiple values (from each load)
  1047. // coming in from the same block, which is illegal SSA form.
  1048. // For this reason, we keep track of and reuse loads we insert.
  1049. BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
  1050. if (auto *CatchRet =
  1051. dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
  1052. // Putting a load above a catchret and use on the phi would still leave
  1053. // a cross-funclet def/use. We need to split the edge, change the
  1054. // catchret to target the new block, and put the load there.
  1055. BasicBlock *PHIBlock = UsingInst->getParent();
  1056. BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
  1057. // SplitEdge gives us:
  1058. // IncomingBlock:
  1059. // ...
  1060. // br label %NewBlock
  1061. // NewBlock:
  1062. // catchret label %PHIBlock
  1063. // But we need:
  1064. // IncomingBlock:
  1065. // ...
  1066. // catchret label %NewBlock
  1067. // NewBlock:
  1068. // br label %PHIBlock
  1069. // So move the terminators to each others' blocks and swap their
  1070. // successors.
  1071. BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
  1072. Goto->removeFromParent();
  1073. CatchRet->removeFromParent();
  1074. IncomingBlock->getInstList().push_back(CatchRet);
  1075. NewBlock->getInstList().push_back(Goto);
  1076. Goto->setSuccessor(0, PHIBlock);
  1077. CatchRet->setSuccessor(NewBlock);
  1078. // Update the color mapping for the newly split edge.
  1079. // Grab a reference to the ColorVector to be inserted before getting the
  1080. // reference to the vector we are copying because inserting the new
  1081. // element in BlockColors might cause the map to be reallocated.
  1082. ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
  1083. ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
  1084. ColorsForNewBlock = ColorsForPHIBlock;
  1085. for (BasicBlock *FuncletPad : ColorsForPHIBlock)
  1086. FuncletBlocks[FuncletPad].push_back(NewBlock);
  1087. // Treat the new block as incoming for load insertion.
  1088. IncomingBlock = NewBlock;
  1089. }
  1090. Value *&Load = Loads[IncomingBlock];
  1091. // Insert the load into the predecessor block
  1092. if (!Load)
  1093. Load = new LoadInst(V->getType(), SpillSlot,
  1094. Twine(V->getName(), ".wineh.reload"),
  1095. /*isVolatile=*/false, IncomingBlock->getTerminator());
  1096. U.set(Load);
  1097. } else {
  1098. // Reload right before the old use.
  1099. auto *Load = new LoadInst(V->getType(), SpillSlot,
  1100. Twine(V->getName(), ".wineh.reload"),
  1101. /*isVolatile=*/false, UsingInst);
  1102. U.set(Load);
  1103. }
  1104. }
  1105. void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
  1106. MCSymbol *InvokeBegin,
  1107. MCSymbol *InvokeEnd) {
  1108. assert(InvokeStateMap.count(II) &&
  1109. "should get invoke with precomputed state");
  1110. LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
  1111. }
  1112. WinEHFuncInfo::WinEHFuncInfo() {}