17d523365SDimitry Andric //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
27d523365SDimitry Andric //
37d523365SDimitry Andric //                     The LLVM Compiler Infrastructure
47d523365SDimitry Andric //
57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source
67d523365SDimitry Andric // License. See LICENSE.TXT for details.
77d523365SDimitry Andric //
87d523365SDimitry Andric //===----------------------------------------------------------------------===//
97d523365SDimitry Andric ///
107d523365SDimitry Andric /// \file
117d523365SDimitry Andric /// \brief This file implements a register stacking pass.
127d523365SDimitry Andric ///
137d523365SDimitry Andric /// This pass reorders instructions to put register uses and defs in an order
147d523365SDimitry Andric /// such that they form single-use expression trees. Registers fitting this form
157d523365SDimitry Andric /// are then marked as "stackified", meaning references to them are replaced by
167d523365SDimitry Andric /// "push" and "pop" from the stack.
177d523365SDimitry Andric ///
187d523365SDimitry Andric /// This is primarily a code size optimization, since temporary values on the
197d523365SDimitry Andric /// expression don't need to be named.
207d523365SDimitry Andric ///
217d523365SDimitry Andric //===----------------------------------------------------------------------===//
227d523365SDimitry Andric 
237d523365SDimitry Andric #include "WebAssembly.h"
247d523365SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
257d523365SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h"
263ca95b02SDimitry Andric #include "WebAssemblySubtarget.h"
277d523365SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
287d523365SDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h"
297d523365SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
303ca95b02SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
313ca95b02SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
327d523365SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
337d523365SDimitry Andric #include "llvm/CodeGen/Passes.h"
347d523365SDimitry Andric #include "llvm/Support/Debug.h"
357d523365SDimitry Andric #include "llvm/Support/raw_ostream.h"
367d523365SDimitry Andric using namespace llvm;
377d523365SDimitry Andric 
387d523365SDimitry Andric #define DEBUG_TYPE "wasm-reg-stackify"
397d523365SDimitry Andric 
407d523365SDimitry Andric namespace {
417d523365SDimitry Andric class WebAssemblyRegStackify final : public MachineFunctionPass {
427d523365SDimitry Andric   const char *getPassName() const override {
437d523365SDimitry Andric     return "WebAssembly Register Stackify";
447d523365SDimitry Andric   }
457d523365SDimitry Andric 
467d523365SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
477d523365SDimitry Andric     AU.setPreservesCFG();
487d523365SDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
493ca95b02SDimitry Andric     AU.addRequired<MachineDominatorTree>();
507d523365SDimitry Andric     AU.addRequired<LiveIntervals>();
517d523365SDimitry Andric     AU.addPreserved<MachineBlockFrequencyInfo>();
527d523365SDimitry Andric     AU.addPreserved<SlotIndexes>();
537d523365SDimitry Andric     AU.addPreserved<LiveIntervals>();
547d523365SDimitry Andric     AU.addPreservedID(LiveVariablesID);
553ca95b02SDimitry Andric     AU.addPreserved<MachineDominatorTree>();
567d523365SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
577d523365SDimitry Andric   }
587d523365SDimitry Andric 
597d523365SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
607d523365SDimitry Andric 
617d523365SDimitry Andric public:
627d523365SDimitry Andric   static char ID; // Pass identification, replacement for typeid
637d523365SDimitry Andric   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
647d523365SDimitry Andric };
657d523365SDimitry Andric } // end anonymous namespace
667d523365SDimitry Andric 
677d523365SDimitry Andric char WebAssemblyRegStackify::ID = 0;
687d523365SDimitry Andric FunctionPass *llvm::createWebAssemblyRegStackify() {
697d523365SDimitry Andric   return new WebAssemblyRegStackify();
707d523365SDimitry Andric }
717d523365SDimitry Andric 
727d523365SDimitry Andric // Decorate the given instruction with implicit operands that enforce the
737d523365SDimitry Andric // expression stack ordering constraints for an instruction which is on
747d523365SDimitry Andric // the expression stack.
757d523365SDimitry Andric static void ImposeStackOrdering(MachineInstr *MI) {
767d523365SDimitry Andric   // Write the opaque EXPR_STACK register.
777d523365SDimitry Andric   if (!MI->definesRegister(WebAssembly::EXPR_STACK))
787d523365SDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
797d523365SDimitry Andric                                              /*isDef=*/true,
807d523365SDimitry Andric                                              /*isImp=*/true));
817d523365SDimitry Andric 
827d523365SDimitry Andric   // Also read the opaque EXPR_STACK register.
837d523365SDimitry Andric   if (!MI->readsRegister(WebAssembly::EXPR_STACK))
847d523365SDimitry Andric     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
857d523365SDimitry Andric                                              /*isDef=*/false,
867d523365SDimitry Andric                                              /*isImp=*/true));
877d523365SDimitry Andric }
887d523365SDimitry Andric 
893ca95b02SDimitry Andric // Determine whether a call to the callee referenced by
903ca95b02SDimitry Andric // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
913ca95b02SDimitry Andric // effects.
923ca95b02SDimitry Andric static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
933ca95b02SDimitry Andric                         bool &Write, bool &Effects, bool &StackPointer) {
943ca95b02SDimitry Andric   // All calls can use the stack pointer.
953ca95b02SDimitry Andric   StackPointer = true;
963ca95b02SDimitry Andric 
973ca95b02SDimitry Andric   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
983ca95b02SDimitry Andric   if (MO.isGlobal()) {
993ca95b02SDimitry Andric     const Constant *GV = MO.getGlobal();
1003ca95b02SDimitry Andric     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1013ca95b02SDimitry Andric       if (!GA->isInterposable())
1023ca95b02SDimitry Andric         GV = GA->getAliasee();
1033ca95b02SDimitry Andric 
1043ca95b02SDimitry Andric     if (const Function *F = dyn_cast<Function>(GV)) {
1053ca95b02SDimitry Andric       if (!F->doesNotThrow())
1063ca95b02SDimitry Andric         Effects = true;
1073ca95b02SDimitry Andric       if (F->doesNotAccessMemory())
1083ca95b02SDimitry Andric         return;
1093ca95b02SDimitry Andric       if (F->onlyReadsMemory()) {
1103ca95b02SDimitry Andric         Read = true;
1113ca95b02SDimitry Andric         return;
1123ca95b02SDimitry Andric       }
1133ca95b02SDimitry Andric     }
1143ca95b02SDimitry Andric   }
1153ca95b02SDimitry Andric 
1163ca95b02SDimitry Andric   // Assume the worst.
1173ca95b02SDimitry Andric   Write = true;
1183ca95b02SDimitry Andric   Read = true;
1193ca95b02SDimitry Andric   Effects = true;
1203ca95b02SDimitry Andric }
1213ca95b02SDimitry Andric 
1223ca95b02SDimitry Andric // Determine whether MI reads memory, writes memory, has side effects,
1233ca95b02SDimitry Andric // and/or uses the __stack_pointer value.
1243ca95b02SDimitry Andric static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
1253ca95b02SDimitry Andric                   bool &Write, bool &Effects, bool &StackPointer) {
1263ca95b02SDimitry Andric   assert(!MI.isPosition());
1273ca95b02SDimitry Andric   assert(!MI.isTerminator());
1283ca95b02SDimitry Andric 
1293ca95b02SDimitry Andric   if (MI.isDebugValue())
1303ca95b02SDimitry Andric     return;
1313ca95b02SDimitry Andric 
1323ca95b02SDimitry Andric   // Check for loads.
1333ca95b02SDimitry Andric   if (MI.mayLoad() && !MI.isInvariantLoad(&AA))
1343ca95b02SDimitry Andric     Read = true;
1353ca95b02SDimitry Andric 
1363ca95b02SDimitry Andric   // Check for stores.
1373ca95b02SDimitry Andric   if (MI.mayStore()) {
1383ca95b02SDimitry Andric     Write = true;
1393ca95b02SDimitry Andric 
1403ca95b02SDimitry Andric     // Check for stores to __stack_pointer.
1413ca95b02SDimitry Andric     for (auto MMO : MI.memoperands()) {
1423ca95b02SDimitry Andric       const MachinePointerInfo &MPI = MMO->getPointerInfo();
1433ca95b02SDimitry Andric       if (MPI.V.is<const PseudoSourceValue *>()) {
1443ca95b02SDimitry Andric         auto PSV = MPI.V.get<const PseudoSourceValue *>();
1453ca95b02SDimitry Andric         if (const ExternalSymbolPseudoSourceValue *EPSV =
1463ca95b02SDimitry Andric                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
1473ca95b02SDimitry Andric           if (StringRef(EPSV->getSymbol()) == "__stack_pointer")
1483ca95b02SDimitry Andric             StackPointer = true;
1493ca95b02SDimitry Andric       }
1503ca95b02SDimitry Andric     }
1513ca95b02SDimitry Andric   } else if (MI.hasOrderedMemoryRef()) {
1523ca95b02SDimitry Andric     switch (MI.getOpcode()) {
1533ca95b02SDimitry Andric     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1543ca95b02SDimitry Andric     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1553ca95b02SDimitry Andric     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1563ca95b02SDimitry Andric     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1573ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1583ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1593ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1603ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1613ca95b02SDimitry Andric       // These instruction have hasUnmodeledSideEffects() returning true
1623ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
1633ca95b02SDimitry Andric       // moved, however hasOrderedMemoryRef() interprets this plus their lack
1643ca95b02SDimitry Andric       // of memoperands as having a potential unknown memory reference.
1653ca95b02SDimitry Andric       break;
1663ca95b02SDimitry Andric     default:
1673ca95b02SDimitry Andric       // Record volatile accesses, unless it's a call, as calls are handled
1683ca95b02SDimitry Andric       // specially below.
1693ca95b02SDimitry Andric       if (!MI.isCall()) {
1703ca95b02SDimitry Andric         Write = true;
1713ca95b02SDimitry Andric         Effects = true;
1723ca95b02SDimitry Andric       }
1733ca95b02SDimitry Andric       break;
1743ca95b02SDimitry Andric     }
1753ca95b02SDimitry Andric   }
1763ca95b02SDimitry Andric 
1773ca95b02SDimitry Andric   // Check for side effects.
1783ca95b02SDimitry Andric   if (MI.hasUnmodeledSideEffects()) {
1793ca95b02SDimitry Andric     switch (MI.getOpcode()) {
1803ca95b02SDimitry Andric     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1813ca95b02SDimitry Andric     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1823ca95b02SDimitry Andric     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1833ca95b02SDimitry Andric     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1843ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1853ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1863ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1873ca95b02SDimitry Andric     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1883ca95b02SDimitry Andric       // These instructions have hasUnmodeledSideEffects() returning true
1893ca95b02SDimitry Andric       // because they trap on overflow and invalid so they can't be arbitrarily
1903ca95b02SDimitry Andric       // moved, however in the specific case of register stackifying, it is safe
1913ca95b02SDimitry Andric       // to move them because overflow and invalid are Undefined Behavior.
1923ca95b02SDimitry Andric       break;
1933ca95b02SDimitry Andric     default:
1943ca95b02SDimitry Andric       Effects = true;
1953ca95b02SDimitry Andric       break;
1963ca95b02SDimitry Andric     }
1973ca95b02SDimitry Andric   }
1983ca95b02SDimitry Andric 
1993ca95b02SDimitry Andric   // Analyze calls.
2003ca95b02SDimitry Andric   if (MI.isCall()) {
2013ca95b02SDimitry Andric     switch (MI.getOpcode()) {
2023ca95b02SDimitry Andric     case WebAssembly::CALL_VOID:
2033ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_VOID:
2043ca95b02SDimitry Andric       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
2053ca95b02SDimitry Andric       break;
2063ca95b02SDimitry Andric     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
2073ca95b02SDimitry Andric     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
2083ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
2093ca95b02SDimitry Andric     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
2103ca95b02SDimitry Andric       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
2113ca95b02SDimitry Andric       break;
2123ca95b02SDimitry Andric     default:
2133ca95b02SDimitry Andric       llvm_unreachable("unexpected call opcode");
2143ca95b02SDimitry Andric     }
2153ca95b02SDimitry Andric   }
2163ca95b02SDimitry Andric }
2173ca95b02SDimitry Andric 
2183ca95b02SDimitry Andric // Test whether Def is safe and profitable to rematerialize.
2193ca95b02SDimitry Andric static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2203ca95b02SDimitry Andric                                 const WebAssemblyInstrInfo *TII) {
2213ca95b02SDimitry Andric   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2223ca95b02SDimitry Andric }
2233ca95b02SDimitry Andric 
2243ca95b02SDimitry Andric // Identify the definition for this register at this point. This is a
2253ca95b02SDimitry Andric // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
2263ca95b02SDimitry Andric // LiveIntervals to handle complex cases.
2273ca95b02SDimitry Andric static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2283ca95b02SDimitry Andric                                 const MachineRegisterInfo &MRI,
2293ca95b02SDimitry Andric                                 const LiveIntervals &LIS)
2303ca95b02SDimitry Andric {
2313ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2323ca95b02SDimitry Andric   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2333ca95b02SDimitry Andric     return Def;
2343ca95b02SDimitry Andric 
2353ca95b02SDimitry Andric   // MRI doesn't know what the Def is. Try asking LIS.
2363ca95b02SDimitry Andric   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2373ca95b02SDimitry Andric           LIS.getInstructionIndex(*Insert)))
2383ca95b02SDimitry Andric     return LIS.getInstructionFromIndex(ValNo->def);
2393ca95b02SDimitry Andric 
2403ca95b02SDimitry Andric   return nullptr;
2413ca95b02SDimitry Andric }
2423ca95b02SDimitry Andric 
2433ca95b02SDimitry Andric // Test whether Reg, as defined at Def, has exactly one use. This is a
2443ca95b02SDimitry Andric // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
2453ca95b02SDimitry Andric // to handle complex cases.
2463ca95b02SDimitry Andric static bool HasOneUse(unsigned Reg, MachineInstr *Def,
2473ca95b02SDimitry Andric                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
2483ca95b02SDimitry Andric                       LiveIntervals &LIS) {
2493ca95b02SDimitry Andric   // Most registers are in SSA form here so we try a quick MRI query first.
2503ca95b02SDimitry Andric   if (MRI.hasOneUse(Reg))
2513ca95b02SDimitry Andric     return true;
2523ca95b02SDimitry Andric 
2533ca95b02SDimitry Andric   bool HasOne = false;
2543ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
2553ca95b02SDimitry Andric   const VNInfo *DefVNI = LI.getVNInfoAt(
2563ca95b02SDimitry Andric       LIS.getInstructionIndex(*Def).getRegSlot());
2573ca95b02SDimitry Andric   assert(DefVNI);
2583ca95b02SDimitry Andric   for (auto I : MRI.use_nodbg_operands(Reg)) {
2593ca95b02SDimitry Andric     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
2603ca95b02SDimitry Andric     if (Result.valueIn() == DefVNI) {
2613ca95b02SDimitry Andric       if (!Result.isKill())
2623ca95b02SDimitry Andric         return false;
2633ca95b02SDimitry Andric       if (HasOne)
2643ca95b02SDimitry Andric         return false;
2653ca95b02SDimitry Andric       HasOne = true;
2663ca95b02SDimitry Andric     }
2673ca95b02SDimitry Andric   }
2683ca95b02SDimitry Andric   return HasOne;
2693ca95b02SDimitry Andric }
2703ca95b02SDimitry Andric 
2717d523365SDimitry Andric // Test whether it's safe to move Def to just before Insert.
2727d523365SDimitry Andric // TODO: Compute memory dependencies in a way that doesn't require always
2737d523365SDimitry Andric // walking the block.
2747d523365SDimitry Andric // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
2757d523365SDimitry Andric // more precise.
2767d523365SDimitry Andric static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
2773ca95b02SDimitry Andric                          AliasAnalysis &AA, const LiveIntervals &LIS,
2783ca95b02SDimitry Andric                          const MachineRegisterInfo &MRI) {
2797d523365SDimitry Andric   assert(Def->getParent() == Insert->getParent());
2807d523365SDimitry Andric 
2817d523365SDimitry Andric   // Check for register dependencies.
2827d523365SDimitry Andric   for (const MachineOperand &MO : Def->operands()) {
2837d523365SDimitry Andric     if (!MO.isReg() || MO.isUndef())
2847d523365SDimitry Andric       continue;
2857d523365SDimitry Andric     unsigned Reg = MO.getReg();
2867d523365SDimitry Andric 
2877d523365SDimitry Andric     // If the register is dead here and at Insert, ignore it.
2887d523365SDimitry Andric     if (MO.isDead() && Insert->definesRegister(Reg) &&
2897d523365SDimitry Andric         !Insert->readsRegister(Reg))
2907d523365SDimitry Andric       continue;
2917d523365SDimitry Andric 
2927d523365SDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2933ca95b02SDimitry Andric       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
2943ca95b02SDimitry Andric       // from moving down, and we've already checked for that.
2953ca95b02SDimitry Andric       if (Reg == WebAssembly::ARGUMENTS)
2963ca95b02SDimitry Andric         continue;
2977d523365SDimitry Andric       // If the physical register is never modified, ignore it.
2987d523365SDimitry Andric       if (!MRI.isPhysRegModified(Reg))
2997d523365SDimitry Andric         continue;
3007d523365SDimitry Andric       // Otherwise, it's a physical register with unknown liveness.
3017d523365SDimitry Andric       return false;
3027d523365SDimitry Andric     }
3037d523365SDimitry Andric 
3047d523365SDimitry Andric     // Ask LiveIntervals whether moving this virtual register use or def to
3053ca95b02SDimitry Andric     // Insert will change which value numbers are seen.
3063ca95b02SDimitry Andric     //
3073ca95b02SDimitry Andric     // If the operand is a use of a register that is also defined in the same
3083ca95b02SDimitry Andric     // instruction, test that the newly defined value reaches the insert point,
3093ca95b02SDimitry Andric     // since the operand will be moving along with the def.
3107d523365SDimitry Andric     const LiveInterval &LI = LIS.getInterval(Reg);
3113ca95b02SDimitry Andric     VNInfo *DefVNI =
3123ca95b02SDimitry Andric         (MO.isDef() || Def->definesRegister(Reg)) ?
3133ca95b02SDimitry Andric         LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) :
3143ca95b02SDimitry Andric         LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
3157d523365SDimitry Andric     assert(DefVNI && "Instruction input missing value number");
3163ca95b02SDimitry Andric     VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
3177d523365SDimitry Andric     if (InsVNI && DefVNI != InsVNI)
3187d523365SDimitry Andric       return false;
3197d523365SDimitry Andric   }
3207d523365SDimitry Andric 
3213ca95b02SDimitry Andric   bool Read = false, Write = false, Effects = false, StackPointer = false;
3223ca95b02SDimitry Andric   Query(*Def, AA, Read, Write, Effects, StackPointer);
3233ca95b02SDimitry Andric 
3243ca95b02SDimitry Andric   // If the instruction does not access memory and has no side effects, it has
3253ca95b02SDimitry Andric   // no additional dependencies.
3263ca95b02SDimitry Andric   if (!Read && !Write && !Effects && !StackPointer)
3273ca95b02SDimitry Andric     return true;
3283ca95b02SDimitry Andric 
3293ca95b02SDimitry Andric   // Scan through the intervening instructions between Def and Insert.
3303ca95b02SDimitry Andric   MachineBasicBlock::const_iterator D(Def), I(Insert);
3313ca95b02SDimitry Andric   for (--I; I != D; --I) {
3323ca95b02SDimitry Andric     bool InterveningRead = false;
3333ca95b02SDimitry Andric     bool InterveningWrite = false;
3343ca95b02SDimitry Andric     bool InterveningEffects = false;
3353ca95b02SDimitry Andric     bool InterveningStackPointer = false;
3363ca95b02SDimitry Andric     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
3373ca95b02SDimitry Andric           InterveningStackPointer);
3383ca95b02SDimitry Andric     if (Effects && InterveningEffects)
3393ca95b02SDimitry Andric       return false;
3403ca95b02SDimitry Andric     if (Read && InterveningWrite)
3413ca95b02SDimitry Andric       return false;
3423ca95b02SDimitry Andric     if (Write && (InterveningRead || InterveningWrite))
3433ca95b02SDimitry Andric       return false;
3443ca95b02SDimitry Andric     if (StackPointer && InterveningStackPointer)
3453ca95b02SDimitry Andric       return false;
3467d523365SDimitry Andric   }
3477d523365SDimitry Andric 
3483ca95b02SDimitry Andric   return true;
3493ca95b02SDimitry Andric }
3503ca95b02SDimitry Andric 
3513ca95b02SDimitry Andric /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
3523ca95b02SDimitry Andric static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
3533ca95b02SDimitry Andric                                      const MachineBasicBlock &MBB,
3543ca95b02SDimitry Andric                                      const MachineRegisterInfo &MRI,
3553ca95b02SDimitry Andric                                      const MachineDominatorTree &MDT,
3563ca95b02SDimitry Andric                                      LiveIntervals &LIS,
3573ca95b02SDimitry Andric                                      WebAssemblyFunctionInfo &MFI) {
3583ca95b02SDimitry Andric   const LiveInterval &LI = LIS.getInterval(Reg);
3593ca95b02SDimitry Andric 
3603ca95b02SDimitry Andric   const MachineInstr *OneUseInst = OneUse.getParent();
3613ca95b02SDimitry Andric   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3623ca95b02SDimitry Andric 
3633ca95b02SDimitry Andric   for (const MachineOperand &Use : MRI.use_operands(Reg)) {
3643ca95b02SDimitry Andric     if (&Use == &OneUse)
3653ca95b02SDimitry Andric       continue;
3663ca95b02SDimitry Andric 
3673ca95b02SDimitry Andric     const MachineInstr *UseInst = Use.getParent();
3683ca95b02SDimitry Andric     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
3693ca95b02SDimitry Andric 
3703ca95b02SDimitry Andric     if (UseVNI != OneUseVNI)
3713ca95b02SDimitry Andric       continue;
3723ca95b02SDimitry Andric 
3733ca95b02SDimitry Andric     const MachineInstr *OneUseInst = OneUse.getParent();
3743ca95b02SDimitry Andric     if (UseInst == OneUseInst) {
3753ca95b02SDimitry Andric       // Another use in the same instruction. We need to ensure that the one
3763ca95b02SDimitry Andric       // selected use happens "before" it.
3773ca95b02SDimitry Andric       if (&OneUse > &Use)
3783ca95b02SDimitry Andric         return false;
3793ca95b02SDimitry Andric     } else {
3803ca95b02SDimitry Andric       // Test that the use is dominated by the one selected use.
3813ca95b02SDimitry Andric       while (!MDT.dominates(OneUseInst, UseInst)) {
3823ca95b02SDimitry Andric         // Actually, dominating is over-conservative. Test that the use would
3833ca95b02SDimitry Andric         // happen after the one selected use in the stack evaluation order.
3843ca95b02SDimitry Andric         //
3853ca95b02SDimitry Andric         // This is needed as a consequence of using implicit get_locals for
3863ca95b02SDimitry Andric         // uses and implicit set_locals for defs.
3873ca95b02SDimitry Andric         if (UseInst->getDesc().getNumDefs() == 0)
3883ca95b02SDimitry Andric           return false;
3893ca95b02SDimitry Andric         const MachineOperand &MO = UseInst->getOperand(0);
3903ca95b02SDimitry Andric         if (!MO.isReg())
3913ca95b02SDimitry Andric           return false;
3923ca95b02SDimitry Andric         unsigned DefReg = MO.getReg();
3933ca95b02SDimitry Andric         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
3943ca95b02SDimitry Andric             !MFI.isVRegStackified(DefReg))
3953ca95b02SDimitry Andric           return false;
3963ca95b02SDimitry Andric         assert(MRI.hasOneUse(DefReg));
3973ca95b02SDimitry Andric         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
3983ca95b02SDimitry Andric         const MachineInstr *NewUseInst = NewUse.getParent();
3993ca95b02SDimitry Andric         if (NewUseInst == OneUseInst) {
4003ca95b02SDimitry Andric           if (&OneUse > &NewUse)
4013ca95b02SDimitry Andric             return false;
4023ca95b02SDimitry Andric           break;
4033ca95b02SDimitry Andric         }
4043ca95b02SDimitry Andric         UseInst = NewUseInst;
4053ca95b02SDimitry Andric       }
4063ca95b02SDimitry Andric     }
4073ca95b02SDimitry Andric   }
4083ca95b02SDimitry Andric   return true;
4093ca95b02SDimitry Andric }
4103ca95b02SDimitry Andric 
4113ca95b02SDimitry Andric /// Get the appropriate tee_local opcode for the given register class.
4123ca95b02SDimitry Andric static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
4133ca95b02SDimitry Andric   if (RC == &WebAssembly::I32RegClass)
4143ca95b02SDimitry Andric     return WebAssembly::TEE_LOCAL_I32;
4153ca95b02SDimitry Andric   if (RC == &WebAssembly::I64RegClass)
4163ca95b02SDimitry Andric     return WebAssembly::TEE_LOCAL_I64;
4173ca95b02SDimitry Andric   if (RC == &WebAssembly::F32RegClass)
4183ca95b02SDimitry Andric     return WebAssembly::TEE_LOCAL_F32;
4193ca95b02SDimitry Andric   if (RC == &WebAssembly::F64RegClass)
4203ca95b02SDimitry Andric     return WebAssembly::TEE_LOCAL_F64;
4213ca95b02SDimitry Andric   llvm_unreachable("Unexpected register class");
4223ca95b02SDimitry Andric }
4233ca95b02SDimitry Andric 
4243ca95b02SDimitry Andric // Shrink LI to its uses, cleaning up LI.
4253ca95b02SDimitry Andric static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4263ca95b02SDimitry Andric   if (LIS.shrinkToUses(&LI)) {
4273ca95b02SDimitry Andric     SmallVector<LiveInterval*, 4> SplitLIs;
4283ca95b02SDimitry Andric     LIS.splitSeparateComponents(LI, SplitLIs);
4293ca95b02SDimitry Andric   }
4303ca95b02SDimitry Andric }
4313ca95b02SDimitry Andric 
4323ca95b02SDimitry Andric /// A single-use def in the same block with no intervening memory or register
4333ca95b02SDimitry Andric /// dependencies; move the def down and nest it with the current instruction.
4343ca95b02SDimitry Andric static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
4353ca95b02SDimitry Andric                                       MachineInstr *Def,
4363ca95b02SDimitry Andric                                       MachineBasicBlock &MBB,
4373ca95b02SDimitry Andric                                       MachineInstr *Insert, LiveIntervals &LIS,
4383ca95b02SDimitry Andric                                       WebAssemblyFunctionInfo &MFI,
4393ca95b02SDimitry Andric                                       MachineRegisterInfo &MRI) {
4403ca95b02SDimitry Andric   DEBUG(dbgs() << "Move for single use: "; Def->dump());
4413ca95b02SDimitry Andric 
4423ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
4433ca95b02SDimitry Andric   LIS.handleMove(*Def);
4443ca95b02SDimitry Andric 
4453ca95b02SDimitry Andric   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
4463ca95b02SDimitry Andric     // No one else is using this register for anything so we can just stackify
4473ca95b02SDimitry Andric     // it in place.
4483ca95b02SDimitry Andric     MFI.stackifyVReg(Reg);
4493ca95b02SDimitry Andric   } else {
4503ca95b02SDimitry Andric     // The register may have unrelated uses or defs; create a new register for
4513ca95b02SDimitry Andric     // just our one def and use so that we can stackify it.
4523ca95b02SDimitry Andric     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4533ca95b02SDimitry Andric     Def->getOperand(0).setReg(NewReg);
4543ca95b02SDimitry Andric     Op.setReg(NewReg);
4553ca95b02SDimitry Andric 
4563ca95b02SDimitry Andric     // Tell LiveIntervals about the new register.
4573ca95b02SDimitry Andric     LIS.createAndComputeVirtRegInterval(NewReg);
4583ca95b02SDimitry Andric 
4593ca95b02SDimitry Andric     // Tell LiveIntervals about the changes to the old register.
4603ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
4613ca95b02SDimitry Andric     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
4623ca95b02SDimitry Andric                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
4633ca95b02SDimitry Andric                      /*RemoveDeadValNo=*/true);
4643ca95b02SDimitry Andric 
4653ca95b02SDimitry Andric     MFI.stackifyVReg(NewReg);
4663ca95b02SDimitry Andric 
4673ca95b02SDimitry Andric     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
4683ca95b02SDimitry Andric   }
4693ca95b02SDimitry Andric 
4703ca95b02SDimitry Andric   ImposeStackOrdering(Def);
4713ca95b02SDimitry Andric   return Def;
4723ca95b02SDimitry Andric }
4733ca95b02SDimitry Andric 
4743ca95b02SDimitry Andric /// A trivially cloneable instruction; clone it and nest the new copy with the
4753ca95b02SDimitry Andric /// current instruction.
4763ca95b02SDimitry Andric static MachineInstr *RematerializeCheapDef(
4773ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
4783ca95b02SDimitry Andric     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
4793ca95b02SDimitry Andric     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
4803ca95b02SDimitry Andric     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
4813ca95b02SDimitry Andric   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
4823ca95b02SDimitry Andric   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
4833ca95b02SDimitry Andric 
4843ca95b02SDimitry Andric   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4853ca95b02SDimitry Andric   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
4863ca95b02SDimitry Andric   Op.setReg(NewReg);
4873ca95b02SDimitry Andric   MachineInstr *Clone = &*std::prev(Insert);
4883ca95b02SDimitry Andric   LIS.InsertMachineInstrInMaps(*Clone);
4893ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(NewReg);
4903ca95b02SDimitry Andric   MFI.stackifyVReg(NewReg);
4913ca95b02SDimitry Andric   ImposeStackOrdering(Clone);
4923ca95b02SDimitry Andric 
4933ca95b02SDimitry Andric   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
4943ca95b02SDimitry Andric 
4953ca95b02SDimitry Andric   // Shrink the interval.
4963ca95b02SDimitry Andric   bool IsDead = MRI.use_empty(Reg);
4973ca95b02SDimitry Andric   if (!IsDead) {
4983ca95b02SDimitry Andric     LiveInterval &LI = LIS.getInterval(Reg);
4993ca95b02SDimitry Andric     ShrinkToUses(LI, LIS);
5003ca95b02SDimitry Andric     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5013ca95b02SDimitry Andric   }
5023ca95b02SDimitry Andric 
5033ca95b02SDimitry Andric   // If that was the last use of the original, delete the original.
5043ca95b02SDimitry Andric   if (IsDead) {
5053ca95b02SDimitry Andric     DEBUG(dbgs() << " - Deleting original\n");
5063ca95b02SDimitry Andric     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
5073ca95b02SDimitry Andric     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
5083ca95b02SDimitry Andric     LIS.removeInterval(Reg);
5093ca95b02SDimitry Andric     LIS.RemoveMachineInstrFromMaps(Def);
5103ca95b02SDimitry Andric     Def.eraseFromParent();
5113ca95b02SDimitry Andric   }
5123ca95b02SDimitry Andric 
5133ca95b02SDimitry Andric   return Clone;
5143ca95b02SDimitry Andric }
5153ca95b02SDimitry Andric 
5163ca95b02SDimitry Andric /// A multiple-use def in the same block with no intervening memory or register
5173ca95b02SDimitry Andric /// dependencies; move the def down, nest it with the current instruction, and
5183ca95b02SDimitry Andric /// insert a tee_local to satisfy the rest of the uses. As an illustration,
5193ca95b02SDimitry Andric /// rewrite this:
5203ca95b02SDimitry Andric ///
5213ca95b02SDimitry Andric ///    Reg = INST ...        // Def
5223ca95b02SDimitry Andric ///    INST ..., Reg, ...    // Insert
5233ca95b02SDimitry Andric ///    INST ..., Reg, ...
5243ca95b02SDimitry Andric ///    INST ..., Reg, ...
5253ca95b02SDimitry Andric ///
5263ca95b02SDimitry Andric /// to this:
5273ca95b02SDimitry Andric ///
5283ca95b02SDimitry Andric ///    DefReg = INST ...     // Def (to become the new Insert)
5293ca95b02SDimitry Andric ///    TeeReg, Reg = TEE_LOCAL_... DefReg
5303ca95b02SDimitry Andric ///    INST ..., TeeReg, ... // Insert
5313ca95b02SDimitry Andric ///    INST ..., Reg, ...
5323ca95b02SDimitry Andric ///    INST ..., Reg, ...
5333ca95b02SDimitry Andric ///
5343ca95b02SDimitry Andric /// with DefReg and TeeReg stackified. This eliminates a get_local from the
5353ca95b02SDimitry Andric /// resulting code.
5363ca95b02SDimitry Andric static MachineInstr *MoveAndTeeForMultiUse(
5373ca95b02SDimitry Andric     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
5383ca95b02SDimitry Andric     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
5393ca95b02SDimitry Andric     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5403ca95b02SDimitry Andric   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5413ca95b02SDimitry Andric 
5423ca95b02SDimitry Andric   // Move Def into place.
5433ca95b02SDimitry Andric   MBB.splice(Insert, &MBB, Def);
5443ca95b02SDimitry Andric   LIS.handleMove(*Def);
5453ca95b02SDimitry Andric 
5463ca95b02SDimitry Andric   // Create the Tee and attach the registers.
5473ca95b02SDimitry Andric   const auto *RegClass = MRI.getRegClass(Reg);
5483ca95b02SDimitry Andric   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5493ca95b02SDimitry Andric   unsigned DefReg = MRI.createVirtualRegister(RegClass);
5503ca95b02SDimitry Andric   MachineOperand &DefMO = Def->getOperand(0);
5513ca95b02SDimitry Andric   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
5523ca95b02SDimitry Andric                               TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
5533ca95b02SDimitry Andric                           .addReg(Reg, RegState::Define)
5543ca95b02SDimitry Andric                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
5553ca95b02SDimitry Andric   Op.setReg(TeeReg);
5563ca95b02SDimitry Andric   DefMO.setReg(DefReg);
5573ca95b02SDimitry Andric   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
5583ca95b02SDimitry Andric   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
5593ca95b02SDimitry Andric 
5603ca95b02SDimitry Andric   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
5613ca95b02SDimitry Andric   LiveInterval &LI = LIS.getInterval(Reg);
5623ca95b02SDimitry Andric   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
5633ca95b02SDimitry Andric   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
5643ca95b02SDimitry Andric   I->start = TeeIdx;
5653ca95b02SDimitry Andric   ValNo->def = TeeIdx;
5663ca95b02SDimitry Andric   ShrinkToUses(LI, LIS);
5673ca95b02SDimitry Andric 
5683ca95b02SDimitry Andric   // Finish stackifying the new regs.
5693ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(TeeReg);
5703ca95b02SDimitry Andric   LIS.createAndComputeVirtRegInterval(DefReg);
5713ca95b02SDimitry Andric   MFI.stackifyVReg(DefReg);
5723ca95b02SDimitry Andric   MFI.stackifyVReg(TeeReg);
5733ca95b02SDimitry Andric   ImposeStackOrdering(Def);
5743ca95b02SDimitry Andric   ImposeStackOrdering(Tee);
5753ca95b02SDimitry Andric 
5763ca95b02SDimitry Andric   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5773ca95b02SDimitry Andric   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
5783ca95b02SDimitry Andric   return Def;
5793ca95b02SDimitry Andric }
5803ca95b02SDimitry Andric 
5813ca95b02SDimitry Andric namespace {
5823ca95b02SDimitry Andric /// A stack for walking the tree of instructions being built, visiting the
5833ca95b02SDimitry Andric /// MachineOperands in DFS order.
5843ca95b02SDimitry Andric class TreeWalkerState {
5853ca95b02SDimitry Andric   typedef MachineInstr::mop_iterator mop_iterator;
5863ca95b02SDimitry Andric   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
5873ca95b02SDimitry Andric   typedef iterator_range<mop_reverse_iterator> RangeTy;
5883ca95b02SDimitry Andric   SmallVector<RangeTy, 4> Worklist;
5893ca95b02SDimitry Andric 
5903ca95b02SDimitry Andric public:
5913ca95b02SDimitry Andric   explicit TreeWalkerState(MachineInstr *Insert) {
5923ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
5933ca95b02SDimitry Andric     if (Range.begin() != Range.end())
5943ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
5953ca95b02SDimitry Andric   }
5963ca95b02SDimitry Andric 
5973ca95b02SDimitry Andric   bool Done() const { return Worklist.empty(); }
5983ca95b02SDimitry Andric 
5993ca95b02SDimitry Andric   MachineOperand &Pop() {
6003ca95b02SDimitry Andric     RangeTy &Range = Worklist.back();
6013ca95b02SDimitry Andric     MachineOperand &Op = *Range.begin();
6023ca95b02SDimitry Andric     Range = drop_begin(Range, 1);
6033ca95b02SDimitry Andric     if (Range.begin() == Range.end())
6043ca95b02SDimitry Andric       Worklist.pop_back();
6053ca95b02SDimitry Andric     assert((Worklist.empty() ||
6063ca95b02SDimitry Andric             Worklist.back().begin() != Worklist.back().end()) &&
6073ca95b02SDimitry Andric            "Empty ranges shouldn't remain in the worklist");
6083ca95b02SDimitry Andric     return Op;
6093ca95b02SDimitry Andric   }
6103ca95b02SDimitry Andric 
6113ca95b02SDimitry Andric   /// Push Instr's operands onto the stack to be visited.
6123ca95b02SDimitry Andric   void PushOperands(MachineInstr *Instr) {
6133ca95b02SDimitry Andric     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
6143ca95b02SDimitry Andric     if (Range.begin() != Range.end())
6153ca95b02SDimitry Andric       Worklist.push_back(reverse(Range));
6163ca95b02SDimitry Andric   }
6173ca95b02SDimitry Andric 
6183ca95b02SDimitry Andric   /// Some of Instr's operands are on the top of the stack; remove them and
6193ca95b02SDimitry Andric   /// re-insert them starting from the beginning (because we've commuted them).
6203ca95b02SDimitry Andric   void ResetTopOperands(MachineInstr *Instr) {
6213ca95b02SDimitry Andric     assert(HasRemainingOperands(Instr) &&
6223ca95b02SDimitry Andric            "Reseting operands should only be done when the instruction has "
6233ca95b02SDimitry Andric            "an operand still on the stack");
6243ca95b02SDimitry Andric     Worklist.back() = reverse(Instr->explicit_uses());
6253ca95b02SDimitry Andric   }
6263ca95b02SDimitry Andric 
6273ca95b02SDimitry Andric   /// Test whether Instr has operands remaining to be visited at the top of
6283ca95b02SDimitry Andric   /// the stack.
6293ca95b02SDimitry Andric   bool HasRemainingOperands(const MachineInstr *Instr) const {
6303ca95b02SDimitry Andric     if (Worklist.empty())
6313ca95b02SDimitry Andric       return false;
6323ca95b02SDimitry Andric     const RangeTy &Range = Worklist.back();
6333ca95b02SDimitry Andric     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
6343ca95b02SDimitry Andric   }
6353ca95b02SDimitry Andric 
6363ca95b02SDimitry Andric   /// Test whether the given register is present on the stack, indicating an
6373ca95b02SDimitry Andric   /// operand in the tree that we haven't visited yet. Moving a definition of
6383ca95b02SDimitry Andric   /// Reg to a point in the tree after that would change its value.
6393ca95b02SDimitry Andric   ///
6403ca95b02SDimitry Andric   /// This is needed as a consequence of using implicit get_locals for
6413ca95b02SDimitry Andric   /// uses and implicit set_locals for defs.
6423ca95b02SDimitry Andric   bool IsOnStack(unsigned Reg) const {
6433ca95b02SDimitry Andric     for (const RangeTy &Range : Worklist)
6443ca95b02SDimitry Andric       for (const MachineOperand &MO : Range)
6453ca95b02SDimitry Andric         if (MO.isReg() && MO.getReg() == Reg)
6463ca95b02SDimitry Andric           return true;
6473ca95b02SDimitry Andric     return false;
6483ca95b02SDimitry Andric   }
6493ca95b02SDimitry Andric };
6503ca95b02SDimitry Andric 
6513ca95b02SDimitry Andric /// State to keep track of whether commuting is in flight or whether it's been
6523ca95b02SDimitry Andric /// tried for the current instruction and didn't work.
6533ca95b02SDimitry Andric class CommutingState {
6543ca95b02SDimitry Andric   /// There are effectively three states: the initial state where we haven't
6553ca95b02SDimitry Andric   /// started commuting anything and we don't know anything yet, the tenative
6563ca95b02SDimitry Andric   /// state where we've commuted the operands of the current instruction and are
6573ca95b02SDimitry Andric   /// revisting it, and the declined state where we've reverted the operands
6583ca95b02SDimitry Andric   /// back to their original order and will no longer commute it further.
6593ca95b02SDimitry Andric   bool TentativelyCommuting;
6603ca95b02SDimitry Andric   bool Declined;
6613ca95b02SDimitry Andric 
6623ca95b02SDimitry Andric   /// During the tentative state, these hold the operand indices of the commuted
6633ca95b02SDimitry Andric   /// operands.
6643ca95b02SDimitry Andric   unsigned Operand0, Operand1;
6653ca95b02SDimitry Andric 
6663ca95b02SDimitry Andric public:
6673ca95b02SDimitry Andric   CommutingState() : TentativelyCommuting(false), Declined(false) {}
6683ca95b02SDimitry Andric 
6693ca95b02SDimitry Andric   /// Stackification for an operand was not successful due to ordering
6703ca95b02SDimitry Andric   /// constraints. If possible, and if we haven't already tried it and declined
6713ca95b02SDimitry Andric   /// it, commute Insert's operands and prepare to revisit it.
6723ca95b02SDimitry Andric   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
6733ca95b02SDimitry Andric                     const WebAssemblyInstrInfo *TII) {
6743ca95b02SDimitry Andric     if (TentativelyCommuting) {
6753ca95b02SDimitry Andric       assert(!Declined &&
6763ca95b02SDimitry Andric              "Don't decline commuting until you've finished trying it");
6773ca95b02SDimitry Andric       // Commuting didn't help. Revert it.
6783ca95b02SDimitry Andric       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
6793ca95b02SDimitry Andric       TentativelyCommuting = false;
6803ca95b02SDimitry Andric       Declined = true;
6813ca95b02SDimitry Andric     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
6823ca95b02SDimitry Andric       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
6833ca95b02SDimitry Andric       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
6843ca95b02SDimitry Andric       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
6853ca95b02SDimitry Andric         // Tentatively commute the operands and try again.
6863ca95b02SDimitry Andric         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
6873ca95b02SDimitry Andric         TreeWalker.ResetTopOperands(Insert);
6883ca95b02SDimitry Andric         TentativelyCommuting = true;
6893ca95b02SDimitry Andric         Declined = false;
6903ca95b02SDimitry Andric       }
6913ca95b02SDimitry Andric     }
6923ca95b02SDimitry Andric   }
6933ca95b02SDimitry Andric 
6943ca95b02SDimitry Andric   /// Stackification for some operand was successful. Reset to the default
6953ca95b02SDimitry Andric   /// state.
6963ca95b02SDimitry Andric   void Reset() {
6973ca95b02SDimitry Andric     TentativelyCommuting = false;
6983ca95b02SDimitry Andric     Declined = false;
6993ca95b02SDimitry Andric   }
7003ca95b02SDimitry Andric };
7013ca95b02SDimitry Andric } // end anonymous namespace
7023ca95b02SDimitry Andric 
7037d523365SDimitry Andric bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7047d523365SDimitry Andric   DEBUG(dbgs() << "********** Register Stackifying **********\n"
7057d523365SDimitry Andric                   "********** Function: "
7067d523365SDimitry Andric                << MF.getName() << '\n');
7077d523365SDimitry Andric 
7087d523365SDimitry Andric   bool Changed = false;
7097d523365SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
7107d523365SDimitry Andric   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
7113ca95b02SDimitry Andric   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
7123ca95b02SDimitry Andric   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
7137d523365SDimitry Andric   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
7143ca95b02SDimitry Andric   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7157d523365SDimitry Andric   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
7167d523365SDimitry Andric 
7177d523365SDimitry Andric   // Walk the instructions from the bottom up. Currently we don't look past
7187d523365SDimitry Andric   // block boundaries, and the blocks aren't ordered so the block visitation
7197d523365SDimitry Andric   // order isn't significant, but we may want to change this in the future.
7207d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
721444ed5c5SDimitry Andric     // Don't use a range-based for loop, because we modify the list as we're
722444ed5c5SDimitry Andric     // iterating over it and the end iterator may change.
723444ed5c5SDimitry Andric     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
724444ed5c5SDimitry Andric       MachineInstr *Insert = &*MII;
7257d523365SDimitry Andric       // Don't nest anything inside an inline asm, because we don't have
7267d523365SDimitry Andric       // constraints for $push inputs.
7277d523365SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
7283ca95b02SDimitry Andric         continue;
7293ca95b02SDimitry Andric 
7303ca95b02SDimitry Andric       // Ignore debugging intrinsics.
7313ca95b02SDimitry Andric       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
7323ca95b02SDimitry Andric         continue;
7337d523365SDimitry Andric 
7347d523365SDimitry Andric       // Iterate through the inputs in reverse order, since we'll be pulling
7357d523365SDimitry Andric       // operands off the stack in LIFO order.
7363ca95b02SDimitry Andric       CommutingState Commuting;
7373ca95b02SDimitry Andric       TreeWalkerState TreeWalker(Insert);
7383ca95b02SDimitry Andric       while (!TreeWalker.Done()) {
7393ca95b02SDimitry Andric         MachineOperand &Op = TreeWalker.Pop();
7403ca95b02SDimitry Andric 
7417d523365SDimitry Andric         // We're only interested in explicit virtual register operands.
7423ca95b02SDimitry Andric         if (!Op.isReg())
7437d523365SDimitry Andric           continue;
7447d523365SDimitry Andric 
7457d523365SDimitry Andric         unsigned Reg = Op.getReg();
7463ca95b02SDimitry Andric         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
7473ca95b02SDimitry Andric         assert(!Op.isImplicit() &&
7483ca95b02SDimitry Andric                "explicit_uses() should only iterate over explicit operands");
7493ca95b02SDimitry Andric         if (TargetRegisterInfo::isPhysicalRegister(Reg))
7507d523365SDimitry Andric           continue;
7517d523365SDimitry Andric 
7523ca95b02SDimitry Andric         // Identify the definition for this register at this point. Most
7533ca95b02SDimitry Andric         // registers are in SSA form here so we try a quick MRI query first.
7543ca95b02SDimitry Andric         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
7553ca95b02SDimitry Andric         if (!Def)
7567d523365SDimitry Andric           continue;
7577d523365SDimitry Andric 
7587d523365SDimitry Andric         // Don't nest an INLINE_ASM def into anything, because we don't have
7597d523365SDimitry Andric         // constraints for $pop outputs.
7607d523365SDimitry Andric         if (Def->getOpcode() == TargetOpcode::INLINEASM)
7617d523365SDimitry Andric           continue;
7627d523365SDimitry Andric 
7637d523365SDimitry Andric         // Argument instructions represent live-in registers and not real
7647d523365SDimitry Andric         // instructions.
7657d523365SDimitry Andric         if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
7667d523365SDimitry Andric             Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
7677d523365SDimitry Andric             Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
7687d523365SDimitry Andric             Def->getOpcode() == WebAssembly::ARGUMENT_F64)
7697d523365SDimitry Andric           continue;
7707d523365SDimitry Andric 
7713ca95b02SDimitry Andric         // Decide which strategy to take. Prefer to move a single-use value
7723ca95b02SDimitry Andric         // over cloning it, and prefer cloning over introducing a tee_local.
7733ca95b02SDimitry Andric         // For moving, we require the def to be in the same block as the use;
7743ca95b02SDimitry Andric         // this makes things simpler (LiveIntervals' handleMove function only
7753ca95b02SDimitry Andric         // supports intra-block moves) and it's MachineSink's job to catch all
7763ca95b02SDimitry Andric         // the sinking opportunities anyway.
7773ca95b02SDimitry Andric         bool SameBlock = Def->getParent() == &MBB;
7783ca95b02SDimitry Andric         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
7793ca95b02SDimitry Andric                        !TreeWalker.IsOnStack(Reg);
7803ca95b02SDimitry Andric         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
7813ca95b02SDimitry Andric           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
7823ca95b02SDimitry Andric         } else if (ShouldRematerialize(*Def, AA, TII)) {
7833ca95b02SDimitry Andric           Insert =
7843ca95b02SDimitry Andric               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
7853ca95b02SDimitry Andric                                     LIS, MFI, MRI, TII, TRI);
7863ca95b02SDimitry Andric         } else if (CanMove &&
7873ca95b02SDimitry Andric                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
7883ca95b02SDimitry Andric           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
7893ca95b02SDimitry Andric                                          MRI, TII);
7903ca95b02SDimitry Andric         } else {
7913ca95b02SDimitry Andric           // We failed to stackify the operand. If the problem was ordering
7923ca95b02SDimitry Andric           // constraints, Commuting may be able to help.
7933ca95b02SDimitry Andric           if (!CanMove && SameBlock)
7943ca95b02SDimitry Andric             Commuting.MaybeCommute(Insert, TreeWalker, TII);
7953ca95b02SDimitry Andric           // Proceed to the next operand.
7967d523365SDimitry Andric           continue;
7977d523365SDimitry Andric         }
7983ca95b02SDimitry Andric 
7993ca95b02SDimitry Andric         // We stackified an operand. Add the defining instruction's operands to
8003ca95b02SDimitry Andric         // the worklist stack now to continue to build an ever deeper tree.
8013ca95b02SDimitry Andric         Commuting.Reset();
8023ca95b02SDimitry Andric         TreeWalker.PushOperands(Insert);
8033ca95b02SDimitry Andric       }
8043ca95b02SDimitry Andric 
8053ca95b02SDimitry Andric       // If we stackified any operands, skip over the tree to start looking for
8063ca95b02SDimitry Andric       // the next instruction we can build a tree on.
8073ca95b02SDimitry Andric       if (Insert != &*MII) {
808444ed5c5SDimitry Andric         ImposeStackOrdering(&*MII);
8093ca95b02SDimitry Andric         MII = std::prev(
8103ca95b02SDimitry Andric             llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
8113ca95b02SDimitry Andric         Changed = true;
8123ca95b02SDimitry Andric       }
8137d523365SDimitry Andric     }
8147d523365SDimitry Andric   }
8157d523365SDimitry Andric 
8163ca95b02SDimitry Andric   // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
8173ca95b02SDimitry Andric   // that it never looks like a use-before-def.
8187d523365SDimitry Andric   if (Changed) {
8197d523365SDimitry Andric     MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
8207d523365SDimitry Andric     for (MachineBasicBlock &MBB : MF)
8217d523365SDimitry Andric       MBB.addLiveIn(WebAssembly::EXPR_STACK);
8227d523365SDimitry Andric   }
8237d523365SDimitry Andric 
8247d523365SDimitry Andric #ifndef NDEBUG
8253ca95b02SDimitry Andric   // Verify that pushes and pops are performed in LIFO order.
8267d523365SDimitry Andric   SmallVector<unsigned, 0> Stack;
8277d523365SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
8287d523365SDimitry Andric     for (MachineInstr &MI : MBB) {
8293ca95b02SDimitry Andric       if (MI.isDebugValue())
8303ca95b02SDimitry Andric         continue;
8317d523365SDimitry Andric       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8327d523365SDimitry Andric         if (!MO.isReg())
8337d523365SDimitry Andric           continue;
8343ca95b02SDimitry Andric         unsigned Reg = MO.getReg();
8357d523365SDimitry Andric 
8363ca95b02SDimitry Andric         if (MFI.isVRegStackified(Reg)) {
8377d523365SDimitry Andric           if (MO.isDef())
8383ca95b02SDimitry Andric             Stack.push_back(Reg);
8397d523365SDimitry Andric           else
8403ca95b02SDimitry Andric             assert(Stack.pop_back_val() == Reg &&
8413ca95b02SDimitry Andric                    "Register stack pop should be paired with a push");
8427d523365SDimitry Andric         }
8437d523365SDimitry Andric       }
8447d523365SDimitry Andric     }
8457d523365SDimitry Andric     // TODO: Generalize this code to support keeping values on the stack across
8467d523365SDimitry Andric     // basic block boundaries.
8473ca95b02SDimitry Andric     assert(Stack.empty() &&
8483ca95b02SDimitry Andric            "Register stack pushes and pops should be balanced");
8497d523365SDimitry Andric   }
8507d523365SDimitry Andric #endif
8517d523365SDimitry Andric 
8527d523365SDimitry Andric   return Changed;
8537d523365SDimitry Andric }
854