11462faadSDan Gohman //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
21462faadSDan Gohman //
3*2946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*2946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
5*2946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61462faadSDan Gohman //
71462faadSDan Gohman //===----------------------------------------------------------------------===//
81462faadSDan Gohman ///
91462faadSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a register stacking pass.
111462faadSDan Gohman ///
121462faadSDan Gohman /// This pass reorders instructions to put register uses and defs in an order
131462faadSDan Gohman /// such that they form single-use expression trees. Registers fitting this form
141462faadSDan Gohman /// are then marked as "stackified", meaning references to them are replaced by
15e040533eSDan Gohman /// "push" and "pop" from the value stack.
161462faadSDan Gohman ///
1731448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
18e040533eSDan Gohman /// value stack don't need to be named.
191462faadSDan Gohman ///
201462faadSDan Gohman //===----------------------------------------------------------------------===//
211462faadSDan Gohman 
224ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
236bda14b3SChandler Carruth #include "WebAssembly.h"
24be24c020SYury Delendik #include "WebAssemblyDebugValueManager.h"
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
274fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
287c18d608SYury Delendik #include "llvm/ADT/SmallPtrSet.h"
2981719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
30f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
311462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
33adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
3482607f56SDan Gohman #include "llvm/CodeGen/MachineModuleInfoImpls.h"
351462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
361462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
371462faadSDan Gohman #include "llvm/Support/Debug.h"
381462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
391462faadSDan Gohman using namespace llvm;
401462faadSDan Gohman 
411462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
421462faadSDan Gohman 
431462faadSDan Gohman namespace {
441462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
45117296c0SMehdi Amini   StringRef getPassName() const override {
461462faadSDan Gohman     return "WebAssembly Register Stackify";
471462faadSDan Gohman   }
481462faadSDan Gohman 
491462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
501462faadSDan Gohman     AU.setPreservesCFG();
5181719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
52adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
538887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
541462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
558887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
568887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
578887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
58adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
591462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
601462faadSDan Gohman   }
611462faadSDan Gohman 
621462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
631462faadSDan Gohman 
641462faadSDan Gohman public:
651462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
661462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
671462faadSDan Gohman };
681462faadSDan Gohman } // end anonymous namespace
691462faadSDan Gohman 
701462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
7140926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
7240926451SJacob Gravelle                 "Reorder instructions to use the WebAssembly value stack",
7340926451SJacob Gravelle                 false, false)
7440926451SJacob Gravelle 
751462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
761462faadSDan Gohman   return new WebAssemblyRegStackify();
771462faadSDan Gohman }
781462faadSDan Gohman 
79b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
808887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
818887d1faSDan Gohman // the expression stack.
828887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
83e040533eSDan Gohman   // Write the opaque VALUE_STACK register.
84e040533eSDan Gohman   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
86b0992dafSDan Gohman                                              /*isDef=*/true,
87b0992dafSDan Gohman                                              /*isImp=*/true));
884da4abd8SDan Gohman 
89e040533eSDan Gohman   // Also read the opaque VALUE_STACK register.
90e040533eSDan Gohman   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
92b0992dafSDan Gohman                                              /*isDef=*/false,
93b0992dafSDan Gohman                                              /*isImp=*/true));
94b0992dafSDan Gohman }
95b0992dafSDan Gohman 
96e81021a5SDan Gohman // Convert an IMPLICIT_DEF instruction into an instruction which defines
97e81021a5SDan Gohman // a constant zero value.
98e81021a5SDan Gohman static void ConvertImplicitDefToConstZero(MachineInstr *MI,
99e81021a5SDan Gohman                                           MachineRegisterInfo &MRI,
100e81021a5SDan Gohman                                           const TargetInstrInfo *TII,
101feb18fe9SThomas Lively                                           MachineFunction &MF,
102feb18fe9SThomas Lively                                           LiveIntervals &LIS) {
103e81021a5SDan Gohman   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
104e81021a5SDan Gohman 
105f208f631SHeejin Ahn   const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
106e81021a5SDan Gohman   if (RegClass == &WebAssembly::I32RegClass) {
107e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I32));
108e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
109e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::I64RegClass) {
110e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I64));
111e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
112e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F32RegClass) {
113e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F32));
114e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
11521109249SDavid Blaikie         Type::getFloatTy(MF.getFunction().getContext())));
116e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
117e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F64RegClass) {
118e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F64));
119e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
12021109249SDavid Blaikie         Type::getDoubleTy(MF.getFunction().getContext())));
121e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
1226ff31fe3SThomas Lively   } else if (RegClass == &WebAssembly::V128RegClass) {
123feb18fe9SThomas Lively     unsigned TempReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
124feb18fe9SThomas Lively     MI->setDesc(TII->get(WebAssembly::SPLAT_v4i32));
125feb18fe9SThomas Lively     MI->addOperand(MachineOperand::CreateReg(TempReg, false));
126feb18fe9SThomas Lively     MachineInstr *Const = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
127feb18fe9SThomas Lively                                   TII->get(WebAssembly::CONST_I32), TempReg)
128feb18fe9SThomas Lively                               .addImm(0);
129feb18fe9SThomas Lively     LIS.InsertMachineInstrInMaps(*Const);
130e81021a5SDan Gohman   } else {
131e81021a5SDan Gohman     llvm_unreachable("Unexpected reg class");
132e81021a5SDan Gohman   }
133e81021a5SDan Gohman }
134e81021a5SDan Gohman 
1352644d74bSDan Gohman // Determine whether a call to the callee referenced by
1362644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1372644d74bSDan Gohman // effects.
138500d0469SDuncan P. N. Exon Smith static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
139500d0469SDuncan P. N. Exon Smith                         bool &Write, bool &Effects, bool &StackPointer) {
140d08cd15fSDan Gohman   // All calls can use the stack pointer.
141d08cd15fSDan Gohman   StackPointer = true;
142d08cd15fSDan Gohman 
143500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
1442644d74bSDan Gohman   if (MO.isGlobal()) {
1452644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
1462644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1472644d74bSDan Gohman       if (!GA->isInterposable())
1482644d74bSDan Gohman         GV = GA->getAliasee();
1492644d74bSDan Gohman 
1502644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
1512644d74bSDan Gohman       if (!F->doesNotThrow())
1522644d74bSDan Gohman         Effects = true;
1532644d74bSDan Gohman       if (F->doesNotAccessMemory())
1542644d74bSDan Gohman         return;
1552644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1562644d74bSDan Gohman         Read = true;
1572644d74bSDan Gohman         return;
1582644d74bSDan Gohman       }
1592644d74bSDan Gohman     }
1602644d74bSDan Gohman   }
1612644d74bSDan Gohman 
1622644d74bSDan Gohman   // Assume the worst.
1632644d74bSDan Gohman   Write = true;
1642644d74bSDan Gohman   Read = true;
1652644d74bSDan Gohman   Effects = true;
1662644d74bSDan Gohman }
1672644d74bSDan Gohman 
168d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
16982607f56SDan Gohman // and/or uses the stack pointer value.
170500d0469SDuncan P. N. Exon Smith static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
171500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
172500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1736c8f20d7SDan Gohman 
1745ef4d5f9SHeejin Ahn   if (MI.isDebugInstr() || MI.isPosition())
1756c8f20d7SDan Gohman     return;
1762644d74bSDan Gohman 
1772644d74bSDan Gohman   // Check for loads.
178d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1792644d74bSDan Gohman     Read = true;
1802644d74bSDan Gohman 
1812644d74bSDan Gohman   // Check for stores.
182500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1832644d74bSDan Gohman     Write = true;
184500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
185500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
186f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
187f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
188f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
189f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
190f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
191f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
192f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
193f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
194f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
195f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
196f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
197f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
198f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
199f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
200f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
201f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
2022644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
2032644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2042644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
2052644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
2062644d74bSDan Gohman       break;
2072644d74bSDan Gohman     default:
2081054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
2092644d74bSDan Gohman       // specially below.
210500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
2112644d74bSDan Gohman         Write = true;
2121054570aSDan Gohman         Effects = true;
2131054570aSDan Gohman       }
2142644d74bSDan Gohman       break;
2152644d74bSDan Gohman     }
2162644d74bSDan Gohman   }
2172644d74bSDan Gohman 
2182644d74bSDan Gohman   // Check for side effects.
219500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
220500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
221f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
222f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
223f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
224f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
225f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
226f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
227f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
228f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
229f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
230f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
231f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
232f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
233f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
234f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
235f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
236f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
2372644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
2382644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2392644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
2402644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
2412644d74bSDan Gohman       break;
2422644d74bSDan Gohman     default:
2432644d74bSDan Gohman       Effects = true;
2442644d74bSDan Gohman       break;
2452644d74bSDan Gohman     }
2462644d74bSDan Gohman   }
2472644d74bSDan Gohman 
248e73c7a1aSHeejin Ahn   // Check for writes to __stack_pointer global.
249e73c7a1aSHeejin Ahn   if (MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 &&
250e73c7a1aSHeejin Ahn       strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
251e73c7a1aSHeejin Ahn     StackPointer = true;
252e73c7a1aSHeejin Ahn 
2532644d74bSDan Gohman   // Analyze calls.
254500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
25556e79dd0SHeejin Ahn     unsigned CalleeOpNo = WebAssembly::getCalleeOpNo(MI);
25656e79dd0SHeejin Ahn     QueryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
2572644d74bSDan Gohman   }
2582644d74bSDan Gohman }
2592644d74bSDan Gohman 
2602644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
2619cfc75c2SDuncan P. N. Exon Smith static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2622644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2639cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2642644d74bSDan Gohman }
2652644d74bSDan Gohman 
26612de0b91SDan Gohman // Identify the definition for this register at this point. This is a
26712de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
26812de0b91SDan Gohman // LiveIntervals to handle complex cases.
2692644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2702644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
271f208f631SHeejin Ahn                                 const LiveIntervals &LIS) {
2722644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2732644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2742644d74bSDan Gohman     return Def;
2752644d74bSDan Gohman 
2762644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2772644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2782644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2792644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2802644d74bSDan Gohman 
2812644d74bSDan Gohman   return nullptr;
2822644d74bSDan Gohman }
2832644d74bSDan Gohman 
28412de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
28512de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
28612de0b91SDan Gohman // to handle complex cases.
287f208f631SHeejin Ahn static bool HasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
288f208f631SHeejin Ahn                       MachineDominatorTree &MDT, LiveIntervals &LIS) {
28912de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
29012de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
29112de0b91SDan Gohman     return true;
29212de0b91SDan Gohman 
29312de0b91SDan Gohman   bool HasOne = false;
29412de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
295f208f631SHeejin Ahn   const VNInfo *DefVNI =
296f208f631SHeejin Ahn       LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
29712de0b91SDan Gohman   assert(DefVNI);
298a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
29912de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
30012de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
30112de0b91SDan Gohman       if (!Result.isKill())
30212de0b91SDan Gohman         return false;
30312de0b91SDan Gohman       if (HasOne)
30412de0b91SDan Gohman         return false;
30512de0b91SDan Gohman       HasOne = true;
30612de0b91SDan Gohman     }
30712de0b91SDan Gohman   }
30812de0b91SDan Gohman   return HasOne;
30912de0b91SDan Gohman }
31012de0b91SDan Gohman 
3118887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
31281719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
31381719f85SDan Gohman // walking the block.
31481719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
31581719f85SDan Gohman // more precise.
31681719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
317e9e6891bSDerek Schuff                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
318391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
3198887d1faSDan Gohman 
3208887d1faSDan Gohman   // Check for register dependencies.
321e9e6891bSDerek Schuff   SmallVector<unsigned, 4> MutableRegisters;
3228887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
3238887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
3248887d1faSDan Gohman       continue;
3258887d1faSDan Gohman     unsigned Reg = MO.getReg();
3268887d1faSDan Gohman 
3278887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
3288887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
3298887d1faSDan Gohman         !Insert->readsRegister(Reg))
3308887d1faSDan Gohman       continue;
3318887d1faSDan Gohman 
3328887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
3330cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3340cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
3350cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
3360cfb5f85SDan Gohman         continue;
3378887d1faSDan Gohman       // If the physical register is never modified, ignore it.
3388887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
3398887d1faSDan Gohman         continue;
3408887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3418887d1faSDan Gohman       return false;
3428887d1faSDan Gohman     }
3438887d1faSDan Gohman 
344e9e6891bSDerek Schuff     // If one of the operands isn't in SSA form, it has different values at
345e9e6891bSDerek Schuff     // different times, and we need to make sure we don't move our use across
346e9e6891bSDerek Schuff     // a different def.
347e9e6891bSDerek Schuff     if (!MO.isDef() && !MRI.hasOneDef(Reg))
348e9e6891bSDerek Schuff       MutableRegisters.push_back(Reg);
3498887d1faSDan Gohman   }
3508887d1faSDan Gohman 
351d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
352500d0469SDuncan P. N. Exon Smith   Query(*Def, AA, Read, Write, Effects, StackPointer);
3532644d74bSDan Gohman 
3542644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3552644d74bSDan Gohman   // no additional dependencies.
356e9e6891bSDerek Schuff   bool HasMutableRegisters = !MutableRegisters.empty();
357e9e6891bSDerek Schuff   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3582644d74bSDan Gohman     return true;
3592644d74bSDan Gohman 
3602644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
3612644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
3622644d74bSDan Gohman   for (--I; I != D; --I) {
3632644d74bSDan Gohman     bool InterveningRead = false;
3642644d74bSDan Gohman     bool InterveningWrite = false;
3652644d74bSDan Gohman     bool InterveningEffects = false;
366d08cd15fSDan Gohman     bool InterveningStackPointer = false;
367500d0469SDuncan P. N. Exon Smith     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
368d08cd15fSDan Gohman           InterveningStackPointer);
3692644d74bSDan Gohman     if (Effects && InterveningEffects)
3702644d74bSDan Gohman       return false;
3712644d74bSDan Gohman     if (Read && InterveningWrite)
3722644d74bSDan Gohman       return false;
3732644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
3742644d74bSDan Gohman       return false;
375d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
376d08cd15fSDan Gohman       return false;
377e9e6891bSDerek Schuff 
378e9e6891bSDerek Schuff     for (unsigned Reg : MutableRegisters)
379e9e6891bSDerek Schuff       for (const MachineOperand &MO : I->operands())
380e9e6891bSDerek Schuff         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
381e9e6891bSDerek Schuff           return false;
3822644d74bSDan Gohman   }
3832644d74bSDan Gohman 
3842644d74bSDan Gohman   return true;
38581719f85SDan Gohman }
38681719f85SDan Gohman 
387adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
388adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
389adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
390adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3910cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
3921054570aSDan Gohman                                      LiveIntervals &LIS,
3931054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
3940cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
3950cfb5f85SDan Gohman 
3960cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
3970cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3980cfb5f85SDan Gohman 
399a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
400adf28177SDan Gohman     if (&Use == &OneUse)
401adf28177SDan Gohman       continue;
4020cfb5f85SDan Gohman 
403adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
4040cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
4050cfb5f85SDan Gohman 
4060cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
4070cfb5f85SDan Gohman       continue;
4080cfb5f85SDan Gohman 
40912de0b91SDan Gohman     if (UseInst == OneUseInst) {
410adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
411adf28177SDan Gohman       // selected use happens "before" it.
412adf28177SDan Gohman       if (&OneUse > &Use)
413adf28177SDan Gohman         return false;
414adf28177SDan Gohman     } else {
415adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
4161054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
4171054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
4181054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
4191054570aSDan Gohman         //
4206a87ddacSThomas Lively         // This is needed as a consequence of using implicit local.gets for
4216a87ddacSThomas Lively         // uses and implicit local.sets for defs.
4221054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
423adf28177SDan Gohman           return false;
4241054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
4251054570aSDan Gohman         if (!MO.isReg())
4261054570aSDan Gohman           return false;
4271054570aSDan Gohman         unsigned DefReg = MO.getReg();
4281054570aSDan Gohman         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
4291054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
4301054570aSDan Gohman           return false;
431b3857e4dSYury Delendik         assert(MRI.hasOneNonDBGUse(DefReg));
432b3857e4dSYury Delendik         const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
4331054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
4341054570aSDan Gohman         if (NewUseInst == OneUseInst) {
4351054570aSDan Gohman           if (&OneUse > &NewUse)
4361054570aSDan Gohman             return false;
4371054570aSDan Gohman           break;
4381054570aSDan Gohman         }
4391054570aSDan Gohman         UseInst = NewUseInst;
4401054570aSDan Gohman       }
441adf28177SDan Gohman     }
442adf28177SDan Gohman   }
443adf28177SDan Gohman   return true;
444adf28177SDan Gohman }
445adf28177SDan Gohman 
4464fc4e42dSDan Gohman /// Get the appropriate tee opcode for the given register class.
4474fc4e42dSDan Gohman static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
448adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
4494fc4e42dSDan Gohman     return WebAssembly::TEE_I32;
450adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
4514fc4e42dSDan Gohman     return WebAssembly::TEE_I64;
452adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
4534fc4e42dSDan Gohman     return WebAssembly::TEE_F32;
454adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
4554fc4e42dSDan Gohman     return WebAssembly::TEE_F64;
45639bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
4574fc4e42dSDan Gohman     return WebAssembly::TEE_V128;
458adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
459adf28177SDan Gohman }
460adf28177SDan Gohman 
4612644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
4622644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4632644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
4642644d74bSDan Gohman     SmallVector<LiveInterval *, 4> SplitLIs;
4652644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
4662644d74bSDan Gohman   }
4672644d74bSDan Gohman }
4682644d74bSDan Gohman 
469adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
470adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
4710cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand &Op,
472f208f631SHeejin Ahn                                       MachineInstr *Def, MachineBasicBlock &MBB,
473adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
4740cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
4750cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
476d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
4772644d74bSDan Gohman 
478be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(Def);
479adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
480be24c020SYury Delendik   DefDIs.move(Insert);
4811afd1e2bSJF Bastien   LIS.handleMove(*Def);
4820cfb5f85SDan Gohman 
48312de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
48412de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
48512de0b91SDan Gohman     // it in place.
486adf28177SDan Gohman     MFI.stackifyVReg(Reg);
4870cfb5f85SDan Gohman   } else {
48812de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
48912de0b91SDan Gohman     // just our one def and use so that we can stackify it.
4900cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4910cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
4920cfb5f85SDan Gohman     Op.setReg(NewReg);
4930cfb5f85SDan Gohman 
4940cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
4950cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
4960cfb5f85SDan Gohman 
4970cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
4980cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
4996c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
5006c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
5016c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
5020cfb5f85SDan Gohman 
5030cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
5042644d74bSDan Gohman 
505be24c020SYury Delendik     DefDIs.updateReg(NewReg);
5067c18d608SYury Delendik 
507d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5080cfb5f85SDan Gohman   }
5090cfb5f85SDan Gohman 
510adf28177SDan Gohman   ImposeStackOrdering(Def);
511adf28177SDan Gohman   return Def;
512adf28177SDan Gohman }
513adf28177SDan Gohman 
514adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
515adf28177SDan Gohman /// current instruction.
5169cfc75c2SDuncan P. N. Exon Smith static MachineInstr *RematerializeCheapDef(
5179cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5189cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5199cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5209cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
521d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
522d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5232644d74bSDan Gohman 
524be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(&Def);
525be24c020SYury Delendik 
526adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
527adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
528adf28177SDan Gohman   Op.setReg(NewReg);
5299cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
53013d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
531adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
532adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
533adf28177SDan Gohman   ImposeStackOrdering(Clone);
534adf28177SDan Gohman 
535d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5362644d74bSDan Gohman 
5370cfb5f85SDan Gohman   // Shrink the interval.
5380cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
5390cfb5f85SDan Gohman   if (!IsDead) {
5400cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5412644d74bSDan Gohman     ShrinkToUses(LI, LIS);
5429cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5430cfb5f85SDan Gohman   }
5440cfb5f85SDan Gohman 
545adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5467c18d608SYury Delendik   // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
5470cfb5f85SDan Gohman   if (IsDead) {
548d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Deleting original\n");
5499cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
550adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
551adf28177SDan Gohman     LIS.removeInterval(Reg);
5529cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
5539cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
5547c18d608SYury Delendik 
555be24c020SYury Delendik     DefDIs.move(&*Insert);
556be24c020SYury Delendik     DefDIs.updateReg(NewReg);
5577c18d608SYury Delendik   } else {
558be24c020SYury Delendik     DefDIs.clone(&*Insert, NewReg);
559adf28177SDan Gohman   }
5600cfb5f85SDan Gohman 
561adf28177SDan Gohman   return Clone;
562adf28177SDan Gohman }
563adf28177SDan Gohman 
564adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
565adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
5664fc4e42dSDan Gohman /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
5674fc4e42dSDan Gohman /// this:
568adf28177SDan Gohman ///
569adf28177SDan Gohman ///    Reg = INST ...        // Def
570adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
571adf28177SDan Gohman ///    INST ..., Reg, ...
572adf28177SDan Gohman ///    INST ..., Reg, ...
573adf28177SDan Gohman ///
574adf28177SDan Gohman /// to this:
575adf28177SDan Gohman ///
5768aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
5774fc4e42dSDan Gohman ///    TeeReg, Reg = TEE_... DefReg
578adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
5796c8f20d7SDan Gohman ///    INST ..., Reg, ...
5806c8f20d7SDan Gohman ///    INST ..., Reg, ...
581adf28177SDan Gohman ///
5826a87ddacSThomas Lively /// with DefReg and TeeReg stackified. This eliminates a local.get from the
583adf28177SDan Gohman /// resulting code.
584adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
585adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
586adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
587adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
588d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5892644d74bSDan Gohman 
590be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(Def);
591be24c020SYury Delendik 
59212de0b91SDan Gohman   // Move Def into place.
593adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
5941afd1e2bSJF Bastien   LIS.handleMove(*Def);
59512de0b91SDan Gohman 
59612de0b91SDan Gohman   // Create the Tee and attach the registers.
597adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
598adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5998aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
60033e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
601adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
6024fc4e42dSDan Gohman                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
60312de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
60433e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
605adf28177SDan Gohman   Op.setReg(TeeReg);
60633e694a8SDan Gohman   DefMO.setReg(DefReg);
60712de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
60812de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
60912de0b91SDan Gohman 
610be24c020SYury Delendik   DefDIs.move(Insert);
6117c18d608SYury Delendik 
61212de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
61312de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
61412de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
61512de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
61612de0b91SDan Gohman   I->start = TeeIdx;
61712de0b91SDan Gohman   ValNo->def = TeeIdx;
61812de0b91SDan Gohman   ShrinkToUses(LI, LIS);
61912de0b91SDan Gohman 
62012de0b91SDan Gohman   // Finish stackifying the new regs.
621adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
6228aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
6238aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
624adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
625adf28177SDan Gohman   ImposeStackOrdering(Def);
626adf28177SDan Gohman   ImposeStackOrdering(Tee);
62712de0b91SDan Gohman 
628be24c020SYury Delendik   DefDIs.clone(Tee, DefReg);
629be24c020SYury Delendik   DefDIs.clone(Insert, TeeReg);
6307c18d608SYury Delendik 
631d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
632d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
633adf28177SDan Gohman   return Def;
634adf28177SDan Gohman }
635adf28177SDan Gohman 
636adf28177SDan Gohman namespace {
637adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
638adf28177SDan Gohman /// MachineOperands in DFS order.
639adf28177SDan Gohman class TreeWalkerState {
640adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
641adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
642adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
643adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
644adf28177SDan Gohman 
645adf28177SDan Gohman public:
646adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
647adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
648adf28177SDan Gohman     if (Range.begin() != Range.end())
649adf28177SDan Gohman       Worklist.push_back(reverse(Range));
650adf28177SDan Gohman   }
651adf28177SDan Gohman 
652adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
653adf28177SDan Gohman 
654adf28177SDan Gohman   MachineOperand &Pop() {
655adf28177SDan Gohman     RangeTy &Range = Worklist.back();
656adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
657adf28177SDan Gohman     Range = drop_begin(Range, 1);
658adf28177SDan Gohman     if (Range.begin() == Range.end())
659adf28177SDan Gohman       Worklist.pop_back();
660adf28177SDan Gohman     assert((Worklist.empty() ||
661adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
662adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
663adf28177SDan Gohman     return Op;
664adf28177SDan Gohman   }
665adf28177SDan Gohman 
666adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
667adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
668adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
669adf28177SDan Gohman     if (Range.begin() != Range.end())
670adf28177SDan Gohman       Worklist.push_back(reverse(Range));
671adf28177SDan Gohman   }
672adf28177SDan Gohman 
673adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
674adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
675adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
676adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
677adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
678adf28177SDan Gohman            "an operand still on the stack");
679adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
680adf28177SDan Gohman   }
681adf28177SDan Gohman 
682adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
683adf28177SDan Gohman   /// the stack.
684adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
685adf28177SDan Gohman     if (Worklist.empty())
686adf28177SDan Gohman       return false;
687adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
688adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
689adf28177SDan Gohman   }
690fbfe5ec4SDan Gohman 
691fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
692fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
693fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
6941054570aSDan Gohman   ///
6956a87ddacSThomas Lively   /// This is needed as a consequence of using implicit local.gets for
6966a87ddacSThomas Lively   /// uses and implicit local.sets for defs.
697fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
698fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
699fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
700fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
701fbfe5ec4SDan Gohman           return true;
702fbfe5ec4SDan Gohman     return false;
703fbfe5ec4SDan Gohman   }
704adf28177SDan Gohman };
705adf28177SDan Gohman 
706adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
707adf28177SDan Gohman /// tried for the current instruction and didn't work.
708adf28177SDan Gohman class CommutingState {
709adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
71099d39463SHeejin Ahn   /// started commuting anything and we don't know anything yet, the tentative
711adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
71299d39463SHeejin Ahn   /// revisiting it, and the declined state where we've reverted the operands
713adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
714adf28177SDan Gohman   bool TentativelyCommuting;
715adf28177SDan Gohman   bool Declined;
716adf28177SDan Gohman 
717adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
718adf28177SDan Gohman   /// operands.
719adf28177SDan Gohman   unsigned Operand0, Operand1;
720adf28177SDan Gohman 
721adf28177SDan Gohman public:
722adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
723adf28177SDan Gohman 
724adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
725adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
726adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
727adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
728adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
729adf28177SDan Gohman     if (TentativelyCommuting) {
730adf28177SDan Gohman       assert(!Declined &&
731adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
732adf28177SDan Gohman       // Commuting didn't help. Revert it.
7339cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
734adf28177SDan Gohman       TentativelyCommuting = false;
735adf28177SDan Gohman       Declined = true;
736adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
737adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
738adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7399cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
740adf28177SDan Gohman         // Tentatively commute the operands and try again.
7419cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
742adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
743adf28177SDan Gohman         TentativelyCommuting = true;
744adf28177SDan Gohman         Declined = false;
745adf28177SDan Gohman       }
746adf28177SDan Gohman     }
747adf28177SDan Gohman   }
748adf28177SDan Gohman 
749adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
750adf28177SDan Gohman   /// state.
751adf28177SDan Gohman   void Reset() {
752adf28177SDan Gohman     TentativelyCommuting = false;
753adf28177SDan Gohman     Declined = false;
754adf28177SDan Gohman   }
755adf28177SDan Gohman };
756adf28177SDan Gohman } // end anonymous namespace
757adf28177SDan Gohman 
7581462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
759d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
7601462faadSDan Gohman                        "********** Function: "
7611462faadSDan Gohman                     << MF.getName() << '\n');
7621462faadSDan Gohman 
7631462faadSDan Gohman   bool Changed = false;
7641462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
7651462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
766b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
767b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
76881719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
769adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7708887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
771d70e5907SDan Gohman 
7721462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
7731462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
7741462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
7751462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
7768f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
7778f59cf75SDan Gohman     // iterating over it and the end iterator may change.
7788f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
7798f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
78081719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
78181719f85SDan Gohman       // constraints for $push inputs.
78281719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
783595e8ab2SDan Gohman         continue;
784595e8ab2SDan Gohman 
785595e8ab2SDan Gohman       // Ignore debugging intrinsics.
786595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
787595e8ab2SDan Gohman         continue;
78881719f85SDan Gohman 
7891462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
79053d13997SDan Gohman       // operands off the stack in LIFO order.
791adf28177SDan Gohman       CommutingState Commuting;
792adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
793adf28177SDan Gohman       while (!TreeWalker.Done()) {
794adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
795adf28177SDan Gohman 
7961462faadSDan Gohman         // We're only interested in explicit virtual register operands.
797adf28177SDan Gohman         if (!Op.isReg())
7981462faadSDan Gohman           continue;
7991462faadSDan Gohman 
8001462faadSDan Gohman         unsigned Reg = Op.getReg();
801adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
802adf28177SDan Gohman         assert(!Op.isImplicit() &&
803adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
804adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
805adf28177SDan Gohman           continue;
8061462faadSDan Gohman 
807ffc184bbSDan Gohman         // Identify the definition for this register at this point.
8082644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
8091462faadSDan Gohman         if (!Def)
8101462faadSDan Gohman           continue;
8111462faadSDan Gohman 
81281719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
81381719f85SDan Gohman         // constraints for $pop outputs.
81481719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
81581719f85SDan Gohman           continue;
81681719f85SDan Gohman 
8174ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
8184ba4816bSDan Gohman         // instructions.
8194fc4e42dSDan Gohman         if (WebAssembly::isArgument(*Def))
8204ba4816bSDan Gohman           continue;
8214ba4816bSDan Gohman 
822adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
8234fc4e42dSDan Gohman         // over cloning it, and prefer cloning over introducing a tee.
824adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
825adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
826adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
827adf28177SDan Gohman         // the sinking opportunities anyway.
828adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
829e9e6891bSDerek Schuff         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
830fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
83112de0b91SDan Gohman         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
8320cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
8339cfc75c2SDuncan P. N. Exon Smith         } else if (ShouldRematerialize(*Def, AA, TII)) {
8349cfc75c2SDuncan P. N. Exon Smith           Insert =
8359cfc75c2SDuncan P. N. Exon Smith               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
8369cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
837cf2a9e28SSam Clegg         } else if (CanMove &&
8381054570aSDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
839adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
840adf28177SDan Gohman                                          MRI, TII);
841b6fd39a3SDan Gohman         } else {
842adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
843adf28177SDan Gohman           // constraints, Commuting may be able to help.
844adf28177SDan Gohman           if (!CanMove && SameBlock)
845adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
846adf28177SDan Gohman           // Proceed to the next operand.
847adf28177SDan Gohman           continue;
848b6fd39a3SDan Gohman         }
849adf28177SDan Gohman 
850e81021a5SDan Gohman         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
851e81021a5SDan Gohman         // to a constant 0 so that the def is explicit, and the push/pop
852e81021a5SDan Gohman         // correspondence is maintained.
853e81021a5SDan Gohman         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
854feb18fe9SThomas Lively           ConvertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
855e81021a5SDan Gohman 
856adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
857adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
858adf28177SDan Gohman         Commuting.Reset();
859adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
860b6fd39a3SDan Gohman       }
861adf28177SDan Gohman 
862adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
863adf28177SDan Gohman       // the next instruction we can build a tree on.
864adf28177SDan Gohman       if (Insert != &*MII) {
8658f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
866c7e5a9ceSEric Liu         MII = MachineBasicBlock::iterator(Insert).getReverse();
867adf28177SDan Gohman         Changed = true;
868adf28177SDan Gohman       }
8691462faadSDan Gohman     }
8701462faadSDan Gohman   }
8711462faadSDan Gohman 
872e040533eSDan Gohman   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
873adf28177SDan Gohman   // that it never looks like a use-before-def.
874b0992dafSDan Gohman   if (Changed) {
875e040533eSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
876b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
877e040533eSDan Gohman       MBB.addLiveIn(WebAssembly::VALUE_STACK);
878b0992dafSDan Gohman   }
879b0992dafSDan Gohman 
8807bafa0eaSDan Gohman #ifndef NDEBUG
881b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
8827bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
8837bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8847bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
885801bf7ebSShiva Chen       if (MI.isDebugInstr())
8860cfb5f85SDan Gohman         continue;
8877bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8887a6b9825SDan Gohman         if (!MO.isReg())
8897a6b9825SDan Gohman           continue;
890adf28177SDan Gohman         unsigned Reg = MO.getReg();
8917bafa0eaSDan Gohman 
892adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
8937bafa0eaSDan Gohman           if (MO.isDef())
894adf28177SDan Gohman             Stack.push_back(Reg);
8957bafa0eaSDan Gohman           else
896adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
897adf28177SDan Gohman                    "Register stack pop should be paired with a push");
8987bafa0eaSDan Gohman         }
8997bafa0eaSDan Gohman       }
9007bafa0eaSDan Gohman     }
9017bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
9027bafa0eaSDan Gohman     // basic block boundaries.
903adf28177SDan Gohman     assert(Stack.empty() &&
904adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
9057bafa0eaSDan Gohman   }
9067bafa0eaSDan Gohman #endif
9077bafa0eaSDan Gohman 
9081462faadSDan Gohman   return Changed;
9091462faadSDan Gohman }
910