11462faadSDan Gohman //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
21462faadSDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61462faadSDan Gohman //
71462faadSDan Gohman //===----------------------------------------------------------------------===//
81462faadSDan Gohman ///
91462faadSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file implements a register stacking pass.
111462faadSDan Gohman ///
121462faadSDan Gohman /// This pass reorders instructions to put register uses and defs in an order
131462faadSDan Gohman /// such that they form single-use expression trees. Registers fitting this form
141462faadSDan Gohman /// are then marked as "stackified", meaning references to them are replaced by
15e040533eSDan Gohman /// "push" and "pop" from the value stack.
161462faadSDan Gohman ///
1731448f16SDan Gohman /// This is primarily a code size optimization, since temporary values on the
18e040533eSDan Gohman /// value stack don't need to be named.
191462faadSDan Gohman ///
201462faadSDan Gohman //===----------------------------------------------------------------------===//
211462faadSDan Gohman 
224ba4816bSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
236bda14b3SChandler Carruth #include "WebAssembly.h"
24be24c020SYury Delendik #include "WebAssemblyDebugValueManager.h"
257a6b9825SDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
26b6fd39a3SDan Gohman #include "WebAssemblySubtarget.h"
274fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
287c18d608SYury Delendik #include "llvm/ADT/SmallPtrSet.h"
2981719f85SDan Gohman #include "llvm/Analysis/AliasAnalysis.h"
30f842297dSMatthias Braun #include "llvm/CodeGen/LiveIntervals.h"
311462faadSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32adf28177SDan Gohman #include "llvm/CodeGen/MachineDominators.h"
33adf28177SDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
3482607f56SDan Gohman #include "llvm/CodeGen/MachineModuleInfoImpls.h"
351462faadSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
361462faadSDan Gohman #include "llvm/CodeGen/Passes.h"
371462faadSDan Gohman #include "llvm/Support/Debug.h"
381462faadSDan Gohman #include "llvm/Support/raw_ostream.h"
3952861809SThomas Lively #include <iterator>
401462faadSDan Gohman using namespace llvm;
411462faadSDan Gohman 
421462faadSDan Gohman #define DEBUG_TYPE "wasm-reg-stackify"
431462faadSDan Gohman 
441462faadSDan Gohman namespace {
451462faadSDan Gohman class WebAssemblyRegStackify final : public MachineFunctionPass {
46117296c0SMehdi Amini   StringRef getPassName() const override {
471462faadSDan Gohman     return "WebAssembly Register Stackify";
481462faadSDan Gohman   }
491462faadSDan Gohman 
501462faadSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
511462faadSDan Gohman     AU.setPreservesCFG();
5281719f85SDan Gohman     AU.addRequired<AAResultsWrapperPass>();
53adf28177SDan Gohman     AU.addRequired<MachineDominatorTree>();
548887d1faSDan Gohman     AU.addRequired<LiveIntervals>();
551462faadSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
568887d1faSDan Gohman     AU.addPreserved<SlotIndexes>();
578887d1faSDan Gohman     AU.addPreserved<LiveIntervals>();
588887d1faSDan Gohman     AU.addPreservedID(LiveVariablesID);
59adf28177SDan Gohman     AU.addPreserved<MachineDominatorTree>();
601462faadSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
611462faadSDan Gohman   }
621462faadSDan Gohman 
631462faadSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
641462faadSDan Gohman 
651462faadSDan Gohman public:
661462faadSDan Gohman   static char ID; // Pass identification, replacement for typeid
671462faadSDan Gohman   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
681462faadSDan Gohman };
691462faadSDan Gohman } // end anonymous namespace
701462faadSDan Gohman 
711462faadSDan Gohman char WebAssemblyRegStackify::ID = 0;
7240926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
7340926451SJacob Gravelle                 "Reorder instructions to use the WebAssembly value stack",
7440926451SJacob Gravelle                 false, false)
7540926451SJacob Gravelle 
761462faadSDan Gohman FunctionPass *llvm::createWebAssemblyRegStackify() {
771462faadSDan Gohman   return new WebAssemblyRegStackify();
781462faadSDan Gohman }
791462faadSDan Gohman 
80b0992dafSDan Gohman // Decorate the given instruction with implicit operands that enforce the
818887d1faSDan Gohman // expression stack ordering constraints for an instruction which is on
828887d1faSDan Gohman // the expression stack.
8318c56a07SHeejin Ahn static void imposeStackOrdering(MachineInstr *MI) {
84e040533eSDan Gohman   // Write the opaque VALUE_STACK register.
85e040533eSDan Gohman   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
86e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
87b0992dafSDan Gohman                                              /*isDef=*/true,
88b0992dafSDan Gohman                                              /*isImp=*/true));
894da4abd8SDan Gohman 
90e040533eSDan Gohman   // Also read the opaque VALUE_STACK register.
91e040533eSDan Gohman   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
92e040533eSDan Gohman     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
93b0992dafSDan Gohman                                              /*isDef=*/false,
94b0992dafSDan Gohman                                              /*isImp=*/true));
95b0992dafSDan Gohman }
96b0992dafSDan Gohman 
97e81021a5SDan Gohman // Convert an IMPLICIT_DEF instruction into an instruction which defines
98e81021a5SDan Gohman // a constant zero value.
9918c56a07SHeejin Ahn static void convertImplicitDefToConstZero(MachineInstr *MI,
100e81021a5SDan Gohman                                           MachineRegisterInfo &MRI,
101e81021a5SDan Gohman                                           const TargetInstrInfo *TII,
102feb18fe9SThomas Lively                                           MachineFunction &MF,
103feb18fe9SThomas Lively                                           LiveIntervals &LIS) {
104e81021a5SDan Gohman   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
105e81021a5SDan Gohman 
106f208f631SHeejin Ahn   const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
107e81021a5SDan Gohman   if (RegClass == &WebAssembly::I32RegClass) {
108e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I32));
109e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
110e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::I64RegClass) {
111e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_I64));
112e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateImm(0));
113e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F32RegClass) {
114e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F32));
11518c56a07SHeejin Ahn     auto *Val = cast<ConstantFP>(Constant::getNullValue(
11621109249SDavid Blaikie         Type::getFloatTy(MF.getFunction().getContext())));
117e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
118e81021a5SDan Gohman   } else if (RegClass == &WebAssembly::F64RegClass) {
119e81021a5SDan Gohman     MI->setDesc(TII->get(WebAssembly::CONST_F64));
12018c56a07SHeejin Ahn     auto *Val = cast<ConstantFP>(Constant::getNullValue(
12121109249SDavid Blaikie         Type::getDoubleTy(MF.getFunction().getContext())));
122e81021a5SDan Gohman     MI->addOperand(MachineOperand::CreateFPImm(Val));
1236ff31fe3SThomas Lively   } else if (RegClass == &WebAssembly::V128RegClass) {
124*e657c84fSThomas Lively     MI->setDesc(TII->get(WebAssembly::CONST_V128_I64x2));
125*e657c84fSThomas Lively     MI->addOperand(MachineOperand::CreateImm(0));
126*e657c84fSThomas Lively     MI->addOperand(MachineOperand::CreateImm(0));
127e81021a5SDan Gohman   } else {
128e81021a5SDan Gohman     llvm_unreachable("Unexpected reg class");
129e81021a5SDan Gohman   }
130e81021a5SDan Gohman }
131e81021a5SDan Gohman 
1322644d74bSDan Gohman // Determine whether a call to the callee referenced by
1332644d74bSDan Gohman // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
1342644d74bSDan Gohman // effects.
1357b64a590SThomas Lively static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write,
1367b64a590SThomas Lively                         bool &Effects, bool &StackPointer) {
137d08cd15fSDan Gohman   // All calls can use the stack pointer.
138d08cd15fSDan Gohman   StackPointer = true;
139d08cd15fSDan Gohman 
1407b64a590SThomas Lively   const MachineOperand &MO = WebAssembly::getCalleeOp(MI);
1412644d74bSDan Gohman   if (MO.isGlobal()) {
1422644d74bSDan Gohman     const Constant *GV = MO.getGlobal();
14318c56a07SHeejin Ahn     if (const auto *GA = dyn_cast<GlobalAlias>(GV))
1442644d74bSDan Gohman       if (!GA->isInterposable())
1452644d74bSDan Gohman         GV = GA->getAliasee();
1462644d74bSDan Gohman 
14718c56a07SHeejin Ahn     if (const auto *F = dyn_cast<Function>(GV)) {
1482644d74bSDan Gohman       if (!F->doesNotThrow())
1492644d74bSDan Gohman         Effects = true;
1502644d74bSDan Gohman       if (F->doesNotAccessMemory())
1512644d74bSDan Gohman         return;
1522644d74bSDan Gohman       if (F->onlyReadsMemory()) {
1532644d74bSDan Gohman         Read = true;
1542644d74bSDan Gohman         return;
1552644d74bSDan Gohman       }
1562644d74bSDan Gohman     }
1572644d74bSDan Gohman   }
1582644d74bSDan Gohman 
1592644d74bSDan Gohman   // Assume the worst.
1602644d74bSDan Gohman   Write = true;
1612644d74bSDan Gohman   Read = true;
1622644d74bSDan Gohman   Effects = true;
1632644d74bSDan Gohman }
1642644d74bSDan Gohman 
165d08cd15fSDan Gohman // Determine whether MI reads memory, writes memory, has side effects,
16682607f56SDan Gohman // and/or uses the stack pointer value.
16718c56a07SHeejin Ahn static void query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
168500d0469SDuncan P. N. Exon Smith                   bool &Write, bool &Effects, bool &StackPointer) {
169500d0469SDuncan P. N. Exon Smith   assert(!MI.isTerminator());
1706c8f20d7SDan Gohman 
1715ef4d5f9SHeejin Ahn   if (MI.isDebugInstr() || MI.isPosition())
1726c8f20d7SDan Gohman     return;
1732644d74bSDan Gohman 
1742644d74bSDan Gohman   // Check for loads.
175d98cf00cSJustin Lebar   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
1762644d74bSDan Gohman     Read = true;
1772644d74bSDan Gohman 
1782644d74bSDan Gohman   // Check for stores.
179500d0469SDuncan P. N. Exon Smith   if (MI.mayStore()) {
1802644d74bSDan Gohman     Write = true;
181500d0469SDuncan P. N. Exon Smith   } else if (MI.hasOrderedMemoryRef()) {
182500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
183f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
184f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
185f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
186f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
187f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
188f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
189f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
190f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
191f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
192f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
193f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
194f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
195f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
196f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
197f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
198f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
1992644d74bSDan Gohman       // These instruction have hasUnmodeledSideEffects() returning true
2002644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2012644d74bSDan Gohman       // moved, however hasOrderedMemoryRef() interprets this plus their lack
2022644d74bSDan Gohman       // of memoperands as having a potential unknown memory reference.
2032644d74bSDan Gohman       break;
2042644d74bSDan Gohman     default:
2051054570aSDan Gohman       // Record volatile accesses, unless it's a call, as calls are handled
2062644d74bSDan Gohman       // specially below.
207500d0469SDuncan P. N. Exon Smith       if (!MI.isCall()) {
2082644d74bSDan Gohman         Write = true;
2091054570aSDan Gohman         Effects = true;
2101054570aSDan Gohman       }
2112644d74bSDan Gohman       break;
2122644d74bSDan Gohman     }
2132644d74bSDan Gohman   }
2142644d74bSDan Gohman 
2152644d74bSDan Gohman   // Check for side effects.
216500d0469SDuncan P. N. Exon Smith   if (MI.hasUnmodeledSideEffects()) {
217500d0469SDuncan P. N. Exon Smith     switch (MI.getOpcode()) {
218f208f631SHeejin Ahn     case WebAssembly::DIV_S_I32:
219f208f631SHeejin Ahn     case WebAssembly::DIV_S_I64:
220f208f631SHeejin Ahn     case WebAssembly::REM_S_I32:
221f208f631SHeejin Ahn     case WebAssembly::REM_S_I64:
222f208f631SHeejin Ahn     case WebAssembly::DIV_U_I32:
223f208f631SHeejin Ahn     case WebAssembly::DIV_U_I64:
224f208f631SHeejin Ahn     case WebAssembly::REM_U_I32:
225f208f631SHeejin Ahn     case WebAssembly::REM_U_I64:
226f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F32:
227f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F32:
228f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_S_F64:
229f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_S_F64:
230f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F32:
231f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F32:
232f208f631SHeejin Ahn     case WebAssembly::I32_TRUNC_U_F64:
233f208f631SHeejin Ahn     case WebAssembly::I64_TRUNC_U_F64:
2342644d74bSDan Gohman       // These instructions have hasUnmodeledSideEffects() returning true
2352644d74bSDan Gohman       // because they trap on overflow and invalid so they can't be arbitrarily
2362644d74bSDan Gohman       // moved, however in the specific case of register stackifying, it is safe
2372644d74bSDan Gohman       // to move them because overflow and invalid are Undefined Behavior.
2382644d74bSDan Gohman       break;
2392644d74bSDan Gohman     default:
2402644d74bSDan Gohman       Effects = true;
2412644d74bSDan Gohman       break;
2422644d74bSDan Gohman     }
2432644d74bSDan Gohman   }
2442644d74bSDan Gohman 
245e73c7a1aSHeejin Ahn   // Check for writes to __stack_pointer global.
246b9a539c0SWouter van Oortmerssen   if ((MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 ||
247b9a539c0SWouter van Oortmerssen        MI.getOpcode() == WebAssembly::GLOBAL_SET_I64) &&
248e73c7a1aSHeejin Ahn       strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
249e73c7a1aSHeejin Ahn     StackPointer = true;
250e73c7a1aSHeejin Ahn 
2512644d74bSDan Gohman   // Analyze calls.
252500d0469SDuncan P. N. Exon Smith   if (MI.isCall()) {
2537b64a590SThomas Lively     queryCallee(MI, Read, Write, Effects, StackPointer);
2542644d74bSDan Gohman   }
2552644d74bSDan Gohman }
2562644d74bSDan Gohman 
2572644d74bSDan Gohman // Test whether Def is safe and profitable to rematerialize.
25818c56a07SHeejin Ahn static bool shouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
2592644d74bSDan Gohman                                 const WebAssemblyInstrInfo *TII) {
2609cfc75c2SDuncan P. N. Exon Smith   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
2612644d74bSDan Gohman }
2622644d74bSDan Gohman 
26312de0b91SDan Gohman // Identify the definition for this register at this point. This is a
26412de0b91SDan Gohman // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
26512de0b91SDan Gohman // LiveIntervals to handle complex cases.
26618c56a07SHeejin Ahn static MachineInstr *getVRegDef(unsigned Reg, const MachineInstr *Insert,
2672644d74bSDan Gohman                                 const MachineRegisterInfo &MRI,
268f208f631SHeejin Ahn                                 const LiveIntervals &LIS) {
2692644d74bSDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
2702644d74bSDan Gohman   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
2712644d74bSDan Gohman     return Def;
2722644d74bSDan Gohman 
2732644d74bSDan Gohman   // MRI doesn't know what the Def is. Try asking LIS.
2742644d74bSDan Gohman   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
2752644d74bSDan Gohman           LIS.getInstructionIndex(*Insert)))
2762644d74bSDan Gohman     return LIS.getInstructionFromIndex(ValNo->def);
2772644d74bSDan Gohman 
2782644d74bSDan Gohman   return nullptr;
2792644d74bSDan Gohman }
2802644d74bSDan Gohman 
28112de0b91SDan Gohman // Test whether Reg, as defined at Def, has exactly one use. This is a
28212de0b91SDan Gohman // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
28312de0b91SDan Gohman // to handle complex cases.
28418c56a07SHeejin Ahn static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
285f208f631SHeejin Ahn                       MachineDominatorTree &MDT, LiveIntervals &LIS) {
28612de0b91SDan Gohman   // Most registers are in SSA form here so we try a quick MRI query first.
28712de0b91SDan Gohman   if (MRI.hasOneUse(Reg))
28812de0b91SDan Gohman     return true;
28912de0b91SDan Gohman 
29012de0b91SDan Gohman   bool HasOne = false;
29112de0b91SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
292f208f631SHeejin Ahn   const VNInfo *DefVNI =
293f208f631SHeejin Ahn       LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
29412de0b91SDan Gohman   assert(DefVNI);
295a8a63829SDominic Chen   for (auto &I : MRI.use_nodbg_operands(Reg)) {
29612de0b91SDan Gohman     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
29712de0b91SDan Gohman     if (Result.valueIn() == DefVNI) {
29812de0b91SDan Gohman       if (!Result.isKill())
29912de0b91SDan Gohman         return false;
30012de0b91SDan Gohman       if (HasOne)
30112de0b91SDan Gohman         return false;
30212de0b91SDan Gohman       HasOne = true;
30312de0b91SDan Gohman     }
30412de0b91SDan Gohman   }
30512de0b91SDan Gohman   return HasOne;
30612de0b91SDan Gohman }
30712de0b91SDan Gohman 
3088887d1faSDan Gohman // Test whether it's safe to move Def to just before Insert.
30981719f85SDan Gohman // TODO: Compute memory dependencies in a way that doesn't require always
31081719f85SDan Gohman // walking the block.
31181719f85SDan Gohman // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
31281719f85SDan Gohman // more precise.
31352861809SThomas Lively static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use,
31452861809SThomas Lively                          const MachineInstr *Insert, AliasAnalysis &AA,
31552861809SThomas Lively                          const WebAssemblyFunctionInfo &MFI,
31652861809SThomas Lively                          const MachineRegisterInfo &MRI) {
31752861809SThomas Lively   const MachineInstr *DefI = Def->getParent();
31852861809SThomas Lively   const MachineInstr *UseI = Use->getParent();
31952861809SThomas Lively   assert(DefI->getParent() == Insert->getParent());
32052861809SThomas Lively   assert(UseI->getParent() == Insert->getParent());
32152861809SThomas Lively 
32252861809SThomas Lively   // The first def of a multivalue instruction can be stackified by moving,
32352861809SThomas Lively   // since the later defs can always be placed into locals if necessary. Later
32452861809SThomas Lively   // defs can only be stackified if all previous defs are already stackified
32552861809SThomas Lively   // since ExplicitLocals will not know how to place a def in a local if a
32652861809SThomas Lively   // subsequent def is stackified. But only one def can be stackified by moving
32752861809SThomas Lively   // the instruction, so it must be the first one.
32852861809SThomas Lively   //
32952861809SThomas Lively   // TODO: This could be loosened to be the first *live* def, but care would
33052861809SThomas Lively   // have to be taken to ensure the drops of the initial dead defs can be
33152861809SThomas Lively   // placed. This would require checking that no previous defs are used in the
33252861809SThomas Lively   // same instruction as subsequent defs.
33352861809SThomas Lively   if (Def != DefI->defs().begin())
33452861809SThomas Lively     return false;
33552861809SThomas Lively 
33652861809SThomas Lively   // If any subsequent def is used prior to the current value by the same
33752861809SThomas Lively   // instruction in which the current value is used, we cannot
33852861809SThomas Lively   // stackify. Stackifying in this case would require that def moving below the
33952861809SThomas Lively   // current def in the stack, which cannot be achieved, even with locals.
34023b0ab2aSKazu Hirata   for (const auto &SubsequentDef : drop_begin(DefI->defs())) {
34152861809SThomas Lively     for (const auto &PriorUse : UseI->uses()) {
34252861809SThomas Lively       if (&PriorUse == Use)
34352861809SThomas Lively         break;
34452861809SThomas Lively       if (PriorUse.isReg() && SubsequentDef.getReg() == PriorUse.getReg())
34552861809SThomas Lively         return false;
34652861809SThomas Lively     }
34752861809SThomas Lively   }
34852861809SThomas Lively 
34952861809SThomas Lively   // If moving is a semantic nop, it is always allowed
35052861809SThomas Lively   const MachineBasicBlock *MBB = DefI->getParent();
35152861809SThomas Lively   auto NextI = std::next(MachineBasicBlock::const_iterator(DefI));
35252861809SThomas Lively   for (auto E = MBB->end(); NextI != E && NextI->isDebugInstr(); ++NextI)
35352861809SThomas Lively     ;
35452861809SThomas Lively   if (NextI == Insert)
35552861809SThomas Lively     return true;
3568887d1faSDan Gohman 
3579e4eadebSHeejin Ahn   // 'catch' and 'catch_all' should be the first instruction of a BB and cannot
3589e4eadebSHeejin Ahn   // move.
3599e4eadebSHeejin Ahn   if (WebAssembly::isCatch(DefI->getOpcode()))
360d6f48786SHeejin Ahn     return false;
361d6f48786SHeejin Ahn 
3628887d1faSDan Gohman   // Check for register dependencies.
363e9e6891bSDerek Schuff   SmallVector<unsigned, 4> MutableRegisters;
36452861809SThomas Lively   for (const MachineOperand &MO : DefI->operands()) {
3658887d1faSDan Gohman     if (!MO.isReg() || MO.isUndef())
3668887d1faSDan Gohman       continue;
36705c145d6SDaniel Sanders     Register Reg = MO.getReg();
3688887d1faSDan Gohman 
3698887d1faSDan Gohman     // If the register is dead here and at Insert, ignore it.
3708887d1faSDan Gohman     if (MO.isDead() && Insert->definesRegister(Reg) &&
3718887d1faSDan Gohman         !Insert->readsRegister(Reg))
3728887d1faSDan Gohman       continue;
3738887d1faSDan Gohman 
3742bea69bfSDaniel Sanders     if (Register::isPhysicalRegister(Reg)) {
3750cfb5f85SDan Gohman       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
3760cfb5f85SDan Gohman       // from moving down, and we've already checked for that.
3770cfb5f85SDan Gohman       if (Reg == WebAssembly::ARGUMENTS)
3780cfb5f85SDan Gohman         continue;
3798887d1faSDan Gohman       // If the physical register is never modified, ignore it.
3808887d1faSDan Gohman       if (!MRI.isPhysRegModified(Reg))
3818887d1faSDan Gohman         continue;
3828887d1faSDan Gohman       // Otherwise, it's a physical register with unknown liveness.
3838887d1faSDan Gohman       return false;
3848887d1faSDan Gohman     }
3858887d1faSDan Gohman 
386e9e6891bSDerek Schuff     // If one of the operands isn't in SSA form, it has different values at
387e9e6891bSDerek Schuff     // different times, and we need to make sure we don't move our use across
388e9e6891bSDerek Schuff     // a different def.
389e9e6891bSDerek Schuff     if (!MO.isDef() && !MRI.hasOneDef(Reg))
390e9e6891bSDerek Schuff       MutableRegisters.push_back(Reg);
3918887d1faSDan Gohman   }
3928887d1faSDan Gohman 
393d08cd15fSDan Gohman   bool Read = false, Write = false, Effects = false, StackPointer = false;
39452861809SThomas Lively   query(*DefI, AA, Read, Write, Effects, StackPointer);
3952644d74bSDan Gohman 
3962644d74bSDan Gohman   // If the instruction does not access memory and has no side effects, it has
3972644d74bSDan Gohman   // no additional dependencies.
398e9e6891bSDerek Schuff   bool HasMutableRegisters = !MutableRegisters.empty();
399e9e6891bSDerek Schuff   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
4002644d74bSDan Gohman     return true;
4012644d74bSDan Gohman 
40252861809SThomas Lively   // Scan through the intervening instructions between DefI and Insert.
40352861809SThomas Lively   MachineBasicBlock::const_iterator D(DefI), I(Insert);
4042644d74bSDan Gohman   for (--I; I != D; --I) {
4052644d74bSDan Gohman     bool InterveningRead = false;
4062644d74bSDan Gohman     bool InterveningWrite = false;
4072644d74bSDan Gohman     bool InterveningEffects = false;
408d08cd15fSDan Gohman     bool InterveningStackPointer = false;
40918c56a07SHeejin Ahn     query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
410d08cd15fSDan Gohman           InterveningStackPointer);
4112644d74bSDan Gohman     if (Effects && InterveningEffects)
4122644d74bSDan Gohman       return false;
4132644d74bSDan Gohman     if (Read && InterveningWrite)
4142644d74bSDan Gohman       return false;
4152644d74bSDan Gohman     if (Write && (InterveningRead || InterveningWrite))
4162644d74bSDan Gohman       return false;
417d08cd15fSDan Gohman     if (StackPointer && InterveningStackPointer)
418d08cd15fSDan Gohman       return false;
419e9e6891bSDerek Schuff 
420e9e6891bSDerek Schuff     for (unsigned Reg : MutableRegisters)
421e9e6891bSDerek Schuff       for (const MachineOperand &MO : I->operands())
422e9e6891bSDerek Schuff         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
423e9e6891bSDerek Schuff           return false;
4242644d74bSDan Gohman   }
4252644d74bSDan Gohman 
4262644d74bSDan Gohman   return true;
42781719f85SDan Gohman }
42881719f85SDan Gohman 
429adf28177SDan Gohman /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
43018c56a07SHeejin Ahn static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
431adf28177SDan Gohman                                      const MachineBasicBlock &MBB,
432adf28177SDan Gohman                                      const MachineRegisterInfo &MRI,
4330cfb5f85SDan Gohman                                      const MachineDominatorTree &MDT,
4341054570aSDan Gohman                                      LiveIntervals &LIS,
4351054570aSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
4360cfb5f85SDan Gohman   const LiveInterval &LI = LIS.getInterval(Reg);
4370cfb5f85SDan Gohman 
4380cfb5f85SDan Gohman   const MachineInstr *OneUseInst = OneUse.getParent();
4390cfb5f85SDan Gohman   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
4400cfb5f85SDan Gohman 
441a8a63829SDominic Chen   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
442adf28177SDan Gohman     if (&Use == &OneUse)
443adf28177SDan Gohman       continue;
4440cfb5f85SDan Gohman 
445adf28177SDan Gohman     const MachineInstr *UseInst = Use.getParent();
4460cfb5f85SDan Gohman     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
4470cfb5f85SDan Gohman 
4480cfb5f85SDan Gohman     if (UseVNI != OneUseVNI)
4490cfb5f85SDan Gohman       continue;
4500cfb5f85SDan Gohman 
45112de0b91SDan Gohman     if (UseInst == OneUseInst) {
452adf28177SDan Gohman       // Another use in the same instruction. We need to ensure that the one
453adf28177SDan Gohman       // selected use happens "before" it.
454adf28177SDan Gohman       if (&OneUse > &Use)
455adf28177SDan Gohman         return false;
456adf28177SDan Gohman     } else {
457adf28177SDan Gohman       // Test that the use is dominated by the one selected use.
4581054570aSDan Gohman       while (!MDT.dominates(OneUseInst, UseInst)) {
4591054570aSDan Gohman         // Actually, dominating is over-conservative. Test that the use would
4601054570aSDan Gohman         // happen after the one selected use in the stack evaluation order.
4611054570aSDan Gohman         //
4626a87ddacSThomas Lively         // This is needed as a consequence of using implicit local.gets for
4636a87ddacSThomas Lively         // uses and implicit local.sets for defs.
4641054570aSDan Gohman         if (UseInst->getDesc().getNumDefs() == 0)
465adf28177SDan Gohman           return false;
4661054570aSDan Gohman         const MachineOperand &MO = UseInst->getOperand(0);
4671054570aSDan Gohman         if (!MO.isReg())
4681054570aSDan Gohman           return false;
46905c145d6SDaniel Sanders         Register DefReg = MO.getReg();
4702bea69bfSDaniel Sanders         if (!Register::isVirtualRegister(DefReg) ||
4711054570aSDan Gohman             !MFI.isVRegStackified(DefReg))
4721054570aSDan Gohman           return false;
473b3857e4dSYury Delendik         assert(MRI.hasOneNonDBGUse(DefReg));
474b3857e4dSYury Delendik         const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
4751054570aSDan Gohman         const MachineInstr *NewUseInst = NewUse.getParent();
4761054570aSDan Gohman         if (NewUseInst == OneUseInst) {
4771054570aSDan Gohman           if (&OneUse > &NewUse)
4781054570aSDan Gohman             return false;
4791054570aSDan Gohman           break;
4801054570aSDan Gohman         }
4811054570aSDan Gohman         UseInst = NewUseInst;
4821054570aSDan Gohman       }
483adf28177SDan Gohman     }
484adf28177SDan Gohman   }
485adf28177SDan Gohman   return true;
486adf28177SDan Gohman }
487adf28177SDan Gohman 
4884fc4e42dSDan Gohman /// Get the appropriate tee opcode for the given register class.
48918c56a07SHeejin Ahn static unsigned getTeeOpcode(const TargetRegisterClass *RC) {
490adf28177SDan Gohman   if (RC == &WebAssembly::I32RegClass)
4914fc4e42dSDan Gohman     return WebAssembly::TEE_I32;
492adf28177SDan Gohman   if (RC == &WebAssembly::I64RegClass)
4934fc4e42dSDan Gohman     return WebAssembly::TEE_I64;
494adf28177SDan Gohman   if (RC == &WebAssembly::F32RegClass)
4954fc4e42dSDan Gohman     return WebAssembly::TEE_F32;
496adf28177SDan Gohman   if (RC == &WebAssembly::F64RegClass)
4974fc4e42dSDan Gohman     return WebAssembly::TEE_F64;
49839bf39f3SDerek Schuff   if (RC == &WebAssembly::V128RegClass)
4994fc4e42dSDan Gohman     return WebAssembly::TEE_V128;
500adf28177SDan Gohman   llvm_unreachable("Unexpected register class");
501adf28177SDan Gohman }
502adf28177SDan Gohman 
5032644d74bSDan Gohman // Shrink LI to its uses, cleaning up LI.
50418c56a07SHeejin Ahn static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
5052644d74bSDan Gohman   if (LIS.shrinkToUses(&LI)) {
5062644d74bSDan Gohman     SmallVector<LiveInterval *, 4> SplitLIs;
5072644d74bSDan Gohman     LIS.splitSeparateComponents(LI, SplitLIs);
5082644d74bSDan Gohman   }
5092644d74bSDan Gohman }
5102644d74bSDan Gohman 
511adf28177SDan Gohman /// A single-use def in the same block with no intervening memory or register
512adf28177SDan Gohman /// dependencies; move the def down and nest it with the current instruction.
51318c56a07SHeejin Ahn static MachineInstr *moveForSingleUse(unsigned Reg, MachineOperand &Op,
514f208f631SHeejin Ahn                                       MachineInstr *Def, MachineBasicBlock &MBB,
515adf28177SDan Gohman                                       MachineInstr *Insert, LiveIntervals &LIS,
5160cfb5f85SDan Gohman                                       WebAssemblyFunctionInfo &MFI,
5170cfb5f85SDan Gohman                                       MachineRegisterInfo &MRI) {
518d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
5192644d74bSDan Gohman 
520be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(Def);
521adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
522be24c020SYury Delendik   DefDIs.move(Insert);
5231afd1e2bSJF Bastien   LIS.handleMove(*Def);
5240cfb5f85SDan Gohman 
52512de0b91SDan Gohman   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
52612de0b91SDan Gohman     // No one else is using this register for anything so we can just stackify
52712de0b91SDan Gohman     // it in place.
528c5d24009SMatt Arsenault     MFI.stackifyVReg(MRI, Reg);
5290cfb5f85SDan Gohman   } else {
53012de0b91SDan Gohman     // The register may have unrelated uses or defs; create a new register for
53112de0b91SDan Gohman     // just our one def and use so that we can stackify it.
53205c145d6SDaniel Sanders     Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
5330cfb5f85SDan Gohman     Def->getOperand(0).setReg(NewReg);
5340cfb5f85SDan Gohman     Op.setReg(NewReg);
5350cfb5f85SDan Gohman 
5360cfb5f85SDan Gohman     // Tell LiveIntervals about the new register.
5370cfb5f85SDan Gohman     LIS.createAndComputeVirtRegInterval(NewReg);
5380cfb5f85SDan Gohman 
5390cfb5f85SDan Gohman     // Tell LiveIntervals about the changes to the old register.
5400cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
5416c8f20d7SDan Gohman     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
5426c8f20d7SDan Gohman                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
5436c8f20d7SDan Gohman                      /*RemoveDeadValNo=*/true);
5440cfb5f85SDan Gohman 
545c5d24009SMatt Arsenault     MFI.stackifyVReg(MRI, NewReg);
5462644d74bSDan Gohman 
547be24c020SYury Delendik     DefDIs.updateReg(NewReg);
5487c18d608SYury Delendik 
549d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
5500cfb5f85SDan Gohman   }
5510cfb5f85SDan Gohman 
55218c56a07SHeejin Ahn   imposeStackOrdering(Def);
553adf28177SDan Gohman   return Def;
554adf28177SDan Gohman }
555adf28177SDan Gohman 
556adf28177SDan Gohman /// A trivially cloneable instruction; clone it and nest the new copy with the
557adf28177SDan Gohman /// current instruction.
55818c56a07SHeejin Ahn static MachineInstr *rematerializeCheapDef(
5599cfc75c2SDuncan P. N. Exon Smith     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
5609cfc75c2SDuncan P. N. Exon Smith     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
5619cfc75c2SDuncan P. N. Exon Smith     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
5629cfc75c2SDuncan P. N. Exon Smith     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
563d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
564d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
5652644d74bSDan Gohman 
566be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(&Def);
567be24c020SYury Delendik 
56805c145d6SDaniel Sanders   Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
569adf28177SDan Gohman   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
570adf28177SDan Gohman   Op.setReg(NewReg);
5719cfc75c2SDuncan P. N. Exon Smith   MachineInstr *Clone = &*std::prev(Insert);
57213d3b9b7SJF Bastien   LIS.InsertMachineInstrInMaps(*Clone);
573adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(NewReg);
574c5d24009SMatt Arsenault   MFI.stackifyVReg(MRI, NewReg);
57518c56a07SHeejin Ahn   imposeStackOrdering(Clone);
576adf28177SDan Gohman 
577d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
5782644d74bSDan Gohman 
5790cfb5f85SDan Gohman   // Shrink the interval.
5800cfb5f85SDan Gohman   bool IsDead = MRI.use_empty(Reg);
5810cfb5f85SDan Gohman   if (!IsDead) {
5820cfb5f85SDan Gohman     LiveInterval &LI = LIS.getInterval(Reg);
58318c56a07SHeejin Ahn     shrinkToUses(LI, LIS);
5849cfc75c2SDuncan P. N. Exon Smith     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
5850cfb5f85SDan Gohman   }
5860cfb5f85SDan Gohman 
587adf28177SDan Gohman   // If that was the last use of the original, delete the original.
5887c18d608SYury Delendik   // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
5890cfb5f85SDan Gohman   if (IsDead) {
590d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - Deleting original\n");
5919cfc75c2SDuncan P. N. Exon Smith     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
5924cfc4025SMircea Trofin     LIS.removePhysRegDefAt(MCRegister::from(WebAssembly::ARGUMENTS), Idx);
593adf28177SDan Gohman     LIS.removeInterval(Reg);
5949cfc75c2SDuncan P. N. Exon Smith     LIS.RemoveMachineInstrFromMaps(Def);
5959cfc75c2SDuncan P. N. Exon Smith     Def.eraseFromParent();
5967c18d608SYury Delendik 
597be24c020SYury Delendik     DefDIs.move(&*Insert);
598be24c020SYury Delendik     DefDIs.updateReg(NewReg);
5997c18d608SYury Delendik   } else {
600be24c020SYury Delendik     DefDIs.clone(&*Insert, NewReg);
601adf28177SDan Gohman   }
6020cfb5f85SDan Gohman 
603adf28177SDan Gohman   return Clone;
604adf28177SDan Gohman }
605adf28177SDan Gohman 
606adf28177SDan Gohman /// A multiple-use def in the same block with no intervening memory or register
607adf28177SDan Gohman /// dependencies; move the def down, nest it with the current instruction, and
6084fc4e42dSDan Gohman /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
6094fc4e42dSDan Gohman /// this:
610adf28177SDan Gohman ///
611adf28177SDan Gohman ///    Reg = INST ...        // Def
612adf28177SDan Gohman ///    INST ..., Reg, ...    // Insert
613adf28177SDan Gohman ///    INST ..., Reg, ...
614adf28177SDan Gohman ///    INST ..., Reg, ...
615adf28177SDan Gohman ///
616adf28177SDan Gohman /// to this:
617adf28177SDan Gohman ///
6188aa237c3SDan Gohman ///    DefReg = INST ...     // Def (to become the new Insert)
6194fc4e42dSDan Gohman ///    TeeReg, Reg = TEE_... DefReg
620adf28177SDan Gohman ///    INST ..., TeeReg, ... // Insert
6216c8f20d7SDan Gohman ///    INST ..., Reg, ...
6226c8f20d7SDan Gohman ///    INST ..., Reg, ...
623adf28177SDan Gohman ///
6246a87ddacSThomas Lively /// with DefReg and TeeReg stackified. This eliminates a local.get from the
625adf28177SDan Gohman /// resulting code.
62618c56a07SHeejin Ahn static MachineInstr *moveAndTeeForMultiUse(
627adf28177SDan Gohman     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
628adf28177SDan Gohman     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
629adf28177SDan Gohman     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
630d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
6312644d74bSDan Gohman 
632be24c020SYury Delendik   WebAssemblyDebugValueManager DefDIs(Def);
633be24c020SYury Delendik 
63412de0b91SDan Gohman   // Move Def into place.
635adf28177SDan Gohman   MBB.splice(Insert, &MBB, Def);
6361afd1e2bSJF Bastien   LIS.handleMove(*Def);
63712de0b91SDan Gohman 
63812de0b91SDan Gohman   // Create the Tee and attach the registers.
639adf28177SDan Gohman   const auto *RegClass = MRI.getRegClass(Reg);
64005c145d6SDaniel Sanders   Register TeeReg = MRI.createVirtualRegister(RegClass);
64105c145d6SDaniel Sanders   Register DefReg = MRI.createVirtualRegister(RegClass);
64233e694a8SDan Gohman   MachineOperand &DefMO = Def->getOperand(0);
643adf28177SDan Gohman   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
64418c56a07SHeejin Ahn                               TII->get(getTeeOpcode(RegClass)), TeeReg)
64512de0b91SDan Gohman                           .addReg(Reg, RegState::Define)
64633e694a8SDan Gohman                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
647adf28177SDan Gohman   Op.setReg(TeeReg);
64833e694a8SDan Gohman   DefMO.setReg(DefReg);
64912de0b91SDan Gohman   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
65012de0b91SDan Gohman   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
65112de0b91SDan Gohman 
652be24c020SYury Delendik   DefDIs.move(Insert);
6537c18d608SYury Delendik 
65412de0b91SDan Gohman   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
65512de0b91SDan Gohman   LiveInterval &LI = LIS.getInterval(Reg);
65612de0b91SDan Gohman   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
65712de0b91SDan Gohman   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
65812de0b91SDan Gohman   I->start = TeeIdx;
65912de0b91SDan Gohman   ValNo->def = TeeIdx;
66018c56a07SHeejin Ahn   shrinkToUses(LI, LIS);
66112de0b91SDan Gohman 
66212de0b91SDan Gohman   // Finish stackifying the new regs.
663adf28177SDan Gohman   LIS.createAndComputeVirtRegInterval(TeeReg);
6648aa237c3SDan Gohman   LIS.createAndComputeVirtRegInterval(DefReg);
665c5d24009SMatt Arsenault   MFI.stackifyVReg(MRI, DefReg);
666c5d24009SMatt Arsenault   MFI.stackifyVReg(MRI, TeeReg);
66718c56a07SHeejin Ahn   imposeStackOrdering(Def);
66818c56a07SHeejin Ahn   imposeStackOrdering(Tee);
66912de0b91SDan Gohman 
670be24c020SYury Delendik   DefDIs.clone(Tee, DefReg);
671be24c020SYury Delendik   DefDIs.clone(Insert, TeeReg);
6727c18d608SYury Delendik 
673d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
674d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
675adf28177SDan Gohman   return Def;
676adf28177SDan Gohman }
677adf28177SDan Gohman 
678adf28177SDan Gohman namespace {
679adf28177SDan Gohman /// A stack for walking the tree of instructions being built, visiting the
680adf28177SDan Gohman /// MachineOperands in DFS order.
681adf28177SDan Gohman class TreeWalkerState {
68218c56a07SHeejin Ahn   using mop_iterator = MachineInstr::mop_iterator;
68318c56a07SHeejin Ahn   using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
68418c56a07SHeejin Ahn   using RangeTy = iterator_range<mop_reverse_iterator>;
685adf28177SDan Gohman   SmallVector<RangeTy, 4> Worklist;
686adf28177SDan Gohman 
687adf28177SDan Gohman public:
688adf28177SDan Gohman   explicit TreeWalkerState(MachineInstr *Insert) {
689adf28177SDan Gohman     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
6902082b10dSKazu Hirata     if (!Range.empty())
691adf28177SDan Gohman       Worklist.push_back(reverse(Range));
692adf28177SDan Gohman   }
693adf28177SDan Gohman 
69418c56a07SHeejin Ahn   bool done() const { return Worklist.empty(); }
695adf28177SDan Gohman 
69618c56a07SHeejin Ahn   MachineOperand &pop() {
697adf28177SDan Gohman     RangeTy &Range = Worklist.back();
698adf28177SDan Gohman     MachineOperand &Op = *Range.begin();
69923b0ab2aSKazu Hirata     Range = drop_begin(Range);
7002082b10dSKazu Hirata     if (Range.empty())
701adf28177SDan Gohman       Worklist.pop_back();
7022082b10dSKazu Hirata     assert((Worklist.empty() || !Worklist.back().empty()) &&
703adf28177SDan Gohman            "Empty ranges shouldn't remain in the worklist");
704adf28177SDan Gohman     return Op;
705adf28177SDan Gohman   }
706adf28177SDan Gohman 
707adf28177SDan Gohman   /// Push Instr's operands onto the stack to be visited.
70818c56a07SHeejin Ahn   void pushOperands(MachineInstr *Instr) {
709adf28177SDan Gohman     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
7102082b10dSKazu Hirata     if (!Range.empty())
711adf28177SDan Gohman       Worklist.push_back(reverse(Range));
712adf28177SDan Gohman   }
713adf28177SDan Gohman 
714adf28177SDan Gohman   /// Some of Instr's operands are on the top of the stack; remove them and
715adf28177SDan Gohman   /// re-insert them starting from the beginning (because we've commuted them).
71618c56a07SHeejin Ahn   void resetTopOperands(MachineInstr *Instr) {
71718c56a07SHeejin Ahn     assert(hasRemainingOperands(Instr) &&
718adf28177SDan Gohman            "Reseting operands should only be done when the instruction has "
719adf28177SDan Gohman            "an operand still on the stack");
720adf28177SDan Gohman     Worklist.back() = reverse(Instr->explicit_uses());
721adf28177SDan Gohman   }
722adf28177SDan Gohman 
723adf28177SDan Gohman   /// Test whether Instr has operands remaining to be visited at the top of
724adf28177SDan Gohman   /// the stack.
72518c56a07SHeejin Ahn   bool hasRemainingOperands(const MachineInstr *Instr) const {
726adf28177SDan Gohman     if (Worklist.empty())
727adf28177SDan Gohman       return false;
728adf28177SDan Gohman     const RangeTy &Range = Worklist.back();
7292082b10dSKazu Hirata     return !Range.empty() && Range.begin()->getParent() == Instr;
730adf28177SDan Gohman   }
731fbfe5ec4SDan Gohman 
732fbfe5ec4SDan Gohman   /// Test whether the given register is present on the stack, indicating an
733fbfe5ec4SDan Gohman   /// operand in the tree that we haven't visited yet. Moving a definition of
734fbfe5ec4SDan Gohman   /// Reg to a point in the tree after that would change its value.
7351054570aSDan Gohman   ///
7366a87ddacSThomas Lively   /// This is needed as a consequence of using implicit local.gets for
7376a87ddacSThomas Lively   /// uses and implicit local.sets for defs.
73818c56a07SHeejin Ahn   bool isOnStack(unsigned Reg) const {
739fbfe5ec4SDan Gohman     for (const RangeTy &Range : Worklist)
740fbfe5ec4SDan Gohman       for (const MachineOperand &MO : Range)
741fbfe5ec4SDan Gohman         if (MO.isReg() && MO.getReg() == Reg)
742fbfe5ec4SDan Gohman           return true;
743fbfe5ec4SDan Gohman     return false;
744fbfe5ec4SDan Gohman   }
745adf28177SDan Gohman };
746adf28177SDan Gohman 
747adf28177SDan Gohman /// State to keep track of whether commuting is in flight or whether it's been
748adf28177SDan Gohman /// tried for the current instruction and didn't work.
749adf28177SDan Gohman class CommutingState {
750adf28177SDan Gohman   /// There are effectively three states: the initial state where we haven't
75199d39463SHeejin Ahn   /// started commuting anything and we don't know anything yet, the tentative
752adf28177SDan Gohman   /// state where we've commuted the operands of the current instruction and are
75399d39463SHeejin Ahn   /// revisiting it, and the declined state where we've reverted the operands
754adf28177SDan Gohman   /// back to their original order and will no longer commute it further.
75518c56a07SHeejin Ahn   bool TentativelyCommuting = false;
75618c56a07SHeejin Ahn   bool Declined = false;
757adf28177SDan Gohman 
758adf28177SDan Gohman   /// During the tentative state, these hold the operand indices of the commuted
759adf28177SDan Gohman   /// operands.
760adf28177SDan Gohman   unsigned Operand0, Operand1;
761adf28177SDan Gohman 
762adf28177SDan Gohman public:
763adf28177SDan Gohman   /// Stackification for an operand was not successful due to ordering
764adf28177SDan Gohman   /// constraints. If possible, and if we haven't already tried it and declined
765adf28177SDan Gohman   /// it, commute Insert's operands and prepare to revisit it.
76618c56a07SHeejin Ahn   void maybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
767adf28177SDan Gohman                     const WebAssemblyInstrInfo *TII) {
768adf28177SDan Gohman     if (TentativelyCommuting) {
769adf28177SDan Gohman       assert(!Declined &&
770adf28177SDan Gohman              "Don't decline commuting until you've finished trying it");
771adf28177SDan Gohman       // Commuting didn't help. Revert it.
7729cfc75c2SDuncan P. N. Exon Smith       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
773adf28177SDan Gohman       TentativelyCommuting = false;
774adf28177SDan Gohman       Declined = true;
77518c56a07SHeejin Ahn     } else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
776adf28177SDan Gohman       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
777adf28177SDan Gohman       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
7789cfc75c2SDuncan P. N. Exon Smith       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
779adf28177SDan Gohman         // Tentatively commute the operands and try again.
7809cfc75c2SDuncan P. N. Exon Smith         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
78118c56a07SHeejin Ahn         TreeWalker.resetTopOperands(Insert);
782adf28177SDan Gohman         TentativelyCommuting = true;
783adf28177SDan Gohman         Declined = false;
784adf28177SDan Gohman       }
785adf28177SDan Gohman     }
786adf28177SDan Gohman   }
787adf28177SDan Gohman 
788adf28177SDan Gohman   /// Stackification for some operand was successful. Reset to the default
789adf28177SDan Gohman   /// state.
79018c56a07SHeejin Ahn   void reset() {
791adf28177SDan Gohman     TentativelyCommuting = false;
792adf28177SDan Gohman     Declined = false;
793adf28177SDan Gohman   }
794adf28177SDan Gohman };
795adf28177SDan Gohman } // end anonymous namespace
796adf28177SDan Gohman 
7971462faadSDan Gohman bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
798d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
7991462faadSDan Gohman                        "********** Function: "
8001462faadSDan Gohman                     << MF.getName() << '\n');
8011462faadSDan Gohman 
8021462faadSDan Gohman   bool Changed = false;
8031462faadSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
8041462faadSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
805b6fd39a3SDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
806b6fd39a3SDan Gohman   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
80781719f85SDan Gohman   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
80818c56a07SHeejin Ahn   auto &MDT = getAnalysis<MachineDominatorTree>();
80918c56a07SHeejin Ahn   auto &LIS = getAnalysis<LiveIntervals>();
810d70e5907SDan Gohman 
8111462faadSDan Gohman   // Walk the instructions from the bottom up. Currently we don't look past
8121462faadSDan Gohman   // block boundaries, and the blocks aren't ordered so the block visitation
8131462faadSDan Gohman   // order isn't significant, but we may want to change this in the future.
8141462faadSDan Gohman   for (MachineBasicBlock &MBB : MF) {
8158f59cf75SDan Gohman     // Don't use a range-based for loop, because we modify the list as we're
8168f59cf75SDan Gohman     // iterating over it and the end iterator may change.
8178f59cf75SDan Gohman     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
8188f59cf75SDan Gohman       MachineInstr *Insert = &*MII;
81981719f85SDan Gohman       // Don't nest anything inside an inline asm, because we don't have
82081719f85SDan Gohman       // constraints for $push inputs.
821c45e39b3SCraig Topper       if (Insert->isInlineAsm())
822595e8ab2SDan Gohman         continue;
823595e8ab2SDan Gohman 
824595e8ab2SDan Gohman       // Ignore debugging intrinsics.
825c45e39b3SCraig Topper       if (Insert->isDebugValue())
826595e8ab2SDan Gohman         continue;
82781719f85SDan Gohman 
8281462faadSDan Gohman       // Iterate through the inputs in reverse order, since we'll be pulling
82953d13997SDan Gohman       // operands off the stack in LIFO order.
830adf28177SDan Gohman       CommutingState Commuting;
831adf28177SDan Gohman       TreeWalkerState TreeWalker(Insert);
83218c56a07SHeejin Ahn       while (!TreeWalker.done()) {
83352861809SThomas Lively         MachineOperand &Use = TreeWalker.pop();
834adf28177SDan Gohman 
8351462faadSDan Gohman         // We're only interested in explicit virtual register operands.
83652861809SThomas Lively         if (!Use.isReg())
8371462faadSDan Gohman           continue;
8381462faadSDan Gohman 
83952861809SThomas Lively         Register Reg = Use.getReg();
84052861809SThomas Lively         assert(Use.isUse() && "explicit_uses() should only iterate over uses");
84152861809SThomas Lively         assert(!Use.isImplicit() &&
842adf28177SDan Gohman                "explicit_uses() should only iterate over explicit operands");
8432bea69bfSDaniel Sanders         if (Register::isPhysicalRegister(Reg))
844adf28177SDan Gohman           continue;
8451462faadSDan Gohman 
846ffc184bbSDan Gohman         // Identify the definition for this register at this point.
84752861809SThomas Lively         MachineInstr *DefI = getVRegDef(Reg, Insert, MRI, LIS);
84852861809SThomas Lively         if (!DefI)
8491462faadSDan Gohman           continue;
8501462faadSDan Gohman 
85181719f85SDan Gohman         // Don't nest an INLINE_ASM def into anything, because we don't have
85281719f85SDan Gohman         // constraints for $pop outputs.
85352861809SThomas Lively         if (DefI->isInlineAsm())
85481719f85SDan Gohman           continue;
85581719f85SDan Gohman 
8564ba4816bSDan Gohman         // Argument instructions represent live-in registers and not real
8574ba4816bSDan Gohman         // instructions.
85852861809SThomas Lively         if (WebAssembly::isArgument(DefI->getOpcode()))
8594ba4816bSDan Gohman           continue;
8604ba4816bSDan Gohman 
86152861809SThomas Lively         MachineOperand *Def = DefI->findRegisterDefOperand(Reg);
86252861809SThomas Lively         assert(Def != nullptr);
86352861809SThomas Lively 
864adf28177SDan Gohman         // Decide which strategy to take. Prefer to move a single-use value
8654fc4e42dSDan Gohman         // over cloning it, and prefer cloning over introducing a tee.
866adf28177SDan Gohman         // For moving, we require the def to be in the same block as the use;
867adf28177SDan Gohman         // this makes things simpler (LiveIntervals' handleMove function only
868adf28177SDan Gohman         // supports intra-block moves) and it's MachineSink's job to catch all
869adf28177SDan Gohman         // the sinking opportunities anyway.
87052861809SThomas Lively         bool SameBlock = DefI->getParent() == &MBB;
87152861809SThomas Lively         bool CanMove = SameBlock &&
87252861809SThomas Lively                        isSafeToMove(Def, &Use, Insert, AA, MFI, MRI) &&
87318c56a07SHeejin Ahn                        !TreeWalker.isOnStack(Reg);
87452861809SThomas Lively         if (CanMove && hasOneUse(Reg, DefI, MRI, MDT, LIS)) {
87552861809SThomas Lively           Insert = moveForSingleUse(Reg, Use, DefI, MBB, Insert, LIS, MFI, MRI);
876d966bf83SDerek Schuff 
877d966bf83SDerek Schuff           // If we are removing the frame base reg completely, remove the debug
878d966bf83SDerek Schuff           // info as well.
879d966bf83SDerek Schuff           // TODO: Encode this properly as a stackified value.
880d966bf83SDerek Schuff           if (MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Reg)
881d966bf83SDerek Schuff             MFI.clearFrameBaseVreg();
88252861809SThomas Lively         } else if (shouldRematerialize(*DefI, AA, TII)) {
8839cfc75c2SDuncan P. N. Exon Smith           Insert =
88452861809SThomas Lively               rematerializeCheapDef(Reg, Use, *DefI, MBB, Insert->getIterator(),
8859cfc75c2SDuncan P. N. Exon Smith                                     LIS, MFI, MRI, TII, TRI);
88652861809SThomas Lively         } else if (CanMove && oneUseDominatesOtherUses(Reg, Use, MBB, MRI, MDT,
88752861809SThomas Lively                                                        LIS, MFI)) {
88852861809SThomas Lively           Insert = moveAndTeeForMultiUse(Reg, Use, DefI, MBB, Insert, LIS, MFI,
889adf28177SDan Gohman                                          MRI, TII);
890b6fd39a3SDan Gohman         } else {
891adf28177SDan Gohman           // We failed to stackify the operand. If the problem was ordering
892adf28177SDan Gohman           // constraints, Commuting may be able to help.
893adf28177SDan Gohman           if (!CanMove && SameBlock)
89418c56a07SHeejin Ahn             Commuting.maybeCommute(Insert, TreeWalker, TII);
895adf28177SDan Gohman           // Proceed to the next operand.
896adf28177SDan Gohman           continue;
897b6fd39a3SDan Gohman         }
898adf28177SDan Gohman 
89952861809SThomas Lively         // Stackifying a multivalue def may unlock in-place stackification of
90052861809SThomas Lively         // subsequent defs. TODO: Handle the case where the consecutive uses are
90152861809SThomas Lively         // not all in the same instruction.
90216aabc86SThomas Lively         auto *SubsequentDef = Insert->defs().begin();
90352861809SThomas Lively         auto *SubsequentUse = &Use;
90416aabc86SThomas Lively         while (SubsequentDef != Insert->defs().end() &&
90552861809SThomas Lively                SubsequentUse != Use.getParent()->uses().end()) {
90652861809SThomas Lively           if (!SubsequentDef->isReg() || !SubsequentUse->isReg())
90752861809SThomas Lively             break;
90852861809SThomas Lively           unsigned DefReg = SubsequentDef->getReg();
90952861809SThomas Lively           unsigned UseReg = SubsequentUse->getReg();
91052861809SThomas Lively           // TODO: This single-use restriction could be relaxed by using tees
91152861809SThomas Lively           if (DefReg != UseReg || !MRI.hasOneUse(DefReg))
91252861809SThomas Lively             break;
913c5d24009SMatt Arsenault           MFI.stackifyVReg(MRI, DefReg);
91452861809SThomas Lively           ++SubsequentDef;
91552861809SThomas Lively           ++SubsequentUse;
91652861809SThomas Lively         }
91752861809SThomas Lively 
918e81021a5SDan Gohman         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
919e81021a5SDan Gohman         // to a constant 0 so that the def is explicit, and the push/pop
920e81021a5SDan Gohman         // correspondence is maintained.
921e81021a5SDan Gohman         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
92218c56a07SHeejin Ahn           convertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
923e81021a5SDan Gohman 
924adf28177SDan Gohman         // We stackified an operand. Add the defining instruction's operands to
925adf28177SDan Gohman         // the worklist stack now to continue to build an ever deeper tree.
92618c56a07SHeejin Ahn         Commuting.reset();
92718c56a07SHeejin Ahn         TreeWalker.pushOperands(Insert);
928b6fd39a3SDan Gohman       }
929adf28177SDan Gohman 
930adf28177SDan Gohman       // If we stackified any operands, skip over the tree to start looking for
931adf28177SDan Gohman       // the next instruction we can build a tree on.
932adf28177SDan Gohman       if (Insert != &*MII) {
93318c56a07SHeejin Ahn         imposeStackOrdering(&*MII);
934c7e5a9ceSEric Liu         MII = MachineBasicBlock::iterator(Insert).getReverse();
935adf28177SDan Gohman         Changed = true;
936adf28177SDan Gohman       }
9371462faadSDan Gohman     }
9381462faadSDan Gohman   }
9391462faadSDan Gohman 
940e040533eSDan Gohman   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
941adf28177SDan Gohman   // that it never looks like a use-before-def.
942b0992dafSDan Gohman   if (Changed) {
943e040533eSDan Gohman     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
944b0992dafSDan Gohman     for (MachineBasicBlock &MBB : MF)
945e040533eSDan Gohman       MBB.addLiveIn(WebAssembly::VALUE_STACK);
946b0992dafSDan Gohman   }
947b0992dafSDan Gohman 
9487bafa0eaSDan Gohman #ifndef NDEBUG
949b6fd39a3SDan Gohman   // Verify that pushes and pops are performed in LIFO order.
9507bafa0eaSDan Gohman   SmallVector<unsigned, 0> Stack;
9517bafa0eaSDan Gohman   for (MachineBasicBlock &MBB : MF) {
9527bafa0eaSDan Gohman     for (MachineInstr &MI : MBB) {
953801bf7ebSShiva Chen       if (MI.isDebugInstr())
9540cfb5f85SDan Gohman         continue;
95552861809SThomas Lively       for (MachineOperand &MO : reverse(MI.explicit_uses())) {
9567a6b9825SDan Gohman         if (!MO.isReg())
9577a6b9825SDan Gohman           continue;
95805c145d6SDaniel Sanders         Register Reg = MO.getReg();
95952861809SThomas Lively         if (MFI.isVRegStackified(Reg))
960adf28177SDan Gohman           assert(Stack.pop_back_val() == Reg &&
961adf28177SDan Gohman                  "Register stack pop should be paired with a push");
9627bafa0eaSDan Gohman       }
96352861809SThomas Lively       for (MachineOperand &MO : MI.defs()) {
96452861809SThomas Lively         if (!MO.isReg())
96552861809SThomas Lively           continue;
96652861809SThomas Lively         Register Reg = MO.getReg();
96752861809SThomas Lively         if (MFI.isVRegStackified(Reg))
96852861809SThomas Lively           Stack.push_back(MO.getReg());
9697bafa0eaSDan Gohman       }
9707bafa0eaSDan Gohman     }
9717bafa0eaSDan Gohman     // TODO: Generalize this code to support keeping values on the stack across
9727bafa0eaSDan Gohman     // basic block boundaries.
973adf28177SDan Gohman     assert(Stack.empty() &&
974adf28177SDan Gohman            "Register stack pushes and pops should be balanced");
9757bafa0eaSDan Gohman   }
9767bafa0eaSDan Gohman #endif
9777bafa0eaSDan Gohman 
9781462faadSDan Gohman   return Changed;
9791462faadSDan Gohman }
980