14fc4e42dSDan Gohman //===-- WebAssemblyExplicitLocals.cpp - Make Locals Explicit --------------===//
24fc4e42dSDan 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
64fc4e42dSDan Gohman //
74fc4e42dSDan Gohman //===----------------------------------------------------------------------===//
84fc4e42dSDan Gohman ///
94fc4e42dSDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file converts any remaining registers into WebAssembly locals.
114fc4e42dSDan Gohman ///
124fc4e42dSDan Gohman /// After register stackification and register coloring, convert non-stackified
136a87ddacSThomas Lively /// registers into locals, inserting explicit local.get and local.set
144fc4e42dSDan Gohman /// instructions.
154fc4e42dSDan Gohman ///
164fc4e42dSDan Gohman //===----------------------------------------------------------------------===//
174fc4e42dSDan Gohman 
184fc4e42dSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
194fc4e42dSDan Gohman #include "WebAssembly.h"
204fc4e42dSDan Gohman #include "WebAssemblyMachineFunctionInfo.h"
214fc4e42dSDan Gohman #include "WebAssemblySubtarget.h"
224fc4e42dSDan Gohman #include "WebAssemblyUtilities.h"
234fc4e42dSDan Gohman #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
244fc4e42dSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h"
254fc4e42dSDan Gohman #include "llvm/CodeGen/MachineRegisterInfo.h"
264fc4e42dSDan Gohman #include "llvm/CodeGen/Passes.h"
274fc4e42dSDan Gohman #include "llvm/Support/Debug.h"
284fc4e42dSDan Gohman #include "llvm/Support/raw_ostream.h"
294fc4e42dSDan Gohman using namespace llvm;
304fc4e42dSDan Gohman 
314fc4e42dSDan Gohman #define DEBUG_TYPE "wasm-explicit-locals"
324fc4e42dSDan Gohman 
338a9cb242SWouter van Oortmerssen // A command-line option to disable this pass, and keep implicit locals
348a9cb242SWouter van Oortmerssen // for the purpose of testing with lit/llc ONLY.
358a9cb242SWouter van Oortmerssen // This produces output which is not valid WebAssembly, and is not supported
368a9cb242SWouter van Oortmerssen // by assemblers/disassemblers and other MC based tools.
378a9cb242SWouter van Oortmerssen static cl::opt<bool> WasmDisableExplicitLocals(
388a9cb242SWouter van Oortmerssen     "wasm-disable-explicit-locals", cl::Hidden,
398a9cb242SWouter van Oortmerssen     cl::desc("WebAssembly: output implicit locals in"
408a9cb242SWouter van Oortmerssen              " instruction output for test purposes only."),
417d7409e5SDan Gohman     cl::init(false));
427d7409e5SDan Gohman 
434fc4e42dSDan Gohman namespace {
444fc4e42dSDan Gohman class WebAssemblyExplicitLocals final : public MachineFunctionPass {
454fc4e42dSDan Gohman   StringRef getPassName() const override {
464fc4e42dSDan Gohman     return "WebAssembly Explicit Locals";
474fc4e42dSDan Gohman   }
484fc4e42dSDan Gohman 
494fc4e42dSDan Gohman   void getAnalysisUsage(AnalysisUsage &AU) const override {
504fc4e42dSDan Gohman     AU.setPreservesCFG();
514fc4e42dSDan Gohman     AU.addPreserved<MachineBlockFrequencyInfo>();
524fc4e42dSDan Gohman     MachineFunctionPass::getAnalysisUsage(AU);
534fc4e42dSDan Gohman   }
544fc4e42dSDan Gohman 
554fc4e42dSDan Gohman   bool runOnMachineFunction(MachineFunction &MF) override;
564fc4e42dSDan Gohman 
574fc4e42dSDan Gohman public:
584fc4e42dSDan Gohman   static char ID; // Pass identification, replacement for typeid
594fc4e42dSDan Gohman   WebAssemblyExplicitLocals() : MachineFunctionPass(ID) {}
604fc4e42dSDan Gohman };
614fc4e42dSDan Gohman } // end anonymous namespace
624fc4e42dSDan Gohman 
634fc4e42dSDan Gohman char WebAssemblyExplicitLocals::ID = 0;
6440926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyExplicitLocals, DEBUG_TYPE,
6540926451SJacob Gravelle                 "Convert registers to WebAssembly locals", false, false)
6640926451SJacob Gravelle 
674fc4e42dSDan Gohman FunctionPass *llvm::createWebAssemblyExplicitLocals() {
684fc4e42dSDan Gohman   return new WebAssemblyExplicitLocals();
694fc4e42dSDan Gohman }
704fc4e42dSDan Gohman 
714fc4e42dSDan Gohman /// Return a local id number for the given register, assigning it a new one
724fc4e42dSDan Gohman /// if it doesn't yet have one.
734fc4e42dSDan Gohman static unsigned getLocalId(DenseMap<unsigned, unsigned> &Reg2Local,
744fc4e42dSDan Gohman                            unsigned &CurLocal, unsigned Reg) {
75d934cb88SDan Gohman   auto P = Reg2Local.insert(std::make_pair(Reg, CurLocal));
76d934cb88SDan Gohman   if (P.second)
77d934cb88SDan Gohman     ++CurLocal;
78d934cb88SDan Gohman   return P.first->second;
79d934cb88SDan Gohman }
80d934cb88SDan Gohman 
81d934cb88SDan Gohman /// Get the appropriate drop opcode for the given register class.
82d934cb88SDan Gohman static unsigned getDropOpcode(const TargetRegisterClass *RC) {
83d934cb88SDan Gohman   if (RC == &WebAssembly::I32RegClass)
84d934cb88SDan Gohman     return WebAssembly::DROP_I32;
85d934cb88SDan Gohman   if (RC == &WebAssembly::I64RegClass)
86d934cb88SDan Gohman     return WebAssembly::DROP_I64;
87d934cb88SDan Gohman   if (RC == &WebAssembly::F32RegClass)
88d934cb88SDan Gohman     return WebAssembly::DROP_F32;
89d934cb88SDan Gohman   if (RC == &WebAssembly::F64RegClass)
90d934cb88SDan Gohman     return WebAssembly::DROP_F64;
91d934cb88SDan Gohman   if (RC == &WebAssembly::V128RegClass)
92d934cb88SDan Gohman     return WebAssembly::DROP_V128;
930de58729SHeejin Ahn   if (RC == &WebAssembly::EXCEPT_REFRegClass)
940de58729SHeejin Ahn     return WebAssembly::DROP_EXCEPT_REF;
95d934cb88SDan Gohman   llvm_unreachable("Unexpected register class");
964fc4e42dSDan Gohman }
974fc4e42dSDan Gohman 
986a87ddacSThomas Lively /// Get the appropriate local.get opcode for the given register class.
994fc4e42dSDan Gohman static unsigned getGetLocalOpcode(const TargetRegisterClass *RC) {
1004fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1016a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_I32;
1024fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1036a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_I64;
1044fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1056a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_F32;
1064fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1076a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_F64;
1084fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1096a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_V128;
1100de58729SHeejin Ahn   if (RC == &WebAssembly::EXCEPT_REFRegClass)
1116a87ddacSThomas Lively     return WebAssembly::LOCAL_GET_EXCEPT_REF;
1124fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1134fc4e42dSDan Gohman }
1144fc4e42dSDan Gohman 
1156a87ddacSThomas Lively /// Get the appropriate local.set opcode for the given register class.
1164fc4e42dSDan Gohman static unsigned getSetLocalOpcode(const TargetRegisterClass *RC) {
1174fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1186a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_I32;
1194fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1206a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_I64;
1214fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1226a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_F32;
1234fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1246a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_F64;
1254fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1266a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_V128;
1270de58729SHeejin Ahn   if (RC == &WebAssembly::EXCEPT_REFRegClass)
1286a87ddacSThomas Lively     return WebAssembly::LOCAL_SET_EXCEPT_REF;
1294fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1304fc4e42dSDan Gohman }
1314fc4e42dSDan Gohman 
1326a87ddacSThomas Lively /// Get the appropriate local.tee opcode for the given register class.
1334fc4e42dSDan Gohman static unsigned getTeeLocalOpcode(const TargetRegisterClass *RC) {
1344fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1356a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_I32;
1364fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1376a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_I64;
1384fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1396a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_F32;
1404fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1416a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_F64;
1424fc4e42dSDan Gohman   if (RC == &WebAssembly::V128RegClass)
1436a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_V128;
1440de58729SHeejin Ahn   if (RC == &WebAssembly::EXCEPT_REFRegClass)
1456a87ddacSThomas Lively     return WebAssembly::LOCAL_TEE_EXCEPT_REF;
1464fc4e42dSDan Gohman   llvm_unreachable("Unexpected register class");
1474fc4e42dSDan Gohman }
1484fc4e42dSDan Gohman 
1494fc4e42dSDan Gohman /// Get the type associated with the given register class.
1503acb187dSDan Gohman static MVT typeForRegClass(const TargetRegisterClass *RC) {
1514fc4e42dSDan Gohman   if (RC == &WebAssembly::I32RegClass)
1523acb187dSDan Gohman     return MVT::i32;
1534fc4e42dSDan Gohman   if (RC == &WebAssembly::I64RegClass)
1543acb187dSDan Gohman     return MVT::i64;
1554fc4e42dSDan Gohman   if (RC == &WebAssembly::F32RegClass)
1563acb187dSDan Gohman     return MVT::f32;
1574fc4e42dSDan Gohman   if (RC == &WebAssembly::F64RegClass)
1583acb187dSDan Gohman     return MVT::f64;
159409f5840SThomas Lively   if (RC == &WebAssembly::V128RegClass)
160409f5840SThomas Lively     return MVT::v16i8;
1610de58729SHeejin Ahn   if (RC == &WebAssembly::EXCEPT_REFRegClass)
1620de58729SHeejin Ahn     return MVT::ExceptRef;
1634fc4e42dSDan Gohman   llvm_unreachable("unrecognized register class");
1644fc4e42dSDan Gohman }
1654fc4e42dSDan Gohman 
1664fc4e42dSDan Gohman /// Given a MachineOperand of a stackified vreg, return the instruction at the
1674fc4e42dSDan Gohman /// start of the expression tree.
1688a9cb242SWouter van Oortmerssen static MachineInstr *findStartOfTree(MachineOperand &MO,
1694fc4e42dSDan Gohman                                      MachineRegisterInfo &MRI,
1704fc4e42dSDan Gohman                                      WebAssemblyFunctionInfo &MFI) {
1714fc4e42dSDan Gohman   unsigned Reg = MO.getReg();
1724fc4e42dSDan Gohman   assert(MFI.isVRegStackified(Reg));
1734fc4e42dSDan Gohman   MachineInstr *Def = MRI.getVRegDef(Reg);
1744fc4e42dSDan Gohman 
1754fc4e42dSDan Gohman   // Find the first stackified use and proceed from there.
1764fc4e42dSDan Gohman   for (MachineOperand &DefMO : Def->explicit_uses()) {
1774fc4e42dSDan Gohman     if (!DefMO.isReg())
1784fc4e42dSDan Gohman       continue;
1798a9cb242SWouter van Oortmerssen     return findStartOfTree(DefMO, MRI, MFI);
1804fc4e42dSDan Gohman   }
1814fc4e42dSDan Gohman 
1824fc4e42dSDan Gohman   // If there were no stackified uses, we've reached the start.
1834fc4e42dSDan Gohman   return Def;
1844fc4e42dSDan Gohman }
1854fc4e42dSDan Gohman 
1864fc4e42dSDan Gohman bool WebAssemblyExplicitLocals::runOnMachineFunction(MachineFunction &MF) {
187d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "********** Make Locals Explicit **********\n"
1884fc4e42dSDan Gohman                        "********** Function: "
1894fc4e42dSDan Gohman                     << MF.getName() << '\n');
1904fc4e42dSDan Gohman 
1917d7409e5SDan Gohman   // Disable this pass if directed to do so.
1928a9cb242SWouter van Oortmerssen   if (WasmDisableExplicitLocals)
1937d7409e5SDan Gohman     return false;
1947d7409e5SDan Gohman 
1954fc4e42dSDan Gohman   bool Changed = false;
1964fc4e42dSDan Gohman   MachineRegisterInfo &MRI = MF.getRegInfo();
1974fc4e42dSDan Gohman   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
1984fc4e42dSDan Gohman   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
1994fc4e42dSDan Gohman 
2004fc4e42dSDan Gohman   // Map non-stackified virtual registers to their local ids.
2014fc4e42dSDan Gohman   DenseMap<unsigned, unsigned> Reg2Local;
2024fc4e42dSDan Gohman 
2034fc4e42dSDan Gohman   // Handle ARGUMENTS first to ensure that they get the designated numbers.
2044fc4e42dSDan Gohman   for (MachineBasicBlock::iterator I = MF.begin()->begin(),
2054fc4e42dSDan Gohman                                    E = MF.begin()->end();
2064fc4e42dSDan Gohman        I != E;) {
2074fc4e42dSDan Gohman     MachineInstr &MI = *I++;
2084fc4e42dSDan Gohman     if (!WebAssembly::isArgument(MI))
2094fc4e42dSDan Gohman       break;
2104fc4e42dSDan Gohman     unsigned Reg = MI.getOperand(0).getReg();
2114fc4e42dSDan Gohman     assert(!MFI.isVRegStackified(Reg));
2128a9cb242SWouter van Oortmerssen     Reg2Local[Reg] = static_cast<unsigned>(MI.getOperand(1).getImm());
2134fc4e42dSDan Gohman     MI.eraseFromParent();
2144fc4e42dSDan Gohman     Changed = true;
2154fc4e42dSDan Gohman   }
2164fc4e42dSDan Gohman 
2174fc4e42dSDan Gohman   // Start assigning local numbers after the last parameter.
2188a9cb242SWouter van Oortmerssen   unsigned CurLocal = static_cast<unsigned>(MFI.getParams().size());
2194fc4e42dSDan Gohman 
220d934cb88SDan Gohman   // Precompute the set of registers that are unused, so that we can insert
221d934cb88SDan Gohman   // drops to their defs.
222d934cb88SDan Gohman   BitVector UseEmpty(MRI.getNumVirtRegs());
2238a9cb242SWouter van Oortmerssen   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I < E; ++I)
2248a9cb242SWouter van Oortmerssen     UseEmpty[I] = MRI.use_empty(TargetRegisterInfo::index2VirtReg(I));
225d934cb88SDan Gohman 
2264fc4e42dSDan Gohman   // Visit each instruction in the function.
2274fc4e42dSDan Gohman   for (MachineBasicBlock &MBB : MF) {
2284fc4e42dSDan Gohman     for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
2294fc4e42dSDan Gohman       MachineInstr &MI = *I++;
2304fc4e42dSDan Gohman       assert(!WebAssembly::isArgument(MI));
2314fc4e42dSDan Gohman 
232801bf7ebSShiva Chen       if (MI.isDebugInstr() || MI.isLabel())
2334fc4e42dSDan Gohman         continue;
2344fc4e42dSDan Gohman 
2356a87ddacSThomas Lively       // Replace tee instructions with local.tee. The difference is that tee
2366a87ddacSThomas Lively       // instructions have two defs, while local.tee instructions have one def
2374fc4e42dSDan Gohman       // and an index of a local to write to.
2384fc4e42dSDan Gohman       if (WebAssembly::isTee(MI)) {
2394fc4e42dSDan Gohman         assert(MFI.isVRegStackified(MI.getOperand(0).getReg()));
2404fc4e42dSDan Gohman         assert(!MFI.isVRegStackified(MI.getOperand(1).getReg()));
2414fc4e42dSDan Gohman         unsigned OldReg = MI.getOperand(2).getReg();
2424fc4e42dSDan Gohman         const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
2434fc4e42dSDan Gohman 
2444fc4e42dSDan Gohman         // Stackify the input if it isn't stackified yet.
2454fc4e42dSDan Gohman         if (!MFI.isVRegStackified(OldReg)) {
2464fc4e42dSDan Gohman           unsigned LocalId = getLocalId(Reg2Local, CurLocal, OldReg);
2474fc4e42dSDan Gohman           unsigned NewReg = MRI.createVirtualRegister(RC);
2484fc4e42dSDan Gohman           unsigned Opc = getGetLocalOpcode(RC);
2494fc4e42dSDan Gohman           BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(Opc), NewReg)
2504fc4e42dSDan Gohman               .addImm(LocalId);
2514fc4e42dSDan Gohman           MI.getOperand(2).setReg(NewReg);
2524fc4e42dSDan Gohman           MFI.stackifyVReg(NewReg);
2534fc4e42dSDan Gohman         }
2544fc4e42dSDan Gohman 
2556a87ddacSThomas Lively         // Replace the TEE with a LOCAL_TEE.
2564fc4e42dSDan Gohman         unsigned LocalId =
2574fc4e42dSDan Gohman             getLocalId(Reg2Local, CurLocal, MI.getOperand(1).getReg());
2584fc4e42dSDan Gohman         unsigned Opc = getTeeLocalOpcode(RC);
2594fc4e42dSDan Gohman         BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(Opc),
2604fc4e42dSDan Gohman                 MI.getOperand(0).getReg())
2614fc4e42dSDan Gohman             .addImm(LocalId)
2624fc4e42dSDan Gohman             .addReg(MI.getOperand(2).getReg());
2634fc4e42dSDan Gohman 
2644fc4e42dSDan Gohman         MI.eraseFromParent();
2654fc4e42dSDan Gohman         Changed = true;
2664fc4e42dSDan Gohman         continue;
2674fc4e42dSDan Gohman       }
2684fc4e42dSDan Gohman 
2696a87ddacSThomas Lively       // Insert local.sets for any defs that aren't stackified yet. Currently
2704fc4e42dSDan Gohman       // we handle at most one def.
2714fc4e42dSDan Gohman       assert(MI.getDesc().getNumDefs() <= 1);
2724fc4e42dSDan Gohman       if (MI.getDesc().getNumDefs() == 1) {
2734fc4e42dSDan Gohman         unsigned OldReg = MI.getOperand(0).getReg();
274d934cb88SDan Gohman         if (!MFI.isVRegStackified(OldReg)) {
2754fc4e42dSDan Gohman           const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
2764fc4e42dSDan Gohman           unsigned NewReg = MRI.createVirtualRegister(RC);
277*5c644c9bSHeejin Ahn           auto InsertPt = std::next(MI.getIterator());
278d934cb88SDan Gohman           if (MI.getOpcode() == WebAssembly::IMPLICIT_DEF) {
279d934cb88SDan Gohman             MI.eraseFromParent();
280d934cb88SDan Gohman             Changed = true;
281d934cb88SDan Gohman             continue;
282d934cb88SDan Gohman           }
283d934cb88SDan Gohman           if (UseEmpty[TargetRegisterInfo::virtReg2Index(OldReg)]) {
284d934cb88SDan Gohman             unsigned Opc = getDropOpcode(RC);
285891a7472SHeejin Ahn             MachineInstr *Drop =
286d934cb88SDan Gohman                 BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc))
287d934cb88SDan Gohman                     .addReg(NewReg);
288891a7472SHeejin Ahn             // After the drop instruction, this reg operand will not be used
289891a7472SHeejin Ahn             Drop->getOperand(0).setIsKill();
290d934cb88SDan Gohman           } else {
291d934cb88SDan Gohman             unsigned LocalId = getLocalId(Reg2Local, CurLocal, OldReg);
2924fc4e42dSDan Gohman             unsigned Opc = getSetLocalOpcode(RC);
2934fc4e42dSDan Gohman             BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc))
2944fc4e42dSDan Gohman                 .addImm(LocalId)
2954fc4e42dSDan Gohman                 .addReg(NewReg);
296d934cb88SDan Gohman           }
2974fc4e42dSDan Gohman           MI.getOperand(0).setReg(NewReg);
2984d98dfb6SHeejin Ahn           // This register operand of the original instruction is now being used
2996a87ddacSThomas Lively           // by the inserted drop or local.set instruction, so make it not dead
3004d98dfb6SHeejin Ahn           // yet.
301891a7472SHeejin Ahn           MI.getOperand(0).setIsDead(false);
3024fc4e42dSDan Gohman           MFI.stackifyVReg(NewReg);
3034fc4e42dSDan Gohman           Changed = true;
3044fc4e42dSDan Gohman         }
3054fc4e42dSDan Gohman       }
3064fc4e42dSDan Gohman 
3076a87ddacSThomas Lively       // Insert local.gets for any uses that aren't stackified yet.
3084fc4e42dSDan Gohman       MachineInstr *InsertPt = &MI;
3094fc4e42dSDan Gohman       for (MachineOperand &MO : reverse(MI.explicit_uses())) {
3104fc4e42dSDan Gohman         if (!MO.isReg())
3114fc4e42dSDan Gohman           continue;
3124fc4e42dSDan Gohman 
3134fc4e42dSDan Gohman         unsigned OldReg = MO.getReg();
3144fc4e42dSDan Gohman 
315b465aa05SDan Gohman         // Inline asm may have a def in the middle of the operands. Our contract
316b465aa05SDan Gohman         // with inline asm register operands is to provide local indices as
317b465aa05SDan Gohman         // immediates.
318b465aa05SDan Gohman         if (MO.isDef()) {
319c45e39b3SCraig Topper           assert(MI.isInlineAsm());
320b465aa05SDan Gohman           unsigned LocalId = getLocalId(Reg2Local, CurLocal, OldReg);
321300f42fbSHeejin Ahn           // If this register operand is tied to another operand, we can't
322300f42fbSHeejin Ahn           // change it to an immediate. Untie it first.
323300f42fbSHeejin Ahn           MI.untieRegOperand(MI.getOperandNo(&MO));
324045a217bSDan Gohman           MO.ChangeToImmediate(LocalId);
325b465aa05SDan Gohman           continue;
326b465aa05SDan Gohman         }
327b465aa05SDan Gohman 
3284fc4e42dSDan Gohman         // If we see a stackified register, prepare to insert subsequent
3296a87ddacSThomas Lively         // local.gets before the start of its tree.
3304fc4e42dSDan Gohman         if (MFI.isVRegStackified(OldReg)) {
3318a9cb242SWouter van Oortmerssen           InsertPt = findStartOfTree(MO, MRI, MFI);
3324fc4e42dSDan Gohman           continue;
3334fc4e42dSDan Gohman         }
3344fc4e42dSDan Gohman 
335b465aa05SDan Gohman         // Our contract with inline asm register operands is to provide local
336b465aa05SDan Gohman         // indices as immediates.
337c45e39b3SCraig Topper         if (MI.isInlineAsm()) {
338b465aa05SDan Gohman           unsigned LocalId = getLocalId(Reg2Local, CurLocal, OldReg);
339300f42fbSHeejin Ahn           // Untie it first if this reg operand is tied to another operand.
340300f42fbSHeejin Ahn           MI.untieRegOperand(MI.getOperandNo(&MO));
341045a217bSDan Gohman           MO.ChangeToImmediate(LocalId);
342b465aa05SDan Gohman           continue;
343b465aa05SDan Gohman         }
344b465aa05SDan Gohman 
3456a87ddacSThomas Lively         // Insert a local.get.
3464fc4e42dSDan Gohman         unsigned LocalId = getLocalId(Reg2Local, CurLocal, OldReg);
3474fc4e42dSDan Gohman         const TargetRegisterClass *RC = MRI.getRegClass(OldReg);
3484fc4e42dSDan Gohman         unsigned NewReg = MRI.createVirtualRegister(RC);
3494fc4e42dSDan Gohman         unsigned Opc = getGetLocalOpcode(RC);
3504fc4e42dSDan Gohman         InsertPt =
3514fc4e42dSDan Gohman             BuildMI(MBB, InsertPt, MI.getDebugLoc(), TII->get(Opc), NewReg)
3524fc4e42dSDan Gohman                 .addImm(LocalId);
3534fc4e42dSDan Gohman         MO.setReg(NewReg);
3544fc4e42dSDan Gohman         MFI.stackifyVReg(NewReg);
3554fc4e42dSDan Gohman         Changed = true;
3564fc4e42dSDan Gohman       }
3574fc4e42dSDan Gohman 
3584fc4e42dSDan Gohman       // Coalesce and eliminate COPY instructions.
3594fc4e42dSDan Gohman       if (WebAssembly::isCopy(MI)) {
3604fc4e42dSDan Gohman         MRI.replaceRegWith(MI.getOperand(1).getReg(),
3614fc4e42dSDan Gohman                            MI.getOperand(0).getReg());
3624fc4e42dSDan Gohman         MI.eraseFromParent();
3634fc4e42dSDan Gohman         Changed = true;
3644fc4e42dSDan Gohman       }
3654fc4e42dSDan Gohman     }
3664fc4e42dSDan Gohman   }
3674fc4e42dSDan Gohman 
3683acb187dSDan Gohman   // Define the locals.
369d934cb88SDan Gohman   // TODO: Sort the locals for better compression.
370d934cb88SDan Gohman   MFI.setNumLocals(CurLocal - MFI.getParams().size());
3718a9cb242SWouter van Oortmerssen   for (unsigned I = 0, E = MRI.getNumVirtRegs(); I < E; ++I) {
3728a9cb242SWouter van Oortmerssen     unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
3738a9cb242SWouter van Oortmerssen     auto RL = Reg2Local.find(Reg);
3748a9cb242SWouter van Oortmerssen     if (RL == Reg2Local.end() || RL->second < MFI.getParams().size())
3754fc4e42dSDan Gohman       continue;
3764fc4e42dSDan Gohman 
3778a9cb242SWouter van Oortmerssen     MFI.setLocal(RL->second - MFI.getParams().size(),
378d934cb88SDan Gohman                  typeForRegClass(MRI.getRegClass(Reg)));
3794fc4e42dSDan Gohman     Changed = true;
3804fc4e42dSDan Gohman   }
3814fc4e42dSDan Gohman 
382a7be3755SWouter van Oortmerssen #ifndef NDEBUG
383a7be3755SWouter van Oortmerssen   // Assert that all registers have been stackified at this point.
384a7be3755SWouter van Oortmerssen   for (const MachineBasicBlock &MBB : MF) {
385a7be3755SWouter van Oortmerssen     for (const MachineInstr &MI : MBB) {
386a7be3755SWouter van Oortmerssen       if (MI.isDebugInstr() || MI.isLabel())
387a7be3755SWouter van Oortmerssen         continue;
388a7be3755SWouter van Oortmerssen       for (const MachineOperand &MO : MI.explicit_operands()) {
389a7be3755SWouter van Oortmerssen         assert(
390a7be3755SWouter van Oortmerssen             (!MO.isReg() || MRI.use_empty(MO.getReg()) ||
391a7be3755SWouter van Oortmerssen              MFI.isVRegStackified(MO.getReg())) &&
392a7be3755SWouter van Oortmerssen             "WebAssemblyExplicitLocals failed to stackify a register operand");
393a67c4137SWouter van Oortmerssen       }
394a7be3755SWouter van Oortmerssen     }
395a7be3755SWouter van Oortmerssen   }
396a7be3755SWouter van Oortmerssen #endif
397ab26bd06SWouter van Oortmerssen 
398a7be3755SWouter van Oortmerssen   return Changed;
399ab26bd06SWouter van Oortmerssen }
400