17d523365SDimitry Andric //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===// 27d523365SDimitry Andric // 37d523365SDimitry Andric // The LLVM Compiler Infrastructure 47d523365SDimitry Andric // 57d523365SDimitry Andric // This file is distributed under the University of Illinois Open Source 67d523365SDimitry Andric // License. See LICENSE.TXT for details. 77d523365SDimitry Andric // 87d523365SDimitry Andric //===----------------------------------------------------------------------===// 97d523365SDimitry Andric /// 107d523365SDimitry Andric /// \file 117d523365SDimitry Andric /// \brief This file implements a register stacking pass. 127d523365SDimitry Andric /// 137d523365SDimitry Andric /// This pass reorders instructions to put register uses and defs in an order 147d523365SDimitry Andric /// such that they form single-use expression trees. Registers fitting this form 157d523365SDimitry Andric /// are then marked as "stackified", meaning references to them are replaced by 16d88c1a5aSDimitry Andric /// "push" and "pop" from the value stack. 177d523365SDimitry Andric /// 187d523365SDimitry Andric /// This is primarily a code size optimization, since temporary values on the 19d88c1a5aSDimitry Andric /// value stack don't need to be named. 207d523365SDimitry Andric /// 217d523365SDimitry Andric //===----------------------------------------------------------------------===// 227d523365SDimitry Andric 237d523365SDimitry Andric #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_* 24db17bf38SDimitry Andric #include "WebAssembly.h" 257d523365SDimitry Andric #include "WebAssemblyMachineFunctionInfo.h" 263ca95b02SDimitry Andric #include "WebAssemblySubtarget.h" 27d88c1a5aSDimitry Andric #include "WebAssemblyUtilities.h" 287d523365SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 297d523365SDimitry Andric #include "llvm/CodeGen/LiveIntervalAnalysis.h" 307d523365SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 313ca95b02SDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 323ca95b02SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 337a7e6055SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h" 347d523365SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 357d523365SDimitry Andric #include "llvm/CodeGen/Passes.h" 367d523365SDimitry Andric #include "llvm/Support/Debug.h" 377d523365SDimitry Andric #include "llvm/Support/raw_ostream.h" 387d523365SDimitry Andric using namespace llvm; 397d523365SDimitry Andric 407d523365SDimitry Andric #define DEBUG_TYPE "wasm-reg-stackify" 417d523365SDimitry Andric 427d523365SDimitry Andric namespace { 437d523365SDimitry Andric class WebAssemblyRegStackify final : public MachineFunctionPass { 44d88c1a5aSDimitry Andric StringRef getPassName() const override { 457d523365SDimitry Andric return "WebAssembly Register Stackify"; 467d523365SDimitry Andric } 477d523365SDimitry Andric 487d523365SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 497d523365SDimitry Andric AU.setPreservesCFG(); 507d523365SDimitry Andric AU.addRequired<AAResultsWrapperPass>(); 513ca95b02SDimitry Andric AU.addRequired<MachineDominatorTree>(); 527d523365SDimitry Andric AU.addRequired<LiveIntervals>(); 537d523365SDimitry Andric AU.addPreserved<MachineBlockFrequencyInfo>(); 547d523365SDimitry Andric AU.addPreserved<SlotIndexes>(); 557d523365SDimitry Andric AU.addPreserved<LiveIntervals>(); 567d523365SDimitry Andric AU.addPreservedID(LiveVariablesID); 573ca95b02SDimitry Andric AU.addPreserved<MachineDominatorTree>(); 587d523365SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 597d523365SDimitry Andric } 607d523365SDimitry Andric 617d523365SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override; 627d523365SDimitry Andric 637d523365SDimitry Andric public: 647d523365SDimitry Andric static char ID; // Pass identification, replacement for typeid 657d523365SDimitry Andric WebAssemblyRegStackify() : MachineFunctionPass(ID) {} 667d523365SDimitry Andric }; 677d523365SDimitry Andric } // end anonymous namespace 687d523365SDimitry Andric 697d523365SDimitry Andric char WebAssemblyRegStackify::ID = 0; 707d523365SDimitry Andric FunctionPass *llvm::createWebAssemblyRegStackify() { 717d523365SDimitry Andric return new WebAssemblyRegStackify(); 727d523365SDimitry Andric } 737d523365SDimitry Andric 747d523365SDimitry Andric // Decorate the given instruction with implicit operands that enforce the 757d523365SDimitry Andric // expression stack ordering constraints for an instruction which is on 767d523365SDimitry Andric // the expression stack. 777d523365SDimitry Andric static void ImposeStackOrdering(MachineInstr *MI) { 78d88c1a5aSDimitry Andric // Write the opaque VALUE_STACK register. 79d88c1a5aSDimitry Andric if (!MI->definesRegister(WebAssembly::VALUE_STACK)) 80d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK, 817d523365SDimitry Andric /*isDef=*/true, 827d523365SDimitry Andric /*isImp=*/true)); 837d523365SDimitry Andric 84d88c1a5aSDimitry Andric // Also read the opaque VALUE_STACK register. 85d88c1a5aSDimitry Andric if (!MI->readsRegister(WebAssembly::VALUE_STACK)) 86d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK, 877d523365SDimitry Andric /*isDef=*/false, 887d523365SDimitry Andric /*isImp=*/true)); 897d523365SDimitry Andric } 907d523365SDimitry Andric 91d88c1a5aSDimitry Andric // Convert an IMPLICIT_DEF instruction into an instruction which defines 92d88c1a5aSDimitry Andric // a constant zero value. 93d88c1a5aSDimitry Andric static void ConvertImplicitDefToConstZero(MachineInstr *MI, 94d88c1a5aSDimitry Andric MachineRegisterInfo &MRI, 95d88c1a5aSDimitry Andric const TargetInstrInfo *TII, 96d88c1a5aSDimitry Andric MachineFunction &MF) { 97d88c1a5aSDimitry Andric assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF); 98d88c1a5aSDimitry Andric 99d88c1a5aSDimitry Andric const auto *RegClass = 100d88c1a5aSDimitry Andric MRI.getRegClass(MI->getOperand(0).getReg()); 101d88c1a5aSDimitry Andric if (RegClass == &WebAssembly::I32RegClass) { 102d88c1a5aSDimitry Andric MI->setDesc(TII->get(WebAssembly::CONST_I32)); 103d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateImm(0)); 104d88c1a5aSDimitry Andric } else if (RegClass == &WebAssembly::I64RegClass) { 105d88c1a5aSDimitry Andric MI->setDesc(TII->get(WebAssembly::CONST_I64)); 106d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateImm(0)); 107d88c1a5aSDimitry Andric } else if (RegClass == &WebAssembly::F32RegClass) { 108d88c1a5aSDimitry Andric MI->setDesc(TII->get(WebAssembly::CONST_F32)); 109d88c1a5aSDimitry Andric ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue( 110d88c1a5aSDimitry Andric Type::getFloatTy(MF.getFunction()->getContext()))); 111d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateFPImm(Val)); 112d88c1a5aSDimitry Andric } else if (RegClass == &WebAssembly::F64RegClass) { 113d88c1a5aSDimitry Andric MI->setDesc(TII->get(WebAssembly::CONST_F64)); 114d88c1a5aSDimitry Andric ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue( 115d88c1a5aSDimitry Andric Type::getDoubleTy(MF.getFunction()->getContext()))); 116d88c1a5aSDimitry Andric MI->addOperand(MachineOperand::CreateFPImm(Val)); 117d88c1a5aSDimitry Andric } else { 118d88c1a5aSDimitry Andric llvm_unreachable("Unexpected reg class"); 119d88c1a5aSDimitry Andric } 120d88c1a5aSDimitry Andric } 121d88c1a5aSDimitry Andric 1223ca95b02SDimitry Andric // Determine whether a call to the callee referenced by 1233ca95b02SDimitry Andric // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side 1243ca95b02SDimitry Andric // effects. 1253ca95b02SDimitry Andric static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read, 1263ca95b02SDimitry Andric bool &Write, bool &Effects, bool &StackPointer) { 1273ca95b02SDimitry Andric // All calls can use the stack pointer. 1283ca95b02SDimitry Andric StackPointer = true; 1293ca95b02SDimitry Andric 1303ca95b02SDimitry Andric const MachineOperand &MO = MI.getOperand(CalleeOpNo); 1313ca95b02SDimitry Andric if (MO.isGlobal()) { 1323ca95b02SDimitry Andric const Constant *GV = MO.getGlobal(); 1333ca95b02SDimitry Andric if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 1343ca95b02SDimitry Andric if (!GA->isInterposable()) 1353ca95b02SDimitry Andric GV = GA->getAliasee(); 1363ca95b02SDimitry Andric 1373ca95b02SDimitry Andric if (const Function *F = dyn_cast<Function>(GV)) { 1383ca95b02SDimitry Andric if (!F->doesNotThrow()) 1393ca95b02SDimitry Andric Effects = true; 1403ca95b02SDimitry Andric if (F->doesNotAccessMemory()) 1413ca95b02SDimitry Andric return; 1423ca95b02SDimitry Andric if (F->onlyReadsMemory()) { 1433ca95b02SDimitry Andric Read = true; 1443ca95b02SDimitry Andric return; 1453ca95b02SDimitry Andric } 1463ca95b02SDimitry Andric } 1473ca95b02SDimitry Andric } 1483ca95b02SDimitry Andric 1493ca95b02SDimitry Andric // Assume the worst. 1503ca95b02SDimitry Andric Write = true; 1513ca95b02SDimitry Andric Read = true; 1523ca95b02SDimitry Andric Effects = true; 1533ca95b02SDimitry Andric } 1543ca95b02SDimitry Andric 1553ca95b02SDimitry Andric // Determine whether MI reads memory, writes memory, has side effects, 1567a7e6055SDimitry Andric // and/or uses the stack pointer value. 1573ca95b02SDimitry Andric static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, 1583ca95b02SDimitry Andric bool &Write, bool &Effects, bool &StackPointer) { 1593ca95b02SDimitry Andric assert(!MI.isPosition()); 1603ca95b02SDimitry Andric assert(!MI.isTerminator()); 1613ca95b02SDimitry Andric 1623ca95b02SDimitry Andric if (MI.isDebugValue()) 1633ca95b02SDimitry Andric return; 1643ca95b02SDimitry Andric 1653ca95b02SDimitry Andric // Check for loads. 166d88c1a5aSDimitry Andric if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA)) 1673ca95b02SDimitry Andric Read = true; 1683ca95b02SDimitry Andric 1693ca95b02SDimitry Andric // Check for stores. 1703ca95b02SDimitry Andric if (MI.mayStore()) { 1713ca95b02SDimitry Andric Write = true; 1723ca95b02SDimitry Andric 1737a7e6055SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent(); 1747a7e6055SDimitry Andric if (MF.getSubtarget<WebAssemblySubtarget>() 1757a7e6055SDimitry Andric .getTargetTriple().isOSBinFormatELF()) { 1763ca95b02SDimitry Andric // Check for stores to __stack_pointer. 1773ca95b02SDimitry Andric for (auto MMO : MI.memoperands()) { 1783ca95b02SDimitry Andric const MachinePointerInfo &MPI = MMO->getPointerInfo(); 1793ca95b02SDimitry Andric if (MPI.V.is<const PseudoSourceValue *>()) { 1803ca95b02SDimitry Andric auto PSV = MPI.V.get<const PseudoSourceValue *>(); 1813ca95b02SDimitry Andric if (const ExternalSymbolPseudoSourceValue *EPSV = 1823ca95b02SDimitry Andric dyn_cast<ExternalSymbolPseudoSourceValue>(PSV)) 1833ca95b02SDimitry Andric if (StringRef(EPSV->getSymbol()) == "__stack_pointer") 1843ca95b02SDimitry Andric StackPointer = true; 1853ca95b02SDimitry Andric } 1863ca95b02SDimitry Andric } 1877a7e6055SDimitry Andric } else { 1887a7e6055SDimitry Andric // Check for sets of the stack pointer. 1897a7e6055SDimitry Andric const MachineModuleInfoWasm &MMIW = 1907a7e6055SDimitry Andric MF.getMMI().getObjFileInfo<MachineModuleInfoWasm>(); 1917a7e6055SDimitry Andric if ((MI.getOpcode() == WebAssembly::SET_LOCAL_I32 || 1927a7e6055SDimitry Andric MI.getOpcode() == WebAssembly::SET_LOCAL_I64) && 1937a7e6055SDimitry Andric MI.getOperand(0).getImm() == MMIW.getStackPointerGlobal()) { 1947a7e6055SDimitry Andric StackPointer = true; 1957a7e6055SDimitry Andric } 1967a7e6055SDimitry Andric } 1973ca95b02SDimitry Andric } else if (MI.hasOrderedMemoryRef()) { 1983ca95b02SDimitry Andric switch (MI.getOpcode()) { 1993ca95b02SDimitry Andric case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64: 2003ca95b02SDimitry Andric case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64: 2013ca95b02SDimitry Andric case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64: 2023ca95b02SDimitry Andric case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64: 2033ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32: 2043ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64: 2053ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32: 2063ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64: 2073ca95b02SDimitry Andric // These instruction have hasUnmodeledSideEffects() returning true 2083ca95b02SDimitry Andric // because they trap on overflow and invalid so they can't be arbitrarily 2093ca95b02SDimitry Andric // moved, however hasOrderedMemoryRef() interprets this plus their lack 2103ca95b02SDimitry Andric // of memoperands as having a potential unknown memory reference. 2113ca95b02SDimitry Andric break; 2123ca95b02SDimitry Andric default: 2133ca95b02SDimitry Andric // Record volatile accesses, unless it's a call, as calls are handled 2143ca95b02SDimitry Andric // specially below. 2153ca95b02SDimitry Andric if (!MI.isCall()) { 2163ca95b02SDimitry Andric Write = true; 2173ca95b02SDimitry Andric Effects = true; 2183ca95b02SDimitry Andric } 2193ca95b02SDimitry Andric break; 2203ca95b02SDimitry Andric } 2213ca95b02SDimitry Andric } 2223ca95b02SDimitry Andric 2233ca95b02SDimitry Andric // Check for side effects. 2243ca95b02SDimitry Andric if (MI.hasUnmodeledSideEffects()) { 2253ca95b02SDimitry Andric switch (MI.getOpcode()) { 2263ca95b02SDimitry Andric case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64: 2273ca95b02SDimitry Andric case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64: 2283ca95b02SDimitry Andric case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64: 2293ca95b02SDimitry Andric case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64: 2303ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32: 2313ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64: 2323ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32: 2333ca95b02SDimitry Andric case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64: 2343ca95b02SDimitry Andric // These instructions have hasUnmodeledSideEffects() returning true 2353ca95b02SDimitry Andric // because they trap on overflow and invalid so they can't be arbitrarily 2363ca95b02SDimitry Andric // moved, however in the specific case of register stackifying, it is safe 2373ca95b02SDimitry Andric // to move them because overflow and invalid are Undefined Behavior. 2383ca95b02SDimitry Andric break; 2393ca95b02SDimitry Andric default: 2403ca95b02SDimitry Andric Effects = true; 2413ca95b02SDimitry Andric break; 2423ca95b02SDimitry Andric } 2433ca95b02SDimitry Andric } 2443ca95b02SDimitry Andric 2453ca95b02SDimitry Andric // Analyze calls. 2463ca95b02SDimitry Andric if (MI.isCall()) { 2473ca95b02SDimitry Andric switch (MI.getOpcode()) { 2483ca95b02SDimitry Andric case WebAssembly::CALL_VOID: 2493ca95b02SDimitry Andric case WebAssembly::CALL_INDIRECT_VOID: 2503ca95b02SDimitry Andric QueryCallee(MI, 0, Read, Write, Effects, StackPointer); 2513ca95b02SDimitry Andric break; 2523ca95b02SDimitry Andric case WebAssembly::CALL_I32: case WebAssembly::CALL_I64: 2533ca95b02SDimitry Andric case WebAssembly::CALL_F32: case WebAssembly::CALL_F64: 2543ca95b02SDimitry Andric case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64: 2553ca95b02SDimitry Andric case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64: 2563ca95b02SDimitry Andric QueryCallee(MI, 1, Read, Write, Effects, StackPointer); 2573ca95b02SDimitry Andric break; 2583ca95b02SDimitry Andric default: 2593ca95b02SDimitry Andric llvm_unreachable("unexpected call opcode"); 2603ca95b02SDimitry Andric } 2613ca95b02SDimitry Andric } 2623ca95b02SDimitry Andric } 2633ca95b02SDimitry Andric 2643ca95b02SDimitry Andric // Test whether Def is safe and profitable to rematerialize. 2653ca95b02SDimitry Andric static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA, 2663ca95b02SDimitry Andric const WebAssemblyInstrInfo *TII) { 2673ca95b02SDimitry Andric return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA); 2683ca95b02SDimitry Andric } 2693ca95b02SDimitry Andric 2703ca95b02SDimitry Andric // Identify the definition for this register at this point. This is a 2713ca95b02SDimitry Andric // generalization of MachineRegisterInfo::getUniqueVRegDef that uses 2723ca95b02SDimitry Andric // LiveIntervals to handle complex cases. 2733ca95b02SDimitry Andric static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert, 2743ca95b02SDimitry Andric const MachineRegisterInfo &MRI, 2753ca95b02SDimitry Andric const LiveIntervals &LIS) 2763ca95b02SDimitry Andric { 2773ca95b02SDimitry Andric // Most registers are in SSA form here so we try a quick MRI query first. 2783ca95b02SDimitry Andric if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg)) 2793ca95b02SDimitry Andric return Def; 2803ca95b02SDimitry Andric 2813ca95b02SDimitry Andric // MRI doesn't know what the Def is. Try asking LIS. 2823ca95b02SDimitry Andric if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore( 2833ca95b02SDimitry Andric LIS.getInstructionIndex(*Insert))) 2843ca95b02SDimitry Andric return LIS.getInstructionFromIndex(ValNo->def); 2853ca95b02SDimitry Andric 2863ca95b02SDimitry Andric return nullptr; 2873ca95b02SDimitry Andric } 2883ca95b02SDimitry Andric 2893ca95b02SDimitry Andric // Test whether Reg, as defined at Def, has exactly one use. This is a 2903ca95b02SDimitry Andric // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals 2913ca95b02SDimitry Andric // to handle complex cases. 2923ca95b02SDimitry Andric static bool HasOneUse(unsigned Reg, MachineInstr *Def, 2933ca95b02SDimitry Andric MachineRegisterInfo &MRI, MachineDominatorTree &MDT, 2943ca95b02SDimitry Andric LiveIntervals &LIS) { 2953ca95b02SDimitry Andric // Most registers are in SSA form here so we try a quick MRI query first. 2963ca95b02SDimitry Andric if (MRI.hasOneUse(Reg)) 2973ca95b02SDimitry Andric return true; 2983ca95b02SDimitry Andric 2993ca95b02SDimitry Andric bool HasOne = false; 3003ca95b02SDimitry Andric const LiveInterval &LI = LIS.getInterval(Reg); 3013ca95b02SDimitry Andric const VNInfo *DefVNI = LI.getVNInfoAt( 3023ca95b02SDimitry Andric LIS.getInstructionIndex(*Def).getRegSlot()); 3033ca95b02SDimitry Andric assert(DefVNI); 304d88c1a5aSDimitry Andric for (auto &I : MRI.use_nodbg_operands(Reg)) { 3053ca95b02SDimitry Andric const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent())); 3063ca95b02SDimitry Andric if (Result.valueIn() == DefVNI) { 3073ca95b02SDimitry Andric if (!Result.isKill()) 3083ca95b02SDimitry Andric return false; 3093ca95b02SDimitry Andric if (HasOne) 3103ca95b02SDimitry Andric return false; 3113ca95b02SDimitry Andric HasOne = true; 3123ca95b02SDimitry Andric } 3133ca95b02SDimitry Andric } 3143ca95b02SDimitry Andric return HasOne; 3153ca95b02SDimitry Andric } 3163ca95b02SDimitry Andric 3177d523365SDimitry Andric // Test whether it's safe to move Def to just before Insert. 3187d523365SDimitry Andric // TODO: Compute memory dependencies in a way that doesn't require always 3197d523365SDimitry Andric // walking the block. 3207d523365SDimitry Andric // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be 3217d523365SDimitry Andric // more precise. 3227d523365SDimitry Andric static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert, 323d88c1a5aSDimitry Andric AliasAnalysis &AA, const MachineRegisterInfo &MRI) { 3247d523365SDimitry Andric assert(Def->getParent() == Insert->getParent()); 3257d523365SDimitry Andric 3267d523365SDimitry Andric // Check for register dependencies. 327d88c1a5aSDimitry Andric SmallVector<unsigned, 4> MutableRegisters; 3287d523365SDimitry Andric for (const MachineOperand &MO : Def->operands()) { 3297d523365SDimitry Andric if (!MO.isReg() || MO.isUndef()) 3307d523365SDimitry Andric continue; 3317d523365SDimitry Andric unsigned Reg = MO.getReg(); 3327d523365SDimitry Andric 3337d523365SDimitry Andric // If the register is dead here and at Insert, ignore it. 3347d523365SDimitry Andric if (MO.isDead() && Insert->definesRegister(Reg) && 3357d523365SDimitry Andric !Insert->readsRegister(Reg)) 3367d523365SDimitry Andric continue; 3377d523365SDimitry Andric 3387d523365SDimitry Andric if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 3393ca95b02SDimitry Andric // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions 3403ca95b02SDimitry Andric // from moving down, and we've already checked for that. 3413ca95b02SDimitry Andric if (Reg == WebAssembly::ARGUMENTS) 3423ca95b02SDimitry Andric continue; 3437d523365SDimitry Andric // If the physical register is never modified, ignore it. 3447d523365SDimitry Andric if (!MRI.isPhysRegModified(Reg)) 3457d523365SDimitry Andric continue; 3467d523365SDimitry Andric // Otherwise, it's a physical register with unknown liveness. 3477d523365SDimitry Andric return false; 3487d523365SDimitry Andric } 3497d523365SDimitry Andric 350d88c1a5aSDimitry Andric // If one of the operands isn't in SSA form, it has different values at 351d88c1a5aSDimitry Andric // different times, and we need to make sure we don't move our use across 352d88c1a5aSDimitry Andric // a different def. 353d88c1a5aSDimitry Andric if (!MO.isDef() && !MRI.hasOneDef(Reg)) 354d88c1a5aSDimitry Andric MutableRegisters.push_back(Reg); 3557d523365SDimitry Andric } 3567d523365SDimitry Andric 3573ca95b02SDimitry Andric bool Read = false, Write = false, Effects = false, StackPointer = false; 3583ca95b02SDimitry Andric Query(*Def, AA, Read, Write, Effects, StackPointer); 3593ca95b02SDimitry Andric 3603ca95b02SDimitry Andric // If the instruction does not access memory and has no side effects, it has 3613ca95b02SDimitry Andric // no additional dependencies. 362d88c1a5aSDimitry Andric bool HasMutableRegisters = !MutableRegisters.empty(); 363d88c1a5aSDimitry Andric if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters) 3643ca95b02SDimitry Andric return true; 3653ca95b02SDimitry Andric 3663ca95b02SDimitry Andric // Scan through the intervening instructions between Def and Insert. 3673ca95b02SDimitry Andric MachineBasicBlock::const_iterator D(Def), I(Insert); 3683ca95b02SDimitry Andric for (--I; I != D; --I) { 3693ca95b02SDimitry Andric bool InterveningRead = false; 3703ca95b02SDimitry Andric bool InterveningWrite = false; 3713ca95b02SDimitry Andric bool InterveningEffects = false; 3723ca95b02SDimitry Andric bool InterveningStackPointer = false; 3733ca95b02SDimitry Andric Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects, 3743ca95b02SDimitry Andric InterveningStackPointer); 3753ca95b02SDimitry Andric if (Effects && InterveningEffects) 3763ca95b02SDimitry Andric return false; 3773ca95b02SDimitry Andric if (Read && InterveningWrite) 3783ca95b02SDimitry Andric return false; 3793ca95b02SDimitry Andric if (Write && (InterveningRead || InterveningWrite)) 3803ca95b02SDimitry Andric return false; 3813ca95b02SDimitry Andric if (StackPointer && InterveningStackPointer) 3823ca95b02SDimitry Andric return false; 383d88c1a5aSDimitry Andric 384d88c1a5aSDimitry Andric for (unsigned Reg : MutableRegisters) 385d88c1a5aSDimitry Andric for (const MachineOperand &MO : I->operands()) 386d88c1a5aSDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) 387d88c1a5aSDimitry Andric return false; 3887d523365SDimitry Andric } 3897d523365SDimitry Andric 3903ca95b02SDimitry Andric return true; 3913ca95b02SDimitry Andric } 3923ca95b02SDimitry Andric 3933ca95b02SDimitry Andric /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses. 3943ca95b02SDimitry Andric static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse, 3953ca95b02SDimitry Andric const MachineBasicBlock &MBB, 3963ca95b02SDimitry Andric const MachineRegisterInfo &MRI, 3973ca95b02SDimitry Andric const MachineDominatorTree &MDT, 3983ca95b02SDimitry Andric LiveIntervals &LIS, 3993ca95b02SDimitry Andric WebAssemblyFunctionInfo &MFI) { 4003ca95b02SDimitry Andric const LiveInterval &LI = LIS.getInterval(Reg); 4013ca95b02SDimitry Andric 4023ca95b02SDimitry Andric const MachineInstr *OneUseInst = OneUse.getParent(); 4033ca95b02SDimitry Andric VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst)); 4043ca95b02SDimitry Andric 405d88c1a5aSDimitry Andric for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) { 4063ca95b02SDimitry Andric if (&Use == &OneUse) 4073ca95b02SDimitry Andric continue; 4083ca95b02SDimitry Andric 4093ca95b02SDimitry Andric const MachineInstr *UseInst = Use.getParent(); 4103ca95b02SDimitry Andric VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst)); 4113ca95b02SDimitry Andric 4123ca95b02SDimitry Andric if (UseVNI != OneUseVNI) 4133ca95b02SDimitry Andric continue; 4143ca95b02SDimitry Andric 4153ca95b02SDimitry Andric const MachineInstr *OneUseInst = OneUse.getParent(); 4163ca95b02SDimitry Andric if (UseInst == OneUseInst) { 4173ca95b02SDimitry Andric // Another use in the same instruction. We need to ensure that the one 4183ca95b02SDimitry Andric // selected use happens "before" it. 4193ca95b02SDimitry Andric if (&OneUse > &Use) 4203ca95b02SDimitry Andric return false; 4213ca95b02SDimitry Andric } else { 4223ca95b02SDimitry Andric // Test that the use is dominated by the one selected use. 4233ca95b02SDimitry Andric while (!MDT.dominates(OneUseInst, UseInst)) { 4243ca95b02SDimitry Andric // Actually, dominating is over-conservative. Test that the use would 4253ca95b02SDimitry Andric // happen after the one selected use in the stack evaluation order. 4263ca95b02SDimitry Andric // 4273ca95b02SDimitry Andric // This is needed as a consequence of using implicit get_locals for 4283ca95b02SDimitry Andric // uses and implicit set_locals for defs. 4293ca95b02SDimitry Andric if (UseInst->getDesc().getNumDefs() == 0) 4303ca95b02SDimitry Andric return false; 4313ca95b02SDimitry Andric const MachineOperand &MO = UseInst->getOperand(0); 4323ca95b02SDimitry Andric if (!MO.isReg()) 4333ca95b02SDimitry Andric return false; 4343ca95b02SDimitry Andric unsigned DefReg = MO.getReg(); 4353ca95b02SDimitry Andric if (!TargetRegisterInfo::isVirtualRegister(DefReg) || 4363ca95b02SDimitry Andric !MFI.isVRegStackified(DefReg)) 4373ca95b02SDimitry Andric return false; 4383ca95b02SDimitry Andric assert(MRI.hasOneUse(DefReg)); 4393ca95b02SDimitry Andric const MachineOperand &NewUse = *MRI.use_begin(DefReg); 4403ca95b02SDimitry Andric const MachineInstr *NewUseInst = NewUse.getParent(); 4413ca95b02SDimitry Andric if (NewUseInst == OneUseInst) { 4423ca95b02SDimitry Andric if (&OneUse > &NewUse) 4433ca95b02SDimitry Andric return false; 4443ca95b02SDimitry Andric break; 4453ca95b02SDimitry Andric } 4463ca95b02SDimitry Andric UseInst = NewUseInst; 4473ca95b02SDimitry Andric } 4483ca95b02SDimitry Andric } 4493ca95b02SDimitry Andric } 4503ca95b02SDimitry Andric return true; 4513ca95b02SDimitry Andric } 4523ca95b02SDimitry Andric 453d88c1a5aSDimitry Andric /// Get the appropriate tee opcode for the given register class. 454d88c1a5aSDimitry Andric static unsigned GetTeeOpcode(const TargetRegisterClass *RC) { 4553ca95b02SDimitry Andric if (RC == &WebAssembly::I32RegClass) 456d88c1a5aSDimitry Andric return WebAssembly::TEE_I32; 4573ca95b02SDimitry Andric if (RC == &WebAssembly::I64RegClass) 458d88c1a5aSDimitry Andric return WebAssembly::TEE_I64; 4593ca95b02SDimitry Andric if (RC == &WebAssembly::F32RegClass) 460d88c1a5aSDimitry Andric return WebAssembly::TEE_F32; 4613ca95b02SDimitry Andric if (RC == &WebAssembly::F64RegClass) 462d88c1a5aSDimitry Andric return WebAssembly::TEE_F64; 463d88c1a5aSDimitry Andric if (RC == &WebAssembly::V128RegClass) 464d88c1a5aSDimitry Andric return WebAssembly::TEE_V128; 4653ca95b02SDimitry Andric llvm_unreachable("Unexpected register class"); 4663ca95b02SDimitry Andric } 4673ca95b02SDimitry Andric 4683ca95b02SDimitry Andric // Shrink LI to its uses, cleaning up LI. 4693ca95b02SDimitry Andric static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) { 4703ca95b02SDimitry Andric if (LIS.shrinkToUses(&LI)) { 4713ca95b02SDimitry Andric SmallVector<LiveInterval*, 4> SplitLIs; 4723ca95b02SDimitry Andric LIS.splitSeparateComponents(LI, SplitLIs); 4733ca95b02SDimitry Andric } 4743ca95b02SDimitry Andric } 4753ca95b02SDimitry Andric 4763ca95b02SDimitry Andric /// A single-use def in the same block with no intervening memory or register 4773ca95b02SDimitry Andric /// dependencies; move the def down and nest it with the current instruction. 4783ca95b02SDimitry Andric static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op, 4793ca95b02SDimitry Andric MachineInstr *Def, 4803ca95b02SDimitry Andric MachineBasicBlock &MBB, 4813ca95b02SDimitry Andric MachineInstr *Insert, LiveIntervals &LIS, 4823ca95b02SDimitry Andric WebAssemblyFunctionInfo &MFI, 4833ca95b02SDimitry Andric MachineRegisterInfo &MRI) { 4843ca95b02SDimitry Andric DEBUG(dbgs() << "Move for single use: "; Def->dump()); 4853ca95b02SDimitry Andric 4863ca95b02SDimitry Andric MBB.splice(Insert, &MBB, Def); 4873ca95b02SDimitry Andric LIS.handleMove(*Def); 4883ca95b02SDimitry Andric 4893ca95b02SDimitry Andric if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) { 4903ca95b02SDimitry Andric // No one else is using this register for anything so we can just stackify 4913ca95b02SDimitry Andric // it in place. 4923ca95b02SDimitry Andric MFI.stackifyVReg(Reg); 4933ca95b02SDimitry Andric } else { 4943ca95b02SDimitry Andric // The register may have unrelated uses or defs; create a new register for 4953ca95b02SDimitry Andric // just our one def and use so that we can stackify it. 4963ca95b02SDimitry Andric unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 4973ca95b02SDimitry Andric Def->getOperand(0).setReg(NewReg); 4983ca95b02SDimitry Andric Op.setReg(NewReg); 4993ca95b02SDimitry Andric 5003ca95b02SDimitry Andric // Tell LiveIntervals about the new register. 5013ca95b02SDimitry Andric LIS.createAndComputeVirtRegInterval(NewReg); 5023ca95b02SDimitry Andric 5033ca95b02SDimitry Andric // Tell LiveIntervals about the changes to the old register. 5043ca95b02SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg); 5053ca95b02SDimitry Andric LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(), 5063ca95b02SDimitry Andric LIS.getInstructionIndex(*Op.getParent()).getRegSlot(), 5073ca95b02SDimitry Andric /*RemoveDeadValNo=*/true); 5083ca95b02SDimitry Andric 5093ca95b02SDimitry Andric MFI.stackifyVReg(NewReg); 5103ca95b02SDimitry Andric 5113ca95b02SDimitry Andric DEBUG(dbgs() << " - Replaced register: "; Def->dump()); 5123ca95b02SDimitry Andric } 5133ca95b02SDimitry Andric 5143ca95b02SDimitry Andric ImposeStackOrdering(Def); 5153ca95b02SDimitry Andric return Def; 5163ca95b02SDimitry Andric } 5173ca95b02SDimitry Andric 5183ca95b02SDimitry Andric /// A trivially cloneable instruction; clone it and nest the new copy with the 5193ca95b02SDimitry Andric /// current instruction. 5203ca95b02SDimitry Andric static MachineInstr *RematerializeCheapDef( 5213ca95b02SDimitry Andric unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB, 5223ca95b02SDimitry Andric MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS, 5233ca95b02SDimitry Andric WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, 5243ca95b02SDimitry Andric const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) { 5253ca95b02SDimitry Andric DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump()); 5263ca95b02SDimitry Andric DEBUG(dbgs() << " - for use in "; Op.getParent()->dump()); 5273ca95b02SDimitry Andric 5283ca95b02SDimitry Andric unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 5293ca95b02SDimitry Andric TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI); 5303ca95b02SDimitry Andric Op.setReg(NewReg); 5313ca95b02SDimitry Andric MachineInstr *Clone = &*std::prev(Insert); 5323ca95b02SDimitry Andric LIS.InsertMachineInstrInMaps(*Clone); 5333ca95b02SDimitry Andric LIS.createAndComputeVirtRegInterval(NewReg); 5343ca95b02SDimitry Andric MFI.stackifyVReg(NewReg); 5353ca95b02SDimitry Andric ImposeStackOrdering(Clone); 5363ca95b02SDimitry Andric 5373ca95b02SDimitry Andric DEBUG(dbgs() << " - Cloned to "; Clone->dump()); 5383ca95b02SDimitry Andric 5393ca95b02SDimitry Andric // Shrink the interval. 5403ca95b02SDimitry Andric bool IsDead = MRI.use_empty(Reg); 5413ca95b02SDimitry Andric if (!IsDead) { 5423ca95b02SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg); 5433ca95b02SDimitry Andric ShrinkToUses(LI, LIS); 5443ca95b02SDimitry Andric IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot()); 5453ca95b02SDimitry Andric } 5463ca95b02SDimitry Andric 5473ca95b02SDimitry Andric // If that was the last use of the original, delete the original. 5483ca95b02SDimitry Andric if (IsDead) { 5493ca95b02SDimitry Andric DEBUG(dbgs() << " - Deleting original\n"); 5503ca95b02SDimitry Andric SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot(); 5513ca95b02SDimitry Andric LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx); 5523ca95b02SDimitry Andric LIS.removeInterval(Reg); 5533ca95b02SDimitry Andric LIS.RemoveMachineInstrFromMaps(Def); 5543ca95b02SDimitry Andric Def.eraseFromParent(); 5553ca95b02SDimitry Andric } 5563ca95b02SDimitry Andric 5573ca95b02SDimitry Andric return Clone; 5583ca95b02SDimitry Andric } 5593ca95b02SDimitry Andric 5603ca95b02SDimitry Andric /// A multiple-use def in the same block with no intervening memory or register 5613ca95b02SDimitry Andric /// dependencies; move the def down, nest it with the current instruction, and 562d88c1a5aSDimitry Andric /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite 563d88c1a5aSDimitry Andric /// this: 5643ca95b02SDimitry Andric /// 5653ca95b02SDimitry Andric /// Reg = INST ... // Def 5663ca95b02SDimitry Andric /// INST ..., Reg, ... // Insert 5673ca95b02SDimitry Andric /// INST ..., Reg, ... 5683ca95b02SDimitry Andric /// INST ..., Reg, ... 5693ca95b02SDimitry Andric /// 5703ca95b02SDimitry Andric /// to this: 5713ca95b02SDimitry Andric /// 5723ca95b02SDimitry Andric /// DefReg = INST ... // Def (to become the new Insert) 573d88c1a5aSDimitry Andric /// TeeReg, Reg = TEE_... DefReg 5743ca95b02SDimitry Andric /// INST ..., TeeReg, ... // Insert 5753ca95b02SDimitry Andric /// INST ..., Reg, ... 5763ca95b02SDimitry Andric /// INST ..., Reg, ... 5773ca95b02SDimitry Andric /// 5783ca95b02SDimitry Andric /// with DefReg and TeeReg stackified. This eliminates a get_local from the 5793ca95b02SDimitry Andric /// resulting code. 5803ca95b02SDimitry Andric static MachineInstr *MoveAndTeeForMultiUse( 5813ca95b02SDimitry Andric unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, 5823ca95b02SDimitry Andric MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, 5833ca95b02SDimitry Andric MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) { 5843ca95b02SDimitry Andric DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump()); 5853ca95b02SDimitry Andric 5863ca95b02SDimitry Andric // Move Def into place. 5873ca95b02SDimitry Andric MBB.splice(Insert, &MBB, Def); 5883ca95b02SDimitry Andric LIS.handleMove(*Def); 5893ca95b02SDimitry Andric 5903ca95b02SDimitry Andric // Create the Tee and attach the registers. 5913ca95b02SDimitry Andric const auto *RegClass = MRI.getRegClass(Reg); 5923ca95b02SDimitry Andric unsigned TeeReg = MRI.createVirtualRegister(RegClass); 5933ca95b02SDimitry Andric unsigned DefReg = MRI.createVirtualRegister(RegClass); 5943ca95b02SDimitry Andric MachineOperand &DefMO = Def->getOperand(0); 5953ca95b02SDimitry Andric MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(), 596d88c1a5aSDimitry Andric TII->get(GetTeeOpcode(RegClass)), TeeReg) 5973ca95b02SDimitry Andric .addReg(Reg, RegState::Define) 5983ca95b02SDimitry Andric .addReg(DefReg, getUndefRegState(DefMO.isDead())); 5993ca95b02SDimitry Andric Op.setReg(TeeReg); 6003ca95b02SDimitry Andric DefMO.setReg(DefReg); 6013ca95b02SDimitry Andric SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot(); 6023ca95b02SDimitry Andric SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot(); 6033ca95b02SDimitry Andric 6043ca95b02SDimitry Andric // Tell LiveIntervals we moved the original vreg def from Def to Tee. 6053ca95b02SDimitry Andric LiveInterval &LI = LIS.getInterval(Reg); 6063ca95b02SDimitry Andric LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx); 6073ca95b02SDimitry Andric VNInfo *ValNo = LI.getVNInfoAt(DefIdx); 6083ca95b02SDimitry Andric I->start = TeeIdx; 6093ca95b02SDimitry Andric ValNo->def = TeeIdx; 6103ca95b02SDimitry Andric ShrinkToUses(LI, LIS); 6113ca95b02SDimitry Andric 6123ca95b02SDimitry Andric // Finish stackifying the new regs. 6133ca95b02SDimitry Andric LIS.createAndComputeVirtRegInterval(TeeReg); 6143ca95b02SDimitry Andric LIS.createAndComputeVirtRegInterval(DefReg); 6153ca95b02SDimitry Andric MFI.stackifyVReg(DefReg); 6163ca95b02SDimitry Andric MFI.stackifyVReg(TeeReg); 6173ca95b02SDimitry Andric ImposeStackOrdering(Def); 6183ca95b02SDimitry Andric ImposeStackOrdering(Tee); 6193ca95b02SDimitry Andric 6203ca95b02SDimitry Andric DEBUG(dbgs() << " - Replaced register: "; Def->dump()); 6213ca95b02SDimitry Andric DEBUG(dbgs() << " - Tee instruction: "; Tee->dump()); 6223ca95b02SDimitry Andric return Def; 6233ca95b02SDimitry Andric } 6243ca95b02SDimitry Andric 6253ca95b02SDimitry Andric namespace { 6263ca95b02SDimitry Andric /// A stack for walking the tree of instructions being built, visiting the 6273ca95b02SDimitry Andric /// MachineOperands in DFS order. 6283ca95b02SDimitry Andric class TreeWalkerState { 6293ca95b02SDimitry Andric typedef MachineInstr::mop_iterator mop_iterator; 6303ca95b02SDimitry Andric typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator; 6313ca95b02SDimitry Andric typedef iterator_range<mop_reverse_iterator> RangeTy; 6323ca95b02SDimitry Andric SmallVector<RangeTy, 4> Worklist; 6333ca95b02SDimitry Andric 6343ca95b02SDimitry Andric public: 6353ca95b02SDimitry Andric explicit TreeWalkerState(MachineInstr *Insert) { 6363ca95b02SDimitry Andric const iterator_range<mop_iterator> &Range = Insert->explicit_uses(); 6373ca95b02SDimitry Andric if (Range.begin() != Range.end()) 6383ca95b02SDimitry Andric Worklist.push_back(reverse(Range)); 6393ca95b02SDimitry Andric } 6403ca95b02SDimitry Andric 6413ca95b02SDimitry Andric bool Done() const { return Worklist.empty(); } 6423ca95b02SDimitry Andric 6433ca95b02SDimitry Andric MachineOperand &Pop() { 6443ca95b02SDimitry Andric RangeTy &Range = Worklist.back(); 6453ca95b02SDimitry Andric MachineOperand &Op = *Range.begin(); 6463ca95b02SDimitry Andric Range = drop_begin(Range, 1); 6473ca95b02SDimitry Andric if (Range.begin() == Range.end()) 6483ca95b02SDimitry Andric Worklist.pop_back(); 6493ca95b02SDimitry Andric assert((Worklist.empty() || 6503ca95b02SDimitry Andric Worklist.back().begin() != Worklist.back().end()) && 6513ca95b02SDimitry Andric "Empty ranges shouldn't remain in the worklist"); 6523ca95b02SDimitry Andric return Op; 6533ca95b02SDimitry Andric } 6543ca95b02SDimitry Andric 6553ca95b02SDimitry Andric /// Push Instr's operands onto the stack to be visited. 6563ca95b02SDimitry Andric void PushOperands(MachineInstr *Instr) { 6573ca95b02SDimitry Andric const iterator_range<mop_iterator> &Range(Instr->explicit_uses()); 6583ca95b02SDimitry Andric if (Range.begin() != Range.end()) 6593ca95b02SDimitry Andric Worklist.push_back(reverse(Range)); 6603ca95b02SDimitry Andric } 6613ca95b02SDimitry Andric 6623ca95b02SDimitry Andric /// Some of Instr's operands are on the top of the stack; remove them and 6633ca95b02SDimitry Andric /// re-insert them starting from the beginning (because we've commuted them). 6643ca95b02SDimitry Andric void ResetTopOperands(MachineInstr *Instr) { 6653ca95b02SDimitry Andric assert(HasRemainingOperands(Instr) && 6663ca95b02SDimitry Andric "Reseting operands should only be done when the instruction has " 6673ca95b02SDimitry Andric "an operand still on the stack"); 6683ca95b02SDimitry Andric Worklist.back() = reverse(Instr->explicit_uses()); 6693ca95b02SDimitry Andric } 6703ca95b02SDimitry Andric 6713ca95b02SDimitry Andric /// Test whether Instr has operands remaining to be visited at the top of 6723ca95b02SDimitry Andric /// the stack. 6733ca95b02SDimitry Andric bool HasRemainingOperands(const MachineInstr *Instr) const { 6743ca95b02SDimitry Andric if (Worklist.empty()) 6753ca95b02SDimitry Andric return false; 6763ca95b02SDimitry Andric const RangeTy &Range = Worklist.back(); 6773ca95b02SDimitry Andric return Range.begin() != Range.end() && Range.begin()->getParent() == Instr; 6783ca95b02SDimitry Andric } 6793ca95b02SDimitry Andric 6803ca95b02SDimitry Andric /// Test whether the given register is present on the stack, indicating an 6813ca95b02SDimitry Andric /// operand in the tree that we haven't visited yet. Moving a definition of 6823ca95b02SDimitry Andric /// Reg to a point in the tree after that would change its value. 6833ca95b02SDimitry Andric /// 6843ca95b02SDimitry Andric /// This is needed as a consequence of using implicit get_locals for 6853ca95b02SDimitry Andric /// uses and implicit set_locals for defs. 6863ca95b02SDimitry Andric bool IsOnStack(unsigned Reg) const { 6873ca95b02SDimitry Andric for (const RangeTy &Range : Worklist) 6883ca95b02SDimitry Andric for (const MachineOperand &MO : Range) 6893ca95b02SDimitry Andric if (MO.isReg() && MO.getReg() == Reg) 6903ca95b02SDimitry Andric return true; 6913ca95b02SDimitry Andric return false; 6923ca95b02SDimitry Andric } 6933ca95b02SDimitry Andric }; 6943ca95b02SDimitry Andric 6953ca95b02SDimitry Andric /// State to keep track of whether commuting is in flight or whether it's been 6963ca95b02SDimitry Andric /// tried for the current instruction and didn't work. 6973ca95b02SDimitry Andric class CommutingState { 6983ca95b02SDimitry Andric /// There are effectively three states: the initial state where we haven't 6993ca95b02SDimitry Andric /// started commuting anything and we don't know anything yet, the tenative 7003ca95b02SDimitry Andric /// state where we've commuted the operands of the current instruction and are 7013ca95b02SDimitry Andric /// revisting it, and the declined state where we've reverted the operands 7023ca95b02SDimitry Andric /// back to their original order and will no longer commute it further. 7033ca95b02SDimitry Andric bool TentativelyCommuting; 7043ca95b02SDimitry Andric bool Declined; 7053ca95b02SDimitry Andric 7063ca95b02SDimitry Andric /// During the tentative state, these hold the operand indices of the commuted 7073ca95b02SDimitry Andric /// operands. 7083ca95b02SDimitry Andric unsigned Operand0, Operand1; 7093ca95b02SDimitry Andric 7103ca95b02SDimitry Andric public: 7113ca95b02SDimitry Andric CommutingState() : TentativelyCommuting(false), Declined(false) {} 7123ca95b02SDimitry Andric 7133ca95b02SDimitry Andric /// Stackification for an operand was not successful due to ordering 7143ca95b02SDimitry Andric /// constraints. If possible, and if we haven't already tried it and declined 7153ca95b02SDimitry Andric /// it, commute Insert's operands and prepare to revisit it. 7163ca95b02SDimitry Andric void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker, 7173ca95b02SDimitry Andric const WebAssemblyInstrInfo *TII) { 7183ca95b02SDimitry Andric if (TentativelyCommuting) { 7193ca95b02SDimitry Andric assert(!Declined && 7203ca95b02SDimitry Andric "Don't decline commuting until you've finished trying it"); 7213ca95b02SDimitry Andric // Commuting didn't help. Revert it. 7223ca95b02SDimitry Andric TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1); 7233ca95b02SDimitry Andric TentativelyCommuting = false; 7243ca95b02SDimitry Andric Declined = true; 7253ca95b02SDimitry Andric } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) { 7263ca95b02SDimitry Andric Operand0 = TargetInstrInfo::CommuteAnyOperandIndex; 7273ca95b02SDimitry Andric Operand1 = TargetInstrInfo::CommuteAnyOperandIndex; 7283ca95b02SDimitry Andric if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) { 7293ca95b02SDimitry Andric // Tentatively commute the operands and try again. 7303ca95b02SDimitry Andric TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1); 7313ca95b02SDimitry Andric TreeWalker.ResetTopOperands(Insert); 7323ca95b02SDimitry Andric TentativelyCommuting = true; 7333ca95b02SDimitry Andric Declined = false; 7343ca95b02SDimitry Andric } 7353ca95b02SDimitry Andric } 7363ca95b02SDimitry Andric } 7373ca95b02SDimitry Andric 7383ca95b02SDimitry Andric /// Stackification for some operand was successful. Reset to the default 7393ca95b02SDimitry Andric /// state. 7403ca95b02SDimitry Andric void Reset() { 7413ca95b02SDimitry Andric TentativelyCommuting = false; 7423ca95b02SDimitry Andric Declined = false; 7433ca95b02SDimitry Andric } 7443ca95b02SDimitry Andric }; 7453ca95b02SDimitry Andric } // end anonymous namespace 7463ca95b02SDimitry Andric 7477d523365SDimitry Andric bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) { 7487d523365SDimitry Andric DEBUG(dbgs() << "********** Register Stackifying **********\n" 7497d523365SDimitry Andric "********** Function: " 7507d523365SDimitry Andric << MF.getName() << '\n'); 7517d523365SDimitry Andric 7527d523365SDimitry Andric bool Changed = false; 7537d523365SDimitry Andric MachineRegisterInfo &MRI = MF.getRegInfo(); 7547d523365SDimitry Andric WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 7553ca95b02SDimitry Andric const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 7563ca95b02SDimitry Andric const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo(); 7577d523365SDimitry Andric AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 7583ca95b02SDimitry Andric MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>(); 7597d523365SDimitry Andric LiveIntervals &LIS = getAnalysis<LiveIntervals>(); 7607d523365SDimitry Andric 7617d523365SDimitry Andric // Walk the instructions from the bottom up. Currently we don't look past 7627d523365SDimitry Andric // block boundaries, and the blocks aren't ordered so the block visitation 7637d523365SDimitry Andric // order isn't significant, but we may want to change this in the future. 7647d523365SDimitry Andric for (MachineBasicBlock &MBB : MF) { 765444ed5c5SDimitry Andric // Don't use a range-based for loop, because we modify the list as we're 766444ed5c5SDimitry Andric // iterating over it and the end iterator may change. 767444ed5c5SDimitry Andric for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) { 768444ed5c5SDimitry Andric MachineInstr *Insert = &*MII; 7697d523365SDimitry Andric // Don't nest anything inside an inline asm, because we don't have 7707d523365SDimitry Andric // constraints for $push inputs. 7717d523365SDimitry Andric if (Insert->getOpcode() == TargetOpcode::INLINEASM) 7723ca95b02SDimitry Andric continue; 7733ca95b02SDimitry Andric 7743ca95b02SDimitry Andric // Ignore debugging intrinsics. 7753ca95b02SDimitry Andric if (Insert->getOpcode() == TargetOpcode::DBG_VALUE) 7763ca95b02SDimitry Andric continue; 7777d523365SDimitry Andric 7787d523365SDimitry Andric // Iterate through the inputs in reverse order, since we'll be pulling 7797d523365SDimitry Andric // operands off the stack in LIFO order. 7803ca95b02SDimitry Andric CommutingState Commuting; 7813ca95b02SDimitry Andric TreeWalkerState TreeWalker(Insert); 7823ca95b02SDimitry Andric while (!TreeWalker.Done()) { 7833ca95b02SDimitry Andric MachineOperand &Op = TreeWalker.Pop(); 7843ca95b02SDimitry Andric 7857d523365SDimitry Andric // We're only interested in explicit virtual register operands. 7863ca95b02SDimitry Andric if (!Op.isReg()) 7877d523365SDimitry Andric continue; 7887d523365SDimitry Andric 7897d523365SDimitry Andric unsigned Reg = Op.getReg(); 7903ca95b02SDimitry Andric assert(Op.isUse() && "explicit_uses() should only iterate over uses"); 7913ca95b02SDimitry Andric assert(!Op.isImplicit() && 7923ca95b02SDimitry Andric "explicit_uses() should only iterate over explicit operands"); 7933ca95b02SDimitry Andric if (TargetRegisterInfo::isPhysicalRegister(Reg)) 7947d523365SDimitry Andric continue; 7957d523365SDimitry Andric 796d88c1a5aSDimitry Andric // Identify the definition for this register at this point. 7973ca95b02SDimitry Andric MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS); 7983ca95b02SDimitry Andric if (!Def) 7997d523365SDimitry Andric continue; 8007d523365SDimitry Andric 8017d523365SDimitry Andric // Don't nest an INLINE_ASM def into anything, because we don't have 8027d523365SDimitry Andric // constraints for $pop outputs. 8037d523365SDimitry Andric if (Def->getOpcode() == TargetOpcode::INLINEASM) 8047d523365SDimitry Andric continue; 8057d523365SDimitry Andric 8067d523365SDimitry Andric // Argument instructions represent live-in registers and not real 8077d523365SDimitry Andric // instructions. 808d88c1a5aSDimitry Andric if (WebAssembly::isArgument(*Def)) 8097d523365SDimitry Andric continue; 8107d523365SDimitry Andric 8113ca95b02SDimitry Andric // Decide which strategy to take. Prefer to move a single-use value 812d88c1a5aSDimitry Andric // over cloning it, and prefer cloning over introducing a tee. 8133ca95b02SDimitry Andric // For moving, we require the def to be in the same block as the use; 8143ca95b02SDimitry Andric // this makes things simpler (LiveIntervals' handleMove function only 8153ca95b02SDimitry Andric // supports intra-block moves) and it's MachineSink's job to catch all 8163ca95b02SDimitry Andric // the sinking opportunities anyway. 8173ca95b02SDimitry Andric bool SameBlock = Def->getParent() == &MBB; 818d88c1a5aSDimitry Andric bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) && 8193ca95b02SDimitry Andric !TreeWalker.IsOnStack(Reg); 8203ca95b02SDimitry Andric if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) { 8213ca95b02SDimitry Andric Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI); 8223ca95b02SDimitry Andric } else if (ShouldRematerialize(*Def, AA, TII)) { 8233ca95b02SDimitry Andric Insert = 8243ca95b02SDimitry Andric RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(), 8253ca95b02SDimitry Andric LIS, MFI, MRI, TII, TRI); 8263ca95b02SDimitry Andric } else if (CanMove && 8273ca95b02SDimitry Andric OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) { 8283ca95b02SDimitry Andric Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI, 8293ca95b02SDimitry Andric MRI, TII); 8303ca95b02SDimitry Andric } else { 8313ca95b02SDimitry Andric // We failed to stackify the operand. If the problem was ordering 8323ca95b02SDimitry Andric // constraints, Commuting may be able to help. 8333ca95b02SDimitry Andric if (!CanMove && SameBlock) 8343ca95b02SDimitry Andric Commuting.MaybeCommute(Insert, TreeWalker, TII); 8353ca95b02SDimitry Andric // Proceed to the next operand. 8367d523365SDimitry Andric continue; 8377d523365SDimitry Andric } 8383ca95b02SDimitry Andric 839d88c1a5aSDimitry Andric // If the instruction we just stackified is an IMPLICIT_DEF, convert it 840d88c1a5aSDimitry Andric // to a constant 0 so that the def is explicit, and the push/pop 841d88c1a5aSDimitry Andric // correspondence is maintained. 842d88c1a5aSDimitry Andric if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF) 843d88c1a5aSDimitry Andric ConvertImplicitDefToConstZero(Insert, MRI, TII, MF); 844d88c1a5aSDimitry Andric 8453ca95b02SDimitry Andric // We stackified an operand. Add the defining instruction's operands to 8463ca95b02SDimitry Andric // the worklist stack now to continue to build an ever deeper tree. 8473ca95b02SDimitry Andric Commuting.Reset(); 8483ca95b02SDimitry Andric TreeWalker.PushOperands(Insert); 8493ca95b02SDimitry Andric } 8503ca95b02SDimitry Andric 8513ca95b02SDimitry Andric // If we stackified any operands, skip over the tree to start looking for 8523ca95b02SDimitry Andric // the next instruction we can build a tree on. 8533ca95b02SDimitry Andric if (Insert != &*MII) { 854444ed5c5SDimitry Andric ImposeStackOrdering(&*MII); 855d88c1a5aSDimitry Andric MII = MachineBasicBlock::iterator(Insert).getReverse(); 8563ca95b02SDimitry Andric Changed = true; 8573ca95b02SDimitry Andric } 8587d523365SDimitry Andric } 8597d523365SDimitry Andric } 8607d523365SDimitry Andric 861d88c1a5aSDimitry Andric // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so 8623ca95b02SDimitry Andric // that it never looks like a use-before-def. 8637d523365SDimitry Andric if (Changed) { 864d88c1a5aSDimitry Andric MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK); 8657d523365SDimitry Andric for (MachineBasicBlock &MBB : MF) 866d88c1a5aSDimitry Andric MBB.addLiveIn(WebAssembly::VALUE_STACK); 8677d523365SDimitry Andric } 8687d523365SDimitry Andric 8697d523365SDimitry Andric #ifndef NDEBUG 8703ca95b02SDimitry Andric // Verify that pushes and pops are performed in LIFO order. 8717d523365SDimitry Andric SmallVector<unsigned, 0> Stack; 8727d523365SDimitry Andric for (MachineBasicBlock &MBB : MF) { 8737d523365SDimitry Andric for (MachineInstr &MI : MBB) { 8743ca95b02SDimitry Andric if (MI.isDebugValue()) 8753ca95b02SDimitry Andric continue; 8767d523365SDimitry Andric for (MachineOperand &MO : reverse(MI.explicit_operands())) { 8777d523365SDimitry Andric if (!MO.isReg()) 8787d523365SDimitry Andric continue; 8793ca95b02SDimitry Andric unsigned Reg = MO.getReg(); 8807d523365SDimitry Andric 8813ca95b02SDimitry Andric if (MFI.isVRegStackified(Reg)) { 8827d523365SDimitry Andric if (MO.isDef()) 8833ca95b02SDimitry Andric Stack.push_back(Reg); 8847d523365SDimitry Andric else 8853ca95b02SDimitry Andric assert(Stack.pop_back_val() == Reg && 8863ca95b02SDimitry Andric "Register stack pop should be paired with a push"); 8877d523365SDimitry Andric } 8887d523365SDimitry Andric } 8897d523365SDimitry Andric } 8907d523365SDimitry Andric // TODO: Generalize this code to support keeping values on the stack across 8917d523365SDimitry Andric // basic block boundaries. 8923ca95b02SDimitry Andric assert(Stack.empty() && 8933ca95b02SDimitry Andric "Register stack pushes and pops should be balanced"); 8947d523365SDimitry Andric } 8957d523365SDimitry Andric #endif 8967d523365SDimitry Andric 8977d523365SDimitry Andric return Changed; 8987d523365SDimitry Andric } 899