blob: e49034467f73bdf296c14bfc09060f0963f70fc1 [file] [log] [blame]
Dan Gohman1462faa2015-11-16 16:18:28 +00001//===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Dan Gohman1462faa2015-11-16 16:18:28 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file implements a register stacking pass.
Dan Gohman1462faa2015-11-16 16:18:28 +000011///
12/// This pass reorders instructions to put register uses and defs in an order
13/// such that they form single-use expression trees. Registers fitting this form
14/// are then marked as "stackified", meaning references to them are replaced by
Dan Gohmane0405332016-10-03 22:43:53 +000015/// "push" and "pop" from the value stack.
Dan Gohman1462faa2015-11-16 16:18:28 +000016///
Dan Gohman31448f12015-12-08 03:43:03 +000017/// This is primarily a code size optimization, since temporary values on the
Dan Gohmane0405332016-10-03 22:43:53 +000018/// value stack don't need to be named.
Dan Gohman1462faa2015-11-16 16:18:28 +000019///
20//===----------------------------------------------------------------------===//
21
Dan Gohman4ba48162015-11-18 16:12:01 +000022#include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
Chandler Carruth6bda14b2017-06-06 11:49:48 +000023#include "WebAssembly.h"
Yury Delendikbe24c022019-01-15 18:14:12 +000024#include "WebAssemblyDebugValueManager.h"
Dan Gohman7a6b9822015-11-29 22:32:02 +000025#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohmanb6fd39a2016-01-19 16:59:23 +000026#include "WebAssemblySubtarget.h"
Dan Gohman4fc4e422016-10-24 19:49:43 +000027#include "WebAssemblyUtilities.h"
Yury Delendik7c18d602018-09-25 18:59:34 +000028#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman81719f82015-11-25 16:55:01 +000029#include "llvm/Analysis/AliasAnalysis.h"
Matthias Braunf8422972017-12-13 02:51:04 +000030#include "llvm/CodeGen/LiveIntervals.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000031#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Dan Gohmanadf28172016-01-28 01:22:44 +000032#include "llvm/CodeGen/MachineDominators.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman82607f52017-02-24 23:46:05 +000034#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39using namespace llvm;
40
41#define DEBUG_TYPE "wasm-reg-stackify"
42
43namespace {
44class WebAssemblyRegStackify final : public MachineFunctionPass {
Mehdi Amini117296c2016-10-01 02:56:57 +000045 StringRef getPassName() const override {
Dan Gohman1462faa2015-11-16 16:18:28 +000046 return "WebAssembly Register Stackify";
47 }
48
49 void getAnalysisUsage(AnalysisUsage &AU) const override {
50 AU.setPreservesCFG();
Dan Gohman81719f82015-11-25 16:55:01 +000051 AU.addRequired<AAResultsWrapperPass>();
Dan Gohmanadf28172016-01-28 01:22:44 +000052 AU.addRequired<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000053 AU.addRequired<LiveIntervals>();
Dan Gohman1462faa2015-11-16 16:18:28 +000054 AU.addPreserved<MachineBlockFrequencyInfo>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000055 AU.addPreserved<SlotIndexes>();
56 AU.addPreserved<LiveIntervals>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000057 AU.addPreservedID(LiveVariablesID);
Dan Gohmanadf28172016-01-28 01:22:44 +000058 AU.addPreserved<MachineDominatorTree>();
Dan Gohman1462faa2015-11-16 16:18:28 +000059 MachineFunctionPass::getAnalysisUsage(AU);
60 }
61
62 bool runOnMachineFunction(MachineFunction &MF) override;
63
64public:
65 static char ID; // Pass identification, replacement for typeid
66 WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
67};
68} // end anonymous namespace
69
70char WebAssemblyRegStackify::ID = 0;
Jacob Gravelle40926452018-03-30 20:36:58 +000071INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
72 "Reorder instructions to use the WebAssembly value stack",
73 false, false)
74
Dan Gohman1462faa2015-11-16 16:18:28 +000075FunctionPass *llvm::createWebAssemblyRegStackify() {
76 return new WebAssemblyRegStackify();
77}
78
Dan Gohmanb0992da2015-11-20 02:19:12 +000079// Decorate the given instruction with implicit operands that enforce the
Dan Gohman8887d1f2015-12-25 00:31:02 +000080// expression stack ordering constraints for an instruction which is on
81// the expression stack.
Heejin Ahn18c56a02019-02-04 19:13:39 +000082static void imposeStackOrdering(MachineInstr *MI) {
Dan Gohmane0405332016-10-03 22:43:53 +000083 // Write the opaque VALUE_STACK register.
84 if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohman4da4abd2015-12-05 00:51:40 +000086 /*isDef=*/true,
87 /*isImp=*/true));
Dan Gohman4da4abd2015-12-05 00:51:40 +000088
Dan Gohmane0405332016-10-03 22:43:53 +000089 // Also read the opaque VALUE_STACK register.
90 if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohmana712a6c2015-12-14 22:37:23 +000092 /*isDef=*/false,
93 /*isImp=*/true));
Dan Gohmanb0992da2015-11-20 02:19:12 +000094}
95
Dan Gohmane81021a2016-11-08 19:40:38 +000096// Convert an IMPLICIT_DEF instruction into an instruction which defines
97// a constant zero value.
Heejin Ahn18c56a02019-02-04 19:13:39 +000098static void convertImplicitDefToConstZero(MachineInstr *MI,
Dan Gohmane81021a2016-11-08 19:40:38 +000099 MachineRegisterInfo &MRI,
100 const TargetInstrInfo *TII,
Thomas Livelyfeb18fe2018-12-20 04:20:32 +0000101 MachineFunction &MF,
102 LiveIntervals &LIS) {
Dan Gohmane81021a2016-11-08 19:40:38 +0000103 assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
104
Heejin Ahnf208f632018-09-05 01:27:38 +0000105 const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
Dan Gohmane81021a2016-11-08 19:40:38 +0000106 if (RegClass == &WebAssembly::I32RegClass) {
107 MI->setDesc(TII->get(WebAssembly::CONST_I32));
108 MI->addOperand(MachineOperand::CreateImm(0));
109 } else if (RegClass == &WebAssembly::I64RegClass) {
110 MI->setDesc(TII->get(WebAssembly::CONST_I64));
111 MI->addOperand(MachineOperand::CreateImm(0));
112 } else if (RegClass == &WebAssembly::F32RegClass) {
113 MI->setDesc(TII->get(WebAssembly::CONST_F32));
Heejin Ahn18c56a02019-02-04 19:13:39 +0000114 auto *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000115 Type::getFloatTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000116 MI->addOperand(MachineOperand::CreateFPImm(Val));
117 } else if (RegClass == &WebAssembly::F64RegClass) {
118 MI->setDesc(TII->get(WebAssembly::CONST_F64));
Heejin Ahn18c56a02019-02-04 19:13:39 +0000119 auto *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000120 Type::getDoubleTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000121 MI->addOperand(MachineOperand::CreateFPImm(Val));
Thomas Lively6ff31fe2018-10-31 23:50:53 +0000122 } else if (RegClass == &WebAssembly::V128RegClass) {
Daniel Sanders05c145d2019-08-12 22:40:45 +0000123 Register TempReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Thomas Livelyfeb18fe2018-12-20 04:20:32 +0000124 MI->setDesc(TII->get(WebAssembly::SPLAT_v4i32));
125 MI->addOperand(MachineOperand::CreateReg(TempReg, false));
126 MachineInstr *Const = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
127 TII->get(WebAssembly::CONST_I32), TempReg)
128 .addImm(0);
129 LIS.InsertMachineInstrInMaps(*Const);
Dan Gohmane81021a2016-11-08 19:40:38 +0000130 } else {
131 llvm_unreachable("Unexpected reg class");
132 }
133}
134
Dan Gohman2644d742016-05-17 04:05:31 +0000135// Determine whether a call to the callee referenced by
136// MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
137// effects.
Thomas Lively3ef169e2019-12-13 10:41:25 -0800138static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write,
139 bool &Effects, bool &StackPointer) {
Dan Gohmand08cd152016-05-17 21:14:26 +0000140 // All calls can use the stack pointer.
141 StackPointer = true;
142
Thomas Lively3ef169e2019-12-13 10:41:25 -0800143 const MachineOperand &MO = WebAssembly::getCalleeOp(MI);
Dan Gohman2644d742016-05-17 04:05:31 +0000144 if (MO.isGlobal()) {
145 const Constant *GV = MO.getGlobal();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000146 if (const auto *GA = dyn_cast<GlobalAlias>(GV))
Dan Gohman2644d742016-05-17 04:05:31 +0000147 if (!GA->isInterposable())
148 GV = GA->getAliasee();
149
Heejin Ahn18c56a02019-02-04 19:13:39 +0000150 if (const auto *F = dyn_cast<Function>(GV)) {
Dan Gohman2644d742016-05-17 04:05:31 +0000151 if (!F->doesNotThrow())
152 Effects = true;
153 if (F->doesNotAccessMemory())
154 return;
155 if (F->onlyReadsMemory()) {
156 Read = true;
157 return;
158 }
159 }
160 }
161
162 // Assume the worst.
163 Write = true;
164 Read = true;
165 Effects = true;
166}
167
Dan Gohmand08cd152016-05-17 21:14:26 +0000168// Determine whether MI reads memory, writes memory, has side effects,
Dan Gohman82607f52017-02-24 23:46:05 +0000169// and/or uses the stack pointer value.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000170static void query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000171 bool &Write, bool &Effects, bool &StackPointer) {
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000172 assert(!MI.isTerminator());
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000173
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000174 if (MI.isDebugInstr() || MI.isPosition())
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000175 return;
Dan Gohman2644d742016-05-17 04:05:31 +0000176
177 // Check for loads.
Justin Lebard98cf002016-09-10 01:03:20 +0000178 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
Dan Gohman2644d742016-05-17 04:05:31 +0000179 Read = true;
180
181 // Check for stores.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000182 if (MI.mayStore()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000183 Write = true;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000184 } else if (MI.hasOrderedMemoryRef()) {
185 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000186 case WebAssembly::DIV_S_I32:
187 case WebAssembly::DIV_S_I64:
188 case WebAssembly::REM_S_I32:
189 case WebAssembly::REM_S_I64:
190 case WebAssembly::DIV_U_I32:
191 case WebAssembly::DIV_U_I64:
192 case WebAssembly::REM_U_I32:
193 case WebAssembly::REM_U_I64:
194 case WebAssembly::I32_TRUNC_S_F32:
195 case WebAssembly::I64_TRUNC_S_F32:
196 case WebAssembly::I32_TRUNC_S_F64:
197 case WebAssembly::I64_TRUNC_S_F64:
198 case WebAssembly::I32_TRUNC_U_F32:
199 case WebAssembly::I64_TRUNC_U_F32:
200 case WebAssembly::I32_TRUNC_U_F64:
201 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000202 // These instruction have hasUnmodeledSideEffects() returning true
203 // because they trap on overflow and invalid so they can't be arbitrarily
204 // moved, however hasOrderedMemoryRef() interprets this plus their lack
205 // of memoperands as having a potential unknown memory reference.
206 break;
207 default:
Dan Gohman10545702016-05-17 22:24:18 +0000208 // Record volatile accesses, unless it's a call, as calls are handled
Dan Gohman2644d742016-05-17 04:05:31 +0000209 // specially below.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000210 if (!MI.isCall()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000211 Write = true;
Dan Gohman10545702016-05-17 22:24:18 +0000212 Effects = true;
213 }
Dan Gohman2644d742016-05-17 04:05:31 +0000214 break;
215 }
216 }
217
218 // Check for side effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000219 if (MI.hasUnmodeledSideEffects()) {
220 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000221 case WebAssembly::DIV_S_I32:
222 case WebAssembly::DIV_S_I64:
223 case WebAssembly::REM_S_I32:
224 case WebAssembly::REM_S_I64:
225 case WebAssembly::DIV_U_I32:
226 case WebAssembly::DIV_U_I64:
227 case WebAssembly::REM_U_I32:
228 case WebAssembly::REM_U_I64:
229 case WebAssembly::I32_TRUNC_S_F32:
230 case WebAssembly::I64_TRUNC_S_F32:
231 case WebAssembly::I32_TRUNC_S_F64:
232 case WebAssembly::I64_TRUNC_S_F64:
233 case WebAssembly::I32_TRUNC_U_F32:
234 case WebAssembly::I64_TRUNC_U_F32:
235 case WebAssembly::I32_TRUNC_U_F64:
236 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000237 // These instructions have hasUnmodeledSideEffects() returning true
238 // because they trap on overflow and invalid so they can't be arbitrarily
239 // moved, however in the specific case of register stackifying, it is safe
240 // to move them because overflow and invalid are Undefined Behavior.
241 break;
242 default:
243 Effects = true;
244 break;
245 }
246 }
247
Heejin Ahne73c7a12019-01-10 23:12:07 +0000248 // Check for writes to __stack_pointer global.
249 if (MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 &&
250 strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
251 StackPointer = true;
252
Dan Gohman2644d742016-05-17 04:05:31 +0000253 // Analyze calls.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000254 if (MI.isCall()) {
Thomas Lively3ef169e2019-12-13 10:41:25 -0800255 queryCallee(MI, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000256 }
257}
258
259// Test whether Def is safe and profitable to rematerialize.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000260static bool shouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
Dan Gohman2644d742016-05-17 04:05:31 +0000261 const WebAssemblyInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000262 return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
Dan Gohman2644d742016-05-17 04:05:31 +0000263}
264
Dan Gohman12de0b92016-05-17 20:19:47 +0000265// Identify the definition for this register at this point. This is a
266// generalization of MachineRegisterInfo::getUniqueVRegDef that uses
267// LiveIntervals to handle complex cases.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000268static MachineInstr *getVRegDef(unsigned Reg, const MachineInstr *Insert,
Dan Gohman2644d742016-05-17 04:05:31 +0000269 const MachineRegisterInfo &MRI,
Heejin Ahnf208f632018-09-05 01:27:38 +0000270 const LiveIntervals &LIS) {
Dan Gohman2644d742016-05-17 04:05:31 +0000271 // Most registers are in SSA form here so we try a quick MRI query first.
272 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
273 return Def;
274
275 // MRI doesn't know what the Def is. Try asking LIS.
276 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
277 LIS.getInstructionIndex(*Insert)))
278 return LIS.getInstructionFromIndex(ValNo->def);
279
280 return nullptr;
281}
282
Dan Gohman12de0b92016-05-17 20:19:47 +0000283// Test whether Reg, as defined at Def, has exactly one use. This is a
284// generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
285// to handle complex cases.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000286static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
Heejin Ahnf208f632018-09-05 01:27:38 +0000287 MachineDominatorTree &MDT, LiveIntervals &LIS) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000288 // Most registers are in SSA form here so we try a quick MRI query first.
289 if (MRI.hasOneUse(Reg))
290 return true;
291
292 bool HasOne = false;
293 const LiveInterval &LI = LIS.getInterval(Reg);
Heejin Ahnf208f632018-09-05 01:27:38 +0000294 const VNInfo *DefVNI =
295 LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
Dan Gohman12de0b92016-05-17 20:19:47 +0000296 assert(DefVNI);
Dominic Chena8a63822016-08-17 23:42:27 +0000297 for (auto &I : MRI.use_nodbg_operands(Reg)) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000298 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
299 if (Result.valueIn() == DefVNI) {
300 if (!Result.isKill())
301 return false;
302 if (HasOne)
303 return false;
304 HasOne = true;
305 }
306 }
307 return HasOne;
308}
309
Dan Gohman8887d1f2015-12-25 00:31:02 +0000310// Test whether it's safe to move Def to just before Insert.
Dan Gohman81719f82015-11-25 16:55:01 +0000311// TODO: Compute memory dependencies in a way that doesn't require always
312// walking the block.
313// TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
314// more precise.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000315static bool isSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
Derek Schuffe9e68912016-09-30 18:02:54 +0000316 AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
Dan Gohman391a98a2015-12-03 23:07:03 +0000317 assert(Def->getParent() == Insert->getParent());
Dan Gohman8887d1f2015-12-25 00:31:02 +0000318
Heejin Ahnd6f48782019-01-30 03:21:57 +0000319 // 'catch' and 'extract_exception' should be the first instruction of a BB and
320 // cannot move.
321 if (Def->getOpcode() == WebAssembly::CATCH ||
322 Def->getOpcode() == WebAssembly::EXTRACT_EXCEPTION_I32) {
323 const MachineBasicBlock *MBB = Def->getParent();
324 auto NextI = std::next(MachineBasicBlock::const_iterator(Def));
325 for (auto E = MBB->end(); NextI != E && NextI->isDebugInstr(); ++NextI)
326 ;
327 if (NextI != Insert)
328 return false;
329 }
330
Dan Gohman8887d1f2015-12-25 00:31:02 +0000331 // Check for register dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000332 SmallVector<unsigned, 4> MutableRegisters;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000333 for (const MachineOperand &MO : Def->operands()) {
334 if (!MO.isReg() || MO.isUndef())
335 continue;
Daniel Sanders05c145d2019-08-12 22:40:45 +0000336 Register Reg = MO.getReg();
Dan Gohman8887d1f2015-12-25 00:31:02 +0000337
338 // If the register is dead here and at Insert, ignore it.
339 if (MO.isDead() && Insert->definesRegister(Reg) &&
340 !Insert->readsRegister(Reg))
341 continue;
342
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000343 if (Register::isPhysicalRegister(Reg)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000344 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
345 // from moving down, and we've already checked for that.
346 if (Reg == WebAssembly::ARGUMENTS)
347 continue;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000348 // If the physical register is never modified, ignore it.
349 if (!MRI.isPhysRegModified(Reg))
350 continue;
351 // Otherwise, it's a physical register with unknown liveness.
352 return false;
353 }
354
Derek Schuffe9e68912016-09-30 18:02:54 +0000355 // If one of the operands isn't in SSA form, it has different values at
356 // different times, and we need to make sure we don't move our use across
357 // a different def.
358 if (!MO.isDef() && !MRI.hasOneDef(Reg))
359 MutableRegisters.push_back(Reg);
Dan Gohman8887d1f2015-12-25 00:31:02 +0000360 }
361
Dan Gohmand08cd152016-05-17 21:14:26 +0000362 bool Read = false, Write = false, Effects = false, StackPointer = false;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000363 query(*Def, AA, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000364
365 // If the instruction does not access memory and has no side effects, it has
366 // no additional dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000367 bool HasMutableRegisters = !MutableRegisters.empty();
368 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
Dan Gohman2644d742016-05-17 04:05:31 +0000369 return true;
370
371 // Scan through the intervening instructions between Def and Insert.
372 MachineBasicBlock::const_iterator D(Def), I(Insert);
373 for (--I; I != D; --I) {
374 bool InterveningRead = false;
375 bool InterveningWrite = false;
376 bool InterveningEffects = false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000377 bool InterveningStackPointer = false;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000378 query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
Dan Gohmand08cd152016-05-17 21:14:26 +0000379 InterveningStackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000380 if (Effects && InterveningEffects)
381 return false;
382 if (Read && InterveningWrite)
383 return false;
384 if (Write && (InterveningRead || InterveningWrite))
385 return false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000386 if (StackPointer && InterveningStackPointer)
387 return false;
Derek Schuffe9e68912016-09-30 18:02:54 +0000388
389 for (unsigned Reg : MutableRegisters)
390 for (const MachineOperand &MO : I->operands())
391 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
392 return false;
Dan Gohman2644d742016-05-17 04:05:31 +0000393 }
394
395 return true;
Dan Gohman81719f82015-11-25 16:55:01 +0000396}
397
Dan Gohmanadf28172016-01-28 01:22:44 +0000398/// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000399static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
Dan Gohmanadf28172016-01-28 01:22:44 +0000400 const MachineBasicBlock &MBB,
401 const MachineRegisterInfo &MRI,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000402 const MachineDominatorTree &MDT,
Dan Gohman10545702016-05-17 22:24:18 +0000403 LiveIntervals &LIS,
404 WebAssemblyFunctionInfo &MFI) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000405 const LiveInterval &LI = LIS.getInterval(Reg);
406
407 const MachineInstr *OneUseInst = OneUse.getParent();
408 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
409
Dominic Chena8a63822016-08-17 23:42:27 +0000410 for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000411 if (&Use == &OneUse)
412 continue;
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000413
Dan Gohmanadf28172016-01-28 01:22:44 +0000414 const MachineInstr *UseInst = Use.getParent();
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000415 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
416
417 if (UseVNI != OneUseVNI)
418 continue;
419
Dan Gohman12de0b92016-05-17 20:19:47 +0000420 if (UseInst == OneUseInst) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000421 // Another use in the same instruction. We need to ensure that the one
422 // selected use happens "before" it.
423 if (&OneUse > &Use)
424 return false;
425 } else {
426 // Test that the use is dominated by the one selected use.
Dan Gohman10545702016-05-17 22:24:18 +0000427 while (!MDT.dominates(OneUseInst, UseInst)) {
428 // Actually, dominating is over-conservative. Test that the use would
429 // happen after the one selected use in the stack evaluation order.
430 //
Thomas Lively6a87dda2019-01-08 06:25:55 +0000431 // This is needed as a consequence of using implicit local.gets for
432 // uses and implicit local.sets for defs.
Dominic Chen4173fff2016-08-11 04:10:56 +0000433 if (UseInst->getDesc().getNumDefs() == 0)
Dan Gohman10545702016-05-17 22:24:18 +0000434 return false;
435 const MachineOperand &MO = UseInst->getOperand(0);
436 if (!MO.isReg())
437 return false;
Daniel Sanders05c145d2019-08-12 22:40:45 +0000438 Register DefReg = MO.getReg();
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000439 if (!Register::isVirtualRegister(DefReg) ||
Dan Gohman10545702016-05-17 22:24:18 +0000440 !MFI.isVRegStackified(DefReg))
441 return false;
Yury Delendikb3857e42018-09-26 23:49:21 +0000442 assert(MRI.hasOneNonDBGUse(DefReg));
443 const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
Dan Gohman10545702016-05-17 22:24:18 +0000444 const MachineInstr *NewUseInst = NewUse.getParent();
445 if (NewUseInst == OneUseInst) {
446 if (&OneUse > &NewUse)
447 return false;
448 break;
449 }
450 UseInst = NewUseInst;
451 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000452 }
453 }
454 return true;
455}
456
Dan Gohman4fc4e422016-10-24 19:49:43 +0000457/// Get the appropriate tee opcode for the given register class.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000458static unsigned getTeeOpcode(const TargetRegisterClass *RC) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000459 if (RC == &WebAssembly::I32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000460 return WebAssembly::TEE_I32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000461 if (RC == &WebAssembly::I64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000462 return WebAssembly::TEE_I64;
Dan Gohmanadf28172016-01-28 01:22:44 +0000463 if (RC == &WebAssembly::F32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000464 return WebAssembly::TEE_F32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000465 if (RC == &WebAssembly::F64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000466 return WebAssembly::TEE_F64;
Derek Schuff39bf39f2016-08-02 23:16:09 +0000467 if (RC == &WebAssembly::V128RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000468 return WebAssembly::TEE_V128;
Dan Gohmanadf28172016-01-28 01:22:44 +0000469 llvm_unreachable("Unexpected register class");
470}
471
Dan Gohman2644d742016-05-17 04:05:31 +0000472// Shrink LI to its uses, cleaning up LI.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000473static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
Dan Gohman2644d742016-05-17 04:05:31 +0000474 if (LIS.shrinkToUses(&LI)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000475 SmallVector<LiveInterval *, 4> SplitLIs;
Dan Gohman2644d742016-05-17 04:05:31 +0000476 LIS.splitSeparateComponents(LI, SplitLIs);
477 }
478}
479
Dan Gohmanadf28172016-01-28 01:22:44 +0000480/// A single-use def in the same block with no intervening memory or register
481/// dependencies; move the def down and nest it with the current instruction.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000482static MachineInstr *moveForSingleUse(unsigned Reg, MachineOperand &Op,
Heejin Ahnf208f632018-09-05 01:27:38 +0000483 MachineInstr *Def, MachineBasicBlock &MBB,
Dan Gohmanadf28172016-01-28 01:22:44 +0000484 MachineInstr *Insert, LiveIntervals &LIS,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000485 WebAssemblyFunctionInfo &MFI,
486 MachineRegisterInfo &MRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000487 LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000488
Yury Delendikbe24c022019-01-15 18:14:12 +0000489 WebAssemblyDebugValueManager DefDIs(Def);
Dan Gohmanadf28172016-01-28 01:22:44 +0000490 MBB.splice(Insert, &MBB, Def);
Yury Delendikbe24c022019-01-15 18:14:12 +0000491 DefDIs.move(Insert);
JF Bastien1afd1e22016-02-28 15:33:53 +0000492 LIS.handleMove(*Def);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000493
Dan Gohman12de0b92016-05-17 20:19:47 +0000494 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
495 // No one else is using this register for anything so we can just stackify
496 // it in place.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000497 MFI.stackifyVReg(Reg);
498 } else {
Dan Gohman12de0b92016-05-17 20:19:47 +0000499 // The register may have unrelated uses or defs; create a new register for
500 // just our one def and use so that we can stackify it.
Daniel Sanders05c145d2019-08-12 22:40:45 +0000501 Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000502 Def->getOperand(0).setReg(NewReg);
503 Op.setReg(NewReg);
504
505 // Tell LiveIntervals about the new register.
506 LIS.createAndComputeVirtRegInterval(NewReg);
507
508 // Tell LiveIntervals about the changes to the old register.
509 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000510 LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
511 LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
512 /*RemoveDeadValNo=*/true);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000513
514 MFI.stackifyVReg(NewReg);
Dan Gohman2644d742016-05-17 04:05:31 +0000515
Yury Delendikbe24c022019-01-15 18:14:12 +0000516 DefDIs.updateReg(NewReg);
Yury Delendik7c18d602018-09-25 18:59:34 +0000517
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000518 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000519 }
520
Heejin Ahn18c56a02019-02-04 19:13:39 +0000521 imposeStackOrdering(Def);
Dan Gohmanadf28172016-01-28 01:22:44 +0000522 return Def;
523}
524
525/// A trivially cloneable instruction; clone it and nest the new copy with the
526/// current instruction.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000527static MachineInstr *rematerializeCheapDef(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000528 unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
529 MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
530 WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
531 const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000532 LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
533 LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000534
Yury Delendikbe24c022019-01-15 18:14:12 +0000535 WebAssemblyDebugValueManager DefDIs(&Def);
536
Daniel Sanders05c145d2019-08-12 22:40:45 +0000537 Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
Dan Gohmanadf28172016-01-28 01:22:44 +0000538 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
539 Op.setReg(NewReg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000540 MachineInstr *Clone = &*std::prev(Insert);
JF Bastien13d3b9b2016-02-27 16:38:23 +0000541 LIS.InsertMachineInstrInMaps(*Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000542 LIS.createAndComputeVirtRegInterval(NewReg);
543 MFI.stackifyVReg(NewReg);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000544 imposeStackOrdering(Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000545
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000546 LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000547
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000548 // Shrink the interval.
549 bool IsDead = MRI.use_empty(Reg);
550 if (!IsDead) {
551 LiveInterval &LI = LIS.getInterval(Reg);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000552 shrinkToUses(LI, LIS);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000553 IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000554 }
555
Dan Gohmanadf28172016-01-28 01:22:44 +0000556 // If that was the last use of the original, delete the original.
Yury Delendik7c18d602018-09-25 18:59:34 +0000557 // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000558 if (IsDead) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000559 LLVM_DEBUG(dbgs() << " - Deleting original\n");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000560 SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
Dan Gohmanadf28172016-01-28 01:22:44 +0000561 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
Dan Gohmanadf28172016-01-28 01:22:44 +0000562 LIS.removeInterval(Reg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000563 LIS.RemoveMachineInstrFromMaps(Def);
564 Def.eraseFromParent();
Yury Delendik7c18d602018-09-25 18:59:34 +0000565
Yury Delendikbe24c022019-01-15 18:14:12 +0000566 DefDIs.move(&*Insert);
567 DefDIs.updateReg(NewReg);
Yury Delendik7c18d602018-09-25 18:59:34 +0000568 } else {
Yury Delendikbe24c022019-01-15 18:14:12 +0000569 DefDIs.clone(&*Insert, NewReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000570 }
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000571
Dan Gohmanadf28172016-01-28 01:22:44 +0000572 return Clone;
573}
574
575/// A multiple-use def in the same block with no intervening memory or register
576/// dependencies; move the def down, nest it with the current instruction, and
Dan Gohman4fc4e422016-10-24 19:49:43 +0000577/// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
578/// this:
Dan Gohmanadf28172016-01-28 01:22:44 +0000579///
580/// Reg = INST ... // Def
581/// INST ..., Reg, ... // Insert
582/// INST ..., Reg, ...
583/// INST ..., Reg, ...
584///
585/// to this:
586///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000587/// DefReg = INST ... // Def (to become the new Insert)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000588/// TeeReg, Reg = TEE_... DefReg
Dan Gohmanadf28172016-01-28 01:22:44 +0000589/// INST ..., TeeReg, ... // Insert
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000590/// INST ..., Reg, ...
591/// INST ..., Reg, ...
Dan Gohmanadf28172016-01-28 01:22:44 +0000592///
Thomas Lively6a87dda2019-01-08 06:25:55 +0000593/// with DefReg and TeeReg stackified. This eliminates a local.get from the
Dan Gohmanadf28172016-01-28 01:22:44 +0000594/// resulting code.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000595static MachineInstr *moveAndTeeForMultiUse(
Dan Gohmanadf28172016-01-28 01:22:44 +0000596 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
597 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
598 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000599 LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000600
Yury Delendikbe24c022019-01-15 18:14:12 +0000601 WebAssemblyDebugValueManager DefDIs(Def);
602
Dan Gohman12de0b92016-05-17 20:19:47 +0000603 // Move Def into place.
Dan Gohmanadf28172016-01-28 01:22:44 +0000604 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000605 LIS.handleMove(*Def);
Dan Gohman12de0b92016-05-17 20:19:47 +0000606
607 // Create the Tee and attach the registers.
Dan Gohmanadf28172016-01-28 01:22:44 +0000608 const auto *RegClass = MRI.getRegClass(Reg);
Daniel Sanders05c145d2019-08-12 22:40:45 +0000609 Register TeeReg = MRI.createVirtualRegister(RegClass);
610 Register DefReg = MRI.createVirtualRegister(RegClass);
Dan Gohman33e694a2016-05-12 04:19:09 +0000611 MachineOperand &DefMO = Def->getOperand(0);
Dan Gohmanadf28172016-01-28 01:22:44 +0000612 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
Heejin Ahn18c56a02019-02-04 19:13:39 +0000613 TII->get(getTeeOpcode(RegClass)), TeeReg)
Dan Gohman12de0b92016-05-17 20:19:47 +0000614 .addReg(Reg, RegState::Define)
Dan Gohman33e694a2016-05-12 04:19:09 +0000615 .addReg(DefReg, getUndefRegState(DefMO.isDead()));
Dan Gohmanadf28172016-01-28 01:22:44 +0000616 Op.setReg(TeeReg);
Dan Gohman33e694a2016-05-12 04:19:09 +0000617 DefMO.setReg(DefReg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000618 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
619 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
620
Yury Delendikbe24c022019-01-15 18:14:12 +0000621 DefDIs.move(Insert);
Yury Delendik7c18d602018-09-25 18:59:34 +0000622
Dan Gohman12de0b92016-05-17 20:19:47 +0000623 // Tell LiveIntervals we moved the original vreg def from Def to Tee.
624 LiveInterval &LI = LIS.getInterval(Reg);
625 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
626 VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
627 I->start = TeeIdx;
628 ValNo->def = TeeIdx;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000629 shrinkToUses(LI, LIS);
Dan Gohman12de0b92016-05-17 20:19:47 +0000630
631 // Finish stackifying the new regs.
Dan Gohmanadf28172016-01-28 01:22:44 +0000632 LIS.createAndComputeVirtRegInterval(TeeReg);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000633 LIS.createAndComputeVirtRegInterval(DefReg);
634 MFI.stackifyVReg(DefReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000635 MFI.stackifyVReg(TeeReg);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000636 imposeStackOrdering(Def);
637 imposeStackOrdering(Tee);
Dan Gohman12de0b92016-05-17 20:19:47 +0000638
Yury Delendikbe24c022019-01-15 18:14:12 +0000639 DefDIs.clone(Tee, DefReg);
640 DefDIs.clone(Insert, TeeReg);
Yury Delendik7c18d602018-09-25 18:59:34 +0000641
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000642 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
643 LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
Dan Gohmanadf28172016-01-28 01:22:44 +0000644 return Def;
645}
646
647namespace {
648/// A stack for walking the tree of instructions being built, visiting the
649/// MachineOperands in DFS order.
650class TreeWalkerState {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000651 using mop_iterator = MachineInstr::mop_iterator;
652 using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
653 using RangeTy = iterator_range<mop_reverse_iterator>;
Dan Gohmanadf28172016-01-28 01:22:44 +0000654 SmallVector<RangeTy, 4> Worklist;
655
656public:
657 explicit TreeWalkerState(MachineInstr *Insert) {
658 const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
659 if (Range.begin() != Range.end())
660 Worklist.push_back(reverse(Range));
661 }
662
Heejin Ahn18c56a02019-02-04 19:13:39 +0000663 bool done() const { return Worklist.empty(); }
Dan Gohmanadf28172016-01-28 01:22:44 +0000664
Heejin Ahn18c56a02019-02-04 19:13:39 +0000665 MachineOperand &pop() {
Dan Gohmanadf28172016-01-28 01:22:44 +0000666 RangeTy &Range = Worklist.back();
667 MachineOperand &Op = *Range.begin();
668 Range = drop_begin(Range, 1);
669 if (Range.begin() == Range.end())
670 Worklist.pop_back();
671 assert((Worklist.empty() ||
672 Worklist.back().begin() != Worklist.back().end()) &&
673 "Empty ranges shouldn't remain in the worklist");
674 return Op;
675 }
676
677 /// Push Instr's operands onto the stack to be visited.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000678 void pushOperands(MachineInstr *Instr) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000679 const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
680 if (Range.begin() != Range.end())
681 Worklist.push_back(reverse(Range));
682 }
683
684 /// Some of Instr's operands are on the top of the stack; remove them and
685 /// re-insert them starting from the beginning (because we've commuted them).
Heejin Ahn18c56a02019-02-04 19:13:39 +0000686 void resetTopOperands(MachineInstr *Instr) {
687 assert(hasRemainingOperands(Instr) &&
Dan Gohmanadf28172016-01-28 01:22:44 +0000688 "Reseting operands should only be done when the instruction has "
689 "an operand still on the stack");
690 Worklist.back() = reverse(Instr->explicit_uses());
691 }
692
693 /// Test whether Instr has operands remaining to be visited at the top of
694 /// the stack.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000695 bool hasRemainingOperands(const MachineInstr *Instr) const {
Dan Gohmanadf28172016-01-28 01:22:44 +0000696 if (Worklist.empty())
697 return false;
698 const RangeTy &Range = Worklist.back();
699 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
700 }
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000701
702 /// Test whether the given register is present on the stack, indicating an
703 /// operand in the tree that we haven't visited yet. Moving a definition of
704 /// Reg to a point in the tree after that would change its value.
Dan Gohman10545702016-05-17 22:24:18 +0000705 ///
Thomas Lively6a87dda2019-01-08 06:25:55 +0000706 /// This is needed as a consequence of using implicit local.gets for
707 /// uses and implicit local.sets for defs.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000708 bool isOnStack(unsigned Reg) const {
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000709 for (const RangeTy &Range : Worklist)
710 for (const MachineOperand &MO : Range)
711 if (MO.isReg() && MO.getReg() == Reg)
712 return true;
713 return false;
714 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000715};
716
717/// State to keep track of whether commuting is in flight or whether it's been
718/// tried for the current instruction and didn't work.
719class CommutingState {
720 /// There are effectively three states: the initial state where we haven't
Heejin Ahn99d39462018-12-26 22:27:46 +0000721 /// started commuting anything and we don't know anything yet, the tentative
Dan Gohmanadf28172016-01-28 01:22:44 +0000722 /// state where we've commuted the operands of the current instruction and are
Heejin Ahn99d39462018-12-26 22:27:46 +0000723 /// revisiting it, and the declined state where we've reverted the operands
Dan Gohmanadf28172016-01-28 01:22:44 +0000724 /// back to their original order and will no longer commute it further.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000725 bool TentativelyCommuting = false;
726 bool Declined = false;
Dan Gohmanadf28172016-01-28 01:22:44 +0000727
728 /// During the tentative state, these hold the operand indices of the commuted
729 /// operands.
730 unsigned Operand0, Operand1;
731
732public:
Dan Gohmanadf28172016-01-28 01:22:44 +0000733 /// Stackification for an operand was not successful due to ordering
734 /// constraints. If possible, and if we haven't already tried it and declined
735 /// it, commute Insert's operands and prepare to revisit it.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000736 void maybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
Dan Gohmanadf28172016-01-28 01:22:44 +0000737 const WebAssemblyInstrInfo *TII) {
738 if (TentativelyCommuting) {
739 assert(!Declined &&
740 "Don't decline commuting until you've finished trying it");
741 // Commuting didn't help. Revert it.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000742 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000743 TentativelyCommuting = false;
744 Declined = true;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000745 } else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000746 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
747 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000748 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000749 // Tentatively commute the operands and try again.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000750 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000751 TreeWalker.resetTopOperands(Insert);
Dan Gohmanadf28172016-01-28 01:22:44 +0000752 TentativelyCommuting = true;
753 Declined = false;
754 }
755 }
756 }
757
758 /// Stackification for some operand was successful. Reset to the default
759 /// state.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000760 void reset() {
Dan Gohmanadf28172016-01-28 01:22:44 +0000761 TentativelyCommuting = false;
762 Declined = false;
763 }
764};
765} // end anonymous namespace
766
Dan Gohman1462faa2015-11-16 16:18:28 +0000767bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000768 LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
769 "********** Function: "
770 << MF.getName() << '\n');
Dan Gohman1462faa2015-11-16 16:18:28 +0000771
772 bool Changed = false;
773 MachineRegisterInfo &MRI = MF.getRegInfo();
774 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000775 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
776 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
Dan Gohman81719f82015-11-25 16:55:01 +0000777 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000778 auto &MDT = getAnalysis<MachineDominatorTree>();
779 auto &LIS = getAnalysis<LiveIntervals>();
Dan Gohmand70e5902015-12-08 03:30:42 +0000780
Dan Gohman1462faa2015-11-16 16:18:28 +0000781 // Walk the instructions from the bottom up. Currently we don't look past
782 // block boundaries, and the blocks aren't ordered so the block visitation
783 // order isn't significant, but we may want to change this in the future.
784 for (MachineBasicBlock &MBB : MF) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000785 // Don't use a range-based for loop, because we modify the list as we're
786 // iterating over it and the end iterator may change.
787 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
788 MachineInstr *Insert = &*MII;
Dan Gohman81719f82015-11-25 16:55:01 +0000789 // Don't nest anything inside an inline asm, because we don't have
790 // constraints for $push inputs.
Craig Topperc45e39b2019-02-04 21:24:13 +0000791 if (Insert->isInlineAsm())
Dan Gohman595e8ab2016-02-22 17:45:20 +0000792 continue;
793
794 // Ignore debugging intrinsics.
Craig Topperc45e39b2019-02-04 21:24:13 +0000795 if (Insert->isDebugValue())
Dan Gohman595e8ab2016-02-22 17:45:20 +0000796 continue;
Dan Gohman81719f82015-11-25 16:55:01 +0000797
Dan Gohman1462faa2015-11-16 16:18:28 +0000798 // Iterate through the inputs in reverse order, since we'll be pulling
Dan Gohman53d13992015-12-02 18:08:49 +0000799 // operands off the stack in LIFO order.
Dan Gohmanadf28172016-01-28 01:22:44 +0000800 CommutingState Commuting;
801 TreeWalkerState TreeWalker(Insert);
Heejin Ahn18c56a02019-02-04 19:13:39 +0000802 while (!TreeWalker.done()) {
803 MachineOperand &Op = TreeWalker.pop();
Dan Gohmanadf28172016-01-28 01:22:44 +0000804
Dan Gohman1462faa2015-11-16 16:18:28 +0000805 // We're only interested in explicit virtual register operands.
Dan Gohmanadf28172016-01-28 01:22:44 +0000806 if (!Op.isReg())
Dan Gohman1462faa2015-11-16 16:18:28 +0000807 continue;
808
Daniel Sanders05c145d2019-08-12 22:40:45 +0000809 Register Reg = Op.getReg();
Dan Gohmanadf28172016-01-28 01:22:44 +0000810 assert(Op.isUse() && "explicit_uses() should only iterate over uses");
811 assert(!Op.isImplicit() &&
812 "explicit_uses() should only iterate over explicit operands");
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000813 if (Register::isPhysicalRegister(Reg))
Dan Gohman1462faa2015-11-16 16:18:28 +0000814 continue;
815
Dan Gohmanffc184b2016-10-03 22:32:21 +0000816 // Identify the definition for this register at this point.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000817 MachineInstr *Def = getVRegDef(Reg, Insert, MRI, LIS);
Dan Gohman2644d742016-05-17 04:05:31 +0000818 if (!Def)
819 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000820
Dan Gohman81719f82015-11-25 16:55:01 +0000821 // Don't nest an INLINE_ASM def into anything, because we don't have
822 // constraints for $pop outputs.
Craig Topperc45e39b2019-02-04 21:24:13 +0000823 if (Def->isInlineAsm())
Dan Gohman81719f82015-11-25 16:55:01 +0000824 continue;
825
Dan Gohman4ba48162015-11-18 16:12:01 +0000826 // Argument instructions represent live-in registers and not real
827 // instructions.
Wouter van Oortmerssend8ddf832019-07-12 22:08:25 +0000828 if (WebAssembly::isArgument(Def->getOpcode()))
Dan Gohman4ba48162015-11-18 16:12:01 +0000829 continue;
830
Heejin Ahnd6f48782019-01-30 03:21:57 +0000831 // Currently catch's return value register cannot be stackified, because
832 // the wasm LLVM backend currently does not support live-in values
833 // entering blocks, which is a part of multi-value proposal.
834 //
835 // Once we support live-in values of wasm blocks, this can be:
Heejin Ahn9f96a582019-07-15 22:49:25 +0000836 // catch ; push exnref value onto stack
837 // block exnref -> i32
838 // br_on_exn $__cpp_exception ; pop the exnref value
Heejin Ahnd6f48782019-01-30 03:21:57 +0000839 // end_block
840 //
841 // But because we don't support it yet, the catch instruction's dst
842 // register should be assigned to a local to be propagated across
843 // 'block' boundary now.
844 //
845 // TODO Fix this once we support the multi-value proposal.
846 if (Def->getOpcode() == WebAssembly::CATCH)
847 continue;
848
Dan Gohmanadf28172016-01-28 01:22:44 +0000849 // Decide which strategy to take. Prefer to move a single-use value
Dan Gohman4fc4e422016-10-24 19:49:43 +0000850 // over cloning it, and prefer cloning over introducing a tee.
Dan Gohmanadf28172016-01-28 01:22:44 +0000851 // For moving, we require the def to be in the same block as the use;
852 // this makes things simpler (LiveIntervals' handleMove function only
853 // supports intra-block moves) and it's MachineSink's job to catch all
854 // the sinking opportunities anyway.
855 bool SameBlock = Def->getParent() == &MBB;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000856 bool CanMove = SameBlock && isSafeToMove(Def, Insert, AA, MRI) &&
857 !TreeWalker.isOnStack(Reg);
858 if (CanMove && hasOneUse(Reg, Def, MRI, MDT, LIS)) {
859 Insert = moveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
Derek Schuffd966bf82020-01-28 13:46:03 -0800860
861 // If we are removing the frame base reg completely, remove the debug
862 // info as well.
863 // TODO: Encode this properly as a stackified value.
864 if (MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Reg)
865 MFI.clearFrameBaseVreg();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000866 } else if (shouldRematerialize(*Def, AA, TII)) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000867 Insert =
Heejin Ahn18c56a02019-02-04 19:13:39 +0000868 rematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000869 LIS, MFI, MRI, TII, TRI);
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000870 } else if (CanMove &&
Heejin Ahn18c56a02019-02-04 19:13:39 +0000871 oneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
872 Insert = moveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
Dan Gohmanadf28172016-01-28 01:22:44 +0000873 MRI, TII);
874 } else {
875 // We failed to stackify the operand. If the problem was ordering
876 // constraints, Commuting may be able to help.
877 if (!CanMove && SameBlock)
Heejin Ahn18c56a02019-02-04 19:13:39 +0000878 Commuting.maybeCommute(Insert, TreeWalker, TII);
Dan Gohmanadf28172016-01-28 01:22:44 +0000879 // Proceed to the next operand.
880 continue;
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000881 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000882
Dan Gohmane81021a2016-11-08 19:40:38 +0000883 // If the instruction we just stackified is an IMPLICIT_DEF, convert it
884 // to a constant 0 so that the def is explicit, and the push/pop
885 // correspondence is maintained.
886 if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
Heejin Ahn18c56a02019-02-04 19:13:39 +0000887 convertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
Dan Gohmane81021a2016-11-08 19:40:38 +0000888
Dan Gohmanadf28172016-01-28 01:22:44 +0000889 // We stackified an operand. Add the defining instruction's operands to
890 // the worklist stack now to continue to build an ever deeper tree.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000891 Commuting.reset();
892 TreeWalker.pushOperands(Insert);
Dan Gohman1462faa2015-11-16 16:18:28 +0000893 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000894
895 // If we stackified any operands, skip over the tree to start looking for
896 // the next instruction we can build a tree on.
897 if (Insert != &*MII) {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000898 imposeStackOrdering(&*MII);
Eric Liuc7e5a9c2016-09-12 09:35:59 +0000899 MII = MachineBasicBlock::iterator(Insert).getReverse();
Dan Gohmanadf28172016-01-28 01:22:44 +0000900 Changed = true;
901 }
Dan Gohman1462faa2015-11-16 16:18:28 +0000902 }
903 }
904
Dan Gohmane0405332016-10-03 22:43:53 +0000905 // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
Dan Gohmanadf28172016-01-28 01:22:44 +0000906 // that it never looks like a use-before-def.
Dan Gohmanb0992da2015-11-20 02:19:12 +0000907 if (Changed) {
Dan Gohmane0405332016-10-03 22:43:53 +0000908 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000909 for (MachineBasicBlock &MBB : MF)
Dan Gohmane0405332016-10-03 22:43:53 +0000910 MBB.addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000911 }
912
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000913#ifndef NDEBUG
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000914 // Verify that pushes and pops are performed in LIFO order.
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000915 SmallVector<unsigned, 0> Stack;
916 for (MachineBasicBlock &MBB : MF) {
917 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000918 if (MI.isDebugInstr())
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000919 continue;
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000920 for (MachineOperand &MO : reverse(MI.explicit_operands())) {
Dan Gohman7a6b9822015-11-29 22:32:02 +0000921 if (!MO.isReg())
922 continue;
Daniel Sanders05c145d2019-08-12 22:40:45 +0000923 Register Reg = MO.getReg();
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000924
Dan Gohmanadf28172016-01-28 01:22:44 +0000925 if (MFI.isVRegStackified(Reg)) {
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000926 if (MO.isDef())
Dan Gohmanadf28172016-01-28 01:22:44 +0000927 Stack.push_back(Reg);
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000928 else
Dan Gohmanadf28172016-01-28 01:22:44 +0000929 assert(Stack.pop_back_val() == Reg &&
930 "Register stack pop should be paired with a push");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000931 }
932 }
933 }
934 // TODO: Generalize this code to support keeping values on the stack across
935 // basic block boundaries.
Dan Gohmanadf28172016-01-28 01:22:44 +0000936 assert(Stack.empty() &&
937 "Register stack pushes and pops should be balanced");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000938 }
939#endif
940
Dan Gohman1462faa2015-11-16 16:18:28 +0000941 return Changed;
942}