WinEHPrepare.cpp 50 KB

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