xref: /freebsd/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyRegStackify.cpp (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a register stacking pass.
11 ///
12 /// This pass reorders instructions to put register uses and defs in an order
13 /// such that they form single-use expression trees. Registers fitting this form
14 /// are then marked as "stackified", meaning references to them are replaced by
15 /// "push" and "pop" from the value stack.
16 ///
17 /// This is primarily a code size optimization, since temporary values on the
18 /// value stack don't need to be named.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
23 #include "Utils/WebAssemblyUtilities.h"
24 #include "WebAssembly.h"
25 #include "WebAssemblyDebugValueManager.h"
26 #include "WebAssemblyMachineFunctionInfo.h"
27 #include "WebAssemblySubtarget.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/CodeGen/LiveIntervals.h"
31 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <iterator>
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "wasm-reg-stackify"
43 
44 namespace {
45 class WebAssemblyRegStackify final : public MachineFunctionPass {
46   StringRef getPassName() const override {
47     return "WebAssembly Register Stackify";
48   }
49 
50   void getAnalysisUsage(AnalysisUsage &AU) const override {
51     AU.setPreservesCFG();
52     AU.addRequired<MachineDominatorTree>();
53     AU.addRequired<LiveIntervals>();
54     AU.addPreserved<MachineBlockFrequencyInfo>();
55     AU.addPreserved<SlotIndexes>();
56     AU.addPreserved<LiveIntervals>();
57     AU.addPreservedID(LiveVariablesID);
58     AU.addPreserved<MachineDominatorTree>();
59     MachineFunctionPass::getAnalysisUsage(AU);
60   }
61 
62   bool runOnMachineFunction(MachineFunction &MF) override;
63 
64 public:
65   static char ID; // Pass identification, replacement for typeid
66   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
67 };
68 } // end anonymous namespace
69 
70 char WebAssemblyRegStackify::ID = 0;
71 INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
72                 "Reorder instructions to use the WebAssembly value stack",
73                 false, false)
74 
75 FunctionPass *llvm::createWebAssemblyRegStackify() {
76   return new WebAssemblyRegStackify();
77 }
78 
79 // Decorate the given instruction with implicit operands that enforce the
80 // expression stack ordering constraints for an instruction which is on
81 // the expression stack.
82 static void imposeStackOrdering(MachineInstr *MI) {
83   // Write the opaque VALUE_STACK register.
84   if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
86                                              /*isDef=*/true,
87                                              /*isImp=*/true));
88 
89   // Also read the opaque VALUE_STACK register.
90   if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91     MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
92                                              /*isDef=*/false,
93                                              /*isImp=*/true));
94 }
95 
96 // Convert an IMPLICIT_DEF instruction into an instruction which defines
97 // a constant zero value.
98 static void convertImplicitDefToConstZero(MachineInstr *MI,
99                                           MachineRegisterInfo &MRI,
100                                           const TargetInstrInfo *TII,
101                                           MachineFunction &MF,
102                                           LiveIntervals &LIS) {
103   assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
104 
105   const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
106   if (RegClass == &WebAssembly::I32RegClass) {
107     MI->setDesc(TII->get(WebAssembly::CONST_I32));
108     MI->addOperand(MachineOperand::CreateImm(0));
109   } else if (RegClass == &WebAssembly::I64RegClass) {
110     MI->setDesc(TII->get(WebAssembly::CONST_I64));
111     MI->addOperand(MachineOperand::CreateImm(0));
112   } else if (RegClass == &WebAssembly::F32RegClass) {
113     MI->setDesc(TII->get(WebAssembly::CONST_F32));
114     auto *Val = cast<ConstantFP>(Constant::getNullValue(
115         Type::getFloatTy(MF.getFunction().getContext())));
116     MI->addOperand(MachineOperand::CreateFPImm(Val));
117   } else if (RegClass == &WebAssembly::F64RegClass) {
118     MI->setDesc(TII->get(WebAssembly::CONST_F64));
119     auto *Val = cast<ConstantFP>(Constant::getNullValue(
120         Type::getDoubleTy(MF.getFunction().getContext())));
121     MI->addOperand(MachineOperand::CreateFPImm(Val));
122   } else if (RegClass == &WebAssembly::V128RegClass) {
123     MI->setDesc(TII->get(WebAssembly::CONST_V128_I64x2));
124     MI->addOperand(MachineOperand::CreateImm(0));
125     MI->addOperand(MachineOperand::CreateImm(0));
126   } else {
127     llvm_unreachable("Unexpected reg class");
128   }
129 }
130 
131 // Determine whether a call to the callee referenced by
132 // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
133 // effects.
134 static void queryCallee(const MachineInstr &MI, bool &Read, bool &Write,
135                         bool &Effects, bool &StackPointer) {
136   // All calls can use the stack pointer.
137   StackPointer = true;
138 
139   const MachineOperand &MO = WebAssembly::getCalleeOp(MI);
140   if (MO.isGlobal()) {
141     const Constant *GV = MO.getGlobal();
142     if (const auto *GA = dyn_cast<GlobalAlias>(GV))
143       if (!GA->isInterposable())
144         GV = GA->getAliasee();
145 
146     if (const auto *F = dyn_cast<Function>(GV)) {
147       if (!F->doesNotThrow())
148         Effects = true;
149       if (F->doesNotAccessMemory())
150         return;
151       if (F->onlyReadsMemory()) {
152         Read = true;
153         return;
154       }
155     }
156   }
157 
158   // Assume the worst.
159   Write = true;
160   Read = true;
161   Effects = true;
162 }
163 
164 // Determine whether MI reads memory, writes memory, has side effects,
165 // and/or uses the stack pointer value.
166 static void query(const MachineInstr &MI, bool &Read, bool &Write,
167                   bool &Effects, bool &StackPointer) {
168   assert(!MI.isTerminator());
169 
170   if (MI.isDebugInstr() || MI.isPosition())
171     return;
172 
173   // Check for loads.
174   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
175     Read = true;
176 
177   // Check for stores.
178   if (MI.mayStore()) {
179     Write = true;
180   } else if (MI.hasOrderedMemoryRef()) {
181     switch (MI.getOpcode()) {
182     case WebAssembly::DIV_S_I32:
183     case WebAssembly::DIV_S_I64:
184     case WebAssembly::REM_S_I32:
185     case WebAssembly::REM_S_I64:
186     case WebAssembly::DIV_U_I32:
187     case WebAssembly::DIV_U_I64:
188     case WebAssembly::REM_U_I32:
189     case WebAssembly::REM_U_I64:
190     case WebAssembly::I32_TRUNC_S_F32:
191     case WebAssembly::I64_TRUNC_S_F32:
192     case WebAssembly::I32_TRUNC_S_F64:
193     case WebAssembly::I64_TRUNC_S_F64:
194     case WebAssembly::I32_TRUNC_U_F32:
195     case WebAssembly::I64_TRUNC_U_F32:
196     case WebAssembly::I32_TRUNC_U_F64:
197     case WebAssembly::I64_TRUNC_U_F64:
198       // These instruction have hasUnmodeledSideEffects() returning true
199       // because they trap on overflow and invalid so they can't be arbitrarily
200       // moved, however hasOrderedMemoryRef() interprets this plus their lack
201       // of memoperands as having a potential unknown memory reference.
202       break;
203     default:
204       // Record volatile accesses, unless it's a call, as calls are handled
205       // specially below.
206       if (!MI.isCall()) {
207         Write = true;
208         Effects = true;
209       }
210       break;
211     }
212   }
213 
214   // Check for side effects.
215   if (MI.hasUnmodeledSideEffects()) {
216     switch (MI.getOpcode()) {
217     case WebAssembly::DIV_S_I32:
218     case WebAssembly::DIV_S_I64:
219     case WebAssembly::REM_S_I32:
220     case WebAssembly::REM_S_I64:
221     case WebAssembly::DIV_U_I32:
222     case WebAssembly::DIV_U_I64:
223     case WebAssembly::REM_U_I32:
224     case WebAssembly::REM_U_I64:
225     case WebAssembly::I32_TRUNC_S_F32:
226     case WebAssembly::I64_TRUNC_S_F32:
227     case WebAssembly::I32_TRUNC_S_F64:
228     case WebAssembly::I64_TRUNC_S_F64:
229     case WebAssembly::I32_TRUNC_U_F32:
230     case WebAssembly::I64_TRUNC_U_F32:
231     case WebAssembly::I32_TRUNC_U_F64:
232     case WebAssembly::I64_TRUNC_U_F64:
233       // These instructions have hasUnmodeledSideEffects() returning true
234       // because they trap on overflow and invalid so they can't be arbitrarily
235       // moved, however in the specific case of register stackifying, it is safe
236       // to move them because overflow and invalid are Undefined Behavior.
237       break;
238     default:
239       Effects = true;
240       break;
241     }
242   }
243 
244   // Check for writes to __stack_pointer global.
245   if ((MI.getOpcode() == WebAssembly::GLOBAL_SET_I32 ||
246        MI.getOpcode() == WebAssembly::GLOBAL_SET_I64) &&
247       strcmp(MI.getOperand(0).getSymbolName(), "__stack_pointer") == 0)
248     StackPointer = true;
249 
250   // Analyze calls.
251   if (MI.isCall()) {
252     queryCallee(MI, Read, Write, Effects, StackPointer);
253   }
254 }
255 
256 // Test whether Def is safe and profitable to rematerialize.
257 static bool shouldRematerialize(const MachineInstr &Def,
258                                 const WebAssemblyInstrInfo *TII) {
259   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def);
260 }
261 
262 // Identify the definition for this register at this point. This is a
263 // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
264 // LiveIntervals to handle complex cases.
265 static MachineInstr *getVRegDef(unsigned Reg, const MachineInstr *Insert,
266                                 const MachineRegisterInfo &MRI,
267                                 const LiveIntervals &LIS) {
268   // Most registers are in SSA form here so we try a quick MRI query first.
269   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
270     return Def;
271 
272   // MRI doesn't know what the Def is. Try asking LIS.
273   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
274           LIS.getInstructionIndex(*Insert)))
275     return LIS.getInstructionFromIndex(ValNo->def);
276 
277   return nullptr;
278 }
279 
280 // Test whether Reg, as defined at Def, has exactly one use. This is a
281 // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
282 // to handle complex cases.
283 static bool hasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
284                       MachineDominatorTree &MDT, LiveIntervals &LIS) {
285   // Most registers are in SSA form here so we try a quick MRI query first.
286   if (MRI.hasOneUse(Reg))
287     return true;
288 
289   bool HasOne = false;
290   const LiveInterval &LI = LIS.getInterval(Reg);
291   const VNInfo *DefVNI =
292       LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
293   assert(DefVNI);
294   for (auto &I : MRI.use_nodbg_operands(Reg)) {
295     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
296     if (Result.valueIn() == DefVNI) {
297       if (!Result.isKill())
298         return false;
299       if (HasOne)
300         return false;
301       HasOne = true;
302     }
303   }
304   return HasOne;
305 }
306 
307 // Test whether it's safe to move Def to just before Insert.
308 // TODO: Compute memory dependencies in a way that doesn't require always
309 // walking the block.
310 // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
311 // more precise.
312 static bool isSafeToMove(const MachineOperand *Def, const MachineOperand *Use,
313                          const MachineInstr *Insert,
314                          const WebAssemblyFunctionInfo &MFI,
315                          const MachineRegisterInfo &MRI) {
316   const MachineInstr *DefI = Def->getParent();
317   const MachineInstr *UseI = Use->getParent();
318   assert(DefI->getParent() == Insert->getParent());
319   assert(UseI->getParent() == Insert->getParent());
320 
321   // The first def of a multivalue instruction can be stackified by moving,
322   // since the later defs can always be placed into locals if necessary. Later
323   // defs can only be stackified if all previous defs are already stackified
324   // since ExplicitLocals will not know how to place a def in a local if a
325   // subsequent def is stackified. But only one def can be stackified by moving
326   // the instruction, so it must be the first one.
327   //
328   // TODO: This could be loosened to be the first *live* def, but care would
329   // have to be taken to ensure the drops of the initial dead defs can be
330   // placed. This would require checking that no previous defs are used in the
331   // same instruction as subsequent defs.
332   if (Def != DefI->defs().begin())
333     return false;
334 
335   // If any subsequent def is used prior to the current value by the same
336   // instruction in which the current value is used, we cannot
337   // stackify. Stackifying in this case would require that def moving below the
338   // current def in the stack, which cannot be achieved, even with locals.
339   for (const auto &SubsequentDef : drop_begin(DefI->defs())) {
340     for (const auto &PriorUse : UseI->uses()) {
341       if (&PriorUse == Use)
342         break;
343       if (PriorUse.isReg() && SubsequentDef.getReg() == PriorUse.getReg())
344         return false;
345     }
346   }
347 
348   // If moving is a semantic nop, it is always allowed
349   const MachineBasicBlock *MBB = DefI->getParent();
350   auto NextI = std::next(MachineBasicBlock::const_iterator(DefI));
351   for (auto E = MBB->end(); NextI != E && NextI->isDebugInstr(); ++NextI)
352     ;
353   if (NextI == Insert)
354     return true;
355 
356   // 'catch' and 'catch_all' should be the first instruction of a BB and cannot
357   // move.
358   if (WebAssembly::isCatch(DefI->getOpcode()))
359     return false;
360 
361   // Check for register dependencies.
362   SmallVector<unsigned, 4> MutableRegisters;
363   for (const MachineOperand &MO : DefI->operands()) {
364     if (!MO.isReg() || MO.isUndef())
365       continue;
366     Register Reg = MO.getReg();
367 
368     // If the register is dead here and at Insert, ignore it.
369     if (MO.isDead() && Insert->definesRegister(Reg) &&
370         !Insert->readsRegister(Reg))
371       continue;
372 
373     if (Register::isPhysicalRegister(Reg)) {
374       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
375       // from moving down, and we've already checked for that.
376       if (Reg == WebAssembly::ARGUMENTS)
377         continue;
378       // If the physical register is never modified, ignore it.
379       if (!MRI.isPhysRegModified(Reg))
380         continue;
381       // Otherwise, it's a physical register with unknown liveness.
382       return false;
383     }
384 
385     // If one of the operands isn't in SSA form, it has different values at
386     // different times, and we need to make sure we don't move our use across
387     // a different def.
388     if (!MO.isDef() && !MRI.hasOneDef(Reg))
389       MutableRegisters.push_back(Reg);
390   }
391 
392   bool Read = false, Write = false, Effects = false, StackPointer = false;
393   query(*DefI, Read, Write, Effects, StackPointer);
394 
395   // If the instruction does not access memory and has no side effects, it has
396   // no additional dependencies.
397   bool HasMutableRegisters = !MutableRegisters.empty();
398   if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
399     return true;
400 
401   // Scan through the intervening instructions between DefI and Insert.
402   MachineBasicBlock::const_iterator D(DefI), I(Insert);
403   for (--I; I != D; --I) {
404     bool InterveningRead = false;
405     bool InterveningWrite = false;
406     bool InterveningEffects = false;
407     bool InterveningStackPointer = false;
408     query(*I, InterveningRead, InterveningWrite, InterveningEffects,
409           InterveningStackPointer);
410     if (Effects && InterveningEffects)
411       return false;
412     if (Read && InterveningWrite)
413       return false;
414     if (Write && (InterveningRead || InterveningWrite))
415       return false;
416     if (StackPointer && InterveningStackPointer)
417       return false;
418 
419     for (unsigned Reg : MutableRegisters)
420       for (const MachineOperand &MO : I->operands())
421         if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
422           return false;
423   }
424 
425   return true;
426 }
427 
428 /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
429 static bool oneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
430                                      const MachineBasicBlock &MBB,
431                                      const MachineRegisterInfo &MRI,
432                                      const MachineDominatorTree &MDT,
433                                      LiveIntervals &LIS,
434                                      WebAssemblyFunctionInfo &MFI) {
435   const LiveInterval &LI = LIS.getInterval(Reg);
436 
437   const MachineInstr *OneUseInst = OneUse.getParent();
438   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
439 
440   for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
441     if (&Use == &OneUse)
442       continue;
443 
444     const MachineInstr *UseInst = Use.getParent();
445     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
446 
447     if (UseVNI != OneUseVNI)
448       continue;
449 
450     if (UseInst == OneUseInst) {
451       // Another use in the same instruction. We need to ensure that the one
452       // selected use happens "before" it.
453       if (&OneUse > &Use)
454         return false;
455     } else {
456       // Test that the use is dominated by the one selected use.
457       while (!MDT.dominates(OneUseInst, UseInst)) {
458         // Actually, dominating is over-conservative. Test that the use would
459         // happen after the one selected use in the stack evaluation order.
460         //
461         // This is needed as a consequence of using implicit local.gets for
462         // uses and implicit local.sets for defs.
463         if (UseInst->getDesc().getNumDefs() == 0)
464           return false;
465         const MachineOperand &MO = UseInst->getOperand(0);
466         if (!MO.isReg())
467           return false;
468         Register DefReg = MO.getReg();
469         if (!Register::isVirtualRegister(DefReg) ||
470             !MFI.isVRegStackified(DefReg))
471           return false;
472         assert(MRI.hasOneNonDBGUse(DefReg));
473         const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
474         const MachineInstr *NewUseInst = NewUse.getParent();
475         if (NewUseInst == OneUseInst) {
476           if (&OneUse > &NewUse)
477             return false;
478           break;
479         }
480         UseInst = NewUseInst;
481       }
482     }
483   }
484   return true;
485 }
486 
487 /// Get the appropriate tee opcode for the given register class.
488 static unsigned getTeeOpcode(const TargetRegisterClass *RC) {
489   if (RC == &WebAssembly::I32RegClass)
490     return WebAssembly::TEE_I32;
491   if (RC == &WebAssembly::I64RegClass)
492     return WebAssembly::TEE_I64;
493   if (RC == &WebAssembly::F32RegClass)
494     return WebAssembly::TEE_F32;
495   if (RC == &WebAssembly::F64RegClass)
496     return WebAssembly::TEE_F64;
497   if (RC == &WebAssembly::V128RegClass)
498     return WebAssembly::TEE_V128;
499   if (RC == &WebAssembly::EXTERNREFRegClass)
500     return WebAssembly::TEE_EXTERNREF;
501   if (RC == &WebAssembly::FUNCREFRegClass)
502     return WebAssembly::TEE_FUNCREF;
503   llvm_unreachable("Unexpected register class");
504 }
505 
506 // Shrink LI to its uses, cleaning up LI.
507 static void shrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
508   if (LIS.shrinkToUses(&LI)) {
509     SmallVector<LiveInterval *, 4> SplitLIs;
510     LIS.splitSeparateComponents(LI, SplitLIs);
511   }
512 }
513 
514 /// A single-use def in the same block with no intervening memory or register
515 /// dependencies; move the def down and nest it with the current instruction.
516 static MachineInstr *moveForSingleUse(unsigned Reg, MachineOperand &Op,
517                                       MachineInstr *Def, MachineBasicBlock &MBB,
518                                       MachineInstr *Insert, LiveIntervals &LIS,
519                                       WebAssemblyFunctionInfo &MFI,
520                                       MachineRegisterInfo &MRI) {
521   LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
522 
523   WebAssemblyDebugValueManager DefDIs(Def);
524   MBB.splice(Insert, &MBB, Def);
525   DefDIs.move(Insert);
526   LIS.handleMove(*Def);
527 
528   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
529     // No one else is using this register for anything so we can just stackify
530     // it in place.
531     MFI.stackifyVReg(MRI, Reg);
532   } else {
533     // The register may have unrelated uses or defs; create a new register for
534     // just our one def and use so that we can stackify it.
535     Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
536     Def->getOperand(0).setReg(NewReg);
537     Op.setReg(NewReg);
538 
539     // Tell LiveIntervals about the new register.
540     LIS.createAndComputeVirtRegInterval(NewReg);
541 
542     // Tell LiveIntervals about the changes to the old register.
543     LiveInterval &LI = LIS.getInterval(Reg);
544     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
545                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
546                      /*RemoveDeadValNo=*/true);
547 
548     MFI.stackifyVReg(MRI, NewReg);
549 
550     DefDIs.updateReg(NewReg);
551 
552     LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
553   }
554 
555   imposeStackOrdering(Def);
556   return Def;
557 }
558 
559 /// A trivially cloneable instruction; clone it and nest the new copy with the
560 /// current instruction.
561 static MachineInstr *rematerializeCheapDef(
562     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
563     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
564     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
565     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
566   LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
567   LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
568 
569   WebAssemblyDebugValueManager DefDIs(&Def);
570 
571   Register NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
572   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
573   Op.setReg(NewReg);
574   MachineInstr *Clone = &*std::prev(Insert);
575   LIS.InsertMachineInstrInMaps(*Clone);
576   LIS.createAndComputeVirtRegInterval(NewReg);
577   MFI.stackifyVReg(MRI, NewReg);
578   imposeStackOrdering(Clone);
579 
580   LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
581 
582   // Shrink the interval.
583   bool IsDead = MRI.use_empty(Reg);
584   if (!IsDead) {
585     LiveInterval &LI = LIS.getInterval(Reg);
586     shrinkToUses(LI, LIS);
587     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
588   }
589 
590   // If that was the last use of the original, delete the original.
591   // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
592   if (IsDead) {
593     LLVM_DEBUG(dbgs() << " - Deleting original\n");
594     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
595     LIS.removePhysRegDefAt(MCRegister::from(WebAssembly::ARGUMENTS), Idx);
596     LIS.removeInterval(Reg);
597     LIS.RemoveMachineInstrFromMaps(Def);
598     Def.eraseFromParent();
599 
600     DefDIs.move(&*Insert);
601     DefDIs.updateReg(NewReg);
602   } else {
603     DefDIs.clone(&*Insert, NewReg);
604   }
605 
606   return Clone;
607 }
608 
609 /// A multiple-use def in the same block with no intervening memory or register
610 /// dependencies; move the def down, nest it with the current instruction, and
611 /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
612 /// this:
613 ///
614 ///    Reg = INST ...        // Def
615 ///    INST ..., Reg, ...    // Insert
616 ///    INST ..., Reg, ...
617 ///    INST ..., Reg, ...
618 ///
619 /// to this:
620 ///
621 ///    DefReg = INST ...     // Def (to become the new Insert)
622 ///    TeeReg, Reg = TEE_... DefReg
623 ///    INST ..., TeeReg, ... // Insert
624 ///    INST ..., Reg, ...
625 ///    INST ..., Reg, ...
626 ///
627 /// with DefReg and TeeReg stackified. This eliminates a local.get from the
628 /// resulting code.
629 static MachineInstr *moveAndTeeForMultiUse(
630     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
631     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
632     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
633   LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
634 
635   WebAssemblyDebugValueManager DefDIs(Def);
636 
637   // Move Def into place.
638   MBB.splice(Insert, &MBB, Def);
639   LIS.handleMove(*Def);
640 
641   // Create the Tee and attach the registers.
642   const auto *RegClass = MRI.getRegClass(Reg);
643   Register TeeReg = MRI.createVirtualRegister(RegClass);
644   Register DefReg = MRI.createVirtualRegister(RegClass);
645   MachineOperand &DefMO = Def->getOperand(0);
646   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
647                               TII->get(getTeeOpcode(RegClass)), TeeReg)
648                           .addReg(Reg, RegState::Define)
649                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
650   Op.setReg(TeeReg);
651   DefMO.setReg(DefReg);
652   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
653   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
654 
655   DefDIs.move(Insert);
656 
657   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
658   LiveInterval &LI = LIS.getInterval(Reg);
659   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
660   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
661   I->start = TeeIdx;
662   ValNo->def = TeeIdx;
663   shrinkToUses(LI, LIS);
664 
665   // Finish stackifying the new regs.
666   LIS.createAndComputeVirtRegInterval(TeeReg);
667   LIS.createAndComputeVirtRegInterval(DefReg);
668   MFI.stackifyVReg(MRI, DefReg);
669   MFI.stackifyVReg(MRI, TeeReg);
670   imposeStackOrdering(Def);
671   imposeStackOrdering(Tee);
672 
673   DefDIs.clone(Tee, DefReg);
674   DefDIs.clone(Insert, TeeReg);
675 
676   LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
677   LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
678   return Def;
679 }
680 
681 namespace {
682 /// A stack for walking the tree of instructions being built, visiting the
683 /// MachineOperands in DFS order.
684 class TreeWalkerState {
685   using mop_iterator = MachineInstr::mop_iterator;
686   using mop_reverse_iterator = std::reverse_iterator<mop_iterator>;
687   using RangeTy = iterator_range<mop_reverse_iterator>;
688   SmallVector<RangeTy, 4> Worklist;
689 
690 public:
691   explicit TreeWalkerState(MachineInstr *Insert) {
692     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
693     if (!Range.empty())
694       Worklist.push_back(reverse(Range));
695   }
696 
697   bool done() const { return Worklist.empty(); }
698 
699   MachineOperand &pop() {
700     RangeTy &Range = Worklist.back();
701     MachineOperand &Op = *Range.begin();
702     Range = drop_begin(Range);
703     if (Range.empty())
704       Worklist.pop_back();
705     assert((Worklist.empty() || !Worklist.back().empty()) &&
706            "Empty ranges shouldn't remain in the worklist");
707     return Op;
708   }
709 
710   /// Push Instr's operands onto the stack to be visited.
711   void pushOperands(MachineInstr *Instr) {
712     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
713     if (!Range.empty())
714       Worklist.push_back(reverse(Range));
715   }
716 
717   /// Some of Instr's operands are on the top of the stack; remove them and
718   /// re-insert them starting from the beginning (because we've commuted them).
719   void resetTopOperands(MachineInstr *Instr) {
720     assert(hasRemainingOperands(Instr) &&
721            "Reseting operands should only be done when the instruction has "
722            "an operand still on the stack");
723     Worklist.back() = reverse(Instr->explicit_uses());
724   }
725 
726   /// Test whether Instr has operands remaining to be visited at the top of
727   /// the stack.
728   bool hasRemainingOperands(const MachineInstr *Instr) const {
729     if (Worklist.empty())
730       return false;
731     const RangeTy &Range = Worklist.back();
732     return !Range.empty() && Range.begin()->getParent() == Instr;
733   }
734 
735   /// Test whether the given register is present on the stack, indicating an
736   /// operand in the tree that we haven't visited yet. Moving a definition of
737   /// Reg to a point in the tree after that would change its value.
738   ///
739   /// This is needed as a consequence of using implicit local.gets for
740   /// uses and implicit local.sets for defs.
741   bool isOnStack(unsigned Reg) const {
742     for (const RangeTy &Range : Worklist)
743       for (const MachineOperand &MO : Range)
744         if (MO.isReg() && MO.getReg() == Reg)
745           return true;
746     return false;
747   }
748 };
749 
750 /// State to keep track of whether commuting is in flight or whether it's been
751 /// tried for the current instruction and didn't work.
752 class CommutingState {
753   /// There are effectively three states: the initial state where we haven't
754   /// started commuting anything and we don't know anything yet, the tentative
755   /// state where we've commuted the operands of the current instruction and are
756   /// revisiting it, and the declined state where we've reverted the operands
757   /// back to their original order and will no longer commute it further.
758   bool TentativelyCommuting = false;
759   bool Declined = false;
760 
761   /// During the tentative state, these hold the operand indices of the commuted
762   /// operands.
763   unsigned Operand0, Operand1;
764 
765 public:
766   /// Stackification for an operand was not successful due to ordering
767   /// constraints. If possible, and if we haven't already tried it and declined
768   /// it, commute Insert's operands and prepare to revisit it.
769   void maybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
770                     const WebAssemblyInstrInfo *TII) {
771     if (TentativelyCommuting) {
772       assert(!Declined &&
773              "Don't decline commuting until you've finished trying it");
774       // Commuting didn't help. Revert it.
775       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
776       TentativelyCommuting = false;
777       Declined = true;
778     } else if (!Declined && TreeWalker.hasRemainingOperands(Insert)) {
779       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
780       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
781       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
782         // Tentatively commute the operands and try again.
783         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
784         TreeWalker.resetTopOperands(Insert);
785         TentativelyCommuting = true;
786         Declined = false;
787       }
788     }
789   }
790 
791   /// Stackification for some operand was successful. Reset to the default
792   /// state.
793   void reset() {
794     TentativelyCommuting = false;
795     Declined = false;
796   }
797 };
798 } // end anonymous namespace
799 
800 bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
801   LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
802                        "********** Function: "
803                     << MF.getName() << '\n');
804 
805   bool Changed = false;
806   MachineRegisterInfo &MRI = MF.getRegInfo();
807   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
808   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
809   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
810   auto &MDT = getAnalysis<MachineDominatorTree>();
811   auto &LIS = getAnalysis<LiveIntervals>();
812 
813   // Walk the instructions from the bottom up. Currently we don't look past
814   // block boundaries, and the blocks aren't ordered so the block visitation
815   // order isn't significant, but we may want to change this in the future.
816   for (MachineBasicBlock &MBB : MF) {
817     // Don't use a range-based for loop, because we modify the list as we're
818     // iterating over it and the end iterator may change.
819     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
820       MachineInstr *Insert = &*MII;
821       // Don't nest anything inside an inline asm, because we don't have
822       // constraints for $push inputs.
823       if (Insert->isInlineAsm())
824         continue;
825 
826       // Ignore debugging intrinsics.
827       if (Insert->isDebugValue())
828         continue;
829 
830       // Iterate through the inputs in reverse order, since we'll be pulling
831       // operands off the stack in LIFO order.
832       CommutingState Commuting;
833       TreeWalkerState TreeWalker(Insert);
834       while (!TreeWalker.done()) {
835         MachineOperand &Use = TreeWalker.pop();
836 
837         // We're only interested in explicit virtual register operands.
838         if (!Use.isReg())
839           continue;
840 
841         Register Reg = Use.getReg();
842         assert(Use.isUse() && "explicit_uses() should only iterate over uses");
843         assert(!Use.isImplicit() &&
844                "explicit_uses() should only iterate over explicit operands");
845         if (Register::isPhysicalRegister(Reg))
846           continue;
847 
848         // Identify the definition for this register at this point.
849         MachineInstr *DefI = getVRegDef(Reg, Insert, MRI, LIS);
850         if (!DefI)
851           continue;
852 
853         // Don't nest an INLINE_ASM def into anything, because we don't have
854         // constraints for $pop outputs.
855         if (DefI->isInlineAsm())
856           continue;
857 
858         // Argument instructions represent live-in registers and not real
859         // instructions.
860         if (WebAssembly::isArgument(DefI->getOpcode()))
861           continue;
862 
863         MachineOperand *Def = DefI->findRegisterDefOperand(Reg);
864         assert(Def != nullptr);
865 
866         // Decide which strategy to take. Prefer to move a single-use value
867         // over cloning it, and prefer cloning over introducing a tee.
868         // For moving, we require the def to be in the same block as the use;
869         // this makes things simpler (LiveIntervals' handleMove function only
870         // supports intra-block moves) and it's MachineSink's job to catch all
871         // the sinking opportunities anyway.
872         bool SameBlock = DefI->getParent() == &MBB;
873         bool CanMove = SameBlock && isSafeToMove(Def, &Use, Insert, MFI, MRI) &&
874                        !TreeWalker.isOnStack(Reg);
875         if (CanMove && hasOneUse(Reg, DefI, MRI, MDT, LIS)) {
876           Insert = moveForSingleUse(Reg, Use, DefI, MBB, Insert, LIS, MFI, MRI);
877 
878           // If we are removing the frame base reg completely, remove the debug
879           // info as well.
880           // TODO: Encode this properly as a stackified value.
881           if (MFI.isFrameBaseVirtual() && MFI.getFrameBaseVreg() == Reg)
882             MFI.clearFrameBaseVreg();
883         } else if (shouldRematerialize(*DefI, TII)) {
884           Insert =
885               rematerializeCheapDef(Reg, Use, *DefI, MBB, Insert->getIterator(),
886                                     LIS, MFI, MRI, TII, TRI);
887         } else if (CanMove && oneUseDominatesOtherUses(Reg, Use, MBB, MRI, MDT,
888                                                        LIS, MFI)) {
889           Insert = moveAndTeeForMultiUse(Reg, Use, DefI, MBB, Insert, LIS, MFI,
890                                          MRI, TII);
891         } else {
892           // We failed to stackify the operand. If the problem was ordering
893           // constraints, Commuting may be able to help.
894           if (!CanMove && SameBlock)
895             Commuting.maybeCommute(Insert, TreeWalker, TII);
896           // Proceed to the next operand.
897           continue;
898         }
899 
900         // Stackifying a multivalue def may unlock in-place stackification of
901         // subsequent defs. TODO: Handle the case where the consecutive uses are
902         // not all in the same instruction.
903         auto *SubsequentDef = Insert->defs().begin();
904         auto *SubsequentUse = &Use;
905         while (SubsequentDef != Insert->defs().end() &&
906                SubsequentUse != Use.getParent()->uses().end()) {
907           if (!SubsequentDef->isReg() || !SubsequentUse->isReg())
908             break;
909           Register DefReg = SubsequentDef->getReg();
910           Register UseReg = SubsequentUse->getReg();
911           // TODO: This single-use restriction could be relaxed by using tees
912           if (DefReg != UseReg || !MRI.hasOneUse(DefReg))
913             break;
914           MFI.stackifyVReg(MRI, DefReg);
915           ++SubsequentDef;
916           ++SubsequentUse;
917         }
918 
919         // If the instruction we just stackified is an IMPLICIT_DEF, convert it
920         // to a constant 0 so that the def is explicit, and the push/pop
921         // correspondence is maintained.
922         if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
923           convertImplicitDefToConstZero(Insert, MRI, TII, MF, LIS);
924 
925         // We stackified an operand. Add the defining instruction's operands to
926         // the worklist stack now to continue to build an ever deeper tree.
927         Commuting.reset();
928         TreeWalker.pushOperands(Insert);
929       }
930 
931       // If we stackified any operands, skip over the tree to start looking for
932       // the next instruction we can build a tree on.
933       if (Insert != &*MII) {
934         imposeStackOrdering(&*MII);
935         MII = MachineBasicBlock::iterator(Insert).getReverse();
936         Changed = true;
937       }
938     }
939   }
940 
941   // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
942   // that it never looks like a use-before-def.
943   if (Changed) {
944     MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
945     for (MachineBasicBlock &MBB : MF)
946       MBB.addLiveIn(WebAssembly::VALUE_STACK);
947   }
948 
949 #ifndef NDEBUG
950   // Verify that pushes and pops are performed in LIFO order.
951   SmallVector<unsigned, 0> Stack;
952   for (MachineBasicBlock &MBB : MF) {
953     for (MachineInstr &MI : MBB) {
954       if (MI.isDebugInstr())
955         continue;
956       for (MachineOperand &MO : reverse(MI.explicit_uses())) {
957         if (!MO.isReg())
958           continue;
959         Register Reg = MO.getReg();
960         if (MFI.isVRegStackified(Reg))
961           assert(Stack.pop_back_val() == Reg &&
962                  "Register stack pop should be paired with a push");
963       }
964       for (MachineOperand &MO : MI.defs()) {
965         if (!MO.isReg())
966           continue;
967         Register Reg = MO.getReg();
968         if (MFI.isVRegStackified(Reg))
969           Stack.push_back(MO.getReg());
970       }
971     }
972     // TODO: Generalize this code to support keeping values on the stack across
973     // basic block boundaries.
974     assert(Stack.empty() &&
975            "Register stack pushes and pops should be balanced");
976   }
977 #endif
978 
979   return Changed;
980 }
981