WebAssemblyRegStackify.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
  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. /// \file
  10. /// This file implements a register stacking pass.
  11. ///
  12. /// This pass reorders instructions to put register uses and defs in an order
  13. /// such that they form single-use expression trees. Registers fitting this form
  14. /// are then marked as "stackified", meaning references to them are replaced by
  15. /// "push" and "pop" from the value stack.
  16. ///
  17. /// This is primarily a code size optimization, since temporary values on the
  18. /// value stack don't need to be named.
  19. ///
  20. //===----------------------------------------------------------------------===//
  21. #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
  22. #include "Utils/WebAssemblyUtilities.h"
  23. #include "WebAssembly.h"
  24. #include "WebAssemblyDebugValueManager.h"
  25. #include "WebAssemblyMachineFunctionInfo.h"
  26. #include "WebAssemblySubtarget.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/CodeGen/LiveIntervals.h"
  30. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  31. #include "llvm/CodeGen/MachineDominators.h"
  32. #include "llvm/CodeGen/MachineInstrBuilder.h"
  33. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  34. #include "llvm/CodeGen/MachineRegisterInfo.h"
  35. #include "llvm/CodeGen/Passes.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <iterator>
  39. using namespace llvm;
  40. #define DEBUG_TYPE "wasm-reg-stackify"
  41. namespace {
  42. class WebAssemblyRegStackify final : public MachineFunctionPass {
  43. StringRef getPassName() const override {
  44. return "WebAssembly Register Stackify";
  45. }
  46. void getAnalysisUsage(AnalysisUsage &AU) const override {
  47. AU.setPreservesCFG();
  48. AU.addRequired<MachineDominatorTree>();
  49. AU.addRequired<LiveIntervals>();
  50. AU.addPreserved<MachineBlockFrequencyInfo>();
  51. AU.addPreserved<SlotIndexes>();
  52. AU.addPreserved<LiveIntervals>();
  53. AU.addPreservedID(LiveVariablesID);
  54. AU.addPreserved<MachineDominatorTree>();
  55. MachineFunctionPass::getAnalysisUsage(AU);
  56. }
  57. bool runOnMachineFunction(MachineFunction &MF) override;
  58. public:
  59. static char ID; // Pass identification, replacement for typeid
  60. WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
  61. };
  62. } // end anonymous namespace
  63. char WebAssemblyRegStackify::ID = 0;
  64. INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
  65. "Reorder instructions to use the WebAssembly value stack",
  66. false, false)
  67. FunctionPass *llvm::createWebAssemblyRegStackify() {
  68. return new WebAssemblyRegStackify();
  69. }
  70. // Decorate the given instruction with implicit operands that enforce the
  71. // expression stack ordering constraints for an instruction which is on
  72. // the expression stack.
  73. static void imposeStackOrdering(MachineInstr *MI) {
  74. // Write the opaque VALUE_STACK register.
  75. if (!MI->definesRegister(WebAssembly::VALUE_STACK))
  76. MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
  77. /*isDef=*/true,
  78. /*isImp=*/true));
  79. // Also read the opaque VALUE_STACK register.
  80. if (!MI->readsRegister(WebAssembly::VALUE_STACK))
  81. MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
  82. /*isDef=*/false,
  83. /*isImp=*/true));
  84. }
  85. // Convert an IMPLICIT_DEF instruction into an instruction which defines
  86. // a constant zero value.
  87. static void convertImplicitDefToConstZero(MachineInstr *MI,
  88. MachineRegisterInfo &MRI,
  89. const TargetInstrInfo *TII,
  90. MachineFunction &MF,
  91. LiveIntervals &LIS) {
  92. assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
  93. const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
  94. if (RegClass == &WebAssembly::I32RegClass) {
  95. MI->setDesc(TII->get(WebAssembly::CONST_I32));
  96. MI->addOperand(MachineOperand::CreateImm(0));
  97. } else if (RegClass == &WebAssembly::I64RegClass) {
  98. MI->setDesc(TII->get(WebAssembly::CONST_I64));
  99. MI->addOperand(MachineOperand::CreateImm(0));
  100. } else if (RegClass == &WebAssembly::F32RegClass) {
  101. MI->setDesc(TII->get(WebAssembly::CONST_F32));
  102. auto *Val = cast<ConstantFP>(Constant::getNullValue(
  103. Type::getFloatTy(MF.getFunction().getContext())));
  104. MI->addOperand(MachineOperand::CreateFPImm(Val));
  105. } else if (RegClass == &WebAssembly::F64RegClass) {
  106. MI->setDesc(TII->get(WebAssembly::CONST_F64));
  107. auto *Val = cast<ConstantFP>(Constant::getNullValue(
  108. Type::getDoubleTy(MF.getFunction().getContext())));
  109. MI->addOperand(MachineOperand::CreateFPImm(Val));
  110. } else if (RegClass == &WebAssembly::V128RegClass) {
  111. MI->setDesc(TII->get(WebAssembly::CONST_V128_I64x2));
  112. MI->addOperand(MachineOperand::CreateImm(0));
  113. MI->addOperand(MachineOperand::CreateImm(0));
  114. } else {
  115. llvm_unreachable("Unexpected reg class");
  116. }
  117. }
  118. // Determine whether a call to the callee referenced by
  119. // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
  120. // effects.
  121. static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write,
  122. bool &Effects, bool &StackPointer) {
  123. // All calls can use the stack pointer.
  124. StackPointer = true;
  125. const MachineOperand &MO = WebAssembly::getCalleeOp(MI);
  126. if (MO.isGlobal()) {
  127. const Constant *GV = MO.getGlobal();
  128. if (const auto *GA = dyn_cast<GlobalAlias>(GV))
  129. if (!GA->isInterposable())
  130. GV = GA->getAliasee();
  131. if (const auto *F = dyn_cast<Function>(GV)) {
  132. if (!F->doesNotThrow())
  133. Effects = true;
  134. if (F->doesNotAccessMemory())
  135. return;
  136. if (F->onlyReadsMemory()) {
  137. Read = true;
  138. return;
  139. }
  140. }
  141. }
  142. // Assume the worst.
  143. Write = true;
  144. Read = true;
  145. Effects = true;
  146. }
  147. // Determine whether MI reads memory, writes memory, has side effects,
  148. // and/or uses the stack pointer value.
  149. static void query(const MachineInstr &MI, bool &Read, bool &Write,
  150. bool &Effects, bool &StackPointer) {
  151. assert(!MI.isTerminator());
  152. if (MI.isDebugInstr() || MI.isPosition())
  153. return;
  154. // Check for loads.
  155. if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
  156. Read = true;
  157. // Check for stores.
  158. if (MI.mayStore()) {
  159. Write = true;
  160. } else if (MI.hasOrderedMemoryRef()) {
  161. switch (MI.getOpcode()) {
  162. case WebAssembly::DIV_S_I32:
  163. case WebAssembly::DIV_S_I64:
  164. case WebAssembly::REM_S_I32:
  165. case WebAssembly::REM_S_I64:
  166. case WebAssembly::DIV_U_I32:
  167. case WebAssembly::DIV_U_I64:
  168. case WebAssembly::REM_U_I32:
  169. case WebAssembly::REM_U_I64:
  170. case WebAssembly::I32_TRUNC_S_F32:
  171. case WebAssembly::I64_TRUNC_S_F32:
  172. case WebAssembly::I32_TRUNC_S_F64:
  173. case WebAssembly::I64_TRUNC_S_F64:
  174. case WebAssembly::I32_TRUNC_U_F32:
  175. case WebAssembly::I64_TRUNC_U_F32:
  176. case WebAssembly::I32_TRUNC_U_F64:
  177. case WebAssembly::I64_TRUNC_U_F64:
  178. // These instruction have hasUnmodeledSideEffects() returning true
  179. // because they trap on overflow and invalid so they can't be arbitrarily
  180. // moved, however hasOrderedMemoryRef() interprets this plus their lack
  181. // of memoperands as having a potential unknown memory reference.
  182. break;
  183. default:
  184. // Record volatile accesses, unless it's a call, as calls are handled
  185. // specially below.
  186. if (!MI.isCall()) {
  187. Write = true;
  188. Effects = true;
  189. }
  190. break;
  191. }
  192. }
  193. // Check for side effects.
  194. if (MI.hasUnmodeledSideEffects()) {
  195. switch (MI.getOpcode()) {
  196. case WebAssembly::DIV_S_I32:
  197. case WebAssembly::DIV_S_I64:
  198. case WebAssembly::REM_S_I32:
  199. case WebAssembly::REM_S_I64:
  200. case WebAssembly::DIV_U_I32:
  201. case WebAssembly::DIV_U_I64:
  202. case WebAssembly::REM_U_I32:
  203. case WebAssembly::REM_U_I64:
  204. case WebAssembly::I32_TRUNC_S_F32:
  205. case WebAssembly::I64_TRUNC_S_F32:
  206. case WebAssembly::I32_TRUNC_S_F64:
  207. case WebAssembly::I64_TRUNC_S_F64:
  208. case WebAssembly::I32_TRUNC_U_F32:
  209. case WebAssembly::I64_TRUNC_U_F32:
  210. case WebAssembly::I32_TRUNC_U_F64:
  211. case WebAssembly::I64_TRUNC_U_F64:
  212. // These instructions have hasUnmodeledSideEffects() returning true
  213. // because they trap on overflow and invalid so they can't be arbitrarily
  214. // moved, however in the specific case of register stackifying, it is safe
  215. // to move them because overflow and invalid are Undefined Behavior.
  216. break;
  217. default:
  218. Effects = true;
  219. break;
  220. }
  221. }
  222. // Check for writes to __stack_pointer global.
  223. if ((MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 ||
  224. MI.getOpcode() == WebAssembly::GLOBAL_SET_I64) &&
  225. strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
  226. StackPointer = true;
  227. // Analyze calls.
  228. if (MI.isCall()) {
  229. queryCallee(MI, Read, Write, Effects, StackPointer);
  230. }
  231. }
  232. // Test whether Def is safe and profitable to rematerialize.
  233. static bool shouldRematerialize(const MachineInstr &Def,
  234. const WebAssemblyInstrInfo *TII) {
  235. return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def);
  236. }
  237. // Identify the definition for this register at this point. This is a
  238. // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
  239. // LiveIntervals to handle complex cases.
  240. static MachineInstr *getVRegDef(unsigned Reg, const MachineInstr *Insert,
  241. const MachineRegisterInfo &MRI,
  242. const LiveIntervals &LIS) {
  243. // Most registers are in SSA form here so we try a quick MRI query first.
  244. if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
  245. return Def;
  246. // MRI doesn't know what the Def is. Try asking LIS.
  247. if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
  248. LIS.getInstructionIndex(*Insert)))
  249. return LIS.getInstructionFromIndex(ValNo->def);
  250. return nullptr;
  251. }
  252. // Test whether Reg, as defined at Def, has exactly one use. This is a
  253. // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
  254. // to handle complex cases.
  255. static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
  256. MachineDominatorTree &MDT, LiveIntervals &LIS) {
  257. // Most registers are in SSA form here so we try a quick MRI query first.
  258. if (MRI.hasOneUse(Reg))
  259. return true;
  260. bool HasOne = false;
  261. const LiveInterval &LI = LIS.getInterval(Reg);
  262. const VNInfo *DefVNI =
  263. LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
  264. assert(DefVNI);
  265. for (auto &I : MRI.use_nodbg_operands(Reg)) {
  266. const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
  267. if (Result.valueIn() == DefVNI) {
  268. if (!Result.isKill())
  269. return false;
  270. if (HasOne)
  271. return false;
  272. HasOne = true;
  273. }
  274. }
  275. return HasOne;
  276. }
  277. // Test whether it's safe to move Def to just before Insert.
  278. // TODO: Compute memory dependencies in a way that doesn't require always
  279. // walking the block.
  280. // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
  281. // more precise.
  282. static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use,
  283. const MachineInstr *Insert,
  284. const WebAssemblyFunctionInfo &MFI,
  285. const MachineRegisterInfo &MRI) {
  286. const MachineInstr *DefI = Def->getParent();
  287. const MachineInstr *UseI = Use->getParent();
  288. assert(DefI->getParent() == Insert->getParent());
  289. assert(UseI->getParent() == Insert->getParent());
  290. // The first def of a multivalue instruction can be stackified by moving,
  291. // since the later defs can always be placed into locals if necessary. Later
  292. // defs can only be stackified if all previous defs are already stackified
  293. // since ExplicitLocals will not know how to place a def in a local if a
  294. // subsequent def is stackified. But only one def can be stackified by moving
  295. // the instruction, so it must be the first one.
  296. //
  297. // TODO: This could be loosened to be the first *live* def, but care would
  298. // have to be taken to ensure the drops of the initial dead defs can be
  299. // placed. This would require checking that no previous defs are used in the
  300. // same instruction as subsequent defs.
  301. if (Def != DefI->defs().begin())
  302. return false;
  303. // If any subsequent def is used prior to the current value by the same
  304. // instruction in which the current value is used, we cannot
  305. // stackify. Stackifying in this case would require that def moving below the
  306. // current def in the stack, which cannot be achieved, even with locals.
  307. // Also ensure we don't sink the def past any other prior uses.
  308. for (const auto &SubsequentDef : drop_begin(DefI->defs())) {
  309. auto I = std::next(MachineBasicBlock::const_iterator(DefI));
  310. auto E = std::next(MachineBasicBlock::const_iterator(UseI));
  311. for (; I != E; ++I) {
  312. for (const auto &PriorUse : I->uses()) {
  313. if (&PriorUse == Use)
  314. break;
  315. if (PriorUse.isReg() && SubsequentDef.getReg() == PriorUse.getReg())
  316. return false;
  317. }
  318. }
  319. }
  320. // If moving is a semantic nop, it is always allowed
  321. const MachineBasicBlock *MBB = DefI->getParent();
  322. auto NextI = std::next(MachineBasicBlock::const_iterator(DefI));
  323. for (auto E = MBB->end(); NextI != E && NextI->isDebugInstr(); ++NextI)
  324. ;
  325. if (NextI == Insert)
  326. return true;
  327. // 'catch' and 'catch_all' should be the first instruction of a BB and cannot
  328. // move.
  329. if (WebAssembly::isCatch(DefI->getOpcode()))
  330. return false;
  331. // Check for register dependencies.
  332. SmallVector<unsigned, 4> MutableRegisters;
  333. for (const MachineOperand &MO : DefI->operands()) {
  334. if (!MO.isReg() || MO.isUndef())
  335. continue;
  336. Register Reg = MO.getReg();
  337. // If the register is dead here and at Insert, ignore it.
  338. if (MO.isDead() && Insert->definesRegister(Reg) &&
  339. !Insert->readsRegister(Reg))
  340. continue;
  341. if (Reg.isPhysical()) {
  342. // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
  343. // from moving down, and we've already checked for that.
  344. if (Reg == WebAssembly::ARGUMENTS)
  345. continue;
  346. // If the physical register is never modified, ignore it.
  347. if (!MRI.isPhysRegModified(Reg))
  348. continue;
  349. // Otherwise, it's a physical register with unknown liveness.
  350. return false;
  351. }
  352. // If one of the operands isn't in SSA form, it has different values at
  353. // different times, and we need to make sure we don't move our use across
  354. // a different def.
  355. if (!MO.isDef() && !MRI.hasOneDef(Reg))
  356. MutableRegisters.push_back(Reg);
  357. }
  358. bool Read = false, Write = false, Effects = false, StackPointer = false;
  359. query(*DefI, Read, Write, Effects, StackPointer);
  360. // If the instruction does not access memory and has no side effects, it has
  361. // no additional dependencies.
  362. bool HasMutableRegisters = !MutableRegisters.empty();
  363. if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
  364. return true;
  365. // Scan through the intervening instructions between DefI and Insert.
  366. MachineBasicBlock::const_iterator D(DefI), I(Insert);
  367. for (--I; I != D; --I) {
  368. bool InterveningRead = false;
  369. bool InterveningWrite = false;
  370. bool InterveningEffects = false;
  371. bool InterveningStackPointer = false;
  372. query(*I, InterveningRead, InterveningWrite, InterveningEffects,
  373. InterveningStackPointer);
  374. if (Effects && InterveningEffects)
  375. return false;
  376. if (Read && InterveningWrite)
  377. return false;
  378. if (Write && (InterveningRead || InterveningWrite))
  379. return false;
  380. if (StackPointer && InterveningStackPointer)
  381. return false;
  382. for (unsigned Reg : MutableRegisters)
  383. for (const MachineOperand &MO : I->operands())
  384. if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
  385. return false;
  386. }
  387. return true;
  388. }
  389. /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
  390. static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
  391. const MachineBasicBlock &MBB,
  392. const MachineRegisterInfo &MRI,
  393. const MachineDominatorTree &MDT,
  394. LiveIntervals &LIS,
  395. WebAssemblyFunctionInfo &MFI) {
  396. const LiveInterval &LI = LIS.getInterval(Reg);
  397. const MachineInstr *OneUseInst = OneUse.getParent();
  398. VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
  399. for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
  400. if (&Use == &OneUse)
  401. continue;
  402. const MachineInstr *UseInst = Use.getParent();
  403. VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
  404. if (UseVNI != OneUseVNI)
  405. continue;
  406. if (UseInst == OneUseInst) {
  407. // Another use in the same instruction. We need to ensure that the one
  408. // selected use happens "before" it.
  409. if (&OneUse > &Use)
  410. return false;
  411. } else {
  412. // Test that the use is dominated by the one selected use.
  413. while (!MDT.dominates(OneUseInst, UseInst)) {
  414. // Actually, dominating is over-conservative. Test that the use would
  415. // happen after the one selected use in the stack evaluation order.
  416. //
  417. // This is needed as a consequence of using implicit local.gets for
  418. // uses and implicit local.sets for defs.
  419. if (UseInst->getDesc().getNumDefs() == 0)
  420. return false;
  421. const MachineOperand &MO = UseInst->getOperand(0);
  422. if (!MO.isReg())
  423. return false;
  424. Register DefReg = MO.getReg();
  425. if (!DefReg.isVirtual() || !MFI.isVRegStackified(DefReg))
  426. return false;
  427. assert(MRI.hasOneNonDBGUse(DefReg));
  428. const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
  429. const MachineInstr *NewUseInst = NewUse.getParent();
  430. if (NewUseInst == OneUseInst) {
  431. if (&OneUse > &NewUse)
  432. return false;
  433. break;
  434. }
  435. UseInst = NewUseInst;
  436. }
  437. }
  438. }
  439. return true;
  440. }
  441. /// Get the appropriate tee opcode for the given register class.
  442. static unsigned getTeeOpcode(const TargetRegisterClass *RC) {
  443. if (RC == &WebAssembly::I32RegClass)
  444. return WebAssembly::TEE_I32;
  445. if (RC == &WebAssembly::I64RegClass)
  446. return WebAssembly::TEE_I64;
  447. if (RC == &WebAssembly::F32RegClass)
  448. return WebAssembly::TEE_F32;
  449. if (RC == &WebAssembly::F64RegClass)
  450. return WebAssembly::TEE_F64;
  451. if (RC == &WebAssembly::V128RegClass)
  452. return WebAssembly::TEE_V128;
  453. if (RC == &WebAssembly::EXTERNREFRegClass)
  454. return WebAssembly::TEE_EXTERNREF;
  455. if (RC == &WebAssembly::FUNCREFRegClass)
  456. return WebAssembly::TEE_FUNCREF;
  457. llvm_unreachable("Unexpected register class");
  458. }
  459. // Shrink LI to its uses, cleaning up LI.
  460. static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
  461. if (LIS.shrinkToUses(&LI)) {
  462. SmallVector<LiveInterval *, 4> SplitLIs;
  463. LIS.splitSeparateComponents(LI, SplitLIs);
  464. }
  465. }
  466. /// A single-use def in the same block with no intervening memory or register
  467. /// dependencies; move the def down and nest it with the current instruction.
  468. static MachineInstr *moveForSingleUse(unsigned Reg, MachineOperand &Op,
  469. MachineInstr *Def, MachineBasicBlock &MBB,
  470. MachineInstr *Insert, LiveIntervals &LIS,
  471. WebAssemblyFunctionInfo &MFI,
  472. MachineRegisterInfo &MRI) {
  473. LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
  474. WebAssemblyDebugValueManager DefDIs(Def);
  475. MBB.splice(Insert, &MBB, Def);
  476. DefDIs.move(Insert);
  477. LIS.handleMove(*Def);
  478. if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
  479. // No one else is using this register for anything so we can just stackify
  480. // it in place.
  481. MFI.stackifyVReg(MRI, Reg);
  482. } else {
  483. // The register may have unrelated uses or defs; create a new register for
  484. // just our one def and use so that we can stackify it.
  485. Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
  486. Def->getOperand(0).setReg(NewReg);
  487. Op.setReg(NewReg);
  488. // Tell LiveIntervals about the new register.
  489. LIS.createAndComputeVirtRegInterval(NewReg);
  490. // Tell LiveIntervals about the changes to the old register.
  491. LiveInterval &LI = LIS.getInterval(Reg);
  492. LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
  493. LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
  494. /*RemoveDeadValNo=*/true);
  495. MFI.stackifyVReg(MRI, NewReg);
  496. DefDIs.updateReg(NewReg);
  497. LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
  498. }
  499. imposeStackOrdering(Def);
  500. return Def;
  501. }
  502. /// A trivially cloneable instruction; clone it and nest the new copy with the
  503. /// current instruction.
  504. static MachineInstr *rematerializeCheapDef(
  505. unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
  506. MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
  507. WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
  508. const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
  509. LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
  510. LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
  511. WebAssemblyDebugValueManager DefDIs(&Def);
  512. Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
  513. TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
  514. Op.setReg(NewReg);
  515. MachineInstr *Clone = &*std::prev(Insert);
  516. LIS.InsertMachineInstrInMaps(*Clone);
  517. LIS.createAndComputeVirtRegInterval(NewReg);
  518. MFI.stackifyVReg(MRI, NewReg);
  519. imposeStackOrdering(Clone);
  520. LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
  521. // Shrink the interval.
  522. bool IsDead = MRI.use_empty(Reg);
  523. if (!IsDead) {
  524. LiveInterval &LI = LIS.getInterval(Reg);
  525. shrinkToUses(LI, LIS);
  526. IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
  527. }
  528. // If that was the last use of the original, delete the original.
  529. // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
  530. if (IsDead) {
  531. LLVM_DEBUG(dbgs() << " - Deleting original\n");
  532. SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
  533. LIS.removePhysRegDefAt(MCRegister::from(WebAssembly::ARGUMENTS), Idx);
  534. LIS.removeInterval(Reg);
  535. LIS.RemoveMachineInstrFromMaps(Def);
  536. Def.eraseFromParent();
  537. DefDIs.move(&*Insert);
  538. DefDIs.updateReg(NewReg);
  539. } else {
  540. DefDIs.clone(&*Insert, NewReg);
  541. }
  542. return Clone;
  543. }
  544. /// A multiple-use def in the same block with no intervening memory or register
  545. /// dependencies; move the def down, nest it with the current instruction, and
  546. /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
  547. /// this:
  548. ///
  549. /// Reg = INST ... // Def
  550. /// INST ..., Reg, ... // Insert
  551. /// INST ..., Reg, ...
  552. /// INST ..., Reg, ...
  553. ///
  554. /// to this:
  555. ///
  556. /// DefReg = INST ... // Def (to become the new Insert)
  557. /// TeeReg, Reg = TEE_... DefReg
  558. /// INST ..., TeeReg, ... // Insert
  559. /// INST ..., Reg, ...
  560. /// INST ..., Reg, ...
  561. ///
  562. /// with DefReg and TeeReg stackified. This eliminates a local.get from the
  563. /// resulting code.
  564. static MachineInstr *moveAndTeeForMultiUse(
  565. unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
  566. MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
  567. MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
  568. LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
  569. WebAssemblyDebugValueManager DefDIs(Def);
  570. // Move Def into place.
  571. MBB.splice(Insert, &MBB, Def);
  572. LIS.handleMove(*Def);
  573. // Create the Tee and attach the registers.
  574. const auto *RegClass = MRI.getRegClass(Reg);
  575. Register TeeReg = MRI.createVirtualRegister(RegClass);
  576. Register DefReg = MRI.createVirtualRegister(RegClass);
  577. MachineOperand &DefMO = Def->getOperand(0);
  578. MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
  579. TII->get(getTeeOpcode(RegClass)), TeeReg)
  580. .addReg(Reg, RegState::Define)
  581. .addReg(DefReg, getUndefRegState(DefMO.isDead()));
  582. Op.setReg(TeeReg);
  583. DefMO.setReg(DefReg);
  584. SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
  585. SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
  586. DefDIs.move(Insert);
  587. // Tell LiveIntervals we moved the original vreg def from Def to Tee.
  588. LiveInterval &LI = LIS.getInterval(Reg);
  589. LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
  590. VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
  591. I->start = TeeIdx;
  592. ValNo->def = TeeIdx;
  593. shrinkToUses(LI, LIS);
  594. // Finish stackifying the new regs.
  595. LIS.createAndComputeVirtRegInterval(TeeReg);
  596. LIS.createAndComputeVirtRegInterval(DefReg);
  597. MFI.stackifyVReg(MRI, DefReg);
  598. MFI.stackifyVReg(MRI, TeeReg);
  599. imposeStackOrdering(Def);
  600. imposeStackOrdering(Tee);
  601. DefDIs.clone(Tee, DefReg);
  602. DefDIs.clone(Insert, TeeReg);
  603. LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
  604. LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
  605. return Def;
  606. }
  607. namespace {
  608. /// A stack for walking the tree of instructions being built, visiting the
  609. /// MachineOperands in DFS order.
  610. class TreeWalkerState {
  611. using mop_iterator = MachineInstr::mop_iterator;
  612. using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
  613. using RangeTy = iterator_range<mop_reverse_iterator>;
  614. SmallVector<RangeTy, 4> Worklist;
  615. public:
  616. explicit TreeWalkerState(MachineInstr *Insert) {
  617. const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
  618. if (!Range.empty())
  619. Worklist.push_back(reverse(Range));
  620. }
  621. bool done() const { return Worklist.empty(); }
  622. MachineOperand &pop() {
  623. RangeTy &Range = Worklist.back();
  624. MachineOperand &Op = *Range.begin();
  625. Range = drop_begin(Range);
  626. if (Range.empty())
  627. Worklist.pop_back();
  628. assert((Worklist.empty() || !Worklist.back().empty()) &&
  629. "Empty ranges shouldn't remain in the worklist");
  630. return Op;
  631. }
  632. /// Push Instr's operands onto the stack to be visited.
  633. void pushOperands(MachineInstr *Instr) {
  634. const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
  635. if (!Range.empty())
  636. Worklist.push_back(reverse(Range));
  637. }
  638. /// Some of Instr's operands are on the top of the stack; remove them and
  639. /// re-insert them starting from the beginning (because we've commuted them).
  640. void resetTopOperands(MachineInstr *Instr) {
  641. assert(hasRemainingOperands(Instr) &&
  642. "Reseting operands should only be done when the instruction has "
  643. "an operand still on the stack");
  644. Worklist.back() = reverse(Instr->explicit_uses());
  645. }
  646. /// Test whether Instr has operands remaining to be visited at the top of
  647. /// the stack.
  648. bool hasRemainingOperands(const MachineInstr *Instr) const {
  649. if (Worklist.empty())
  650. return false;
  651. const RangeTy &Range = Worklist.back();
  652. return !Range.empty() && Range.begin()->getParent() == Instr;
  653. }
  654. /// Test whether the given register is present on the stack, indicating an
  655. /// operand in the tree that we haven't visited yet. Moving a definition of
  656. /// Reg to a point in the tree after that would change its value.
  657. ///
  658. /// This is needed as a consequence of using implicit local.gets for
  659. /// uses and implicit local.sets for defs.
  660. bool isOnStack(unsigned Reg) const {
  661. for (const RangeTy &Range : Worklist)
  662. for (const MachineOperand &MO : Range)
  663. if (MO.isReg() && MO.getReg() == Reg)
  664. return true;
  665. return false;
  666. }
  667. };
  668. /// State to keep track of whether commuting is in flight or whether it's been
  669. /// tried for the current instruction and didn't work.
  670. class CommutingState {
  671. /// There are effectively three states: the initial state where we haven't
  672. /// started commuting anything and we don't know anything yet, the tentative
  673. /// state where we've commuted the operands of the current instruction and are
  674. /// revisiting it, and the declined state where we've reverted the operands
  675. /// back to their original order and will no longer commute it further.
  676. bool TentativelyCommuting = false;
  677. bool Declined = false;
  678. /// During the tentative state, these hold the operand indices of the commuted
  679. /// operands.
  680. unsigned Operand0, Operand1;
  681. public:
  682. /// Stackification for an operand was not successful due to ordering
  683. /// constraints. If possible, and if we haven't already tried it and declined
  684. /// it, commute Insert's operands and prepare to revisit it.
  685. void maybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
  686. const WebAssemblyInstrInfo *TII) {
  687. if (TentativelyCommuting) {
  688. assert(!Declined &&
  689. "Don't decline commuting until you've finished trying it");
  690. // Commuting didn't help. Revert it.
  691. TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
  692. TentativelyCommuting = false;
  693. Declined = true;
  694. } else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
  695. Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
  696. Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
  697. if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
  698. // Tentatively commute the operands and try again.
  699. TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
  700. TreeWalker.resetTopOperands(Insert);
  701. TentativelyCommuting = true;
  702. Declined = false;
  703. }
  704. }
  705. }
  706. /// Stackification for some operand was successful. Reset to the default
  707. /// state.
  708. void reset() {
  709. TentativelyCommuting = false;
  710. Declined = false;
  711. }
  712. };
  713. } // end anonymous namespace
  714. bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
  715. LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
  716. "********** Function: "
  717. << MF.getName() << '\n');
  718. bool Changed = false;
  719. MachineRegisterInfo &MRI = MF.getRegInfo();
  720. WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
  721. const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
  722. const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
  723. auto &MDT = getAnalysis<MachineDominatorTree>();
  724. auto &LIS = getAnalysis<LiveIntervals>();
  725. // Walk the instructions from the bottom up. Currently we don't look past
  726. // block boundaries, and the blocks aren't ordered so the block visitation
  727. // order isn't significant, but we may want to change this in the future.
  728. for (MachineBasicBlock &MBB : MF) {
  729. // Don't use a range-based for loop, because we modify the list as we're
  730. // iterating over it and the end iterator may change.
  731. for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
  732. MachineInstr *Insert = &*MII;
  733. // Don't nest anything inside an inline asm, because we don't have
  734. // constraints for $push inputs.
  735. if (Insert->isInlineAsm())
  736. continue;
  737. // Ignore debugging intrinsics.
  738. if (Insert->isDebugValue())
  739. continue;
  740. // Iterate through the inputs in reverse order, since we'll be pulling
  741. // operands off the stack in LIFO order.
  742. CommutingState Commuting;
  743. TreeWalkerState TreeWalker(Insert);
  744. while (!TreeWalker.done()) {
  745. MachineOperand &Use = TreeWalker.pop();
  746. // We're only interested in explicit virtual register operands.
  747. if (!Use.isReg())
  748. continue;
  749. Register Reg = Use.getReg();
  750. assert(Use.isUse() && "explicit_uses() should only iterate over uses");
  751. assert(!Use.isImplicit() &&
  752. "explicit_uses() should only iterate over explicit operands");
  753. if (Reg.isPhysical())
  754. continue;
  755. // Identify the definition for this register at this point.
  756. MachineInstr *DefI = getVRegDef(Reg, Insert, MRI, LIS);
  757. if (!DefI)
  758. continue;
  759. // Don't nest an INLINE_ASM def into anything, because we don't have
  760. // constraints for $pop outputs.
  761. if (DefI->isInlineAsm())
  762. continue;
  763. // Argument instructions represent live-in registers and not real
  764. // instructions.
  765. if (WebAssembly::isArgument(DefI->getOpcode()))
  766. continue;
  767. MachineOperand *Def = DefI->findRegisterDefOperand(Reg);
  768. assert(Def != nullptr);
  769. // Decide which strategy to take. Prefer to move a single-use value
  770. // over cloning it, and prefer cloning over introducing a tee.
  771. // For moving, we require the def to be in the same block as the use;
  772. // this makes things simpler (LiveIntervals' handleMove function only
  773. // supports intra-block moves) and it's MachineSink's job to catch all
  774. // the sinking opportunities anyway.
  775. bool SameBlock = DefI->getParent() == &MBB;
  776. bool CanMove = SameBlock && isSafeToMove(Def, &Use, Insert, MFI, MRI) &&
  777. !TreeWalker.isOnStack(Reg);
  778. if (CanMove && hasOneUse(Reg, DefI, MRI, MDT, LIS)) {
  779. Insert = moveForSingleUse(Reg, Use, DefI, MBB, Insert, LIS, MFI, MRI);
  780. // If we are removing the frame base reg completely, remove the debug
  781. // info as well.
  782. // TODO: Encode this properly as a stackified value.
  783. if (MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Reg)
  784. MFI.clearFrameBaseVreg();
  785. } else if (shouldRematerialize(*DefI, TII)) {
  786. Insert =
  787. rematerializeCheapDef(Reg, Use, *DefI, MBB, Insert->getIterator(),
  788. LIS, MFI, MRI, TII, TRI);
  789. } else if (CanMove && oneUseDominatesOtherUses(Reg, Use, MBB, MRI, MDT,
  790. LIS, MFI)) {
  791. Insert = moveAndTeeForMultiUse(Reg, Use, DefI, MBB, Insert, LIS, MFI,
  792. MRI, TII);
  793. } else {
  794. // We failed to stackify the operand. If the problem was ordering
  795. // constraints, Commuting may be able to help.
  796. if (!CanMove && SameBlock)
  797. Commuting.maybeCommute(Insert, TreeWalker, TII);
  798. // Proceed to the next operand.
  799. continue;
  800. }
  801. // Stackifying a multivalue def may unlock in-place stackification of
  802. // subsequent defs. TODO: Handle the case where the consecutive uses are
  803. // not all in the same instruction.
  804. auto *SubsequentDef = Insert->defs().begin();
  805. auto *SubsequentUse = &Use;
  806. while (SubsequentDef != Insert->defs().end() &&
  807. SubsequentUse != Use.getParent()->uses().end()) {
  808. if (!SubsequentDef->isReg() || !SubsequentUse->isReg())
  809. break;
  810. Register DefReg = SubsequentDef->getReg();
  811. Register UseReg = SubsequentUse->getReg();
  812. // TODO: This single-use restriction could be relaxed by using tees
  813. if (DefReg != UseReg || !MRI.hasOneUse(DefReg))
  814. break;
  815. MFI.stackifyVReg(MRI, DefReg);
  816. ++SubsequentDef;
  817. ++SubsequentUse;
  818. }
  819. // If the instruction we just stackified is an IMPLICIT_DEF, convert it
  820. // to a constant 0 so that the def is explicit, and the push/pop
  821. // correspondence is maintained.
  822. if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
  823. convertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
  824. // We stackified an operand. Add the defining instruction's operands to
  825. // the worklist stack now to continue to build an ever deeper tree.
  826. Commuting.reset();
  827. TreeWalker.pushOperands(Insert);
  828. }
  829. // If we stackified any operands, skip over the tree to start looking for
  830. // the next instruction we can build a tree on.
  831. if (Insert != &*MII) {
  832. imposeStackOrdering(&*MII);
  833. MII = MachineBasicBlock::iterator(Insert).getReverse();
  834. Changed = true;
  835. }
  836. }
  837. }
  838. // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
  839. // that it never looks like a use-before-def.
  840. if (Changed) {
  841. MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
  842. for (MachineBasicBlock &MBB : MF)
  843. MBB.addLiveIn(WebAssembly::VALUE_STACK);
  844. }
  845. #ifndef NDEBUG
  846. // Verify that pushes and pops are performed in LIFO order.
  847. SmallVector<unsigned, 0> Stack;
  848. for (MachineBasicBlock &MBB : MF) {
  849. for (MachineInstr &MI : MBB) {
  850. if (MI.isDebugInstr())
  851. continue;
  852. for (MachineOperand &MO : reverse(MI.explicit_uses())) {
  853. if (!MO.isReg())
  854. continue;
  855. Register Reg = MO.getReg();
  856. if (MFI.isVRegStackified(Reg))
  857. assert(Stack.pop_back_val() == Reg &&
  858. "Register stack pop should be paired with a push");
  859. }
  860. for (MachineOperand &MO : MI.defs()) {
  861. if (!MO.isReg())
  862. continue;
  863. Register Reg = MO.getReg();
  864. if (MFI.isVRegStackified(Reg))
  865. Stack.push_back(MO.getReg());
  866. }
  867. }
  868. // TODO: Generalize this code to support keeping values on the stack across
  869. // basic block boundaries.
  870. assert(Stack.empty() &&
  871. "Register stack pushes and pops should be balanced");
  872. }
  873. #endif
  874. return Changed;
  875. }