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
111462faadSDan Gohman /// \brief 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
161462faadSDan Gohman /// "push" and "pop" from the stack.
171462faadSDan Gohman ///
1831448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
191462faadSDan Gohman /// expression don't need to be named.
201462faadSDan Gohman ///
211462faadSDan Gohman //===----------------------------------------------------------------------===//
221462faadSDan Gohman 
231462faadSDan Gohman #include "WebAssembly.h"
244ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
2781719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
288887d1faSDan Gohman #include "llvm/CodeGen/LiveIntervalAnalysis.h"
291462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
31adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
321462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
331462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
341462faadSDan Gohman #include "llvm/Support/Debug.h"
351462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
361462faadSDan Gohman using namespace llvm;
371462faadSDan Gohman 
381462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
391462faadSDan Gohman 
401462faadSDan Gohman namespace {
411462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
421462faadSDan Gohman   const char *getPassName() const override {
431462faadSDan Gohman     return "WebAssembly Register Stackify";
441462faadSDan Gohman   }
451462faadSDan Gohman 
461462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
471462faadSDan Gohman     AU.setPreservesCFG();
4881719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
49adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
508887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
511462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
528887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
538887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
548887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
55adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
561462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
571462faadSDan Gohman   }
581462faadSDan Gohman 
591462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
601462faadSDan Gohman 
611462faadSDan Gohman public:
621462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
631462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
641462faadSDan Gohman };
651462faadSDan Gohman } // end anonymous namespace
661462faadSDan Gohman 
671462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
681462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
691462faadSDan Gohman   return new WebAssemblyRegStackify();
701462faadSDan Gohman }
711462faadSDan Gohman 
72b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
738887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
748887d1faSDan Gohman // the expression stack.
758887d1faSDan Gohman static void ImposeStackOrdering(MachineInstr *MI) {
764da4abd8SDan Gohman   // Write the opaque EXPR_STACK register.
774da4abd8SDan Gohman   if (!MI->definesRegister(WebAssembly::EXPR_STACK))
78b0992dafSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
79b0992dafSDan Gohman                                              /*isDef=*/true,
80b0992dafSDan Gohman                                              /*isImp=*/true));
814da4abd8SDan Gohman 
824da4abd8SDan Gohman   // Also read the opaque EXPR_STACK register.
83a712a6c4SDan Gohman   if (!MI->readsRegister(WebAssembly::EXPR_STACK))
84b0992dafSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
85b0992dafSDan Gohman                                              /*isDef=*/false,
86b0992dafSDan Gohman                                              /*isImp=*/true));
87b0992dafSDan Gohman }
88b0992dafSDan Gohman 
892644d74bSDan Gohman // Determine whether a call to the callee referenced by
902644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
912644d74bSDan Gohman // effects.
92500d0469SDuncan P. N. Exon Smith static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
93500d0469SDuncan P. N. Exon Smith                         bool &Write, bool &Effects, bool &StackPointer) {
94d08cd15fSDan Gohman   // All calls can use the stack pointer.
95d08cd15fSDan Gohman   StackPointer = true;
96d08cd15fSDan Gohman 
97500d0469SDuncan P. N. Exon Smith   const MachineOperand &MO = MI.getOperand(CalleeOpNo);
982644d74bSDan Gohman   if (MO.isGlobal()) {
992644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
1002644d74bSDan Gohman     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1012644d74bSDan Gohman       if (!GA->isInterposable())
1022644d74bSDan Gohman         GV = GA->getAliasee();
1032644d74bSDan Gohman 
1042644d74bSDan Gohman     if (const Function *F = dyn_cast<Function>(GV)) {
1052644d74bSDan Gohman       if (!F->doesNotThrow())
1062644d74bSDan Gohman         Effects = true;
1072644d74bSDan Gohman       if (F->doesNotAccessMemory())
1082644d74bSDan Gohman         return;
1092644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1102644d74bSDan Gohman         Read = true;
1112644d74bSDan Gohman         return;
1122644d74bSDan Gohman       }
1132644d74bSDan Gohman     }
1142644d74bSDan Gohman   }
1152644d74bSDan Gohman 
1162644d74bSDan Gohman   // Assume the worst.
1172644d74bSDan Gohman   Write = true;
1182644d74bSDan Gohman   Read = true;
1192644d74bSDan Gohman   Effects = true;
1202644d74bSDan Gohman }
1212644d74bSDan Gohman 
122d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
123d08cd15fSDan Gohman // and/or uses the __stack_pointer value.
124500d0469SDuncan P. N. Exon Smith static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
125500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
126500d0469SDuncan P. N. Exon Smith   assert(!MI.isPosition());
127500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1286c8f20d7SDan Gohman 
129500d0469SDuncan P. N. Exon Smith   if (MI.isDebugValue())
1306c8f20d7SDan Gohman     return;
1312644d74bSDan Gohman 
1322644d74bSDan Gohman   // Check for loads.
133*d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1342644d74bSDan Gohman     Read = true;
1352644d74bSDan Gohman 
1362644d74bSDan Gohman   // Check for stores.
137500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1382644d74bSDan Gohman     Write = true;
139d08cd15fSDan Gohman 
140d08cd15fSDan Gohman     // Check for stores to __stack_pointer.
141500d0469SDuncan P. N. Exon Smith     for (auto MMO : MI.memoperands()) {
142d08cd15fSDan Gohman       const MachinePointerInfo &MPI = MMO->getPointerInfo();
143d08cd15fSDan Gohman       if (MPI.V.is<const PseudoSourceValue *>()) {
144d08cd15fSDan Gohman         auto PSV = MPI.V.get<const PseudoSourceValue *>();
145d08cd15fSDan Gohman         if (const ExternalSymbolPseudoSourceValue *EPSV =
146d08cd15fSDan Gohman                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
147d08cd15fSDan Gohman           if (StringRef(EPSV->getSymbol()) == "__stack_pointer")
148d08cd15fSDan Gohman             StackPointer = true;
149d08cd15fSDan Gohman       }
150d08cd15fSDan Gohman     }
151500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
152500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
1532644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1542644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1552644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1562644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1572644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1582644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1592644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1602644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1612644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
1622644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
1632644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
1642644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
1652644d74bSDan Gohman       break;
1662644d74bSDan Gohman     default:
1671054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
1682644d74bSDan Gohman       // specially below.
169500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
1702644d74bSDan Gohman         Write = true;
1711054570aSDan Gohman         Effects = true;
1721054570aSDan Gohman       }
1732644d74bSDan Gohman       break;
1742644d74bSDan Gohman     }
1752644d74bSDan Gohman   }
1762644d74bSDan Gohman 
1772644d74bSDan Gohman   // Check for side effects.
178500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
179500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
1802644d74bSDan Gohman     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
1812644d74bSDan Gohman     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
1822644d74bSDan Gohman     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
1832644d74bSDan Gohman     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
1842644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
1852644d74bSDan Gohman     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
1862644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
1872644d74bSDan Gohman     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
1882644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
1892644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
1902644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
1912644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
1922644d74bSDan Gohman       break;
1932644d74bSDan Gohman     default:
1942644d74bSDan Gohman       Effects = true;
1952644d74bSDan Gohman       break;
1962644d74bSDan Gohman     }
1972644d74bSDan Gohman   }
1982644d74bSDan Gohman 
1992644d74bSDan Gohman   // Analyze calls.
200500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
201500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
2022644d74bSDan Gohman     case WebAssembly::CALL_VOID:
2031054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_VOID:
204d08cd15fSDan Gohman       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
2052644d74bSDan Gohman       break;
2061054570aSDan Gohman     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
2071054570aSDan Gohman     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
2081054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
2091054570aSDan Gohman     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
210d08cd15fSDan Gohman       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
2112644d74bSDan Gohman       break;
2122644d74bSDan Gohman     default:
2132644d74bSDan Gohman       llvm_unreachable("unexpected call opcode");
2142644d74bSDan Gohman     }
2152644d74bSDan Gohman   }
2162644d74bSDan Gohman }
2172644d74bSDan Gohman 
2182644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
2199cfc75c2SDuncan P. N. Exon Smith static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2202644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2219cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2222644d74bSDan Gohman }
2232644d74bSDan Gohman 
22412de0b91SDan Gohman // Identify the definition for this register at this point. This is a
22512de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
22612de0b91SDan Gohman // LiveIntervals to handle complex cases.
2272644d74bSDan Gohman static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
2282644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
2292644d74bSDan Gohman                                 const LiveIntervals &LIS)
2302644d74bSDan Gohman {
2312644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2322644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2332644d74bSDan Gohman     return Def;
2342644d74bSDan Gohman 
2352644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2362644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2372644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2382644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2392644d74bSDan Gohman 
2402644d74bSDan Gohman   return nullptr;
2412644d74bSDan Gohman }
2422644d74bSDan Gohman 
24312de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
24412de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
24512de0b91SDan Gohman // to handle complex cases.
24612de0b91SDan Gohman static bool HasOneUse(unsigned Reg, MachineInstr *Def,
24712de0b91SDan Gohman                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
24812de0b91SDan Gohman                       LiveIntervals &LIS) {
24912de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
25012de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
25112de0b91SDan Gohman     return true;
25212de0b91SDan Gohman 
25312de0b91SDan Gohman   bool HasOne = false;
25412de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
25512de0b91SDan Gohman   const VNInfo *DefVNI = LI.getVNInfoAt(
25612de0b91SDan Gohman       LIS.getInstructionIndex(*Def).getRegSlot());
25712de0b91SDan Gohman   assert(DefVNI);
258a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
25912de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
26012de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
26112de0b91SDan Gohman       if (!Result.isKill())
26212de0b91SDan Gohman         return false;
26312de0b91SDan Gohman       if (HasOne)
26412de0b91SDan Gohman         return false;
26512de0b91SDan Gohman       HasOne = true;
26612de0b91SDan Gohman     }
26712de0b91SDan Gohman   }
26812de0b91SDan Gohman   return HasOne;
26912de0b91SDan Gohman }
27012de0b91SDan Gohman 
2718887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
27281719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
27381719f85SDan Gohman // walking the block.
27481719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
27581719f85SDan Gohman // more precise.
27681719f85SDan Gohman static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
277adf28177SDan Gohman                          AliasAnalysis &AA, const LiveIntervals &LIS,
278adf28177SDan Gohman                          const MachineRegisterInfo &MRI) {
279391a98afSDan Gohman   assert(Def->getParent() == Insert->getParent());
2808887d1faSDan Gohman 
2818887d1faSDan Gohman   // Check for register dependencies.
2828887d1faSDan Gohman   for (const MachineOperand &MO : Def->operands()) {
2838887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
2848887d1faSDan Gohman       continue;
2858887d1faSDan Gohman     unsigned Reg = MO.getReg();
2868887d1faSDan Gohman 
2878887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
2888887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
2898887d1faSDan Gohman         !Insert->readsRegister(Reg))
2908887d1faSDan Gohman       continue;
2918887d1faSDan Gohman 
2928887d1faSDan Gohman     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2930cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
2940cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
2950cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
2960cfb5f85SDan Gohman         continue;
2978887d1faSDan Gohman       // If the physical register is never modified, ignore it.
2988887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
2998887d1faSDan Gohman         continue;
3008887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3018887d1faSDan Gohman       return false;
3028887d1faSDan Gohman     }
3038887d1faSDan Gohman 
3048887d1faSDan Gohman     // Ask LiveIntervals whether moving this virtual register use or def to
3050cfb5f85SDan Gohman     // Insert will change which value numbers are seen.
30612de0b91SDan Gohman     //
30712de0b91SDan Gohman     // If the operand is a use of a register that is also defined in the same
30812de0b91SDan Gohman     // instruction, test that the newly defined value reaches the insert point,
30912de0b91SDan Gohman     // since the operand will be moving along with the def.
3108887d1faSDan Gohman     const LiveInterval &LI = LIS.getInterval(Reg);
311b6fd39a3SDan Gohman     VNInfo *DefVNI =
31212de0b91SDan Gohman         (MO.isDef() || Def->definesRegister(Reg)) ?
31312de0b91SDan Gohman         LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) :
31412de0b91SDan Gohman         LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
3158887d1faSDan Gohman     assert(DefVNI && "Instruction input missing value number");
31613d3b9b7SJF Bastien     VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
3178887d1faSDan Gohman     if (InsVNI && DefVNI != InsVNI)
3188887d1faSDan Gohman       return false;
3198887d1faSDan Gohman   }
3208887d1faSDan Gohman 
321d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
322500d0469SDuncan P. N. Exon Smith   Query(*Def, AA, Read, Write, Effects, StackPointer);
3232644d74bSDan Gohman 
3242644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3252644d74bSDan Gohman   // no additional dependencies.
326d08cd15fSDan Gohman   if (!Read && !Write && !Effects && !StackPointer)
3272644d74bSDan Gohman     return true;
3282644d74bSDan Gohman 
3292644d74bSDan Gohman   // Scan through the intervening instructions between Def and Insert.
3302644d74bSDan Gohman   MachineBasicBlock::const_iterator D(Def), I(Insert);
3312644d74bSDan Gohman   for (--I; I != D; --I) {
3322644d74bSDan Gohman     bool InterveningRead = false;
3332644d74bSDan Gohman     bool InterveningWrite = false;
3342644d74bSDan Gohman     bool InterveningEffects = false;
335d08cd15fSDan Gohman     bool InterveningStackPointer = false;
336500d0469SDuncan P. N. Exon Smith     Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
337d08cd15fSDan Gohman           InterveningStackPointer);
3382644d74bSDan Gohman     if (Effects && InterveningEffects)
3392644d74bSDan Gohman       return false;
3402644d74bSDan Gohman     if (Read && InterveningWrite)
3412644d74bSDan Gohman       return false;
3422644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
3432644d74bSDan Gohman       return false;
344d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
345d08cd15fSDan Gohman       return false;
3462644d74bSDan Gohman   }
3472644d74bSDan Gohman 
3482644d74bSDan Gohman   return true;
34981719f85SDan Gohman }
35081719f85SDan Gohman 
351adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
352adf28177SDan Gohman static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
353adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
354adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
3550cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
3561054570aSDan Gohman                                      LiveIntervals &LIS,
3571054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
3580cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
3590cfb5f85SDan Gohman 
3600cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
3610cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
3620cfb5f85SDan Gohman 
363a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
364adf28177SDan Gohman     if (&Use == &OneUse)
365adf28177SDan Gohman       continue;
3660cfb5f85SDan Gohman 
367adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
3680cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
3690cfb5f85SDan Gohman 
3700cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
3710cfb5f85SDan Gohman       continue;
3720cfb5f85SDan Gohman 
373adf28177SDan Gohman     const MachineInstr *OneUseInst = OneUse.getParent();
37412de0b91SDan Gohman     if (UseInst == OneUseInst) {
375adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
376adf28177SDan Gohman       // selected use happens "before" it.
377adf28177SDan Gohman       if (&OneUse > &Use)
378adf28177SDan Gohman         return false;
379adf28177SDan Gohman     } else {
380adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
3811054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
3821054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
3831054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
3841054570aSDan Gohman         //
3851054570aSDan Gohman         // This is needed as a consequence of using implicit get_locals for
3861054570aSDan Gohman         // uses and implicit set_locals for defs.
3871054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
388adf28177SDan Gohman           return false;
3891054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
3901054570aSDan Gohman         if (!MO.isReg())
3911054570aSDan Gohman           return false;
3921054570aSDan Gohman         unsigned DefReg = MO.getReg();
3931054570aSDan Gohman         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
3941054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
3951054570aSDan Gohman           return false;
3961054570aSDan Gohman         assert(MRI.hasOneUse(DefReg));
3971054570aSDan Gohman         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
3981054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
3991054570aSDan Gohman         if (NewUseInst == OneUseInst) {
4001054570aSDan Gohman           if (&OneUse > &NewUse)
4011054570aSDan Gohman             return false;
4021054570aSDan Gohman           break;
4031054570aSDan Gohman         }
4041054570aSDan Gohman         UseInst = NewUseInst;
4051054570aSDan Gohman       }
406adf28177SDan Gohman     }
407adf28177SDan Gohman   }
408adf28177SDan Gohman   return true;
409adf28177SDan Gohman }
410adf28177SDan Gohman 
411adf28177SDan Gohman /// Get the appropriate tee_local opcode for the given register class.
412adf28177SDan Gohman static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
413adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
414adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_I32;
415adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
416adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_I64;
417adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
418adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_F32;
419adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
420adf28177SDan Gohman     return WebAssembly::TEE_LOCAL_F64;
42139bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
42239bf39f3SDerek Schuff     return WebAssembly::TEE_LOCAL_V128;
423adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
424adf28177SDan Gohman }
425adf28177SDan Gohman 
4262644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
4272644d74bSDan Gohman static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
4282644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
4292644d74bSDan Gohman     SmallVector<LiveInterval*, 4> SplitLIs;
4302644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
4312644d74bSDan Gohman   }
4322644d74bSDan Gohman }
4332644d74bSDan Gohman 
434adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
435adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
4360cfb5f85SDan Gohman static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
4370cfb5f85SDan Gohman                                       MachineInstr *Def,
438adf28177SDan Gohman                                       MachineBasicBlock &MBB,
439adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
4400cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
4410cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
4422644d74bSDan Gohman   DEBUG(dbgs() << "Move for single use: "; Def->dump());
4432644d74bSDan Gohman 
444adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
4451afd1e2bSJF Bastien   LIS.handleMove(*Def);
4460cfb5f85SDan Gohman 
44712de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
44812de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
44912de0b91SDan Gohman     // it in place.
450adf28177SDan Gohman     MFI.stackifyVReg(Reg);
4510cfb5f85SDan Gohman   } else {
45212de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
45312de0b91SDan Gohman     // just our one def and use so that we can stackify it.
4540cfb5f85SDan Gohman     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
4550cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
4560cfb5f85SDan Gohman     Op.setReg(NewReg);
4570cfb5f85SDan Gohman 
4580cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
4590cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
4600cfb5f85SDan Gohman 
4610cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
4620cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
4636c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
4646c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
4656c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
4660cfb5f85SDan Gohman 
4670cfb5f85SDan Gohman     MFI.stackifyVReg(NewReg);
4682644d74bSDan Gohman 
4692644d74bSDan Gohman     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
4700cfb5f85SDan Gohman   }
4710cfb5f85SDan Gohman 
472adf28177SDan Gohman   ImposeStackOrdering(Def);
473adf28177SDan Gohman   return Def;
474adf28177SDan Gohman }
475adf28177SDan Gohman 
476adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
477adf28177SDan Gohman /// current instruction.
4789cfc75c2SDuncan P. N. Exon Smith static MachineInstr *RematerializeCheapDef(
4799cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
4809cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
4819cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
4829cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
4839cfc75c2SDuncan P. N. Exon Smith   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
4842644d74bSDan Gohman   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
4852644d74bSDan Gohman 
486adf28177SDan Gohman   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
487adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
488adf28177SDan Gohman   Op.setReg(NewReg);
4899cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
49013d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
491adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
492adf28177SDan Gohman   MFI.stackifyVReg(NewReg);
493adf28177SDan Gohman   ImposeStackOrdering(Clone);
494adf28177SDan Gohman 
4952644d74bSDan Gohman   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
4962644d74bSDan Gohman 
4970cfb5f85SDan Gohman   // Shrink the interval.
4980cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
4990cfb5f85SDan Gohman   if (!IsDead) {
5000cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5012644d74bSDan Gohman     ShrinkToUses(LI, LIS);
5029cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5030cfb5f85SDan Gohman   }
5040cfb5f85SDan Gohman 
505adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5060cfb5f85SDan Gohman   if (IsDead) {
5072644d74bSDan Gohman     DEBUG(dbgs() << " - Deleting original\n");
5089cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
509adf28177SDan Gohman     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
510adf28177SDan Gohman     LIS.removeInterval(Reg);
5119cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
5129cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
513adf28177SDan Gohman   }
5140cfb5f85SDan Gohman 
515adf28177SDan Gohman   return Clone;
516adf28177SDan Gohman }
517adf28177SDan Gohman 
518adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
519adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
520adf28177SDan Gohman /// insert a tee_local to satisfy the rest of the uses. As an illustration,
521adf28177SDan Gohman /// rewrite this:
522adf28177SDan Gohman ///
523adf28177SDan Gohman ///    Reg = INST ...        // Def
524adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
525adf28177SDan Gohman ///    INST ..., Reg, ...
526adf28177SDan Gohman ///    INST ..., Reg, ...
527adf28177SDan Gohman ///
528adf28177SDan Gohman /// to this:
529adf28177SDan Gohman ///
5308aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
53112de0b91SDan Gohman ///    TeeReg, Reg = TEE_LOCAL_... DefReg
532adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
5336c8f20d7SDan Gohman ///    INST ..., Reg, ...
5346c8f20d7SDan Gohman ///    INST ..., Reg, ...
535adf28177SDan Gohman ///
5368aa237c3SDan Gohman /// with DefReg and TeeReg stackified. This eliminates a get_local from the
537adf28177SDan Gohman /// resulting code.
538adf28177SDan Gohman static MachineInstr *MoveAndTeeForMultiUse(
539adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
540adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
541adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
5422644d74bSDan Gohman   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
5432644d74bSDan Gohman 
54412de0b91SDan Gohman   // Move Def into place.
545adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
5461afd1e2bSJF Bastien   LIS.handleMove(*Def);
54712de0b91SDan Gohman 
54812de0b91SDan Gohman   // Create the Tee and attach the registers.
549adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
550adf28177SDan Gohman   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
5518aa237c3SDan Gohman   unsigned DefReg = MRI.createVirtualRegister(RegClass);
55233e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
553adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
554adf28177SDan Gohman                               TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
55512de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
55633e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
557adf28177SDan Gohman   Op.setReg(TeeReg);
55833e694a8SDan Gohman   DefMO.setReg(DefReg);
55912de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
56012de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
56112de0b91SDan Gohman 
56212de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
56312de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
56412de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
56512de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
56612de0b91SDan Gohman   I->start = TeeIdx;
56712de0b91SDan Gohman   ValNo->def = TeeIdx;
56812de0b91SDan Gohman   ShrinkToUses(LI, LIS);
56912de0b91SDan Gohman 
57012de0b91SDan Gohman   // Finish stackifying the new regs.
571adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
5728aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
5738aa237c3SDan Gohman   MFI.stackifyVReg(DefReg);
574adf28177SDan Gohman   MFI.stackifyVReg(TeeReg);
575adf28177SDan Gohman   ImposeStackOrdering(Def);
576adf28177SDan Gohman   ImposeStackOrdering(Tee);
57712de0b91SDan Gohman 
57812de0b91SDan Gohman   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
57912de0b91SDan Gohman   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
580adf28177SDan Gohman   return Def;
581adf28177SDan Gohman }
582adf28177SDan Gohman 
583adf28177SDan Gohman namespace {
584adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
585adf28177SDan Gohman /// MachineOperands in DFS order.
586adf28177SDan Gohman class TreeWalkerState {
587adf28177SDan Gohman   typedef MachineInstr::mop_iterator mop_iterator;
588adf28177SDan Gohman   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
589adf28177SDan Gohman   typedef iterator_range<mop_reverse_iterator> RangeTy;
590adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
591adf28177SDan Gohman 
592adf28177SDan Gohman public:
593adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
594adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
595adf28177SDan Gohman     if (Range.begin() != Range.end())
596adf28177SDan Gohman       Worklist.push_back(reverse(Range));
597adf28177SDan Gohman   }
598adf28177SDan Gohman 
599adf28177SDan Gohman   bool Done() const { return Worklist.empty(); }
600adf28177SDan Gohman 
601adf28177SDan Gohman   MachineOperand &Pop() {
602adf28177SDan Gohman     RangeTy &Range = Worklist.back();
603adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
604adf28177SDan Gohman     Range = drop_begin(Range, 1);
605adf28177SDan Gohman     if (Range.begin() == Range.end())
606adf28177SDan Gohman       Worklist.pop_back();
607adf28177SDan Gohman     assert((Worklist.empty() ||
608adf28177SDan Gohman             Worklist.back().begin() != Worklist.back().end()) &&
609adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
610adf28177SDan Gohman     return Op;
611adf28177SDan Gohman   }
612adf28177SDan Gohman 
613adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
614adf28177SDan Gohman   void PushOperands(MachineInstr *Instr) {
615adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
616adf28177SDan Gohman     if (Range.begin() != Range.end())
617adf28177SDan Gohman       Worklist.push_back(reverse(Range));
618adf28177SDan Gohman   }
619adf28177SDan Gohman 
620adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
621adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
622adf28177SDan Gohman   void ResetTopOperands(MachineInstr *Instr) {
623adf28177SDan Gohman     assert(HasRemainingOperands(Instr) &&
624adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
625adf28177SDan Gohman            "an operand still on the stack");
626adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
627adf28177SDan Gohman   }
628adf28177SDan Gohman 
629adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
630adf28177SDan Gohman   /// the stack.
631adf28177SDan Gohman   bool HasRemainingOperands(const MachineInstr *Instr) const {
632adf28177SDan Gohman     if (Worklist.empty())
633adf28177SDan Gohman       return false;
634adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
635adf28177SDan Gohman     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
636adf28177SDan Gohman   }
637fbfe5ec4SDan Gohman 
638fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
639fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
640fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
6411054570aSDan Gohman   ///
6421054570aSDan Gohman   /// This is needed as a consequence of using implicit get_locals for
6431054570aSDan Gohman   /// uses and implicit set_locals for defs.
644fbfe5ec4SDan Gohman   bool IsOnStack(unsigned Reg) const {
645fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
646fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
647fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
648fbfe5ec4SDan Gohman           return true;
649fbfe5ec4SDan Gohman     return false;
650fbfe5ec4SDan Gohman   }
651adf28177SDan Gohman };
652adf28177SDan Gohman 
653adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
654adf28177SDan Gohman /// tried for the current instruction and didn't work.
655adf28177SDan Gohman class CommutingState {
656adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
657adf28177SDan Gohman   /// started commuting anything and we don't know anything yet, the tenative
658adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
659adf28177SDan Gohman   /// revisting it, and the declined state where we've reverted the operands
660adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
661adf28177SDan Gohman   bool TentativelyCommuting;
662adf28177SDan Gohman   bool Declined;
663adf28177SDan Gohman 
664adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
665adf28177SDan Gohman   /// operands.
666adf28177SDan Gohman   unsigned Operand0, Operand1;
667adf28177SDan Gohman 
668adf28177SDan Gohman public:
669adf28177SDan Gohman   CommutingState() : TentativelyCommuting(false), Declined(false) {}
670adf28177SDan Gohman 
671adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
672adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
673adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
674adf28177SDan Gohman   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
675adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
676adf28177SDan Gohman     if (TentativelyCommuting) {
677adf28177SDan Gohman       assert(!Declined &&
678adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
679adf28177SDan Gohman       // Commuting didn't help. Revert it.
6809cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
681adf28177SDan Gohman       TentativelyCommuting = false;
682adf28177SDan Gohman       Declined = true;
683adf28177SDan Gohman     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
684adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
685adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
6869cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
687adf28177SDan Gohman         // Tentatively commute the operands and try again.
6889cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
689adf28177SDan Gohman         TreeWalker.ResetTopOperands(Insert);
690adf28177SDan Gohman         TentativelyCommuting = true;
691adf28177SDan Gohman         Declined = false;
692adf28177SDan Gohman       }
693adf28177SDan Gohman     }
694adf28177SDan Gohman   }
695adf28177SDan Gohman 
696adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
697adf28177SDan Gohman   /// state.
698adf28177SDan Gohman   void Reset() {
699adf28177SDan Gohman     TentativelyCommuting = false;
700adf28177SDan Gohman     Declined = false;
701adf28177SDan Gohman   }
702adf28177SDan Gohman };
703adf28177SDan Gohman } // end anonymous namespace
704adf28177SDan Gohman 
7051462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
7061462faadSDan Gohman   DEBUG(dbgs() << "********** Register Stackifying **********\n"
7071462faadSDan Gohman                   "********** Function: "
7081462faadSDan Gohman                << MF.getName() << '\n');
7091462faadSDan Gohman 
7101462faadSDan Gohman   bool Changed = false;
7111462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
7121462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
713b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
714b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
71581719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
716adf28177SDan Gohman   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
7178887d1faSDan Gohman   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
718d70e5907SDan Gohman 
7191462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
7201462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
7211462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
7221462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
7238f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
7248f59cf75SDan Gohman     // iterating over it and the end iterator may change.
7258f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
7268f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
72781719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
72881719f85SDan Gohman       // constraints for $push inputs.
72981719f85SDan Gohman       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
730595e8ab2SDan Gohman         continue;
731595e8ab2SDan Gohman 
732595e8ab2SDan Gohman       // Ignore debugging intrinsics.
733595e8ab2SDan Gohman       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
734595e8ab2SDan Gohman         continue;
73581719f85SDan Gohman 
7361462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
73753d13997SDan Gohman       // operands off the stack in LIFO order.
738adf28177SDan Gohman       CommutingState Commuting;
739adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
740adf28177SDan Gohman       while (!TreeWalker.Done()) {
741adf28177SDan Gohman         MachineOperand &Op = TreeWalker.Pop();
742adf28177SDan Gohman 
7431462faadSDan Gohman         // We're only interested in explicit virtual register operands.
744adf28177SDan Gohman         if (!Op.isReg())
7451462faadSDan Gohman           continue;
7461462faadSDan Gohman 
7471462faadSDan Gohman         unsigned Reg = Op.getReg();
748adf28177SDan Gohman         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
749adf28177SDan Gohman         assert(!Op.isImplicit() &&
750adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
751adf28177SDan Gohman         if (TargetRegisterInfo::isPhysicalRegister(Reg))
752adf28177SDan Gohman           continue;
7531462faadSDan Gohman 
754adf28177SDan Gohman         // Identify the definition for this register at this point. Most
755adf28177SDan Gohman         // registers are in SSA form here so we try a quick MRI query first.
7562644d74bSDan Gohman         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
7571462faadSDan Gohman         if (!Def)
7581462faadSDan Gohman           continue;
7591462faadSDan Gohman 
76081719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
76181719f85SDan Gohman         // constraints for $pop outputs.
76281719f85SDan Gohman         if (Def->getOpcode() == TargetOpcode::INLINEASM)
76381719f85SDan Gohman           continue;
76481719f85SDan Gohman 
7654ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
7664ba4816bSDan Gohman         // instructions.
7674ba4816bSDan Gohman         if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
7684ba4816bSDan Gohman             Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
7694ba4816bSDan Gohman             Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
77039bf39f3SDerek Schuff             Def->getOpcode() == WebAssembly::ARGUMENT_F64 ||
77139bf39f3SDerek Schuff             Def->getOpcode() == WebAssembly::ARGUMENT_v16i8 ||
77239bf39f3SDerek Schuff             Def->getOpcode() == WebAssembly::ARGUMENT_v8i16 ||
77339bf39f3SDerek Schuff             Def->getOpcode() == WebAssembly::ARGUMENT_v4i32 ||
77439bf39f3SDerek Schuff             Def->getOpcode() == WebAssembly::ARGUMENT_v4f32)
7754ba4816bSDan Gohman           continue;
7764ba4816bSDan Gohman 
777adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
778adf28177SDan Gohman         // over cloning it, and prefer cloning over introducing a tee_local.
779adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
780adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
781adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
782adf28177SDan Gohman         // the sinking opportunities anyway.
783adf28177SDan Gohman         bool SameBlock = Def->getParent() == &MBB;
784fbfe5ec4SDan Gohman         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
785fbfe5ec4SDan Gohman                        !TreeWalker.IsOnStack(Reg);
78612de0b91SDan Gohman         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
7870cfb5f85SDan Gohman           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
7889cfc75c2SDuncan P. N. Exon Smith         } else if (ShouldRematerialize(*Def, AA, TII)) {
7899cfc75c2SDuncan P. N. Exon Smith           Insert =
7909cfc75c2SDuncan P. N. Exon Smith               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
7919cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
792adf28177SDan Gohman         } else if (CanMove &&
7931054570aSDan Gohman                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
794adf28177SDan Gohman           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
795adf28177SDan Gohman                                          MRI, TII);
796b6fd39a3SDan Gohman         } else {
797adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
798adf28177SDan Gohman           // constraints, Commuting may be able to help.
799adf28177SDan Gohman           if (!CanMove && SameBlock)
800adf28177SDan Gohman             Commuting.MaybeCommute(Insert, TreeWalker, TII);
801adf28177SDan Gohman           // Proceed to the next operand.
802adf28177SDan Gohman           continue;
803b6fd39a3SDan Gohman         }
804adf28177SDan Gohman 
805adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
806adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
807adf28177SDan Gohman         Commuting.Reset();
808adf28177SDan Gohman         TreeWalker.PushOperands(Insert);
809b6fd39a3SDan Gohman       }
810adf28177SDan Gohman 
811adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
812adf28177SDan Gohman       // the next instruction we can build a tree on.
813adf28177SDan Gohman       if (Insert != &*MII) {
8148f59cf75SDan Gohman         ImposeStackOrdering(&*MII);
815adf28177SDan Gohman         MII = std::prev(
816369ebfe4SHans Wennborg             llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
817adf28177SDan Gohman         Changed = true;
818adf28177SDan Gohman       }
8191462faadSDan Gohman     }
8201462faadSDan Gohman   }
8211462faadSDan Gohman 
822adf28177SDan Gohman   // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
823adf28177SDan Gohman   // that it never looks like a use-before-def.
824b0992dafSDan Gohman   if (Changed) {
825b0992dafSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
826b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
827b0992dafSDan Gohman       MBB.addLiveIn(WebAssembly::EXPR_STACK);
828b0992dafSDan Gohman   }
829b0992dafSDan Gohman 
8307bafa0eaSDan Gohman #ifndef NDEBUG
831b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
8327bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
8337bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8347bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
8350cfb5f85SDan Gohman       if (MI.isDebugValue())
8360cfb5f85SDan Gohman         continue;
8377bafa0eaSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
8387a6b9825SDan Gohman         if (!MO.isReg())
8397a6b9825SDan Gohman           continue;
840adf28177SDan Gohman         unsigned Reg = MO.getReg();
8417bafa0eaSDan Gohman 
842adf28177SDan Gohman         if (MFI.isVRegStackified(Reg)) {
8437bafa0eaSDan Gohman           if (MO.isDef())
844adf28177SDan Gohman             Stack.push_back(Reg);
8457bafa0eaSDan Gohman           else
846adf28177SDan Gohman             assert(Stack.pop_back_val() == Reg &&
847adf28177SDan Gohman                    "Register stack pop should be paired with a push");
8487bafa0eaSDan Gohman         }
8497bafa0eaSDan Gohman       }
8507bafa0eaSDan Gohman     }
8517bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
8527bafa0eaSDan Gohman     // basic block boundaries.
853adf28177SDan Gohman     assert(Stack.empty() &&
854adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
8557bafa0eaSDan Gohman   }
8567bafa0eaSDan Gohman #endif
8577bafa0eaSDan Gohman 
8581462faadSDan Gohman   return Changed;
8591462faadSDan Gohman }
860