11462faadSDan Gohman //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
21462faadSDan Gohman //
31462faadSDan Gohman //                     The LLVM Compiler Infrastructure
41462faadSDan Gohman //
51462faadSDan Gohman // This file is distributed under the University of Illinois Open Source
61462faadSDan Gohman // License. See LICENSE.TXT for details.
71462faadSDan Gohman //
81462faadSDan Gohman //===----------------------------------------------------------------------===//
91462faadSDan Gohman ///
101462faadSDan Gohman /// \file
115f8f34e4SAdrian Prantl /// This file implements a register stacking pass.
121462faadSDan Gohman ///
131462faadSDan Gohman /// This pass reorders instructions to put register uses and defs in an order
141462faadSDan Gohman /// such that they form single-use expression trees. Registers fitting this form
151462faadSDan Gohman /// are then marked as "stackified", meaning references to them are replaced by
16e040533eSDan Gohman /// "push" and "pop" from the value stack.
171462faadSDan Gohman ///
1831448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
19e040533eSDan Gohman /// value stack don't need to be named.
201462faadSDan Gohman ///
211462faadSDan Gohman //===----------------------------------------------------------------------===//
221462faadSDan Gohman 
234ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
246bda14b3SChandler Carruth #include "WebAssembly.h"
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
274fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
2881719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
29f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
301462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
32adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
3382607f56SDan Gohman #include "llvm/CodeGen/MachineModuleInfoImpls.h"
341462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
351462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
361462faadSDan Gohman #include "llvm/Support/Debug.h"
371462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
381462faadSDan Gohman using namespace llvm;
391462faadSDan Gohman 
401462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
411462faadSDan Gohman 
421462faadSDan Gohman namespace {
431462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
44117296c0SMehdi Amini   StringRef getPassName() const override {
451462faadSDan Gohman     return "WebAssembly Register Stackify";
461462faadSDan Gohman   }
471462faadSDan Gohman 
481462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
491462faadSDan Gohman     AU.setPreservesCFG();
5081719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
51adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
528887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
531462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
548887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
558887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
568887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
57adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
581462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
591462faadSDan Gohman   }
601462faadSDan Gohman 
611462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
621462faadSDan Gohman 
631462faadSDan Gohman public:
641462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
651462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
661462faadSDan Gohman };
671462faadSDan Gohman } // end anonymous namespace
681462faadSDan Gohman 
691462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
7040926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
7140926451SJacob Gravelle                 "Reorder instructions to use the WebAssembly value stack",
7240926451SJacob Gravelle                 false, false)
7340926451SJacob Gravelle 
741462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
751462faadSDan Gohman   return new WebAssemblyRegStackify();
761462faadSDan Gohman }
771462faadSDan Gohman 
78b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
798887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
808887d1faSDan Gohman // the expression stack.
818887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
82e040533eSDan Gohman   // Write the opaque VALUE_STACK register.
83e040533eSDan Gohman   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
84e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
85b0992dafSDan Gohman                                              /*isDef=*/true,
86b0992dafSDan Gohman                                              /*isImp=*/true));
874da4abd8SDan Gohman 
88e040533eSDan Gohman   // Also read the opaque VALUE_STACK register.
89e040533eSDan Gohman   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
90e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
91b0992dafSDan Gohman                                              /*isDef=*/false,
92b0992dafSDan Gohman                                              /*isImp=*/true));
93b0992dafSDan Gohman }
94b0992dafSDan Gohman 
95e81021a5SDan Gohman // Convert an IMPLICIT_DEF instruction into an instruction which defines
96e81021a5SDan Gohman // a constant zero value.
97e81021a5SDan Gohman static void ConvertImplicitDefToConstZero(MachineInstr *MI,
98e81021a5SDan Gohman                                           MachineRegisterInfo &MRI,
99e81021a5SDan Gohman                                           const TargetInstrInfo *TII,
100e81021a5SDan Gohman                                           MachineFunction &MF) {
101e81021a5SDan Gohman   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
102e81021a5SDan Gohman 
103e81021a5SDan Gohman   const auto *RegClass =
104e81021a5SDan Gohman       MRI.getRegClass(MI->getOperand(0).getReg());
105e81021a5SDan Gohman   if (RegClass == &WebAssembly::I32RegClass) {
106e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I32));
107e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
108e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::I64RegClass) {
109e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I64));
110e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
111e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F32RegClass) {
112e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F32));
113e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
11421109249SDavid Blaikie         Type::getFloatTy(MF.getFunction().getContext())));
115e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
116e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F64RegClass) {
117e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F64));
118e81021a5SDan Gohman     ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
11921109249SDavid Blaikie         Type::getDoubleTy(MF.getFunction().getContext())));
120e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
121e81021a5SDan Gohman   } else {
122e81021a5SDan Gohman     llvm_unreachable("Unexpected reg class");
123e81021a5SDan Gohman   }
124e81021a5SDan Gohman }
125e81021a5SDan Gohman 
1262644d74bSDan Gohman // Determine whether a call to the callee referenced by
1272644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1282644d74bSDan Gohman // effects.
129500d0469SDuncan P. N. Exon Smith static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
130500d0469SDuncan P. N. Exon Smith                         bool &Write, bool &Effects, bool &StackPointer) {
131d08cd15fSDan Gohman   // All calls can use the stack pointer.
132d08cd15fSDan Gohman   StackPointer = true;
133d08cd15fSDan Gohman 
134500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
1352644d74bSDan Gohman   if (MO.isGlobal()) {
1362644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
1372644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1382644d74bSDan Gohman       if (!GA->isInterposable())
1392644d74bSDan Gohman         GV = GA->getAliasee();
1402644d74bSDan Gohman 
1412644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
1422644d74bSDan Gohman       if (!F->doesNotThrow())
1432644d74bSDan Gohman         Effects = true;
1442644d74bSDan Gohman       if (F->doesNotAccessMemory())
1452644d74bSDan Gohman         return;
1462644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1472644d74bSDan Gohman         Read = true;
1482644d74bSDan Gohman         return;
1492644d74bSDan Gohman       }
1502644d74bSDan Gohman     }
1512644d74bSDan Gohman   }
1522644d74bSDan Gohman 
1532644d74bSDan Gohman   // Assume the worst.
1542644d74bSDan Gohman   Write = true;
1552644d74bSDan Gohman   Read = true;
1562644d74bSDan Gohman   Effects = true;
1572644d74bSDan Gohman }
1582644d74bSDan Gohman 
159d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
16082607f56SDan Gohman // and/or uses the stack pointer value.
161500d0469SDuncan P. N. Exon Smith static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
162500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
163500d0469SDuncan P. N. Exon Smith   assert(!MI.isPosition());
164500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1656c8f20d7SDan Gohman 
166*801bf7ebSShiva Chen   if (MI.isDebugInstr())
1676c8f20d7SDan Gohman     return;
1682644d74bSDan Gohman 
1692644d74bSDan Gohman   // Check for loads.
170d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1712644d74bSDan Gohman     Read = true;
1722644d74bSDan Gohman 
1732644d74bSDan Gohman   // Check for stores.
174500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1752644d74bSDan Gohman     Write = true;
176d08cd15fSDan Gohman 
177d08cd15fSDan Gohman     // Check for stores to __stack_pointer.
178500d0469SDuncan P. N. Exon Smith     for (auto MMO : MI.memoperands()) {
179d08cd15fSDan Gohman       const MachinePointerInfo &MPI = MMO->getPointerInfo();
180d08cd15fSDan Gohman       if (MPI.V.is<const PseudoSourceValue *>()) {
181d08cd15fSDan Gohman         auto PSV = MPI.V.get<const PseudoSourceValue *>();
182d08cd15fSDan Gohman         if (const ExternalSymbolPseudoSourceValue *EPSV =
183d08cd15fSDan Gohman                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
1849d24fb7fSSam Clegg           if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
185d08cd15fSDan Gohman             StackPointer = true;
186d08cd15fSDan Gohman           }
187d08cd15fSDan Gohman       }
18882607f56SDan Gohman     }
189500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
190500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
1912644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1922644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1932644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1942644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1952644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1962644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1972644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1982644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1992644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
2002644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2012644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
2022644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
2032644d74bSDan Gohman       break;
2042644d74bSDan Gohman     default:
2051054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
2062644d74bSDan Gohman       // specially below.
207500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
2082644d74bSDan Gohman         Write = true;
2091054570aSDan Gohman         Effects = true;
2101054570aSDan Gohman       }
2112644d74bSDan Gohman       break;
2122644d74bSDan Gohman     }
2132644d74bSDan Gohman   }
2142644d74bSDan Gohman 
2152644d74bSDan Gohman   // Check for side effects.
216500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
217500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
2182644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
2192644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
2202644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
2212644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
2222644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
2232644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
2242644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
2252644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
2262644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
2272644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2282644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
2292644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
2302644d74bSDan Gohman       break;
2312644d74bSDan Gohman     default:
2322644d74bSDan Gohman       Effects = true;
2332644d74bSDan Gohman       break;
2342644d74bSDan Gohman     }
2352644d74bSDan Gohman   }
2362644d74bSDan Gohman 
2372644d74bSDan Gohman   // Analyze calls.
238500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
239500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
2402644d74bSDan Gohman     case WebAssembly::CALL_VOID:
2411054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_VOID:
242d08cd15fSDan Gohman       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
2432644d74bSDan Gohman       break;
2441054570aSDan Gohman     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
2451054570aSDan Gohman     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
2461054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
2471054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
248d08cd15fSDan Gohman       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
2492644d74bSDan Gohman       break;
2502644d74bSDan Gohman     default:
2512644d74bSDan Gohman       llvm_unreachable("unexpected call opcode");
2522644d74bSDan Gohman     }
2532644d74bSDan Gohman   }
2542644d74bSDan Gohman }
2552644d74bSDan Gohman 
2562644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
2579cfc75c2SDuncan P. N. Exon Smith static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2582644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2599cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2602644d74bSDan Gohman }
2612644d74bSDan Gohman 
26212de0b91SDan Gohman // Identify the definition for this register at this point. This is a
26312de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
26412de0b91SDan Gohman // LiveIntervals to handle complex cases.
2652644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2662644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
2672644d74bSDan Gohman                                 const LiveIntervals &LIS)
2682644d74bSDan Gohman {
2692644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2702644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2712644d74bSDan Gohman     return Def;
2722644d74bSDan Gohman 
2732644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2742644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2752644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2762644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2772644d74bSDan Gohman 
2782644d74bSDan Gohman   return nullptr;
2792644d74bSDan Gohman }
2802644d74bSDan Gohman 
28112de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
28212de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
28312de0b91SDan Gohman // to handle complex cases.
28412de0b91SDan Gohman static bool HasOneUse(unsigned Reg, MachineInstr *Def,
28512de0b91SDan Gohman                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
28612de0b91SDan Gohman                       LiveIntervals &LIS) {
28712de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
28812de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
28912de0b91SDan Gohman     return true;
29012de0b91SDan Gohman 
29112de0b91SDan Gohman   bool HasOne = false;
29212de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
29312de0b91SDan Gohman   const VNInfo *DefVNI = LI.getVNInfoAt(
29412de0b91SDan Gohman       LIS.getInstructionIndex(*Def).getRegSlot());
29512de0b91SDan Gohman   assert(DefVNI);
296a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
29712de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
29812de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
29912de0b91SDan Gohman       if (!Result.isKill())
30012de0b91SDan Gohman         return false;
30112de0b91SDan Gohman       if (HasOne)
30212de0b91SDan Gohman         return false;
30312de0b91SDan Gohman       HasOne = true;
30412de0b91SDan Gohman     }
30512de0b91SDan Gohman   }
30612de0b91SDan Gohman   return HasOne;
30712de0b91SDan Gohman }
30812de0b91SDan Gohman 
3098887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
31081719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
31181719f85SDan Gohman // walking the block.
31281719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
31381719f85SDan Gohman // more precise.
31481719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
315e9e6891bSDerek Schuff                          AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
316391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
3178887d1faSDan Gohman 
3188887d1faSDan Gohman   // Check for register dependencies.
319e9e6891bSDerek Schuff   SmallVector<unsigned, 4> MutableRegisters;
3208887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
3218887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
3228887d1faSDan Gohman       continue;
3238887d1faSDan Gohman     unsigned Reg = MO.getReg();
3248887d1faSDan Gohman 
3258887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
3268887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
3278887d1faSDan Gohman         !Insert->readsRegister(Reg))
3288887d1faSDan Gohman       continue;
3298887d1faSDan Gohman 
3308887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
3310cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3320cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
3330cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
3340cfb5f85SDan Gohman         continue;
3358887d1faSDan Gohman       // If the physical register is never modified, ignore it.
3368887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
3378887d1faSDan Gohman         continue;
3388887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3398887d1faSDan Gohman       return false;
3408887d1faSDan Gohman     }
3418887d1faSDan Gohman 
342e9e6891bSDerek Schuff     // If one of the operands isn't in SSA form, it has different values at
343e9e6891bSDerek Schuff     // different times, and we need to make sure we don't move our use across
344e9e6891bSDerek Schuff     // a different def.
345e9e6891bSDerek Schuff     if (!MO.isDef() && !MRI.hasOneDef(Reg))
346e9e6891bSDerek Schuff       MutableRegisters.push_back(Reg);
3478887d1faSDan Gohman   }
3488887d1faSDan Gohman 
349d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
350500d0469SDuncan P. N. Exon Smith   Query(*Def, AA, Read, Write, Effects, StackPointer);
3512644d74bSDan Gohman 
3522644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3532644d74bSDan Gohman   // no additional dependencies.
354e9e6891bSDerek Schuff   bool HasMutableRegisters = !MutableRegisters.empty();
355e9e6891bSDerek Schuff   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
3562644d74bSDan Gohman     return true;
3572644d74bSDan Gohman 
3582644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
3592644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
3602644d74bSDan Gohman   for (--I; I != D; --I) {
3612644d74bSDan Gohman     bool InterveningRead = false;
3622644d74bSDan Gohman     bool InterveningWrite = false;
3632644d74bSDan Gohman     bool InterveningEffects = false;
364d08cd15fSDan Gohman     bool InterveningStackPointer = false;
365500d0469SDuncan P. N. Exon Smith     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
366d08cd15fSDan Gohman           InterveningStackPointer);
3672644d74bSDan Gohman     if (Effects && InterveningEffects)
3682644d74bSDan Gohman       return false;
3692644d74bSDan Gohman     if (Read && InterveningWrite)
3702644d74bSDan Gohman       return false;
3712644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
3722644d74bSDan Gohman       return false;
373d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
374d08cd15fSDan Gohman       return false;
375e9e6891bSDerek Schuff 
376e9e6891bSDerek Schuff     for (unsigned Reg : MutableRegisters)
377e9e6891bSDerek Schuff       for (const MachineOperand &MO : I->operands())
378e9e6891bSDerek Schuff         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
379e9e6891bSDerek Schuff           return false;
3802644d74bSDan Gohman   }
3812644d74bSDan Gohman 
3822644d74bSDan Gohman   return true;
38381719f85SDan Gohman }
38481719f85SDan Gohman 
385adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
386adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
387adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
388adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3890cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
3901054570aSDan Gohman                                      LiveIntervals &LIS,
3911054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
3920cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
3930cfb5f85SDan Gohman 
3940cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
3950cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3960cfb5f85SDan Gohman 
397a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
398adf28177SDan Gohman     if (&Use == &OneUse)
399adf28177SDan Gohman       continue;
4000cfb5f85SDan Gohman 
401adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
4020cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
4030cfb5f85SDan Gohman 
4040cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
4050cfb5f85SDan Gohman       continue;
4060cfb5f85SDan Gohman 
407adf28177SDan Gohman     const MachineInstr *OneUseInst = OneUse.getParent();
40812de0b91SDan Gohman     if (UseInst == OneUseInst) {
409adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
410adf28177SDan Gohman       // selected use happens "before" it.
411adf28177SDan Gohman       if (&OneUse > &Use)
412adf28177SDan Gohman         return false;
413adf28177SDan Gohman     } else {
414adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
4151054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
4161054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
4171054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
4181054570aSDan Gohman         //
4191054570aSDan Gohman         // This is needed as a consequence of using implicit get_locals for
4201054570aSDan Gohman         // uses and implicit set_locals for defs.
4211054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
422adf28177SDan Gohman           return false;
4231054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
4241054570aSDan Gohman         if (!MO.isReg())
4251054570aSDan Gohman           return false;
4261054570aSDan Gohman         unsigned DefReg = MO.getReg();
4271054570aSDan Gohman         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
4281054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
4291054570aSDan Gohman           return false;
4301054570aSDan Gohman         assert(MRI.hasOneUse(DefReg));
4311054570aSDan Gohman         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
4321054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
4331054570aSDan Gohman         if (NewUseInst == OneUseInst) {
4341054570aSDan Gohman           if (&OneUse > &NewUse)
4351054570aSDan Gohman             return false;
4361054570aSDan Gohman           break;
4371054570aSDan Gohman         }
4381054570aSDan Gohman         UseInst = NewUseInst;
4391054570aSDan Gohman       }
440adf28177SDan Gohman     }
441adf28177SDan Gohman   }
442adf28177SDan Gohman   return true;
443adf28177SDan Gohman }
444adf28177SDan Gohman 
4454fc4e42dSDan Gohman /// Get the appropriate tee opcode for the given register class.
4464fc4e42dSDan Gohman static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
447adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
4484fc4e42dSDan Gohman     return WebAssembly::TEE_I32;
449adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
4504fc4e42dSDan Gohman     return WebAssembly::TEE_I64;
451adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
4524fc4e42dSDan Gohman     return WebAssembly::TEE_F32;
453adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
4544fc4e42dSDan Gohman     return WebAssembly::TEE_F64;
45539bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
4564fc4e42dSDan Gohman     return WebAssembly::TEE_V128;
457adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
458adf28177SDan Gohman }
459adf28177SDan Gohman 
4602644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
4612644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4622644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
4632644d74bSDan Gohman     SmallVector<LiveInterval*, 4> SplitLIs;
4642644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
4652644d74bSDan Gohman   }
4662644d74bSDan Gohman }
4672644d74bSDan Gohman 
468adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
469adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
4700cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
4710cfb5f85SDan Gohman                                       MachineInstr *Def,
472adf28177SDan Gohman                                       MachineBasicBlock &MBB,
473adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
4740cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
4750cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
4762644d74bSDan Gohman   DEBUG(dbgs() << "Move for single use: "; Def->dump());
4772644d74bSDan Gohman 
478adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
4791afd1e2bSJF Bastien   LIS.handleMove(*Def);
4800cfb5f85SDan Gohman 
48112de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
48212de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
48312de0b91SDan Gohman     // it in place.
484adf28177SDan Gohman     MFI.stackifyVReg(Reg);
4850cfb5f85SDan Gohman   } else {
48612de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
48712de0b91SDan Gohman     // just our one def and use so that we can stackify it.
4880cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4890cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
4900cfb5f85SDan Gohman     Op.setReg(NewReg);
4910cfb5f85SDan Gohman 
4920cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
4930cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
4940cfb5f85SDan Gohman 
4950cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
4960cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
4976c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
4986c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
4996c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
5000cfb5f85SDan Gohman 
5010cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
5022644d74bSDan Gohman 
5032644d74bSDan Gohman     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5040cfb5f85SDan Gohman   }
5050cfb5f85SDan Gohman 
506adf28177SDan Gohman   ImposeStackOrdering(Def);
507adf28177SDan Gohman   return Def;
508adf28177SDan Gohman }
509adf28177SDan Gohman 
510adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
511adf28177SDan Gohman /// current instruction.
5129cfc75c2SDuncan P. N. Exon Smith static MachineInstr *RematerializeCheapDef(
5139cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5149cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5159cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5169cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
5179cfc75c2SDuncan P. N. Exon Smith   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
5182644d74bSDan Gohman   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5192644d74bSDan Gohman 
520adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
521adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
522adf28177SDan Gohman   Op.setReg(NewReg);
5239cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
52413d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
525adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
526adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
527adf28177SDan Gohman   ImposeStackOrdering(Clone);
528adf28177SDan Gohman 
5292644d74bSDan Gohman   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5302644d74bSDan Gohman 
5310cfb5f85SDan Gohman   // Shrink the interval.
5320cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
5330cfb5f85SDan Gohman   if (!IsDead) {
5340cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5352644d74bSDan Gohman     ShrinkToUses(LI, LIS);
5369cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5370cfb5f85SDan Gohman   }
5380cfb5f85SDan Gohman 
539adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5400cfb5f85SDan Gohman   if (IsDead) {
5412644d74bSDan Gohman     DEBUG(dbgs() << " - Deleting original\n");
5429cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
543adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
544adf28177SDan Gohman     LIS.removeInterval(Reg);
5459cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
5469cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
547adf28177SDan Gohman   }
5480cfb5f85SDan Gohman 
549adf28177SDan Gohman   return Clone;
550adf28177SDan Gohman }
551adf28177SDan Gohman 
552adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
553adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
5544fc4e42dSDan Gohman /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
5554fc4e42dSDan Gohman /// this:
556adf28177SDan Gohman ///
557adf28177SDan Gohman ///    Reg = INST ...        // Def
558adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
559adf28177SDan Gohman ///    INST ..., Reg, ...
560adf28177SDan Gohman ///    INST ..., Reg, ...
561adf28177SDan Gohman ///
562adf28177SDan Gohman /// to this:
563adf28177SDan Gohman ///
5648aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
5654fc4e42dSDan Gohman ///    TeeReg, Reg = TEE_... DefReg
566adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
5676c8f20d7SDan Gohman ///    INST ..., Reg, ...
5686c8f20d7SDan Gohman ///    INST ..., Reg, ...
569adf28177SDan Gohman ///
5708aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the
571adf28177SDan Gohman /// resulting code.
572adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
573adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
574adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
575adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5762644d74bSDan Gohman   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5772644d74bSDan Gohman 
57812de0b91SDan Gohman   // Move Def into place.
579adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
5801afd1e2bSJF Bastien   LIS.handleMove(*Def);
58112de0b91SDan Gohman 
58212de0b91SDan Gohman   // Create the Tee and attach the registers.
583adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
584adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5858aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
58633e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
587adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
5884fc4e42dSDan Gohman                               TII->get(GetTeeOpcode(RegClass)), TeeReg)
58912de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
59033e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
591adf28177SDan Gohman   Op.setReg(TeeReg);
59233e694a8SDan Gohman   DefMO.setReg(DefReg);
59312de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
59412de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
59512de0b91SDan Gohman 
59612de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
59712de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
59812de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
59912de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
60012de0b91SDan Gohman   I->start = TeeIdx;
60112de0b91SDan Gohman   ValNo->def = TeeIdx;
60212de0b91SDan Gohman   ShrinkToUses(LI, LIS);
60312de0b91SDan Gohman 
60412de0b91SDan Gohman   // Finish stackifying the new regs.
605adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
6068aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
6078aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
608adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
609adf28177SDan Gohman   ImposeStackOrdering(Def);
610adf28177SDan Gohman   ImposeStackOrdering(Tee);
61112de0b91SDan Gohman 
61212de0b91SDan Gohman   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
61312de0b91SDan Gohman   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
614adf28177SDan Gohman   return Def;
615adf28177SDan Gohman }
616adf28177SDan Gohman 
617adf28177SDan Gohman namespace {
618adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
619adf28177SDan Gohman /// MachineOperands in DFS order.
620adf28177SDan Gohman class TreeWalkerState {
621adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
622adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
623adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
624adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
625adf28177SDan Gohman 
626adf28177SDan Gohman public:
627adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
628adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
629adf28177SDan Gohman     if (Range.begin() != Range.end())
630adf28177SDan Gohman       Worklist.push_back(reverse(Range));
631adf28177SDan Gohman   }
632adf28177SDan Gohman 
633adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
634adf28177SDan Gohman 
635adf28177SDan Gohman   MachineOperand &Pop() {
636adf28177SDan Gohman     RangeTy &Range = Worklist.back();
637adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
638adf28177SDan Gohman     Range = drop_begin(Range, 1);
639adf28177SDan Gohman     if (Range.begin() == Range.end())
640adf28177SDan Gohman       Worklist.pop_back();
641adf28177SDan Gohman     assert((Worklist.empty() ||
642adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
643adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
644adf28177SDan Gohman     return Op;
645adf28177SDan Gohman   }
646adf28177SDan Gohman 
647adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
648adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
649adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
650adf28177SDan Gohman     if (Range.begin() != Range.end())
651adf28177SDan Gohman       Worklist.push_back(reverse(Range));
652adf28177SDan Gohman   }
653adf28177SDan Gohman 
654adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
655adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
656adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
657adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
658adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
659adf28177SDan Gohman            "an operand still on the stack");
660adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
661adf28177SDan Gohman   }
662adf28177SDan Gohman 
663adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
664adf28177SDan Gohman   /// the stack.
665adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
666adf28177SDan Gohman     if (Worklist.empty())
667adf28177SDan Gohman       return false;
668adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
669adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
670adf28177SDan Gohman   }
671fbfe5ec4SDan Gohman 
672fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
673fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
674fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
6751054570aSDan Gohman   ///
6761054570aSDan Gohman   /// This is needed as a consequence of using implicit get_locals for
6771054570aSDan Gohman   /// uses and implicit set_locals for defs.
678fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
679fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
680fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
681fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
682fbfe5ec4SDan Gohman           return true;
683fbfe5ec4SDan Gohman     return false;
684fbfe5ec4SDan Gohman   }
685adf28177SDan Gohman };
686adf28177SDan Gohman 
687adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
688adf28177SDan Gohman /// tried for the current instruction and didn't work.
689adf28177SDan Gohman class CommutingState {
690adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
691adf28177SDan Gohman   /// started commuting anything and we don't know anything yet, the tenative
692adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
693adf28177SDan Gohman   /// revisting it, and the declined state where we've reverted the operands
694adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
695adf28177SDan Gohman   bool TentativelyCommuting;
696adf28177SDan Gohman   bool Declined;
697adf28177SDan Gohman 
698adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
699adf28177SDan Gohman   /// operands.
700adf28177SDan Gohman   unsigned Operand0, Operand1;
701adf28177SDan Gohman 
702adf28177SDan Gohman public:
703adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
704adf28177SDan Gohman 
705adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
706adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
707adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
708adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
709adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
710adf28177SDan Gohman     if (TentativelyCommuting) {
711adf28177SDan Gohman       assert(!Declined &&
712adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
713adf28177SDan Gohman       // Commuting didn't help. Revert it.
7149cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
715adf28177SDan Gohman       TentativelyCommuting = false;
716adf28177SDan Gohman       Declined = true;
717adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
718adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
719adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7209cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
721adf28177SDan Gohman         // Tentatively commute the operands and try again.
7229cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
723adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
724adf28177SDan Gohman         TentativelyCommuting = true;
725adf28177SDan Gohman         Declined = false;
726adf28177SDan Gohman       }
727adf28177SDan Gohman     }
728adf28177SDan Gohman   }
729adf28177SDan Gohman 
730adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
731adf28177SDan Gohman   /// state.
732adf28177SDan Gohman   void Reset() {
733adf28177SDan Gohman     TentativelyCommuting = false;
734adf28177SDan Gohman     Declined = false;
735adf28177SDan Gohman   }
736adf28177SDan Gohman };
737adf28177SDan Gohman } // end anonymous namespace
738adf28177SDan Gohman 
7391462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7401462faadSDan Gohman   DEBUG(dbgs() << "********** Register Stackifying **********\n"
7411462faadSDan Gohman                   "********** Function: "
7421462faadSDan Gohman                << MF.getName() << '\n');
7431462faadSDan Gohman 
7441462faadSDan Gohman   bool Changed = false;
7451462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
7461462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
747b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
748b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
74981719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
750adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7518887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
752d70e5907SDan Gohman 
753b5f53449SDan Gohman   // Disable the TEE optimization if we aren't doing direct wasm object
754b5f53449SDan Gohman   // emission, because lowering TEE to TEE_LOCAL is done in the ExplicitLocals
755b5f53449SDan Gohman   // pass, which is also disabled.
756b5f53449SDan Gohman   bool UseTee = true;
757b5f53449SDan Gohman   if (MF.getSubtarget<WebAssemblySubtarget>()
758b5f53449SDan Gohman         .getTargetTriple().isOSBinFormatELF())
759b5f53449SDan Gohman     UseTee = false;
760b5f53449SDan Gohman 
7611462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
7621462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
7631462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
7641462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
7658f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
7668f59cf75SDan Gohman     // iterating over it and the end iterator may change.
7678f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
7688f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
76981719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
77081719f85SDan Gohman       // constraints for $push inputs.
77181719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
772595e8ab2SDan Gohman         continue;
773595e8ab2SDan Gohman 
774595e8ab2SDan Gohman       // Ignore debugging intrinsics.
775595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
776595e8ab2SDan Gohman         continue;
77781719f85SDan Gohman 
7781462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
77953d13997SDan Gohman       // operands off the stack in LIFO order.
780adf28177SDan Gohman       CommutingState Commuting;
781adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
782adf28177SDan Gohman       while (!TreeWalker.Done()) {
783adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
784adf28177SDan Gohman 
7851462faadSDan Gohman         // We're only interested in explicit virtual register operands.
786adf28177SDan Gohman         if (!Op.isReg())
7871462faadSDan Gohman           continue;
7881462faadSDan Gohman 
7891462faadSDan Gohman         unsigned Reg = Op.getReg();
790adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
791adf28177SDan Gohman         assert(!Op.isImplicit() &&
792adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
793adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
794adf28177SDan Gohman           continue;
7951462faadSDan Gohman 
796ffc184bbSDan Gohman         // Identify the definition for this register at this point.
7972644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
7981462faadSDan Gohman         if (!Def)
7991462faadSDan Gohman           continue;
8001462faadSDan Gohman 
80181719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
80281719f85SDan Gohman         // constraints for $pop outputs.
80381719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
80481719f85SDan Gohman           continue;
80581719f85SDan Gohman 
8064ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
8074ba4816bSDan Gohman         // instructions.
8084fc4e42dSDan Gohman         if (WebAssembly::isArgument(*Def))
8094ba4816bSDan Gohman           continue;
8104ba4816bSDan Gohman 
811adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
8124fc4e42dSDan Gohman         // over cloning it, and prefer cloning over introducing a tee.
813adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
814adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
815adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
816adf28177SDan Gohman         // the sinking opportunities anyway.
817adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
818e9e6891bSDerek Schuff         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
819fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
82012de0b91SDan Gohman         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
8210cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
8229cfc75c2SDuncan P. N. Exon Smith         } else if (ShouldRematerialize(*Def, AA, TII)) {
8239cfc75c2SDuncan P. N. Exon Smith           Insert =
8249cfc75c2SDuncan P. N. Exon Smith               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
8259cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
826b5f53449SDan Gohman         } else if (UseTee && CanMove &&
8271054570aSDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
828adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
829adf28177SDan Gohman                                          MRI, TII);
830b6fd39a3SDan Gohman         } else {
831adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
832adf28177SDan Gohman           // constraints, Commuting may be able to help.
833adf28177SDan Gohman           if (!CanMove && SameBlock)
834adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
835adf28177SDan Gohman           // Proceed to the next operand.
836adf28177SDan Gohman           continue;
837b6fd39a3SDan Gohman         }
838adf28177SDan Gohman 
839e81021a5SDan Gohman         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
840e81021a5SDan Gohman         // to a constant 0 so that the def is explicit, and the push/pop
841e81021a5SDan Gohman         // correspondence is maintained.
842e81021a5SDan Gohman         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
843e81021a5SDan Gohman           ConvertImplicitDefToConstZero(Insert, MRI, TII, MF);
844e81021a5SDan Gohman 
845adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
846adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
847adf28177SDan Gohman         Commuting.Reset();
848adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
849b6fd39a3SDan Gohman       }
850adf28177SDan Gohman 
851adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
852adf28177SDan Gohman       // the next instruction we can build a tree on.
853adf28177SDan Gohman       if (Insert != &*MII) {
8548f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
855c7e5a9ceSEric Liu         MII = MachineBasicBlock::iterator(Insert).getReverse();
856adf28177SDan Gohman         Changed = true;
857adf28177SDan Gohman       }
8581462faadSDan Gohman     }
8591462faadSDan Gohman   }
8601462faadSDan Gohman 
861e040533eSDan Gohman   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
862adf28177SDan Gohman   // that it never looks like a use-before-def.
863b0992dafSDan Gohman   if (Changed) {
864e040533eSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
865b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
866e040533eSDan Gohman       MBB.addLiveIn(WebAssembly::VALUE_STACK);
867b0992dafSDan Gohman   }
868b0992dafSDan Gohman 
8697bafa0eaSDan Gohman #ifndef NDEBUG
870b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
8717bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
8727bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8737bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
874*801bf7ebSShiva Chen       if (MI.isDebugInstr())
8750cfb5f85SDan Gohman         continue;
8767bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8777a6b9825SDan Gohman         if (!MO.isReg())
8787a6b9825SDan Gohman           continue;
879adf28177SDan Gohman         unsigned Reg = MO.getReg();
8807bafa0eaSDan Gohman 
881adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
8827bafa0eaSDan Gohman           if (MO.isDef())
883adf28177SDan Gohman             Stack.push_back(Reg);
8847bafa0eaSDan Gohman           else
885adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
886adf28177SDan Gohman                    "Register stack pop should be paired with a push");
8877bafa0eaSDan Gohman         }
8887bafa0eaSDan Gohman       }
8897bafa0eaSDan Gohman     }
8907bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
8917bafa0eaSDan Gohman     // basic block boundaries.
892adf28177SDan Gohman     assert(Stack.empty() &&
893adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
8947bafa0eaSDan Gohman   }
8957bafa0eaSDan Gohman #endif
8967bafa0eaSDan Gohman 
8971462faadSDan Gohman   return Changed;
8981462faadSDan Gohman }
899