blob: 2bdba96ab6740725c563766c0f021ca8bf8dc0b2 [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
11/// \brief This file implements a register stacking pass.
12///
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;
70FunctionPass *llvm::createWebAssemblyRegStackify() {
71 return new WebAssemblyRegStackify();
72}
73
Dan Gohmanb0992da2015-11-20 02:19:12 +000074// Decorate the given instruction with implicit operands that enforce the
Dan Gohman8887d1f2015-12-25 00:31:02 +000075// expression stack ordering constraints for an instruction which is on
76// the expression stack.
77static void ImposeStackOrdering(MachineInstr *MI) {
Dan Gohmane0405332016-10-03 22:43:53 +000078 // Write the opaque VALUE_STACK register.
79 if (!MI->definesRegister(WebAssembly::VALUE_STACK))
80 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohman4da4abd2015-12-05 00:51:40 +000081 /*isDef=*/true,
82 /*isImp=*/true));
Dan Gohman4da4abd2015-12-05 00:51:40 +000083
Dan Gohmane0405332016-10-03 22:43:53 +000084 // Also read the opaque VALUE_STACK register.
85 if (!MI->readsRegister(WebAssembly::VALUE_STACK))
86 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohmana712a6c2015-12-14 22:37:23 +000087 /*isDef=*/false,
88 /*isImp=*/true));
Dan Gohmanb0992da2015-11-20 02:19:12 +000089}
90
Dan Gohmane81021a2016-11-08 19:40:38 +000091// Convert an IMPLICIT_DEF instruction into an instruction which defines
92// a constant zero value.
93static void ConvertImplicitDefToConstZero(MachineInstr *MI,
94 MachineRegisterInfo &MRI,
95 const TargetInstrInfo *TII,
96 MachineFunction &MF) {
97 assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
98
99 const auto *RegClass =
100 MRI.getRegClass(MI->getOperand(0).getReg());
101 if (RegClass == &WebAssembly::I32RegClass) {
102 MI->setDesc(TII->get(WebAssembly::CONST_I32));
103 MI->addOperand(MachineOperand::CreateImm(0));
104 } else if (RegClass == &WebAssembly::I64RegClass) {
105 MI->setDesc(TII->get(WebAssembly::CONST_I64));
106 MI->addOperand(MachineOperand::CreateImm(0));
107 } else if (RegClass == &WebAssembly::F32RegClass) {
108 MI->setDesc(TII->get(WebAssembly::CONST_F32));
109 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000110 Type::getFloatTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000111 MI->addOperand(MachineOperand::CreateFPImm(Val));
112 } else if (RegClass == &WebAssembly::F64RegClass) {
113 MI->setDesc(TII->get(WebAssembly::CONST_F64));
114 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000115 Type::getDoubleTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000116 MI->addOperand(MachineOperand::CreateFPImm(Val));
117 } else {
118 llvm_unreachable("Unexpected reg class");
119 }
120}
121
Dan Gohman2644d742016-05-17 04:05:31 +0000122// Determine whether a call to the callee referenced by
123// MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
124// effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000125static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
126 bool &Write, bool &Effects, bool &StackPointer) {
Dan Gohmand08cd152016-05-17 21:14:26 +0000127 // All calls can use the stack pointer.
128 StackPointer = true;
129
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000130 const MachineOperand &MO = MI.getOperand(CalleeOpNo);
Dan Gohman2644d742016-05-17 04:05:31 +0000131 if (MO.isGlobal()) {
132 const Constant *GV = MO.getGlobal();
133 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
134 if (!GA->isInterposable())
135 GV = GA->getAliasee();
136
137 if (const Function *F = dyn_cast<Function>(GV)) {
138 if (!F->doesNotThrow())
139 Effects = true;
140 if (F->doesNotAccessMemory())
141 return;
142 if (F->onlyReadsMemory()) {
143 Read = true;
144 return;
145 }
146 }
147 }
148
149 // Assume the worst.
150 Write = true;
151 Read = true;
152 Effects = true;
153}
154
Dan Gohmand08cd152016-05-17 21:14:26 +0000155// Determine whether MI reads memory, writes memory, has side effects,
Dan Gohman82607f52017-02-24 23:46:05 +0000156// and/or uses the stack pointer value.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000157static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
158 bool &Write, bool &Effects, bool &StackPointer) {
159 assert(!MI.isPosition());
160 assert(!MI.isTerminator());
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000161
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000162 if (MI.isDebugValue())
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000163 return;
Dan Gohman2644d742016-05-17 04:05:31 +0000164
165 // Check for loads.
Justin Lebard98cf002016-09-10 01:03:20 +0000166 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
Dan Gohman2644d742016-05-17 04:05:31 +0000167 Read = true;
168
169 // Check for stores.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000170 if (MI.mayStore()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000171 Write = true;
Dan Gohmand08cd152016-05-17 21:14:26 +0000172
Sam Clegg9d24fb72017-06-16 23:59:10 +0000173 // Check for stores to __stack_pointer.
174 for (auto MMO : MI.memoperands()) {
175 const MachinePointerInfo &MPI = MMO->getPointerInfo();
176 if (MPI.V.is<const PseudoSourceValue *>()) {
177 auto PSV = MPI.V.get<const PseudoSourceValue *>();
178 if (const ExternalSymbolPseudoSourceValue *EPSV =
179 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
180 if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
181 StackPointer = true;
182 }
Dan Gohmand08cd152016-05-17 21:14:26 +0000183 }
184 }
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000185 } else if (MI.hasOrderedMemoryRef()) {
186 switch (MI.getOpcode()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000187 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
188 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
189 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
190 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
191 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
192 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
193 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
194 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
195 // These instruction have hasUnmodeledSideEffects() returning true
196 // because they trap on overflow and invalid so they can't be arbitrarily
197 // moved, however hasOrderedMemoryRef() interprets this plus their lack
198 // of memoperands as having a potential unknown memory reference.
199 break;
200 default:
Dan Gohman10545702016-05-17 22:24:18 +0000201 // Record volatile accesses, unless it's a call, as calls are handled
Dan Gohman2644d742016-05-17 04:05:31 +0000202 // specially below.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000203 if (!MI.isCall()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000204 Write = true;
Dan Gohman10545702016-05-17 22:24:18 +0000205 Effects = true;
206 }
Dan Gohman2644d742016-05-17 04:05:31 +0000207 break;
208 }
209 }
210
211 // Check for side effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000212 if (MI.hasUnmodeledSideEffects()) {
213 switch (MI.getOpcode()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000214 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
215 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
216 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
217 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
218 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
219 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
220 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
221 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
222 // These instructions have hasUnmodeledSideEffects() returning true
223 // because they trap on overflow and invalid so they can't be arbitrarily
224 // moved, however in the specific case of register stackifying, it is safe
225 // to move them because overflow and invalid are Undefined Behavior.
226 break;
227 default:
228 Effects = true;
229 break;
230 }
231 }
232
233 // Analyze calls.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000234 if (MI.isCall()) {
235 switch (MI.getOpcode()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000236 case WebAssembly::CALL_VOID:
Dan Gohman10545702016-05-17 22:24:18 +0000237 case WebAssembly::CALL_INDIRECT_VOID:
Dan Gohmand08cd152016-05-17 21:14:26 +0000238 QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000239 break;
Dan Gohman10545702016-05-17 22:24:18 +0000240 case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
241 case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
242 case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
243 case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
Dan Gohmand08cd152016-05-17 21:14:26 +0000244 QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000245 break;
Dan Gohman2644d742016-05-17 04:05:31 +0000246 default:
247 llvm_unreachable("unexpected call opcode");
248 }
249 }
250}
251
252// Test whether Def is safe and profitable to rematerialize.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000253static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
Dan Gohman2644d742016-05-17 04:05:31 +0000254 const WebAssemblyInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000255 return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
Dan Gohman2644d742016-05-17 04:05:31 +0000256}
257
Dan Gohman12de0b92016-05-17 20:19:47 +0000258// Identify the definition for this register at this point. This is a
259// generalization of MachineRegisterInfo::getUniqueVRegDef that uses
260// LiveIntervals to handle complex cases.
Dan Gohman2644d742016-05-17 04:05:31 +0000261static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
262 const MachineRegisterInfo &MRI,
263 const LiveIntervals &LIS)
264{
265 // Most registers are in SSA form here so we try a quick MRI query first.
266 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
267 return Def;
268
269 // MRI doesn't know what the Def is. Try asking LIS.
270 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
271 LIS.getInstructionIndex(*Insert)))
272 return LIS.getInstructionFromIndex(ValNo->def);
273
274 return nullptr;
275}
276
Dan Gohman12de0b92016-05-17 20:19:47 +0000277// Test whether Reg, as defined at Def, has exactly one use. This is a
278// generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
279// to handle complex cases.
280static bool HasOneUse(unsigned Reg, MachineInstr *Def,
281 MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
282 LiveIntervals &LIS) {
283 // Most registers are in SSA form here so we try a quick MRI query first.
284 if (MRI.hasOneUse(Reg))
285 return true;
286
287 bool HasOne = false;
288 const LiveInterval &LI = LIS.getInterval(Reg);
289 const VNInfo *DefVNI = LI.getVNInfoAt(
290 LIS.getInstructionIndex(*Def).getRegSlot());
291 assert(DefVNI);
Dominic Chena8a63822016-08-17 23:42:27 +0000292 for (auto &I : MRI.use_nodbg_operands(Reg)) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000293 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
294 if (Result.valueIn() == DefVNI) {
295 if (!Result.isKill())
296 return false;
297 if (HasOne)
298 return false;
299 HasOne = true;
300 }
301 }
302 return HasOne;
303}
304
Dan Gohman8887d1f2015-12-25 00:31:02 +0000305// Test whether it's safe to move Def to just before Insert.
Dan Gohman81719f82015-11-25 16:55:01 +0000306// TODO: Compute memory dependencies in a way that doesn't require always
307// walking the block.
308// TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
309// more precise.
310static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
Derek Schuffe9e68912016-09-30 18:02:54 +0000311 AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
Dan Gohman391a98a2015-12-03 23:07:03 +0000312 assert(Def->getParent() == Insert->getParent());
Dan Gohman8887d1f2015-12-25 00:31:02 +0000313
314 // Check for register dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000315 SmallVector<unsigned, 4> MutableRegisters;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000316 for (const MachineOperand &MO : Def->operands()) {
317 if (!MO.isReg() || MO.isUndef())
318 continue;
319 unsigned Reg = MO.getReg();
320
321 // If the register is dead here and at Insert, ignore it.
322 if (MO.isDead() && Insert->definesRegister(Reg) &&
323 !Insert->readsRegister(Reg))
324 continue;
325
326 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000327 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
328 // from moving down, and we've already checked for that.
329 if (Reg == WebAssembly::ARGUMENTS)
330 continue;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000331 // If the physical register is never modified, ignore it.
332 if (!MRI.isPhysRegModified(Reg))
333 continue;
334 // Otherwise, it's a physical register with unknown liveness.
335 return false;
336 }
337
Derek Schuffe9e68912016-09-30 18:02:54 +0000338 // If one of the operands isn't in SSA form, it has different values at
339 // different times, and we need to make sure we don't move our use across
340 // a different def.
341 if (!MO.isDef() && !MRI.hasOneDef(Reg))
342 MutableRegisters.push_back(Reg);
Dan Gohman8887d1f2015-12-25 00:31:02 +0000343 }
344
Dan Gohmand08cd152016-05-17 21:14:26 +0000345 bool Read = false, Write = false, Effects = false, StackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000346 Query(*Def, AA, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000347
348 // If the instruction does not access memory and has no side effects, it has
349 // no additional dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000350 bool HasMutableRegisters = !MutableRegisters.empty();
351 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
Dan Gohman2644d742016-05-17 04:05:31 +0000352 return true;
353
354 // Scan through the intervening instructions between Def and Insert.
355 MachineBasicBlock::const_iterator D(Def), I(Insert);
356 for (--I; I != D; --I) {
357 bool InterveningRead = false;
358 bool InterveningWrite = false;
359 bool InterveningEffects = false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000360 bool InterveningStackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000361 Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
Dan Gohmand08cd152016-05-17 21:14:26 +0000362 InterveningStackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000363 if (Effects && InterveningEffects)
364 return false;
365 if (Read && InterveningWrite)
366 return false;
367 if (Write && (InterveningRead || InterveningWrite))
368 return false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000369 if (StackPointer && InterveningStackPointer)
370 return false;
Derek Schuffe9e68912016-09-30 18:02:54 +0000371
372 for (unsigned Reg : MutableRegisters)
373 for (const MachineOperand &MO : I->operands())
374 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
375 return false;
Dan Gohman2644d742016-05-17 04:05:31 +0000376 }
377
378 return true;
Dan Gohman81719f82015-11-25 16:55:01 +0000379}
380
Dan Gohmanadf28172016-01-28 01:22:44 +0000381/// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
382static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
383 const MachineBasicBlock &MBB,
384 const MachineRegisterInfo &MRI,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000385 const MachineDominatorTree &MDT,
Dan Gohman10545702016-05-17 22:24:18 +0000386 LiveIntervals &LIS,
387 WebAssemblyFunctionInfo &MFI) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000388 const LiveInterval &LI = LIS.getInterval(Reg);
389
390 const MachineInstr *OneUseInst = OneUse.getParent();
391 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
392
Dominic Chena8a63822016-08-17 23:42:27 +0000393 for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000394 if (&Use == &OneUse)
395 continue;
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000396
Dan Gohmanadf28172016-01-28 01:22:44 +0000397 const MachineInstr *UseInst = Use.getParent();
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000398 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
399
400 if (UseVNI != OneUseVNI)
401 continue;
402
Dan Gohmanadf28172016-01-28 01:22:44 +0000403 const MachineInstr *OneUseInst = OneUse.getParent();
Dan Gohman12de0b92016-05-17 20:19:47 +0000404 if (UseInst == OneUseInst) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000405 // Another use in the same instruction. We need to ensure that the one
406 // selected use happens "before" it.
407 if (&OneUse > &Use)
408 return false;
409 } else {
410 // Test that the use is dominated by the one selected use.
Dan Gohman10545702016-05-17 22:24:18 +0000411 while (!MDT.dominates(OneUseInst, UseInst)) {
412 // Actually, dominating is over-conservative. Test that the use would
413 // happen after the one selected use in the stack evaluation order.
414 //
415 // This is needed as a consequence of using implicit get_locals for
416 // uses and implicit set_locals for defs.
Dominic Chen4173fff2016-08-11 04:10:56 +0000417 if (UseInst->getDesc().getNumDefs() == 0)
Dan Gohman10545702016-05-17 22:24:18 +0000418 return false;
419 const MachineOperand &MO = UseInst->getOperand(0);
420 if (!MO.isReg())
421 return false;
422 unsigned DefReg = MO.getReg();
423 if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
424 !MFI.isVRegStackified(DefReg))
425 return false;
426 assert(MRI.hasOneUse(DefReg));
427 const MachineOperand &NewUse = *MRI.use_begin(DefReg);
428 const MachineInstr *NewUseInst = NewUse.getParent();
429 if (NewUseInst == OneUseInst) {
430 if (&OneUse > &NewUse)
431 return false;
432 break;
433 }
434 UseInst = NewUseInst;
435 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000436 }
437 }
438 return true;
439}
440
Dan Gohman4fc4e422016-10-24 19:49:43 +0000441/// Get the appropriate tee opcode for the given register class.
442static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000443 if (RC == &WebAssembly::I32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000444 return WebAssembly::TEE_I32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000445 if (RC == &WebAssembly::I64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000446 return WebAssembly::TEE_I64;
Dan Gohmanadf28172016-01-28 01:22:44 +0000447 if (RC == &WebAssembly::F32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000448 return WebAssembly::TEE_F32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000449 if (RC == &WebAssembly::F64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000450 return WebAssembly::TEE_F64;
Derek Schuff39bf39f2016-08-02 23:16:09 +0000451 if (RC == &WebAssembly::V128RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000452 return WebAssembly::TEE_V128;
Dan Gohmanadf28172016-01-28 01:22:44 +0000453 llvm_unreachable("Unexpected register class");
454}
455
Dan Gohman2644d742016-05-17 04:05:31 +0000456// Shrink LI to its uses, cleaning up LI.
457static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
458 if (LIS.shrinkToUses(&LI)) {
459 SmallVector<LiveInterval*, 4> SplitLIs;
460 LIS.splitSeparateComponents(LI, SplitLIs);
461 }
462}
463
Dan Gohmanadf28172016-01-28 01:22:44 +0000464/// A single-use def in the same block with no intervening memory or register
465/// dependencies; move the def down and nest it with the current instruction.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000466static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
467 MachineInstr *Def,
Dan Gohmanadf28172016-01-28 01:22:44 +0000468 MachineBasicBlock &MBB,
469 MachineInstr *Insert, LiveIntervals &LIS,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000470 WebAssemblyFunctionInfo &MFI,
471 MachineRegisterInfo &MRI) {
Dan Gohman2644d742016-05-17 04:05:31 +0000472 DEBUG(dbgs() << "Move for single use: "; Def->dump());
473
Dan Gohmanadf28172016-01-28 01:22:44 +0000474 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000475 LIS.handleMove(*Def);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000476
Dan Gohman12de0b92016-05-17 20:19:47 +0000477 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
478 // No one else is using this register for anything so we can just stackify
479 // it in place.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000480 MFI.stackifyVReg(Reg);
481 } else {
Dan Gohman12de0b92016-05-17 20:19:47 +0000482 // The register may have unrelated uses or defs; create a new register for
483 // just our one def and use so that we can stackify it.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000484 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
485 Def->getOperand(0).setReg(NewReg);
486 Op.setReg(NewReg);
487
488 // Tell LiveIntervals about the new register.
489 LIS.createAndComputeVirtRegInterval(NewReg);
490
491 // Tell LiveIntervals about the changes to the old register.
492 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000493 LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
494 LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
495 /*RemoveDeadValNo=*/true);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000496
497 MFI.stackifyVReg(NewReg);
Dan Gohman2644d742016-05-17 04:05:31 +0000498
499 DEBUG(dbgs() << " - Replaced register: "; Def->dump());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000500 }
501
Dan Gohmanadf28172016-01-28 01:22:44 +0000502 ImposeStackOrdering(Def);
503 return Def;
504}
505
506/// A trivially cloneable instruction; clone it and nest the new copy with the
507/// current instruction.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000508static MachineInstr *RematerializeCheapDef(
509 unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
510 MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
511 WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
512 const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
513 DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000514 DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
515
Dan Gohmanadf28172016-01-28 01:22:44 +0000516 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
517 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
518 Op.setReg(NewReg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000519 MachineInstr *Clone = &*std::prev(Insert);
JF Bastien13d3b9b2016-02-27 16:38:23 +0000520 LIS.InsertMachineInstrInMaps(*Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000521 LIS.createAndComputeVirtRegInterval(NewReg);
522 MFI.stackifyVReg(NewReg);
523 ImposeStackOrdering(Clone);
524
Dan Gohman2644d742016-05-17 04:05:31 +0000525 DEBUG(dbgs() << " - Cloned to "; Clone->dump());
526
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000527 // Shrink the interval.
528 bool IsDead = MRI.use_empty(Reg);
529 if (!IsDead) {
530 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman2644d742016-05-17 04:05:31 +0000531 ShrinkToUses(LI, LIS);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000532 IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000533 }
534
Dan Gohmanadf28172016-01-28 01:22:44 +0000535 // If that was the last use of the original, delete the original.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000536 if (IsDead) {
Dan Gohman2644d742016-05-17 04:05:31 +0000537 DEBUG(dbgs() << " - Deleting original\n");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000538 SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
Dan Gohmanadf28172016-01-28 01:22:44 +0000539 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
Dan Gohmanadf28172016-01-28 01:22:44 +0000540 LIS.removeInterval(Reg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000541 LIS.RemoveMachineInstrFromMaps(Def);
542 Def.eraseFromParent();
Dan Gohmanadf28172016-01-28 01:22:44 +0000543 }
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000544
Dan Gohmanadf28172016-01-28 01:22:44 +0000545 return Clone;
546}
547
548/// A multiple-use def in the same block with no intervening memory or register
549/// dependencies; move the def down, nest it with the current instruction, and
Dan Gohman4fc4e422016-10-24 19:49:43 +0000550/// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
551/// this:
Dan Gohmanadf28172016-01-28 01:22:44 +0000552///
553/// Reg = INST ... // Def
554/// INST ..., Reg, ... // Insert
555/// INST ..., Reg, ...
556/// INST ..., Reg, ...
557///
558/// to this:
559///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000560/// DefReg = INST ... // Def (to become the new Insert)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000561/// TeeReg, Reg = TEE_... DefReg
Dan Gohmanadf28172016-01-28 01:22:44 +0000562/// INST ..., TeeReg, ... // Insert
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000563/// INST ..., Reg, ...
564/// INST ..., Reg, ...
Dan Gohmanadf28172016-01-28 01:22:44 +0000565///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000566/// with DefReg and TeeReg stackified. This eliminates a get_local from the
Dan Gohmanadf28172016-01-28 01:22:44 +0000567/// resulting code.
568static MachineInstr *MoveAndTeeForMultiUse(
569 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
570 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
571 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
Dan Gohman2644d742016-05-17 04:05:31 +0000572 DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
573
Dan Gohman12de0b92016-05-17 20:19:47 +0000574 // Move Def into place.
Dan Gohmanadf28172016-01-28 01:22:44 +0000575 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000576 LIS.handleMove(*Def);
Dan Gohman12de0b92016-05-17 20:19:47 +0000577
578 // Create the Tee and attach the registers.
Dan Gohmanadf28172016-01-28 01:22:44 +0000579 const auto *RegClass = MRI.getRegClass(Reg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000580 unsigned TeeReg = MRI.createVirtualRegister(RegClass);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000581 unsigned DefReg = MRI.createVirtualRegister(RegClass);
Dan Gohman33e694a2016-05-12 04:19:09 +0000582 MachineOperand &DefMO = Def->getOperand(0);
Dan Gohmanadf28172016-01-28 01:22:44 +0000583 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
Dan Gohman4fc4e422016-10-24 19:49:43 +0000584 TII->get(GetTeeOpcode(RegClass)), TeeReg)
Dan Gohman12de0b92016-05-17 20:19:47 +0000585 .addReg(Reg, RegState::Define)
Dan Gohman33e694a2016-05-12 04:19:09 +0000586 .addReg(DefReg, getUndefRegState(DefMO.isDead()));
Dan Gohmanadf28172016-01-28 01:22:44 +0000587 Op.setReg(TeeReg);
Dan Gohman33e694a2016-05-12 04:19:09 +0000588 DefMO.setReg(DefReg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000589 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
590 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
591
592 // Tell LiveIntervals we moved the original vreg def from Def to Tee.
593 LiveInterval &LI = LIS.getInterval(Reg);
594 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
595 VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
596 I->start = TeeIdx;
597 ValNo->def = TeeIdx;
598 ShrinkToUses(LI, LIS);
599
600 // Finish stackifying the new regs.
Dan Gohmanadf28172016-01-28 01:22:44 +0000601 LIS.createAndComputeVirtRegInterval(TeeReg);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000602 LIS.createAndComputeVirtRegInterval(DefReg);
603 MFI.stackifyVReg(DefReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000604 MFI.stackifyVReg(TeeReg);
605 ImposeStackOrdering(Def);
606 ImposeStackOrdering(Tee);
Dan Gohman12de0b92016-05-17 20:19:47 +0000607
608 DEBUG(dbgs() << " - Replaced register: "; Def->dump());
609 DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
Dan Gohmanadf28172016-01-28 01:22:44 +0000610 return Def;
611}
612
613namespace {
614/// A stack for walking the tree of instructions being built, visiting the
615/// MachineOperands in DFS order.
616class TreeWalkerState {
617 typedef MachineInstr::mop_iterator mop_iterator;
618 typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
619 typedef iterator_range<mop_reverse_iterator> RangeTy;
620 SmallVector<RangeTy, 4> Worklist;
621
622public:
623 explicit TreeWalkerState(MachineInstr *Insert) {
624 const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
625 if (Range.begin() != Range.end())
626 Worklist.push_back(reverse(Range));
627 }
628
629 bool Done() const { return Worklist.empty(); }
630
631 MachineOperand &Pop() {
632 RangeTy &Range = Worklist.back();
633 MachineOperand &Op = *Range.begin();
634 Range = drop_begin(Range, 1);
635 if (Range.begin() == Range.end())
636 Worklist.pop_back();
637 assert((Worklist.empty() ||
638 Worklist.back().begin() != Worklist.back().end()) &&
639 "Empty ranges shouldn't remain in the worklist");
640 return Op;
641 }
642
643 /// Push Instr's operands onto the stack to be visited.
644 void PushOperands(MachineInstr *Instr) {
645 const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
646 if (Range.begin() != Range.end())
647 Worklist.push_back(reverse(Range));
648 }
649
650 /// Some of Instr's operands are on the top of the stack; remove them and
651 /// re-insert them starting from the beginning (because we've commuted them).
652 void ResetTopOperands(MachineInstr *Instr) {
653 assert(HasRemainingOperands(Instr) &&
654 "Reseting operands should only be done when the instruction has "
655 "an operand still on the stack");
656 Worklist.back() = reverse(Instr->explicit_uses());
657 }
658
659 /// Test whether Instr has operands remaining to be visited at the top of
660 /// the stack.
661 bool HasRemainingOperands(const MachineInstr *Instr) const {
662 if (Worklist.empty())
663 return false;
664 const RangeTy &Range = Worklist.back();
665 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
666 }
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000667
668 /// Test whether the given register is present on the stack, indicating an
669 /// operand in the tree that we haven't visited yet. Moving a definition of
670 /// Reg to a point in the tree after that would change its value.
Dan Gohman10545702016-05-17 22:24:18 +0000671 ///
672 /// This is needed as a consequence of using implicit get_locals for
673 /// uses and implicit set_locals for defs.
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000674 bool IsOnStack(unsigned Reg) const {
675 for (const RangeTy &Range : Worklist)
676 for (const MachineOperand &MO : Range)
677 if (MO.isReg() && MO.getReg() == Reg)
678 return true;
679 return false;
680 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000681};
682
683/// State to keep track of whether commuting is in flight or whether it's been
684/// tried for the current instruction and didn't work.
685class CommutingState {
686 /// There are effectively three states: the initial state where we haven't
687 /// started commuting anything and we don't know anything yet, the tenative
688 /// state where we've commuted the operands of the current instruction and are
689 /// revisting it, and the declined state where we've reverted the operands
690 /// back to their original order and will no longer commute it further.
691 bool TentativelyCommuting;
692 bool Declined;
693
694 /// During the tentative state, these hold the operand indices of the commuted
695 /// operands.
696 unsigned Operand0, Operand1;
697
698public:
699 CommutingState() : TentativelyCommuting(false), Declined(false) {}
700
701 /// Stackification for an operand was not successful due to ordering
702 /// constraints. If possible, and if we haven't already tried it and declined
703 /// it, commute Insert's operands and prepare to revisit it.
704 void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
705 const WebAssemblyInstrInfo *TII) {
706 if (TentativelyCommuting) {
707 assert(!Declined &&
708 "Don't decline commuting until you've finished trying it");
709 // Commuting didn't help. Revert it.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000710 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000711 TentativelyCommuting = false;
712 Declined = true;
713 } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
714 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
715 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000716 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000717 // Tentatively commute the operands and try again.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000718 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000719 TreeWalker.ResetTopOperands(Insert);
720 TentativelyCommuting = true;
721 Declined = false;
722 }
723 }
724 }
725
726 /// Stackification for some operand was successful. Reset to the default
727 /// state.
728 void Reset() {
729 TentativelyCommuting = false;
730 Declined = false;
731 }
732};
733} // end anonymous namespace
734
Dan Gohman1462faa2015-11-16 16:18:28 +0000735bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
736 DEBUG(dbgs() << "********** Register Stackifying **********\n"
737 "********** Function: "
738 << MF.getName() << '\n');
739
740 bool Changed = false;
741 MachineRegisterInfo &MRI = MF.getRegInfo();
742 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000743 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
744 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
Dan Gohman81719f82015-11-25 16:55:01 +0000745 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Dan Gohmanadf28172016-01-28 01:22:44 +0000746 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +0000747 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
Dan Gohmand70e5902015-12-08 03:30:42 +0000748
Dan Gohman1462faa2015-11-16 16:18:28 +0000749 // Walk the instructions from the bottom up. Currently we don't look past
750 // block boundaries, and the blocks aren't ordered so the block visitation
751 // order isn't significant, but we may want to change this in the future.
752 for (MachineBasicBlock &MBB : MF) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000753 // Don't use a range-based for loop, because we modify the list as we're
754 // iterating over it and the end iterator may change.
755 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
756 MachineInstr *Insert = &*MII;
Dan Gohman81719f82015-11-25 16:55:01 +0000757 // Don't nest anything inside an inline asm, because we don't have
758 // constraints for $push inputs.
759 if (Insert->getOpcode() == TargetOpcode::INLINEASM)
Dan Gohman595e8ab2016-02-22 17:45:20 +0000760 continue;
761
762 // Ignore debugging intrinsics.
763 if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
764 continue;
Dan Gohman81719f82015-11-25 16:55:01 +0000765
Dan Gohman1462faa2015-11-16 16:18:28 +0000766 // Iterate through the inputs in reverse order, since we'll be pulling
Dan Gohman53d13992015-12-02 18:08:49 +0000767 // operands off the stack in LIFO order.
Dan Gohmanadf28172016-01-28 01:22:44 +0000768 CommutingState Commuting;
769 TreeWalkerState TreeWalker(Insert);
770 while (!TreeWalker.Done()) {
771 MachineOperand &Op = TreeWalker.Pop();
772
Dan Gohman1462faa2015-11-16 16:18:28 +0000773 // We're only interested in explicit virtual register operands.
Dan Gohmanadf28172016-01-28 01:22:44 +0000774 if (!Op.isReg())
Dan Gohman1462faa2015-11-16 16:18:28 +0000775 continue;
776
777 unsigned Reg = Op.getReg();
Dan Gohmanadf28172016-01-28 01:22:44 +0000778 assert(Op.isUse() && "explicit_uses() should only iterate over uses");
779 assert(!Op.isImplicit() &&
780 "explicit_uses() should only iterate over explicit operands");
781 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Dan Gohman1462faa2015-11-16 16:18:28 +0000782 continue;
783
Dan Gohmanffc184b2016-10-03 22:32:21 +0000784 // Identify the definition for this register at this point.
Dan Gohman2644d742016-05-17 04:05:31 +0000785 MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
786 if (!Def)
787 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000788
Dan Gohman81719f82015-11-25 16:55:01 +0000789 // Don't nest an INLINE_ASM def into anything, because we don't have
790 // constraints for $pop outputs.
791 if (Def->getOpcode() == TargetOpcode::INLINEASM)
792 continue;
793
Dan Gohman4ba48162015-11-18 16:12:01 +0000794 // Argument instructions represent live-in registers and not real
795 // instructions.
Dan Gohman4fc4e422016-10-24 19:49:43 +0000796 if (WebAssembly::isArgument(*Def))
Dan Gohman4ba48162015-11-18 16:12:01 +0000797 continue;
798
Dan Gohmanadf28172016-01-28 01:22:44 +0000799 // Decide which strategy to take. Prefer to move a single-use value
Dan Gohman4fc4e422016-10-24 19:49:43 +0000800 // over cloning it, and prefer cloning over introducing a tee.
Dan Gohmanadf28172016-01-28 01:22:44 +0000801 // For moving, we require the def to be in the same block as the use;
802 // this makes things simpler (LiveIntervals' handleMove function only
803 // supports intra-block moves) and it's MachineSink's job to catch all
804 // the sinking opportunities anyway.
805 bool SameBlock = Def->getParent() == &MBB;
Derek Schuffe9e68912016-09-30 18:02:54 +0000806 bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000807 !TreeWalker.IsOnStack(Reg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000808 if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000809 Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000810 } else if (ShouldRematerialize(*Def, AA, TII)) {
811 Insert =
812 RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
813 LIS, MFI, MRI, TII, TRI);
Dan Gohmanadf28172016-01-28 01:22:44 +0000814 } else if (CanMove &&
Dan Gohman10545702016-05-17 22:24:18 +0000815 OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000816 Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
817 MRI, TII);
818 } else {
819 // We failed to stackify the operand. If the problem was ordering
820 // constraints, Commuting may be able to help.
821 if (!CanMove && SameBlock)
822 Commuting.MaybeCommute(Insert, TreeWalker, TII);
823 // Proceed to the next operand.
824 continue;
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000825 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000826
Dan Gohmane81021a2016-11-08 19:40:38 +0000827 // If the instruction we just stackified is an IMPLICIT_DEF, convert it
828 // to a constant 0 so that the def is explicit, and the push/pop
829 // correspondence is maintained.
830 if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
831 ConvertImplicitDefToConstZero(Insert, MRI, TII, MF);
832
Dan Gohmanadf28172016-01-28 01:22:44 +0000833 // We stackified an operand. Add the defining instruction's operands to
834 // the worklist stack now to continue to build an ever deeper tree.
835 Commuting.Reset();
836 TreeWalker.PushOperands(Insert);
Dan Gohman1462faa2015-11-16 16:18:28 +0000837 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000838
839 // If we stackified any operands, skip over the tree to start looking for
840 // the next instruction we can build a tree on.
841 if (Insert != &*MII) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000842 ImposeStackOrdering(&*MII);
Eric Liuc7e5a9c2016-09-12 09:35:59 +0000843 MII = MachineBasicBlock::iterator(Insert).getReverse();
Dan Gohmanadf28172016-01-28 01:22:44 +0000844 Changed = true;
845 }
Dan Gohman1462faa2015-11-16 16:18:28 +0000846 }
847 }
848
Dan Gohmane0405332016-10-03 22:43:53 +0000849 // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
Dan Gohmanadf28172016-01-28 01:22:44 +0000850 // that it never looks like a use-before-def.
Dan Gohmanb0992da2015-11-20 02:19:12 +0000851 if (Changed) {
Dan Gohmane0405332016-10-03 22:43:53 +0000852 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000853 for (MachineBasicBlock &MBB : MF)
Dan Gohmane0405332016-10-03 22:43:53 +0000854 MBB.addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000855 }
856
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000857#ifndef NDEBUG
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000858 // Verify that pushes and pops are performed in LIFO order.
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000859 SmallVector<unsigned, 0> Stack;
860 for (MachineBasicBlock &MBB : MF) {
861 for (MachineInstr &MI : MBB) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000862 if (MI.isDebugValue())
863 continue;
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000864 for (MachineOperand &MO : reverse(MI.explicit_operands())) {
Dan Gohman7a6b9822015-11-29 22:32:02 +0000865 if (!MO.isReg())
866 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000867 unsigned Reg = MO.getReg();
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000868
Dan Gohmanadf28172016-01-28 01:22:44 +0000869 if (MFI.isVRegStackified(Reg)) {
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000870 if (MO.isDef())
Dan Gohmanadf28172016-01-28 01:22:44 +0000871 Stack.push_back(Reg);
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000872 else
Dan Gohmanadf28172016-01-28 01:22:44 +0000873 assert(Stack.pop_back_val() == Reg &&
874 "Register stack pop should be paired with a push");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000875 }
876 }
877 }
878 // TODO: Generalize this code to support keeping values on the stack across
879 // basic block boundaries.
Dan Gohmanadf28172016-01-28 01:22:44 +0000880 assert(Stack.empty() &&
881 "Register stack pushes and pops should be balanced");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000882 }
883#endif
884
Dan Gohman1462faa2015-11-16 16:18:28 +0000885 return Changed;
886}