blob: e6d02a5a0e8c0fe0fe0304ca785db7e444c2961d [file] [log] [blame]
Dan Gohman1462faa2015-11-16 16:18:28 +00001//===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// This file implements a register stacking pass.
Dan Gohman1462faa2015-11-16 16:18:28 +000012///
13/// This pass reorders instructions to put register uses and defs in an order
14/// such that they form single-use expression trees. Registers fitting this form
15/// are then marked as "stackified", meaning references to them are replaced by
Dan Gohmane0405332016-10-03 22:43:53 +000016/// "push" and "pop" from the value stack.
Dan Gohman1462faa2015-11-16 16:18:28 +000017///
Dan Gohman31448f12015-12-08 03:43:03 +000018/// This is primarily a code size optimization, since temporary values on the
Dan Gohmane0405332016-10-03 22:43:53 +000019/// value stack don't need to be named.
Dan Gohman1462faa2015-11-16 16:18:28 +000020///
21//===----------------------------------------------------------------------===//
22
Dan Gohman4ba48162015-11-18 16:12:01 +000023#include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "WebAssembly.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"
Dan Gohman81719f82015-11-25 16:55:01 +000028#include "llvm/Analysis/AliasAnalysis.h"
Matthias Braunf8422972017-12-13 02:51:04 +000029#include "llvm/CodeGen/LiveIntervals.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000030#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Dan Gohmanadf28172016-01-28 01:22:44 +000031#include "llvm/CodeGen/MachineDominators.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman82607f52017-02-24 23:46:05 +000033#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/Passes.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
38using namespace llvm;
39
40#define DEBUG_TYPE "wasm-reg-stackify"
41
42namespace {
43class WebAssemblyRegStackify final : public MachineFunctionPass {
Mehdi Amini117296c2016-10-01 02:56:57 +000044 StringRef getPassName() const override {
Dan Gohman1462faa2015-11-16 16:18:28 +000045 return "WebAssembly Register Stackify";
46 }
47
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.setPreservesCFG();
Dan Gohman81719f82015-11-25 16:55:01 +000050 AU.addRequired<AAResultsWrapperPass>();
Dan Gohmanadf28172016-01-28 01:22:44 +000051 AU.addRequired<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000052 AU.addRequired<LiveIntervals>();
Dan Gohman1462faa2015-11-16 16:18:28 +000053 AU.addPreserved<MachineBlockFrequencyInfo>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000054 AU.addPreserved<SlotIndexes>();
55 AU.addPreserved<LiveIntervals>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000056 AU.addPreservedID(LiveVariablesID);
Dan Gohmanadf28172016-01-28 01:22:44 +000057 AU.addPreserved<MachineDominatorTree>();
Dan Gohman1462faa2015-11-16 16:18:28 +000058 MachineFunctionPass::getAnalysisUsage(AU);
59 }
60
61 bool runOnMachineFunction(MachineFunction &MF) override;
62
63public:
64 static char ID; // Pass identification, replacement for typeid
65 WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
66};
67} // end anonymous namespace
68
69char WebAssemblyRegStackify::ID = 0;
Jacob Gravelle40926452018-03-30 20:36:58 +000070INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
71 "Reorder instructions to use the WebAssembly value stack",
72 false, false)
73
Dan Gohman1462faa2015-11-16 16:18:28 +000074FunctionPass *llvm::createWebAssemblyRegStackify() {
75 return new WebAssemblyRegStackify();
76}
77
Dan Gohmanb0992da2015-11-20 02:19:12 +000078// Decorate the given instruction with implicit operands that enforce the
Dan Gohman8887d1f2015-12-25 00:31:02 +000079// expression stack ordering constraints for an instruction which is on
80// the expression stack.
81static void ImposeStackOrdering(MachineInstr *MI) {
Dan Gohmane0405332016-10-03 22:43:53 +000082 // Write the opaque VALUE_STACK register.
83 if (!MI->definesRegister(WebAssembly::VALUE_STACK))
84 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohman4da4abd2015-12-05 00:51:40 +000085 /*isDef=*/true,
86 /*isImp=*/true));
Dan Gohman4da4abd2015-12-05 00:51:40 +000087
Dan Gohmane0405332016-10-03 22:43:53 +000088 // Also read the opaque VALUE_STACK register.
89 if (!MI->readsRegister(WebAssembly::VALUE_STACK))
90 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohmana712a6c2015-12-14 22:37:23 +000091 /*isDef=*/false,
92 /*isImp=*/true));
Dan Gohmanb0992da2015-11-20 02:19:12 +000093}
94
Dan Gohmane81021a2016-11-08 19:40:38 +000095// Convert an IMPLICIT_DEF instruction into an instruction which defines
96// a constant zero value.
97static void ConvertImplicitDefToConstZero(MachineInstr *MI,
98 MachineRegisterInfo &MRI,
99 const TargetInstrInfo *TII,
100 MachineFunction &MF) {
101 assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
102
Heejin Ahnf208f632018-09-05 01:27:38 +0000103 const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
Dan Gohmane81021a2016-11-08 19:40:38 +0000104 if (RegClass == &WebAssembly::I32RegClass) {
105 MI->setDesc(TII->get(WebAssembly::CONST_I32));
106 MI->addOperand(MachineOperand::CreateImm(0));
107 } else if (RegClass == &WebAssembly::I64RegClass) {
108 MI->setDesc(TII->get(WebAssembly::CONST_I64));
109 MI->addOperand(MachineOperand::CreateImm(0));
110 } else if (RegClass == &WebAssembly::F32RegClass) {
111 MI->setDesc(TII->get(WebAssembly::CONST_F32));
112 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000113 Type::getFloatTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000114 MI->addOperand(MachineOperand::CreateFPImm(Val));
115 } else if (RegClass == &WebAssembly::F64RegClass) {
116 MI->setDesc(TII->get(WebAssembly::CONST_F64));
117 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000118 Type::getDoubleTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000119 MI->addOperand(MachineOperand::CreateFPImm(Val));
120 } else {
121 llvm_unreachable("Unexpected reg class");
122 }
123}
124
Dan Gohman2644d742016-05-17 04:05:31 +0000125// Determine whether a call to the callee referenced by
126// MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
127// effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000128static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
129 bool &Write, bool &Effects, bool &StackPointer) {
Dan Gohmand08cd152016-05-17 21:14:26 +0000130 // All calls can use the stack pointer.
131 StackPointer = true;
132
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000133 const MachineOperand &MO = MI.getOperand(CalleeOpNo);
Dan Gohman2644d742016-05-17 04:05:31 +0000134 if (MO.isGlobal()) {
135 const Constant *GV = MO.getGlobal();
136 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
137 if (!GA->isInterposable())
138 GV = GA->getAliasee();
139
140 if (const Function *F = dyn_cast<Function>(GV)) {
141 if (!F->doesNotThrow())
142 Effects = true;
143 if (F->doesNotAccessMemory())
144 return;
145 if (F->onlyReadsMemory()) {
146 Read = true;
147 return;
148 }
149 }
150 }
151
152 // Assume the worst.
153 Write = true;
154 Read = true;
155 Effects = true;
156}
157
Dan Gohmand08cd152016-05-17 21:14:26 +0000158// Determine whether MI reads memory, writes memory, has side effects,
Dan Gohman82607f52017-02-24 23:46:05 +0000159// and/or uses the stack pointer value.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000160static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
161 bool &Write, bool &Effects, bool &StackPointer) {
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000162 assert(!MI.isTerminator());
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000163
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000164 if (MI.isDebugInstr() || MI.isPosition())
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000165 return;
Dan Gohman2644d742016-05-17 04:05:31 +0000166
167 // Check for loads.
Justin Lebard98cf002016-09-10 01:03:20 +0000168 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
Dan Gohman2644d742016-05-17 04:05:31 +0000169 Read = true;
170
171 // Check for stores.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000172 if (MI.mayStore()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000173 Write = true;
Dan Gohmand08cd152016-05-17 21:14:26 +0000174
Sam Clegg9d24fb72017-06-16 23:59:10 +0000175 // Check for stores to __stack_pointer.
176 for (auto MMO : MI.memoperands()) {
177 const MachinePointerInfo &MPI = MMO->getPointerInfo();
178 if (MPI.V.is<const PseudoSourceValue *>()) {
179 auto PSV = MPI.V.get<const PseudoSourceValue *>();
180 if (const ExternalSymbolPseudoSourceValue *EPSV =
181 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
182 if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
183 StackPointer = true;
184 }
Dan Gohmand08cd152016-05-17 21:14:26 +0000185 }
186 }
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000187 } else if (MI.hasOrderedMemoryRef()) {
188 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000189 case WebAssembly::DIV_S_I32:
190 case WebAssembly::DIV_S_I64:
191 case WebAssembly::REM_S_I32:
192 case WebAssembly::REM_S_I64:
193 case WebAssembly::DIV_U_I32:
194 case WebAssembly::DIV_U_I64:
195 case WebAssembly::REM_U_I32:
196 case WebAssembly::REM_U_I64:
197 case WebAssembly::I32_TRUNC_S_F32:
198 case WebAssembly::I64_TRUNC_S_F32:
199 case WebAssembly::I32_TRUNC_S_F64:
200 case WebAssembly::I64_TRUNC_S_F64:
201 case WebAssembly::I32_TRUNC_U_F32:
202 case WebAssembly::I64_TRUNC_U_F32:
203 case WebAssembly::I32_TRUNC_U_F64:
204 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000205 // These instruction have hasUnmodeledSideEffects() returning true
206 // because they trap on overflow and invalid so they can't be arbitrarily
207 // moved, however hasOrderedMemoryRef() interprets this plus their lack
208 // of memoperands as having a potential unknown memory reference.
209 break;
210 default:
Dan Gohman10545702016-05-17 22:24:18 +0000211 // Record volatile accesses, unless it's a call, as calls are handled
Dan Gohman2644d742016-05-17 04:05:31 +0000212 // specially below.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000213 if (!MI.isCall()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000214 Write = true;
Dan Gohman10545702016-05-17 22:24:18 +0000215 Effects = true;
216 }
Dan Gohman2644d742016-05-17 04:05:31 +0000217 break;
218 }
219 }
220
221 // Check for side effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000222 if (MI.hasUnmodeledSideEffects()) {
223 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000224 case WebAssembly::DIV_S_I32:
225 case WebAssembly::DIV_S_I64:
226 case WebAssembly::REM_S_I32:
227 case WebAssembly::REM_S_I64:
228 case WebAssembly::DIV_U_I32:
229 case WebAssembly::DIV_U_I64:
230 case WebAssembly::REM_U_I32:
231 case WebAssembly::REM_U_I64:
232 case WebAssembly::I32_TRUNC_S_F32:
233 case WebAssembly::I64_TRUNC_S_F32:
234 case WebAssembly::I32_TRUNC_S_F64:
235 case WebAssembly::I64_TRUNC_S_F64:
236 case WebAssembly::I32_TRUNC_U_F32:
237 case WebAssembly::I64_TRUNC_U_F32:
238 case WebAssembly::I32_TRUNC_U_F64:
239 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000240 // These instructions have hasUnmodeledSideEffects() returning true
241 // because they trap on overflow and invalid so they can't be arbitrarily
242 // moved, however in the specific case of register stackifying, it is safe
243 // to move them because overflow and invalid are Undefined Behavior.
244 break;
245 default:
246 Effects = true;
247 break;
248 }
249 }
250
251 // Analyze calls.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000252 if (MI.isCall()) {
Heejin Ahn56e79dd2018-08-28 17:49:39 +0000253 unsigned CalleeOpNo = WebAssembly::getCalleeOpNo(MI);
254 QueryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000255 }
256}
257
258// Test whether Def is safe and profitable to rematerialize.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000259static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
Dan Gohman2644d742016-05-17 04:05:31 +0000260 const WebAssemblyInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000261 return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
Dan Gohman2644d742016-05-17 04:05:31 +0000262}
263
Dan Gohman12de0b92016-05-17 20:19:47 +0000264// Identify the definition for this register at this point. This is a
265// generalization of MachineRegisterInfo::getUniqueVRegDef that uses
266// LiveIntervals to handle complex cases.
Dan Gohman2644d742016-05-17 04:05:31 +0000267static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
268 const MachineRegisterInfo &MRI,
Heejin Ahnf208f632018-09-05 01:27:38 +0000269 const LiveIntervals &LIS) {
Dan Gohman2644d742016-05-17 04:05:31 +0000270 // Most registers are in SSA form here so we try a quick MRI query first.
271 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
272 return Def;
273
274 // MRI doesn't know what the Def is. Try asking LIS.
275 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
276 LIS.getInstructionIndex(*Insert)))
277 return LIS.getInstructionFromIndex(ValNo->def);
278
279 return nullptr;
280}
281
Dan Gohman12de0b92016-05-17 20:19:47 +0000282// Test whether Reg, as defined at Def, has exactly one use. This is a
283// generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
284// to handle complex cases.
Heejin Ahnf208f632018-09-05 01:27:38 +0000285static bool HasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
286 MachineDominatorTree &MDT, LiveIntervals &LIS) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000287 // Most registers are in SSA form here so we try a quick MRI query first.
288 if (MRI.hasOneUse(Reg))
289 return true;
290
291 bool HasOne = false;
292 const LiveInterval &LI = LIS.getInterval(Reg);
Heejin Ahnf208f632018-09-05 01:27:38 +0000293 const VNInfo *DefVNI =
294 LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
Dan Gohman12de0b92016-05-17 20:19:47 +0000295 assert(DefVNI);
Dominic Chena8a63822016-08-17 23:42:27 +0000296 for (auto &I : MRI.use_nodbg_operands(Reg)) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000297 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
298 if (Result.valueIn() == DefVNI) {
299 if (!Result.isKill())
300 return false;
301 if (HasOne)
302 return false;
303 HasOne = true;
304 }
305 }
306 return HasOne;
307}
308
Dan Gohman8887d1f2015-12-25 00:31:02 +0000309// Test whether it's safe to move Def to just before Insert.
Dan Gohman81719f82015-11-25 16:55:01 +0000310// TODO: Compute memory dependencies in a way that doesn't require always
311// walking the block.
312// TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
313// more precise.
314static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
Derek Schuffe9e68912016-09-30 18:02:54 +0000315 AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
Dan Gohman391a98a2015-12-03 23:07:03 +0000316 assert(Def->getParent() == Insert->getParent());
Dan Gohman8887d1f2015-12-25 00:31:02 +0000317
318 // Check for register dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000319 SmallVector<unsigned, 4> MutableRegisters;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000320 for (const MachineOperand &MO : Def->operands()) {
321 if (!MO.isReg() || MO.isUndef())
322 continue;
323 unsigned Reg = MO.getReg();
324
325 // If the register is dead here and at Insert, ignore it.
326 if (MO.isDead() && Insert->definesRegister(Reg) &&
327 !Insert->readsRegister(Reg))
328 continue;
329
330 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000331 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
332 // from moving down, and we've already checked for that.
333 if (Reg == WebAssembly::ARGUMENTS)
334 continue;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000335 // If the physical register is never modified, ignore it.
336 if (!MRI.isPhysRegModified(Reg))
337 continue;
338 // Otherwise, it's a physical register with unknown liveness.
339 return false;
340 }
341
Derek Schuffe9e68912016-09-30 18:02:54 +0000342 // If one of the operands isn't in SSA form, it has different values at
343 // different times, and we need to make sure we don't move our use across
344 // a different def.
345 if (!MO.isDef() && !MRI.hasOneDef(Reg))
346 MutableRegisters.push_back(Reg);
Dan Gohman8887d1f2015-12-25 00:31:02 +0000347 }
348
Dan Gohmand08cd152016-05-17 21:14:26 +0000349 bool Read = false, Write = false, Effects = false, StackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000350 Query(*Def, AA, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000351
352 // If the instruction does not access memory and has no side effects, it has
353 // no additional dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000354 bool HasMutableRegisters = !MutableRegisters.empty();
355 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
Dan Gohman2644d742016-05-17 04:05:31 +0000356 return true;
357
358 // Scan through the intervening instructions between Def and Insert.
359 MachineBasicBlock::const_iterator D(Def), I(Insert);
360 for (--I; I != D; --I) {
361 bool InterveningRead = false;
362 bool InterveningWrite = false;
363 bool InterveningEffects = false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000364 bool InterveningStackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000365 Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
Dan Gohmand08cd152016-05-17 21:14:26 +0000366 InterveningStackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000367 if (Effects && InterveningEffects)
368 return false;
369 if (Read && InterveningWrite)
370 return false;
371 if (Write && (InterveningRead || InterveningWrite))
372 return false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000373 if (StackPointer && InterveningStackPointer)
374 return false;
Derek Schuffe9e68912016-09-30 18:02:54 +0000375
376 for (unsigned Reg : MutableRegisters)
377 for (const MachineOperand &MO : I->operands())
378 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
379 return false;
Dan Gohman2644d742016-05-17 04:05:31 +0000380 }
381
382 return true;
Dan Gohman81719f82015-11-25 16:55:01 +0000383}
384
Dan Gohmanadf28172016-01-28 01:22:44 +0000385/// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
386static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
387 const MachineBasicBlock &MBB,
388 const MachineRegisterInfo &MRI,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000389 const MachineDominatorTree &MDT,
Dan Gohman10545702016-05-17 22:24:18 +0000390 LiveIntervals &LIS,
391 WebAssemblyFunctionInfo &MFI) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000392 const LiveInterval &LI = LIS.getInterval(Reg);
393
394 const MachineInstr *OneUseInst = OneUse.getParent();
395 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
396
Dominic Chena8a63822016-08-17 23:42:27 +0000397 for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000398 if (&Use == &OneUse)
399 continue;
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000400
Dan Gohmanadf28172016-01-28 01:22:44 +0000401 const MachineInstr *UseInst = Use.getParent();
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000402 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
403
404 if (UseVNI != OneUseVNI)
405 continue;
406
Dan Gohmanadf28172016-01-28 01:22:44 +0000407 const MachineInstr *OneUseInst = OneUse.getParent();
Dan Gohman12de0b92016-05-17 20:19:47 +0000408 if (UseInst == OneUseInst) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000409 // Another use in the same instruction. We need to ensure that the one
410 // selected use happens "before" it.
411 if (&OneUse > &Use)
412 return false;
413 } else {
414 // Test that the use is dominated by the one selected use.
Dan Gohman10545702016-05-17 22:24:18 +0000415 while (!MDT.dominates(OneUseInst, UseInst)) {
416 // Actually, dominating is over-conservative. Test that the use would
417 // happen after the one selected use in the stack evaluation order.
418 //
419 // This is needed as a consequence of using implicit get_locals for
420 // uses and implicit set_locals for defs.
Dominic Chen4173fff2016-08-11 04:10:56 +0000421 if (UseInst->getDesc().getNumDefs() == 0)
Dan Gohman10545702016-05-17 22:24:18 +0000422 return false;
423 const MachineOperand &MO = UseInst->getOperand(0);
424 if (!MO.isReg())
425 return false;
426 unsigned DefReg = MO.getReg();
427 if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
428 !MFI.isVRegStackified(DefReg))
429 return false;
430 assert(MRI.hasOneUse(DefReg));
431 const MachineOperand &NewUse = *MRI.use_begin(DefReg);
432 const MachineInstr *NewUseInst = NewUse.getParent();
433 if (NewUseInst == OneUseInst) {
434 if (&OneUse > &NewUse)
435 return false;
436 break;
437 }
438 UseInst = NewUseInst;
439 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000440 }
441 }
442 return true;
443}
444
Dan Gohman4fc4e422016-10-24 19:49:43 +0000445/// Get the appropriate tee opcode for the given register class.
446static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000447 if (RC == &WebAssembly::I32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000448 return WebAssembly::TEE_I32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000449 if (RC == &WebAssembly::I64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000450 return WebAssembly::TEE_I64;
Dan Gohmanadf28172016-01-28 01:22:44 +0000451 if (RC == &WebAssembly::F32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000452 return WebAssembly::TEE_F32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000453 if (RC == &WebAssembly::F64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000454 return WebAssembly::TEE_F64;
Derek Schuff39bf39f2016-08-02 23:16:09 +0000455 if (RC == &WebAssembly::V128RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000456 return WebAssembly::TEE_V128;
Dan Gohmanadf28172016-01-28 01:22:44 +0000457 llvm_unreachable("Unexpected register class");
458}
459
Dan Gohman2644d742016-05-17 04:05:31 +0000460// Shrink LI to its uses, cleaning up LI.
461static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
462 if (LIS.shrinkToUses(&LI)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000463 SmallVector<LiveInterval *, 4> SplitLIs;
Dan Gohman2644d742016-05-17 04:05:31 +0000464 LIS.splitSeparateComponents(LI, SplitLIs);
465 }
466}
467
Dan Gohmanadf28172016-01-28 01:22:44 +0000468/// A single-use def in the same block with no intervening memory or register
469/// dependencies; move the def down and nest it with the current instruction.
Heejin Ahnf208f632018-09-05 01:27:38 +0000470static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand &Op,
471 MachineInstr *Def, MachineBasicBlock &MBB,
Dan Gohmanadf28172016-01-28 01:22:44 +0000472 MachineInstr *Insert, LiveIntervals &LIS,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000473 WebAssemblyFunctionInfo &MFI,
474 MachineRegisterInfo &MRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000475 LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000476
Dan Gohmanadf28172016-01-28 01:22:44 +0000477 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000478 LIS.handleMove(*Def);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000479
Dan Gohman12de0b92016-05-17 20:19:47 +0000480 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
481 // No one else is using this register for anything so we can just stackify
482 // it in place.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000483 MFI.stackifyVReg(Reg);
484 } else {
Dan Gohman12de0b92016-05-17 20:19:47 +0000485 // The register may have unrelated uses or defs; create a new register for
486 // just our one def and use so that we can stackify it.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000487 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
488 Def->getOperand(0).setReg(NewReg);
489 Op.setReg(NewReg);
490
491 // Tell LiveIntervals about the new register.
492 LIS.createAndComputeVirtRegInterval(NewReg);
493
494 // Tell LiveIntervals about the changes to the old register.
495 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000496 LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
497 LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
498 /*RemoveDeadValNo=*/true);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000499
500 MFI.stackifyVReg(NewReg);
Dan Gohman2644d742016-05-17 04:05:31 +0000501
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000502 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000503 }
504
Dan Gohmanadf28172016-01-28 01:22:44 +0000505 ImposeStackOrdering(Def);
506 return Def;
507}
508
509/// A trivially cloneable instruction; clone it and nest the new copy with the
510/// current instruction.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000511static MachineInstr *RematerializeCheapDef(
512 unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
513 MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
514 WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
515 const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000516 LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
517 LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000518
Dan Gohmanadf28172016-01-28 01:22:44 +0000519 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
520 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
521 Op.setReg(NewReg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000522 MachineInstr *Clone = &*std::prev(Insert);
JF Bastien13d3b9b2016-02-27 16:38:23 +0000523 LIS.InsertMachineInstrInMaps(*Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000524 LIS.createAndComputeVirtRegInterval(NewReg);
525 MFI.stackifyVReg(NewReg);
526 ImposeStackOrdering(Clone);
527
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000528 LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000529
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000530 // Shrink the interval.
531 bool IsDead = MRI.use_empty(Reg);
532 if (!IsDead) {
533 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman2644d742016-05-17 04:05:31 +0000534 ShrinkToUses(LI, LIS);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000535 IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000536 }
537
Dan Gohmanadf28172016-01-28 01:22:44 +0000538 // If that was the last use of the original, delete the original.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000539 if (IsDead) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000540 LLVM_DEBUG(dbgs() << " - Deleting original\n");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000541 SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
Dan Gohmanadf28172016-01-28 01:22:44 +0000542 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
Dan Gohmanadf28172016-01-28 01:22:44 +0000543 LIS.removeInterval(Reg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000544 LIS.RemoveMachineInstrFromMaps(Def);
545 Def.eraseFromParent();
Dan Gohmanadf28172016-01-28 01:22:44 +0000546 }
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000547
Dan Gohmanadf28172016-01-28 01:22:44 +0000548 return Clone;
549}
550
551/// A multiple-use def in the same block with no intervening memory or register
552/// dependencies; move the def down, nest it with the current instruction, and
Dan Gohman4fc4e422016-10-24 19:49:43 +0000553/// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
554/// this:
Dan Gohmanadf28172016-01-28 01:22:44 +0000555///
556/// Reg = INST ... // Def
557/// INST ..., Reg, ... // Insert
558/// INST ..., Reg, ...
559/// INST ..., Reg, ...
560///
561/// to this:
562///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000563/// DefReg = INST ... // Def (to become the new Insert)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000564/// TeeReg, Reg = TEE_... DefReg
Dan Gohmanadf28172016-01-28 01:22:44 +0000565/// INST ..., TeeReg, ... // Insert
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000566/// INST ..., Reg, ...
567/// INST ..., Reg, ...
Dan Gohmanadf28172016-01-28 01:22:44 +0000568///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000569/// with DefReg and TeeReg stackified. This eliminates a get_local from the
Dan Gohmanadf28172016-01-28 01:22:44 +0000570/// resulting code.
571static MachineInstr *MoveAndTeeForMultiUse(
572 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
573 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
574 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000575 LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000576
Dan Gohman12de0b92016-05-17 20:19:47 +0000577 // Move Def into place.
Dan Gohmanadf28172016-01-28 01:22:44 +0000578 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000579 LIS.handleMove(*Def);
Dan Gohman12de0b92016-05-17 20:19:47 +0000580
581 // Create the Tee and attach the registers.
Dan Gohmanadf28172016-01-28 01:22:44 +0000582 const auto *RegClass = MRI.getRegClass(Reg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000583 unsigned TeeReg = MRI.createVirtualRegister(RegClass);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000584 unsigned DefReg = MRI.createVirtualRegister(RegClass);
Dan Gohman33e694a2016-05-12 04:19:09 +0000585 MachineOperand &DefMO = Def->getOperand(0);
Dan Gohmanadf28172016-01-28 01:22:44 +0000586 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
Dan Gohman4fc4e422016-10-24 19:49:43 +0000587 TII->get(GetTeeOpcode(RegClass)), TeeReg)
Dan Gohman12de0b92016-05-17 20:19:47 +0000588 .addReg(Reg, RegState::Define)
Dan Gohman33e694a2016-05-12 04:19:09 +0000589 .addReg(DefReg, getUndefRegState(DefMO.isDead()));
Dan Gohmanadf28172016-01-28 01:22:44 +0000590 Op.setReg(TeeReg);
Dan Gohman33e694a2016-05-12 04:19:09 +0000591 DefMO.setReg(DefReg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000592 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
593 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
594
595 // Tell LiveIntervals we moved the original vreg def from Def to Tee.
596 LiveInterval &LI = LIS.getInterval(Reg);
597 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
598 VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
599 I->start = TeeIdx;
600 ValNo->def = TeeIdx;
601 ShrinkToUses(LI, LIS);
602
603 // Finish stackifying the new regs.
Dan Gohmanadf28172016-01-28 01:22:44 +0000604 LIS.createAndComputeVirtRegInterval(TeeReg);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000605 LIS.createAndComputeVirtRegInterval(DefReg);
606 MFI.stackifyVReg(DefReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000607 MFI.stackifyVReg(TeeReg);
608 ImposeStackOrdering(Def);
609 ImposeStackOrdering(Tee);
Dan Gohman12de0b92016-05-17 20:19:47 +0000610
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000611 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
612 LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
Dan Gohmanadf28172016-01-28 01:22:44 +0000613 return Def;
614}
615
616namespace {
617/// A stack for walking the tree of instructions being built, visiting the
618/// MachineOperands in DFS order.
619class TreeWalkerState {
620 typedef MachineInstr::mop_iterator mop_iterator;
621 typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
622 typedef iterator_range<mop_reverse_iterator> RangeTy;
623 SmallVector<RangeTy, 4> Worklist;
624
625public:
626 explicit TreeWalkerState(MachineInstr *Insert) {
627 const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
628 if (Range.begin() != Range.end())
629 Worklist.push_back(reverse(Range));
630 }
631
632 bool Done() const { return Worklist.empty(); }
633
634 MachineOperand &Pop() {
635 RangeTy &Range = Worklist.back();
636 MachineOperand &Op = *Range.begin();
637 Range = drop_begin(Range, 1);
638 if (Range.begin() == Range.end())
639 Worklist.pop_back();
640 assert((Worklist.empty() ||
641 Worklist.back().begin() != Worklist.back().end()) &&
642 "Empty ranges shouldn't remain in the worklist");
643 return Op;
644 }
645
646 /// Push Instr's operands onto the stack to be visited.
647 void PushOperands(MachineInstr *Instr) {
648 const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
649 if (Range.begin() != Range.end())
650 Worklist.push_back(reverse(Range));
651 }
652
653 /// Some of Instr's operands are on the top of the stack; remove them and
654 /// re-insert them starting from the beginning (because we've commuted them).
655 void ResetTopOperands(MachineInstr *Instr) {
656 assert(HasRemainingOperands(Instr) &&
657 "Reseting operands should only be done when the instruction has "
658 "an operand still on the stack");
659 Worklist.back() = reverse(Instr->explicit_uses());
660 }
661
662 /// Test whether Instr has operands remaining to be visited at the top of
663 /// the stack.
664 bool HasRemainingOperands(const MachineInstr *Instr) const {
665 if (Worklist.empty())
666 return false;
667 const RangeTy &Range = Worklist.back();
668 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
669 }
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000670
671 /// Test whether the given register is present on the stack, indicating an
672 /// operand in the tree that we haven't visited yet. Moving a definition of
673 /// Reg to a point in the tree after that would change its value.
Dan Gohman10545702016-05-17 22:24:18 +0000674 ///
675 /// This is needed as a consequence of using implicit get_locals for
676 /// uses and implicit set_locals for defs.
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000677 bool IsOnStack(unsigned Reg) const {
678 for (const RangeTy &Range : Worklist)
679 for (const MachineOperand &MO : Range)
680 if (MO.isReg() && MO.getReg() == Reg)
681 return true;
682 return false;
683 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000684};
685
686/// State to keep track of whether commuting is in flight or whether it's been
687/// tried for the current instruction and didn't work.
688class CommutingState {
689 /// There are effectively three states: the initial state where we haven't
690 /// started commuting anything and we don't know anything yet, the tenative
691 /// state where we've commuted the operands of the current instruction and are
692 /// revisting it, and the declined state where we've reverted the operands
693 /// back to their original order and will no longer commute it further.
694 bool TentativelyCommuting;
695 bool Declined;
696
697 /// During the tentative state, these hold the operand indices of the commuted
698 /// operands.
699 unsigned Operand0, Operand1;
700
701public:
702 CommutingState() : TentativelyCommuting(false), Declined(false) {}
703
704 /// Stackification for an operand was not successful due to ordering
705 /// constraints. If possible, and if we haven't already tried it and declined
706 /// it, commute Insert's operands and prepare to revisit it.
707 void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
708 const WebAssemblyInstrInfo *TII) {
709 if (TentativelyCommuting) {
710 assert(!Declined &&
711 "Don't decline commuting until you've finished trying it");
712 // Commuting didn't help. Revert it.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000713 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000714 TentativelyCommuting = false;
715 Declined = true;
716 } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
717 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
718 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000719 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000720 // Tentatively commute the operands and try again.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000721 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000722 TreeWalker.ResetTopOperands(Insert);
723 TentativelyCommuting = true;
724 Declined = false;
725 }
726 }
727 }
728
729 /// Stackification for some operand was successful. Reset to the default
730 /// state.
731 void Reset() {
732 TentativelyCommuting = false;
733 Declined = false;
734 }
735};
736} // end anonymous namespace
737
Dan Gohman1462faa2015-11-16 16:18:28 +0000738bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000739 LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
740 "********** Function: "
741 << MF.getName() << '\n');
Dan Gohman1462faa2015-11-16 16:18:28 +0000742
743 bool Changed = false;
744 MachineRegisterInfo &MRI = MF.getRegInfo();
745 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000746 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
747 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
Dan Gohman81719f82015-11-25 16:55:01 +0000748 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Dan Gohmanadf28172016-01-28 01:22:44 +0000749 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +0000750 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
Dan Gohmand70e5902015-12-08 03:30:42 +0000751
Dan Gohman1462faa2015-11-16 16:18:28 +0000752 // Walk the instructions from the bottom up. Currently we don't look past
753 // block boundaries, and the blocks aren't ordered so the block visitation
754 // order isn't significant, but we may want to change this in the future.
755 for (MachineBasicBlock &MBB : MF) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000756 // Don't use a range-based for loop, because we modify the list as we're
757 // iterating over it and the end iterator may change.
758 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
759 MachineInstr *Insert = &*MII;
Dan Gohman81719f82015-11-25 16:55:01 +0000760 // Don't nest anything inside an inline asm, because we don't have
761 // constraints for $push inputs.
762 if (Insert->getOpcode() == TargetOpcode::INLINEASM)
Dan Gohman595e8ab2016-02-22 17:45:20 +0000763 continue;
764
765 // Ignore debugging intrinsics.
766 if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
767 continue;
Dan Gohman81719f82015-11-25 16:55:01 +0000768
Dan Gohman1462faa2015-11-16 16:18:28 +0000769 // Iterate through the inputs in reverse order, since we'll be pulling
Dan Gohman53d13992015-12-02 18:08:49 +0000770 // operands off the stack in LIFO order.
Dan Gohmanadf28172016-01-28 01:22:44 +0000771 CommutingState Commuting;
772 TreeWalkerState TreeWalker(Insert);
773 while (!TreeWalker.Done()) {
774 MachineOperand &Op = TreeWalker.Pop();
775
Dan Gohman1462faa2015-11-16 16:18:28 +0000776 // We're only interested in explicit virtual register operands.
Dan Gohmanadf28172016-01-28 01:22:44 +0000777 if (!Op.isReg())
Dan Gohman1462faa2015-11-16 16:18:28 +0000778 continue;
779
780 unsigned Reg = Op.getReg();
Dan Gohmanadf28172016-01-28 01:22:44 +0000781 assert(Op.isUse() && "explicit_uses() should only iterate over uses");
782 assert(!Op.isImplicit() &&
783 "explicit_uses() should only iterate over explicit operands");
784 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Dan Gohman1462faa2015-11-16 16:18:28 +0000785 continue;
786
Dan Gohmanffc184b2016-10-03 22:32:21 +0000787 // Identify the definition for this register at this point.
Dan Gohman2644d742016-05-17 04:05:31 +0000788 MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
789 if (!Def)
790 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000791
Dan Gohman81719f82015-11-25 16:55:01 +0000792 // Don't nest an INLINE_ASM def into anything, because we don't have
793 // constraints for $pop outputs.
794 if (Def->getOpcode() == TargetOpcode::INLINEASM)
795 continue;
796
Dan Gohman4ba48162015-11-18 16:12:01 +0000797 // Argument instructions represent live-in registers and not real
798 // instructions.
Dan Gohman4fc4e422016-10-24 19:49:43 +0000799 if (WebAssembly::isArgument(*Def))
Dan Gohman4ba48162015-11-18 16:12:01 +0000800 continue;
801
Dan Gohmanadf28172016-01-28 01:22:44 +0000802 // Decide which strategy to take. Prefer to move a single-use value
Dan Gohman4fc4e422016-10-24 19:49:43 +0000803 // over cloning it, and prefer cloning over introducing a tee.
Dan Gohmanadf28172016-01-28 01:22:44 +0000804 // For moving, we require the def to be in the same block as the use;
805 // this makes things simpler (LiveIntervals' handleMove function only
806 // supports intra-block moves) and it's MachineSink's job to catch all
807 // the sinking opportunities anyway.
808 bool SameBlock = Def->getParent() == &MBB;
Derek Schuffe9e68912016-09-30 18:02:54 +0000809 bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000810 !TreeWalker.IsOnStack(Reg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000811 if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000812 Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000813 } else if (ShouldRematerialize(*Def, AA, TII)) {
814 Insert =
815 RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
816 LIS, MFI, MRI, TII, TRI);
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000817 } else if (CanMove &&
Dan Gohman10545702016-05-17 22:24:18 +0000818 OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000819 Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
820 MRI, TII);
821 } else {
822 // We failed to stackify the operand. If the problem was ordering
823 // constraints, Commuting may be able to help.
824 if (!CanMove && SameBlock)
825 Commuting.MaybeCommute(Insert, TreeWalker, TII);
826 // Proceed to the next operand.
827 continue;
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000828 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000829
Dan Gohmane81021a2016-11-08 19:40:38 +0000830 // If the instruction we just stackified is an IMPLICIT_DEF, convert it
831 // to a constant 0 so that the def is explicit, and the push/pop
832 // correspondence is maintained.
833 if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
834 ConvertImplicitDefToConstZero(Insert, MRI, TII, MF);
835
Dan Gohmanadf28172016-01-28 01:22:44 +0000836 // We stackified an operand. Add the defining instruction's operands to
837 // the worklist stack now to continue to build an ever deeper tree.
838 Commuting.Reset();
839 TreeWalker.PushOperands(Insert);
Dan Gohman1462faa2015-11-16 16:18:28 +0000840 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000841
842 // If we stackified any operands, skip over the tree to start looking for
843 // the next instruction we can build a tree on.
844 if (Insert != &*MII) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000845 ImposeStackOrdering(&*MII);
Eric Liuc7e5a9c2016-09-12 09:35:59 +0000846 MII = MachineBasicBlock::iterator(Insert).getReverse();
Dan Gohmanadf28172016-01-28 01:22:44 +0000847 Changed = true;
848 }
Dan Gohman1462faa2015-11-16 16:18:28 +0000849 }
850 }
851
Dan Gohmane0405332016-10-03 22:43:53 +0000852 // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
Dan Gohmanadf28172016-01-28 01:22:44 +0000853 // that it never looks like a use-before-def.
Dan Gohmanb0992da2015-11-20 02:19:12 +0000854 if (Changed) {
Dan Gohmane0405332016-10-03 22:43:53 +0000855 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000856 for (MachineBasicBlock &MBB : MF)
Dan Gohmane0405332016-10-03 22:43:53 +0000857 MBB.addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000858 }
859
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000860#ifndef NDEBUG
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000861 // Verify that pushes and pops are performed in LIFO order.
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000862 SmallVector<unsigned, 0> Stack;
863 for (MachineBasicBlock &MBB : MF) {
864 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000865 if (MI.isDebugInstr())
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000866 continue;
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000867 for (MachineOperand &MO : reverse(MI.explicit_operands())) {
Dan Gohman7a6b9822015-11-29 22:32:02 +0000868 if (!MO.isReg())
869 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000870 unsigned Reg = MO.getReg();
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000871
Dan Gohmanadf28172016-01-28 01:22:44 +0000872 if (MFI.isVRegStackified(Reg)) {
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000873 if (MO.isDef())
Dan Gohmanadf28172016-01-28 01:22:44 +0000874 Stack.push_back(Reg);
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000875 else
Dan Gohmanadf28172016-01-28 01:22:44 +0000876 assert(Stack.pop_back_val() == Reg &&
877 "Register stack pop should be paired with a push");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000878 }
879 }
880 }
881 // TODO: Generalize this code to support keeping values on the stack across
882 // basic block boundaries.
Dan Gohmanadf28172016-01-28 01:22:44 +0000883 assert(Stack.empty() &&
884 "Register stack pushes and pops should be balanced");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000885 }
886#endif
887
Dan Gohman1462faa2015-11-16 16:18:28 +0000888 return Changed;
889}