blob: b47de787999653f5e56bfe617b05ea58c91670cb [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
16/// "push" and "pop" from the stack.
17///
Dan Gohman31448f12015-12-08 03:43:03 +000018/// This is primarily a code size optimization, since temporary values on the
Dan Gohman1462faa2015-11-16 16:18:28 +000019/// expression don't need to be named.
20///
21//===----------------------------------------------------------------------===//
22
23#include "WebAssembly.h"
Dan Gohman4ba48162015-11-18 16:12:01 +000024#include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
Dan Gohman7a6b9822015-11-29 22:32:02 +000025#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohmanb6fd39a2016-01-19 16:59:23 +000026#include "WebAssemblySubtarget.h"
Dan Gohman81719f82015-11-25 16:55:01 +000027#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman8887d1f2015-12-25 00:31:02 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000029#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Dan Gohmanadf28172016-01-28 01:22:44 +000030#include "llvm/CodeGen/MachineDominators.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/Passes.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "wasm-reg-stackify"
39
40namespace {
41class WebAssemblyRegStackify final : public MachineFunctionPass {
42 const char *getPassName() const override {
43 return "WebAssembly Register Stackify";
44 }
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 AU.setPreservesCFG();
Dan Gohman81719f82015-11-25 16:55:01 +000048 AU.addRequired<AAResultsWrapperPass>();
Dan Gohmanadf28172016-01-28 01:22:44 +000049 AU.addRequired<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000050 AU.addRequired<LiveIntervals>();
Dan Gohman1462faa2015-11-16 16:18:28 +000051 AU.addPreserved<MachineBlockFrequencyInfo>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000052 AU.addPreserved<SlotIndexes>();
53 AU.addPreserved<LiveIntervals>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000054 AU.addPreservedID(LiveVariablesID);
Dan Gohmanadf28172016-01-28 01:22:44 +000055 AU.addPreserved<MachineDominatorTree>();
Dan Gohman1462faa2015-11-16 16:18:28 +000056 MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
59 bool runOnMachineFunction(MachineFunction &MF) override;
60
61public:
62 static char ID; // Pass identification, replacement for typeid
63 WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
64};
65} // end anonymous namespace
66
67char WebAssemblyRegStackify::ID = 0;
68FunctionPass *llvm::createWebAssemblyRegStackify() {
69 return new WebAssemblyRegStackify();
70}
71
Dan Gohmanb0992da2015-11-20 02:19:12 +000072// Decorate the given instruction with implicit operands that enforce the
Dan Gohman8887d1f2015-12-25 00:31:02 +000073// expression stack ordering constraints for an instruction which is on
74// the expression stack.
75static void ImposeStackOrdering(MachineInstr *MI) {
Dan Gohman4da4abd2015-12-05 00:51:40 +000076 // Write the opaque EXPR_STACK register.
77 if (!MI->definesRegister(WebAssembly::EXPR_STACK))
78 MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
79 /*isDef=*/true,
80 /*isImp=*/true));
Dan Gohman4da4abd2015-12-05 00:51:40 +000081
82 // Also read the opaque EXPR_STACK register.
Dan Gohmana712a6c2015-12-14 22:37:23 +000083 if (!MI->readsRegister(WebAssembly::EXPR_STACK))
84 MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
85 /*isDef=*/false,
86 /*isImp=*/true));
Dan Gohmanb0992da2015-11-20 02:19:12 +000087}
88
Dan Gohman2644d742016-05-17 04:05:31 +000089// Determine whether a call to the callee referenced by
90// MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
91// effects.
92static void QueryCallee(const MachineInstr *MI, unsigned CalleeOpNo,
93 bool &Read, bool &Write, bool &Effects) {
94 const MachineOperand &MO = MI->getOperand(CalleeOpNo);
95 if (MO.isGlobal()) {
96 const Constant *GV = MO.getGlobal();
97 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
98 if (!GA->isInterposable())
99 GV = GA->getAliasee();
100
101 if (const Function *F = dyn_cast<Function>(GV)) {
102 if (!F->doesNotThrow())
103 Effects = true;
104 if (F->doesNotAccessMemory())
105 return;
106 if (F->onlyReadsMemory()) {
107 Read = true;
108 return;
109 }
110 }
111 }
112
113 // Assume the worst.
114 Write = true;
115 Read = true;
116 Effects = true;
117}
118
119// Determine whether MI reads memory, writes memory, and/or has side
120// effects.
121static void Query(const MachineInstr *MI, AliasAnalysis &AA,
122 bool &Read, bool &Write, bool &Effects) {
123 assert(!MI->isPosition());
124 assert(!MI->isTerminator());
125 assert(!MI->isDebugValue());
126
127 // Check for loads.
128 if (MI->mayLoad() && !MI->isInvariantLoad(&AA))
129 Read = true;
130
131 // Check for stores.
132 if (MI->mayStore())
133 Write = true;
134 else if (MI->hasOrderedMemoryRef()) {
135 switch (MI->getOpcode()) {
136 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
137 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
138 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
139 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
140 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
141 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
142 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
143 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
144 // These instruction have hasUnmodeledSideEffects() returning true
145 // because they trap on overflow and invalid so they can't be arbitrarily
146 // moved, however hasOrderedMemoryRef() interprets this plus their lack
147 // of memoperands as having a potential unknown memory reference.
148 break;
149 default:
150 // Record potential stores, unless it's a call, as calls are handled
151 // specially below.
152 if (!MI->isCall())
153 Write = true;
154 break;
155 }
156 }
157
158 // Check for side effects.
159 if (MI->hasUnmodeledSideEffects()) {
160 switch (MI->getOpcode()) {
161 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
162 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
163 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
164 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
165 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
166 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
167 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
168 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
169 // These instructions have hasUnmodeledSideEffects() returning true
170 // because they trap on overflow and invalid so they can't be arbitrarily
171 // moved, however in the specific case of register stackifying, it is safe
172 // to move them because overflow and invalid are Undefined Behavior.
173 break;
174 default:
175 Effects = true;
176 break;
177 }
178 }
179
180 // Analyze calls.
181 if (MI->isCall()) {
182 switch (MI->getOpcode()) {
183 case WebAssembly::CALL_VOID:
184 QueryCallee(MI, 0, Read, Write, Effects);
185 break;
186 case WebAssembly::CALL_I32:
187 case WebAssembly::CALL_I64:
188 case WebAssembly::CALL_F32:
189 case WebAssembly::CALL_F64:
190 QueryCallee(MI, 1, Read, Write, Effects);
191 break;
192 case WebAssembly::CALL_INDIRECT_VOID:
193 case WebAssembly::CALL_INDIRECT_I32:
194 case WebAssembly::CALL_INDIRECT_I64:
195 case WebAssembly::CALL_INDIRECT_F32:
196 case WebAssembly::CALL_INDIRECT_F64:
197 Read = true;
198 Write = true;
199 Effects = true;
200 break;
201 default:
202 llvm_unreachable("unexpected call opcode");
203 }
204 }
205}
206
207// Test whether Def is safe and profitable to rematerialize.
208static bool ShouldRematerialize(const MachineInstr *Def, AliasAnalysis &AA,
209 const WebAssemblyInstrInfo *TII) {
210 return Def->isAsCheapAsAMove() &&
211 TII->isTriviallyReMaterializable(Def, &AA);
212}
213
Dan Gohman12de0b92016-05-17 20:19:47 +0000214// Identify the definition for this register at this point. This is a
215// generalization of MachineRegisterInfo::getUniqueVRegDef that uses
216// LiveIntervals to handle complex cases.
Dan Gohman2644d742016-05-17 04:05:31 +0000217static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
218 const MachineRegisterInfo &MRI,
219 const LiveIntervals &LIS)
220{
221 // Most registers are in SSA form here so we try a quick MRI query first.
222 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
223 return Def;
224
225 // MRI doesn't know what the Def is. Try asking LIS.
226 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
227 LIS.getInstructionIndex(*Insert)))
228 return LIS.getInstructionFromIndex(ValNo->def);
229
230 return nullptr;
231}
232
Dan Gohman12de0b92016-05-17 20:19:47 +0000233// Test whether Reg, as defined at Def, has exactly one use. This is a
234// generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
235// to handle complex cases.
236static bool HasOneUse(unsigned Reg, MachineInstr *Def,
237 MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
238 LiveIntervals &LIS) {
239 // Most registers are in SSA form here so we try a quick MRI query first.
240 if (MRI.hasOneUse(Reg))
241 return true;
242
243 bool HasOne = false;
244 const LiveInterval &LI = LIS.getInterval(Reg);
245 const VNInfo *DefVNI = LI.getVNInfoAt(
246 LIS.getInstructionIndex(*Def).getRegSlot());
247 assert(DefVNI);
248 for (auto I : MRI.use_operands(Reg)) {
249 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
250 if (Result.valueIn() == DefVNI) {
251 if (!Result.isKill())
252 return false;
253 if (HasOne)
254 return false;
255 HasOne = true;
256 }
257 }
258 return HasOne;
259}
260
Dan Gohman8887d1f2015-12-25 00:31:02 +0000261// Test whether it's safe to move Def to just before Insert.
Dan Gohman81719f82015-11-25 16:55:01 +0000262// TODO: Compute memory dependencies in a way that doesn't require always
263// walking the block.
264// TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
265// more precise.
266static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
Dan Gohmanadf28172016-01-28 01:22:44 +0000267 AliasAnalysis &AA, const LiveIntervals &LIS,
268 const MachineRegisterInfo &MRI) {
Dan Gohman391a98a2015-12-03 23:07:03 +0000269 assert(Def->getParent() == Insert->getParent());
Dan Gohman8887d1f2015-12-25 00:31:02 +0000270
271 // Check for register dependencies.
272 for (const MachineOperand &MO : Def->operands()) {
273 if (!MO.isReg() || MO.isUndef())
274 continue;
275 unsigned Reg = MO.getReg();
276
277 // If the register is dead here and at Insert, ignore it.
278 if (MO.isDead() && Insert->definesRegister(Reg) &&
279 !Insert->readsRegister(Reg))
280 continue;
281
282 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000283 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
284 // from moving down, and we've already checked for that.
285 if (Reg == WebAssembly::ARGUMENTS)
286 continue;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000287 // If the physical register is never modified, ignore it.
288 if (!MRI.isPhysRegModified(Reg))
289 continue;
290 // Otherwise, it's a physical register with unknown liveness.
291 return false;
292 }
293
294 // Ask LiveIntervals whether moving this virtual register use or def to
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000295 // Insert will change which value numbers are seen.
Dan Gohman12de0b92016-05-17 20:19:47 +0000296 //
297 // If the operand is a use of a register that is also defined in the same
298 // instruction, test that the newly defined value reaches the insert point,
299 // since the operand will be moving along with the def.
Dan Gohman8887d1f2015-12-25 00:31:02 +0000300 const LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000301 VNInfo *DefVNI =
Dan Gohman12de0b92016-05-17 20:19:47 +0000302 (MO.isDef() || Def->definesRegister(Reg)) ?
303 LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) :
304 LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
Dan Gohman8887d1f2015-12-25 00:31:02 +0000305 assert(DefVNI && "Instruction input missing value number");
JF Bastien13d3b9b2016-02-27 16:38:23 +0000306 VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
Dan Gohman8887d1f2015-12-25 00:31:02 +0000307 if (InsVNI && DefVNI != InsVNI)
308 return false;
309 }
310
Dan Gohman2644d742016-05-17 04:05:31 +0000311 bool Read = false, Write = false, Effects = false;
312 Query(Def, AA, Read, Write, Effects);
313
314 // If the instruction does not access memory and has no side effects, it has
315 // no additional dependencies.
316 if (!Read && !Write && !Effects)
317 return true;
318
319 // Scan through the intervening instructions between Def and Insert.
320 MachineBasicBlock::const_iterator D(Def), I(Insert);
321 for (--I; I != D; --I) {
322 bool InterveningRead = false;
323 bool InterveningWrite = false;
324 bool InterveningEffects = false;
325 Query(I, AA, InterveningRead, InterveningWrite, InterveningEffects);
326 if (Effects && InterveningEffects)
327 return false;
328 if (Read && InterveningWrite)
329 return false;
330 if (Write && (InterveningRead || InterveningWrite))
331 return false;
332 }
333
334 return true;
Dan Gohman81719f82015-11-25 16:55:01 +0000335}
336
Dan Gohmanadf28172016-01-28 01:22:44 +0000337/// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
338static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
339 const MachineBasicBlock &MBB,
340 const MachineRegisterInfo &MRI,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000341 const MachineDominatorTree &MDT,
342 LiveIntervals &LIS) {
343 const LiveInterval &LI = LIS.getInterval(Reg);
344
345 const MachineInstr *OneUseInst = OneUse.getParent();
346 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
347
Dan Gohmanadf28172016-01-28 01:22:44 +0000348 for (const MachineOperand &Use : MRI.use_operands(Reg)) {
349 if (&Use == &OneUse)
350 continue;
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000351
Dan Gohmanadf28172016-01-28 01:22:44 +0000352 const MachineInstr *UseInst = Use.getParent();
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000353 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
354
355 if (UseVNI != OneUseVNI)
356 continue;
357
Dan Gohmanadf28172016-01-28 01:22:44 +0000358 const MachineInstr *OneUseInst = OneUse.getParent();
Dan Gohman12de0b92016-05-17 20:19:47 +0000359 if (UseInst == OneUseInst) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000360 // Another use in the same instruction. We need to ensure that the one
361 // selected use happens "before" it.
362 if (&OneUse > &Use)
363 return false;
364 } else {
365 // Test that the use is dominated by the one selected use.
366 if (!MDT.dominates(OneUseInst, UseInst))
367 return false;
368 }
369 }
370 return true;
371}
372
373/// Get the appropriate tee_local opcode for the given register class.
374static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
375 if (RC == &WebAssembly::I32RegClass)
376 return WebAssembly::TEE_LOCAL_I32;
377 if (RC == &WebAssembly::I64RegClass)
378 return WebAssembly::TEE_LOCAL_I64;
379 if (RC == &WebAssembly::F32RegClass)
380 return WebAssembly::TEE_LOCAL_F32;
381 if (RC == &WebAssembly::F64RegClass)
382 return WebAssembly::TEE_LOCAL_F64;
383 llvm_unreachable("Unexpected register class");
384}
385
Dan Gohman2644d742016-05-17 04:05:31 +0000386// Shrink LI to its uses, cleaning up LI.
387static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
388 if (LIS.shrinkToUses(&LI)) {
389 SmallVector<LiveInterval*, 4> SplitLIs;
390 LIS.splitSeparateComponents(LI, SplitLIs);
391 }
392}
393
Dan Gohmanadf28172016-01-28 01:22:44 +0000394/// A single-use def in the same block with no intervening memory or register
395/// dependencies; move the def down and nest it with the current instruction.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000396static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
397 MachineInstr *Def,
Dan Gohmanadf28172016-01-28 01:22:44 +0000398 MachineBasicBlock &MBB,
399 MachineInstr *Insert, LiveIntervals &LIS,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000400 WebAssemblyFunctionInfo &MFI,
401 MachineRegisterInfo &MRI) {
Dan Gohman2644d742016-05-17 04:05:31 +0000402 DEBUG(dbgs() << "Move for single use: "; Def->dump());
403
Dan Gohmanadf28172016-01-28 01:22:44 +0000404 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000405 LIS.handleMove(*Def);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000406
Dan Gohman12de0b92016-05-17 20:19:47 +0000407 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
408 // No one else is using this register for anything so we can just stackify
409 // it in place.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000410 MFI.stackifyVReg(Reg);
411 } else {
Dan Gohman12de0b92016-05-17 20:19:47 +0000412 // The register may have unrelated uses or defs; create a new register for
413 // just our one def and use so that we can stackify it.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000414 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
415 Def->getOperand(0).setReg(NewReg);
416 Op.setReg(NewReg);
417
418 // Tell LiveIntervals about the new register.
419 LIS.createAndComputeVirtRegInterval(NewReg);
420
421 // Tell LiveIntervals about the changes to the old register.
422 LiveInterval &LI = LIS.getInterval(Reg);
423 LIS.removeVRegDefAt(LI, LIS.getInstructionIndex(*Def).getRegSlot());
Dan Gohman2644d742016-05-17 04:05:31 +0000424 ShrinkToUses(LI, LIS);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000425
426 MFI.stackifyVReg(NewReg);
Dan Gohman2644d742016-05-17 04:05:31 +0000427
428 DEBUG(dbgs() << " - Replaced register: "; Def->dump());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000429 }
430
Dan Gohmanadf28172016-01-28 01:22:44 +0000431 ImposeStackOrdering(Def);
432 return Def;
433}
434
435/// A trivially cloneable instruction; clone it and nest the new copy with the
436/// current instruction.
437static MachineInstr *
438RematerializeCheapDef(unsigned Reg, MachineOperand &Op, MachineInstr *Def,
439 MachineBasicBlock &MBB, MachineInstr *Insert,
440 LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
441 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII,
442 const WebAssemblyRegisterInfo *TRI) {
Dan Gohman2644d742016-05-17 04:05:31 +0000443 DEBUG(dbgs() << "Rematerializing cheap def: "; Def->dump());
444 DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
445
Dan Gohmanadf28172016-01-28 01:22:44 +0000446 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
447 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
448 Op.setReg(NewReg);
449 MachineInstr *Clone = &*std::prev(MachineBasicBlock::instr_iterator(Insert));
JF Bastien13d3b9b2016-02-27 16:38:23 +0000450 LIS.InsertMachineInstrInMaps(*Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000451 LIS.createAndComputeVirtRegInterval(NewReg);
452 MFI.stackifyVReg(NewReg);
453 ImposeStackOrdering(Clone);
454
Dan Gohman2644d742016-05-17 04:05:31 +0000455 DEBUG(dbgs() << " - Cloned to "; Clone->dump());
456
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000457 // Shrink the interval.
458 bool IsDead = MRI.use_empty(Reg);
459 if (!IsDead) {
460 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman2644d742016-05-17 04:05:31 +0000461 ShrinkToUses(LI, LIS);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000462 IsDead = !LI.liveAt(LIS.getInstructionIndex(*Def).getDeadSlot());
463 }
464
Dan Gohmanadf28172016-01-28 01:22:44 +0000465 // If that was the last use of the original, delete the original.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000466 if (IsDead) {
Dan Gohman2644d742016-05-17 04:05:31 +0000467 DEBUG(dbgs() << " - Deleting original\n");
JF Bastien13d3b9b2016-02-27 16:38:23 +0000468 SlotIndex Idx = LIS.getInstructionIndex(*Def).getRegSlot();
Dan Gohmanadf28172016-01-28 01:22:44 +0000469 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
Dan Gohmanadf28172016-01-28 01:22:44 +0000470 LIS.removeInterval(Reg);
JF Bastien13d3b9b2016-02-27 16:38:23 +0000471 LIS.RemoveMachineInstrFromMaps(*Def);
Dan Gohmanadf28172016-01-28 01:22:44 +0000472 Def->eraseFromParent();
Dan Gohmanadf28172016-01-28 01:22:44 +0000473 }
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000474
Dan Gohmanadf28172016-01-28 01:22:44 +0000475 return Clone;
476}
477
478/// A multiple-use def in the same block with no intervening memory or register
479/// dependencies; move the def down, nest it with the current instruction, and
480/// insert a tee_local to satisfy the rest of the uses. As an illustration,
481/// rewrite this:
482///
483/// Reg = INST ... // Def
484/// INST ..., Reg, ... // Insert
485/// INST ..., Reg, ...
486/// INST ..., Reg, ...
487///
488/// to this:
489///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000490/// DefReg = INST ... // Def (to become the new Insert)
Dan Gohman12de0b92016-05-17 20:19:47 +0000491/// TeeReg, Reg = TEE_LOCAL_... DefReg
Dan Gohmanadf28172016-01-28 01:22:44 +0000492/// INST ..., TeeReg, ... // Insert
493/// INST ..., NewReg, ...
494/// INST ..., NewReg, ...
495///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000496/// with DefReg and TeeReg stackified. This eliminates a get_local from the
Dan Gohmanadf28172016-01-28 01:22:44 +0000497/// resulting code.
498static MachineInstr *MoveAndTeeForMultiUse(
499 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
500 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
501 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
Dan Gohman2644d742016-05-17 04:05:31 +0000502 DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
503
Dan Gohman12de0b92016-05-17 20:19:47 +0000504 // Move Def into place.
Dan Gohmanadf28172016-01-28 01:22:44 +0000505 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000506 LIS.handleMove(*Def);
Dan Gohman12de0b92016-05-17 20:19:47 +0000507
508 // Create the Tee and attach the registers.
Dan Gohmanadf28172016-01-28 01:22:44 +0000509 const auto *RegClass = MRI.getRegClass(Reg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000510 unsigned TeeReg = MRI.createVirtualRegister(RegClass);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000511 unsigned DefReg = MRI.createVirtualRegister(RegClass);
Dan Gohman33e694a2016-05-12 04:19:09 +0000512 MachineOperand &DefMO = Def->getOperand(0);
Dan Gohmanadf28172016-01-28 01:22:44 +0000513 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
514 TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
Dan Gohman12de0b92016-05-17 20:19:47 +0000515 .addReg(Reg, RegState::Define)
Dan Gohman33e694a2016-05-12 04:19:09 +0000516 .addReg(DefReg, getUndefRegState(DefMO.isDead()));
Dan Gohmanadf28172016-01-28 01:22:44 +0000517 Op.setReg(TeeReg);
Dan Gohman33e694a2016-05-12 04:19:09 +0000518 DefMO.setReg(DefReg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000519 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
520 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
521
522 // Tell LiveIntervals we moved the original vreg def from Def to Tee.
523 LiveInterval &LI = LIS.getInterval(Reg);
524 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
525 VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
526 I->start = TeeIdx;
527 ValNo->def = TeeIdx;
528 ShrinkToUses(LI, LIS);
529
530 // Finish stackifying the new regs.
Dan Gohmanadf28172016-01-28 01:22:44 +0000531 LIS.createAndComputeVirtRegInterval(TeeReg);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000532 LIS.createAndComputeVirtRegInterval(DefReg);
533 MFI.stackifyVReg(DefReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000534 MFI.stackifyVReg(TeeReg);
535 ImposeStackOrdering(Def);
536 ImposeStackOrdering(Tee);
Dan Gohman12de0b92016-05-17 20:19:47 +0000537
538 DEBUG(dbgs() << " - Replaced register: "; Def->dump());
539 DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
Dan Gohmanadf28172016-01-28 01:22:44 +0000540 return Def;
541}
542
543namespace {
544/// A stack for walking the tree of instructions being built, visiting the
545/// MachineOperands in DFS order.
546class TreeWalkerState {
547 typedef MachineInstr::mop_iterator mop_iterator;
548 typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
549 typedef iterator_range<mop_reverse_iterator> RangeTy;
550 SmallVector<RangeTy, 4> Worklist;
551
552public:
553 explicit TreeWalkerState(MachineInstr *Insert) {
554 const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
555 if (Range.begin() != Range.end())
556 Worklist.push_back(reverse(Range));
557 }
558
559 bool Done() const { return Worklist.empty(); }
560
561 MachineOperand &Pop() {
562 RangeTy &Range = Worklist.back();
563 MachineOperand &Op = *Range.begin();
564 Range = drop_begin(Range, 1);
565 if (Range.begin() == Range.end())
566 Worklist.pop_back();
567 assert((Worklist.empty() ||
568 Worklist.back().begin() != Worklist.back().end()) &&
569 "Empty ranges shouldn't remain in the worklist");
570 return Op;
571 }
572
573 /// Push Instr's operands onto the stack to be visited.
574 void PushOperands(MachineInstr *Instr) {
575 const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
576 if (Range.begin() != Range.end())
577 Worklist.push_back(reverse(Range));
578 }
579
580 /// Some of Instr's operands are on the top of the stack; remove them and
581 /// re-insert them starting from the beginning (because we've commuted them).
582 void ResetTopOperands(MachineInstr *Instr) {
583 assert(HasRemainingOperands(Instr) &&
584 "Reseting operands should only be done when the instruction has "
585 "an operand still on the stack");
586 Worklist.back() = reverse(Instr->explicit_uses());
587 }
588
589 /// Test whether Instr has operands remaining to be visited at the top of
590 /// the stack.
591 bool HasRemainingOperands(const MachineInstr *Instr) const {
592 if (Worklist.empty())
593 return false;
594 const RangeTy &Range = Worklist.back();
595 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
596 }
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000597
598 /// Test whether the given register is present on the stack, indicating an
599 /// operand in the tree that we haven't visited yet. Moving a definition of
600 /// Reg to a point in the tree after that would change its value.
601 bool IsOnStack(unsigned Reg) const {
602 for (const RangeTy &Range : Worklist)
603 for (const MachineOperand &MO : Range)
604 if (MO.isReg() && MO.getReg() == Reg)
605 return true;
606 return false;
607 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000608};
609
610/// State to keep track of whether commuting is in flight or whether it's been
611/// tried for the current instruction and didn't work.
612class CommutingState {
613 /// There are effectively three states: the initial state where we haven't
614 /// started commuting anything and we don't know anything yet, the tenative
615 /// state where we've commuted the operands of the current instruction and are
616 /// revisting it, and the declined state where we've reverted the operands
617 /// back to their original order and will no longer commute it further.
618 bool TentativelyCommuting;
619 bool Declined;
620
621 /// During the tentative state, these hold the operand indices of the commuted
622 /// operands.
623 unsigned Operand0, Operand1;
624
625public:
626 CommutingState() : TentativelyCommuting(false), Declined(false) {}
627
628 /// Stackification for an operand was not successful due to ordering
629 /// constraints. If possible, and if we haven't already tried it and declined
630 /// it, commute Insert's operands and prepare to revisit it.
631 void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
632 const WebAssemblyInstrInfo *TII) {
633 if (TentativelyCommuting) {
634 assert(!Declined &&
635 "Don't decline commuting until you've finished trying it");
636 // Commuting didn't help. Revert it.
637 TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
638 TentativelyCommuting = false;
639 Declined = true;
640 } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
641 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
642 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
643 if (TII->findCommutedOpIndices(Insert, Operand0, Operand1)) {
644 // Tentatively commute the operands and try again.
645 TII->commuteInstruction(Insert, /*NewMI=*/false, Operand0, Operand1);
646 TreeWalker.ResetTopOperands(Insert);
647 TentativelyCommuting = true;
648 Declined = false;
649 }
650 }
651 }
652
653 /// Stackification for some operand was successful. Reset to the default
654 /// state.
655 void Reset() {
656 TentativelyCommuting = false;
657 Declined = false;
658 }
659};
660} // end anonymous namespace
661
Dan Gohman1462faa2015-11-16 16:18:28 +0000662bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
663 DEBUG(dbgs() << "********** Register Stackifying **********\n"
664 "********** Function: "
665 << MF.getName() << '\n');
666
667 bool Changed = false;
668 MachineRegisterInfo &MRI = MF.getRegInfo();
669 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000670 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
671 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
Dan Gohman81719f82015-11-25 16:55:01 +0000672 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Dan Gohmanadf28172016-01-28 01:22:44 +0000673 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +0000674 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
Dan Gohmand70e5902015-12-08 03:30:42 +0000675
Dan Gohman1462faa2015-11-16 16:18:28 +0000676 // Walk the instructions from the bottom up. Currently we don't look past
677 // block boundaries, and the blocks aren't ordered so the block visitation
678 // order isn't significant, but we may want to change this in the future.
679 for (MachineBasicBlock &MBB : MF) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000680 // Don't use a range-based for loop, because we modify the list as we're
681 // iterating over it and the end iterator may change.
682 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
683 MachineInstr *Insert = &*MII;
Dan Gohman81719f82015-11-25 16:55:01 +0000684 // Don't nest anything inside an inline asm, because we don't have
685 // constraints for $push inputs.
686 if (Insert->getOpcode() == TargetOpcode::INLINEASM)
Dan Gohman595e8ab2016-02-22 17:45:20 +0000687 continue;
688
689 // Ignore debugging intrinsics.
690 if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
691 continue;
Dan Gohman81719f82015-11-25 16:55:01 +0000692
Dan Gohman1462faa2015-11-16 16:18:28 +0000693 // Iterate through the inputs in reverse order, since we'll be pulling
Dan Gohman53d13992015-12-02 18:08:49 +0000694 // operands off the stack in LIFO order.
Dan Gohmanadf28172016-01-28 01:22:44 +0000695 CommutingState Commuting;
696 TreeWalkerState TreeWalker(Insert);
697 while (!TreeWalker.Done()) {
698 MachineOperand &Op = TreeWalker.Pop();
699
Dan Gohman1462faa2015-11-16 16:18:28 +0000700 // We're only interested in explicit virtual register operands.
Dan Gohmanadf28172016-01-28 01:22:44 +0000701 if (!Op.isReg())
Dan Gohman1462faa2015-11-16 16:18:28 +0000702 continue;
703
704 unsigned Reg = Op.getReg();
Dan Gohmanadf28172016-01-28 01:22:44 +0000705 assert(Op.isUse() && "explicit_uses() should only iterate over uses");
706 assert(!Op.isImplicit() &&
707 "explicit_uses() should only iterate over explicit operands");
708 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Dan Gohman1462faa2015-11-16 16:18:28 +0000709 continue;
710
Dan Gohmanadf28172016-01-28 01:22:44 +0000711 // Identify the definition for this register at this point. Most
712 // registers are in SSA form here so we try a quick MRI query first.
Dan Gohman2644d742016-05-17 04:05:31 +0000713 MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
714 if (!Def)
715 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000716
Dan Gohman81719f82015-11-25 16:55:01 +0000717 // Don't nest an INLINE_ASM def into anything, because we don't have
718 // constraints for $pop outputs.
719 if (Def->getOpcode() == TargetOpcode::INLINEASM)
720 continue;
721
Dan Gohman4ba48162015-11-18 16:12:01 +0000722 // Argument instructions represent live-in registers and not real
723 // instructions.
724 if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
725 Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
726 Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
727 Def->getOpcode() == WebAssembly::ARGUMENT_F64)
728 continue;
729
Dan Gohmanadf28172016-01-28 01:22:44 +0000730 // Decide which strategy to take. Prefer to move a single-use value
731 // over cloning it, and prefer cloning over introducing a tee_local.
732 // For moving, we require the def to be in the same block as the use;
733 // this makes things simpler (LiveIntervals' handleMove function only
734 // supports intra-block moves) and it's MachineSink's job to catch all
735 // the sinking opportunities anyway.
736 bool SameBlock = Def->getParent() == &MBB;
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000737 bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
738 !TreeWalker.IsOnStack(Reg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000739 if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000740 Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
Dan Gohman2644d742016-05-17 04:05:31 +0000741 } else if (ShouldRematerialize(Def, AA, TII)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000742 Insert = RematerializeCheapDef(Reg, Op, Def, MBB, Insert, LIS, MFI,
743 MRI, TII, TRI);
744 } else if (CanMove &&
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000745 OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000746 Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
747 MRI, TII);
748 } else {
749 // We failed to stackify the operand. If the problem was ordering
750 // constraints, Commuting may be able to help.
751 if (!CanMove && SameBlock)
752 Commuting.MaybeCommute(Insert, TreeWalker, TII);
753 // Proceed to the next operand.
754 continue;
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000755 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000756
757 // We stackified an operand. Add the defining instruction's operands to
758 // the worklist stack now to continue to build an ever deeper tree.
759 Commuting.Reset();
760 TreeWalker.PushOperands(Insert);
Dan Gohman1462faa2015-11-16 16:18:28 +0000761 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000762
763 // If we stackified any operands, skip over the tree to start looking for
764 // the next instruction we can build a tree on.
765 if (Insert != &*MII) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000766 ImposeStackOrdering(&*MII);
Dan Gohmanadf28172016-01-28 01:22:44 +0000767 MII = std::prev(
Hans Wennborg369ebfe2016-03-14 11:04:15 +0000768 llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
Dan Gohmanadf28172016-01-28 01:22:44 +0000769 Changed = true;
770 }
Dan Gohman1462faa2015-11-16 16:18:28 +0000771 }
772 }
773
Dan Gohmanadf28172016-01-28 01:22:44 +0000774 // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
775 // that it never looks like a use-before-def.
Dan Gohmanb0992da2015-11-20 02:19:12 +0000776 if (Changed) {
777 MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
778 for (MachineBasicBlock &MBB : MF)
779 MBB.addLiveIn(WebAssembly::EXPR_STACK);
780 }
781
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000782#ifndef NDEBUG
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000783 // Verify that pushes and pops are performed in LIFO order.
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000784 SmallVector<unsigned, 0> Stack;
785 for (MachineBasicBlock &MBB : MF) {
786 for (MachineInstr &MI : MBB) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000787 if (MI.isDebugValue())
788 continue;
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000789 for (MachineOperand &MO : reverse(MI.explicit_operands())) {
Dan Gohman7a6b9822015-11-29 22:32:02 +0000790 if (!MO.isReg())
791 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000792 unsigned Reg = MO.getReg();
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000793
Dan Gohmanadf28172016-01-28 01:22:44 +0000794 if (MFI.isVRegStackified(Reg)) {
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000795 if (MO.isDef())
Dan Gohmanadf28172016-01-28 01:22:44 +0000796 Stack.push_back(Reg);
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000797 else
Dan Gohmanadf28172016-01-28 01:22:44 +0000798 assert(Stack.pop_back_val() == Reg &&
799 "Register stack pop should be paired with a push");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000800 }
801 }
802 }
803 // TODO: Generalize this code to support keeping values on the stack across
804 // basic block boundaries.
Dan Gohmanadf28172016-01-28 01:22:44 +0000805 assert(Stack.empty() &&
806 "Register stack pushes and pops should be balanced");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000807 }
808#endif
809
Dan Gohman1462faa2015-11-16 16:18:28 +0000810 return Changed;
811}