1 //===-- 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 ///
18 /// This is primarily a code size optimization, since temporary values on the
19 /// expression don't need to be named.
20 ///
21 //===----------------------------------------------------------------------===//
22 
23 #include "WebAssembly.h"
24 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
25 #include "WebAssemblyMachineFunctionInfo.h"
26 #include "WebAssemblySubtarget.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "wasm-reg-stackify"
39 
40 namespace {
41 class 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();
48     AU.addRequired<AAResultsWrapperPass>();
49     AU.addRequired<MachineDominatorTree>();
50     AU.addRequired<LiveIntervals>();
51     AU.addPreserved<MachineBlockFrequencyInfo>();
52     AU.addPreserved<SlotIndexes>();
53     AU.addPreserved<LiveIntervals>();
54     AU.addPreservedID(LiveVariablesID);
55     AU.addPreserved<MachineDominatorTree>();
56     MachineFunctionPass::getAnalysisUsage(AU);
57   }
58 
59   bool runOnMachineFunction(MachineFunction &MF) override;
60 
61 public:
62   static char ID; // Pass identification, replacement for typeid
63   WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
64 };
65 } // end anonymous namespace
66 
67 char WebAssemblyRegStackify::ID = 0;
68 FunctionPass *llvm::createWebAssemblyRegStackify() {
69   return new WebAssemblyRegStackify();
70 }
71 
72 // Decorate the given instruction with implicit operands that enforce the
73 // expression stack ordering constraints for an instruction which is on
74 // the expression stack.
75 static void ImposeStackOrdering(MachineInstr *MI) {
76   // 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));
81 
82   // Also read the opaque EXPR_STACK register.
83   if (!MI->readsRegister(WebAssembly::EXPR_STACK))
84     MI->addOperand(MachineOperand::CreateReg(WebAssembly::EXPR_STACK,
85                                              /*isDef=*/false,
86                                              /*isImp=*/true));
87 }
88 
89 // Determine whether a call to the callee referenced by
90 // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
91 // effects.
92 static void QueryCallee(const MachineInstr *MI, unsigned CalleeOpNo,
93                         bool &Read, bool &Write, bool &Effects,
94                         bool &StackPointer) {
95   // All calls can use the stack pointer.
96   StackPointer = true;
97 
98   const MachineOperand &MO = MI->getOperand(CalleeOpNo);
99   if (MO.isGlobal()) {
100     const Constant *GV = MO.getGlobal();
101     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
102       if (!GA->isInterposable())
103         GV = GA->getAliasee();
104 
105     if (const Function *F = dyn_cast<Function>(GV)) {
106       if (!F->doesNotThrow())
107         Effects = true;
108       if (F->doesNotAccessMemory())
109         return;
110       if (F->onlyReadsMemory()) {
111         Read = true;
112         return;
113       }
114     }
115   }
116 
117   // Assume the worst.
118   Write = true;
119   Read = true;
120   Effects = true;
121 }
122 
123 // Determine whether MI reads memory, writes memory, has side effects,
124 // and/or uses the __stack_pointer value.
125 static void Query(const MachineInstr *MI, AliasAnalysis &AA,
126                   bool &Read, bool &Write, bool &Effects, bool &StackPointer) {
127   assert(!MI->isPosition());
128   assert(!MI->isTerminator());
129 
130   if (MI->isDebugValue())
131     return;
132 
133   // Check for loads.
134   if (MI->mayLoad() && !MI->isInvariantLoad(&AA))
135     Read = true;
136 
137   // Check for stores.
138   if (MI->mayStore()) {
139     Write = true;
140 
141     // Check for stores to __stack_pointer.
142     for (auto MMO : MI->memoperands()) {
143       const MachinePointerInfo &MPI = MMO->getPointerInfo();
144       if (MPI.V.is<const PseudoSourceValue *>()) {
145         auto PSV = MPI.V.get<const PseudoSourceValue *>();
146         if (const ExternalSymbolPseudoSourceValue *EPSV =
147                 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
148           if (StringRef(EPSV->getSymbol()) == "__stack_pointer")
149             StackPointer = true;
150       }
151     }
152   } else if (MI->hasOrderedMemoryRef()) {
153     switch (MI->getOpcode()) {
154     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
155     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
156     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
157     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
158     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
159     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
160     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
161     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
162       // These instruction have hasUnmodeledSideEffects() returning true
163       // because they trap on overflow and invalid so they can't be arbitrarily
164       // moved, however hasOrderedMemoryRef() interprets this plus their lack
165       // of memoperands as having a potential unknown memory reference.
166       break;
167     default:
168       // Record volatile accesses, unless it's a call, as calls are handled
169       // specially below.
170       if (!MI->isCall()) {
171         Write = true;
172         Effects = true;
173       }
174       break;
175     }
176   }
177 
178   // Check for side effects.
179   if (MI->hasUnmodeledSideEffects()) {
180     switch (MI->getOpcode()) {
181     case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64:
182     case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64:
183     case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64:
184     case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64:
185     case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32:
186     case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64:
187     case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32:
188     case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64:
189       // These instructions have hasUnmodeledSideEffects() returning true
190       // because they trap on overflow and invalid so they can't be arbitrarily
191       // moved, however in the specific case of register stackifying, it is safe
192       // to move them because overflow and invalid are Undefined Behavior.
193       break;
194     default:
195       Effects = true;
196       break;
197     }
198   }
199 
200   // Analyze calls.
201   if (MI->isCall()) {
202     switch (MI->getOpcode()) {
203     case WebAssembly::CALL_VOID:
204     case WebAssembly::CALL_INDIRECT_VOID:
205       QueryCallee(MI, 0, Read, Write, Effects, StackPointer);
206       break;
207     case WebAssembly::CALL_I32: case WebAssembly::CALL_I64:
208     case WebAssembly::CALL_F32: case WebAssembly::CALL_F64:
209     case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64:
210     case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64:
211       QueryCallee(MI, 1, Read, Write, Effects, StackPointer);
212       break;
213     default:
214       llvm_unreachable("unexpected call opcode");
215     }
216   }
217 }
218 
219 // Test whether Def is safe and profitable to rematerialize.
220 static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
221                                 const WebAssemblyInstrInfo *TII) {
222   return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
223 }
224 
225 // Identify the definition for this register at this point. This is a
226 // generalization of MachineRegisterInfo::getUniqueVRegDef that uses
227 // LiveIntervals to handle complex cases.
228 static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
229                                 const MachineRegisterInfo &MRI,
230                                 const LiveIntervals &LIS)
231 {
232   // Most registers are in SSA form here so we try a quick MRI query first.
233   if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
234     return Def;
235 
236   // MRI doesn't know what the Def is. Try asking LIS.
237   if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
238           LIS.getInstructionIndex(*Insert)))
239     return LIS.getInstructionFromIndex(ValNo->def);
240 
241   return nullptr;
242 }
243 
244 // Test whether Reg, as defined at Def, has exactly one use. This is a
245 // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
246 // to handle complex cases.
247 static bool HasOneUse(unsigned Reg, MachineInstr *Def,
248                       MachineRegisterInfo &MRI, MachineDominatorTree &MDT,
249                       LiveIntervals &LIS) {
250   // Most registers are in SSA form here so we try a quick MRI query first.
251   if (MRI.hasOneUse(Reg))
252     return true;
253 
254   bool HasOne = false;
255   const LiveInterval &LI = LIS.getInterval(Reg);
256   const VNInfo *DefVNI = LI.getVNInfoAt(
257       LIS.getInstructionIndex(*Def).getRegSlot());
258   assert(DefVNI);
259   for (auto I : MRI.use_nodbg_operands(Reg)) {
260     const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
261     if (Result.valueIn() == DefVNI) {
262       if (!Result.isKill())
263         return false;
264       if (HasOne)
265         return false;
266       HasOne = true;
267     }
268   }
269   return HasOne;
270 }
271 
272 // Test whether it's safe to move Def to just before Insert.
273 // TODO: Compute memory dependencies in a way that doesn't require always
274 // walking the block.
275 // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
276 // more precise.
277 static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
278                          AliasAnalysis &AA, const LiveIntervals &LIS,
279                          const MachineRegisterInfo &MRI) {
280   assert(Def->getParent() == Insert->getParent());
281 
282   // Check for register dependencies.
283   for (const MachineOperand &MO : Def->operands()) {
284     if (!MO.isReg() || MO.isUndef())
285       continue;
286     unsigned Reg = MO.getReg();
287 
288     // If the register is dead here and at Insert, ignore it.
289     if (MO.isDead() && Insert->definesRegister(Reg) &&
290         !Insert->readsRegister(Reg))
291       continue;
292 
293     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
294       // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
295       // from moving down, and we've already checked for that.
296       if (Reg == WebAssembly::ARGUMENTS)
297         continue;
298       // If the physical register is never modified, ignore it.
299       if (!MRI.isPhysRegModified(Reg))
300         continue;
301       // Otherwise, it's a physical register with unknown liveness.
302       return false;
303     }
304 
305     // Ask LiveIntervals whether moving this virtual register use or def to
306     // Insert will change which value numbers are seen.
307     //
308     // If the operand is a use of a register that is also defined in the same
309     // instruction, test that the newly defined value reaches the insert point,
310     // since the operand will be moving along with the def.
311     const LiveInterval &LI = LIS.getInterval(Reg);
312     VNInfo *DefVNI =
313         (MO.isDef() || Def->definesRegister(Reg)) ?
314         LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot()) :
315         LI.getVNInfoBefore(LIS.getInstructionIndex(*Def));
316     assert(DefVNI && "Instruction input missing value number");
317     VNInfo *InsVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*Insert));
318     if (InsVNI && DefVNI != InsVNI)
319       return false;
320   }
321 
322   bool Read = false, Write = false, Effects = false, StackPointer = false;
323   Query(Def, AA, Read, Write, Effects, StackPointer);
324 
325   // If the instruction does not access memory and has no side effects, it has
326   // no additional dependencies.
327   if (!Read && !Write && !Effects && !StackPointer)
328     return true;
329 
330   // Scan through the intervening instructions between Def and Insert.
331   MachineBasicBlock::const_iterator D(Def), I(Insert);
332   for (--I; I != D; --I) {
333     bool InterveningRead = false;
334     bool InterveningWrite = false;
335     bool InterveningEffects = false;
336     bool InterveningStackPointer = false;
337     Query(I, AA, InterveningRead, InterveningWrite, InterveningEffects,
338           InterveningStackPointer);
339     if (Effects && InterveningEffects)
340       return false;
341     if (Read && InterveningWrite)
342       return false;
343     if (Write && (InterveningRead || InterveningWrite))
344       return false;
345     if (StackPointer && InterveningStackPointer)
346       return false;
347   }
348 
349   return true;
350 }
351 
352 /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
353 static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
354                                      const MachineBasicBlock &MBB,
355                                      const MachineRegisterInfo &MRI,
356                                      const MachineDominatorTree &MDT,
357                                      LiveIntervals &LIS,
358                                      WebAssemblyFunctionInfo &MFI) {
359   const LiveInterval &LI = LIS.getInterval(Reg);
360 
361   const MachineInstr *OneUseInst = OneUse.getParent();
362   VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
363 
364   for (const MachineOperand &Use : MRI.use_operands(Reg)) {
365     if (&Use == &OneUse)
366       continue;
367 
368     const MachineInstr *UseInst = Use.getParent();
369     VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
370 
371     if (UseVNI != OneUseVNI)
372       continue;
373 
374     const MachineInstr *OneUseInst = OneUse.getParent();
375     if (UseInst == OneUseInst) {
376       // Another use in the same instruction. We need to ensure that the one
377       // selected use happens "before" it.
378       if (&OneUse > &Use)
379         return false;
380     } else {
381       // Test that the use is dominated by the one selected use.
382       while (!MDT.dominates(OneUseInst, UseInst)) {
383         // Actually, dominating is over-conservative. Test that the use would
384         // happen after the one selected use in the stack evaluation order.
385         //
386         // This is needed as a consequence of using implicit get_locals for
387         // uses and implicit set_locals for defs.
388         if (UseInst->getDesc().getNumDefs() == 0)
389           return false;
390         const MachineOperand &MO = UseInst->getOperand(0);
391         if (!MO.isReg())
392           return false;
393         unsigned DefReg = MO.getReg();
394         if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
395             !MFI.isVRegStackified(DefReg))
396           return false;
397         assert(MRI.hasOneUse(DefReg));
398         const MachineOperand &NewUse = *MRI.use_begin(DefReg);
399         const MachineInstr *NewUseInst = NewUse.getParent();
400         if (NewUseInst == OneUseInst) {
401           if (&OneUse > &NewUse)
402             return false;
403           break;
404         }
405         UseInst = NewUseInst;
406       }
407     }
408   }
409   return true;
410 }
411 
412 /// Get the appropriate tee_local opcode for the given register class.
413 static unsigned GetTeeLocalOpcode(const TargetRegisterClass *RC) {
414   if (RC == &WebAssembly::I32RegClass)
415     return WebAssembly::TEE_LOCAL_I32;
416   if (RC == &WebAssembly::I64RegClass)
417     return WebAssembly::TEE_LOCAL_I64;
418   if (RC == &WebAssembly::F32RegClass)
419     return WebAssembly::TEE_LOCAL_F32;
420   if (RC == &WebAssembly::F64RegClass)
421     return WebAssembly::TEE_LOCAL_F64;
422   llvm_unreachable("Unexpected register class");
423 }
424 
425 // Shrink LI to its uses, cleaning up LI.
426 static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
427   if (LIS.shrinkToUses(&LI)) {
428     SmallVector<LiveInterval*, 4> SplitLIs;
429     LIS.splitSeparateComponents(LI, SplitLIs);
430   }
431 }
432 
433 /// A single-use def in the same block with no intervening memory or register
434 /// dependencies; move the def down and nest it with the current instruction.
435 static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op,
436                                       MachineInstr *Def,
437                                       MachineBasicBlock &MBB,
438                                       MachineInstr *Insert, LiveIntervals &LIS,
439                                       WebAssemblyFunctionInfo &MFI,
440                                       MachineRegisterInfo &MRI) {
441   DEBUG(dbgs() << "Move for single use: "; Def->dump());
442 
443   MBB.splice(Insert, &MBB, Def);
444   LIS.handleMove(*Def);
445 
446   if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
447     // No one else is using this register for anything so we can just stackify
448     // it in place.
449     MFI.stackifyVReg(Reg);
450   } else {
451     // The register may have unrelated uses or defs; create a new register for
452     // just our one def and use so that we can stackify it.
453     unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
454     Def->getOperand(0).setReg(NewReg);
455     Op.setReg(NewReg);
456 
457     // Tell LiveIntervals about the new register.
458     LIS.createAndComputeVirtRegInterval(NewReg);
459 
460     // Tell LiveIntervals about the changes to the old register.
461     LiveInterval &LI = LIS.getInterval(Reg);
462     LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
463                      LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
464                      /*RemoveDeadValNo=*/true);
465 
466     MFI.stackifyVReg(NewReg);
467 
468     DEBUG(dbgs() << " - Replaced register: "; Def->dump());
469   }
470 
471   ImposeStackOrdering(Def);
472   return Def;
473 }
474 
475 /// A trivially cloneable instruction; clone it and nest the new copy with the
476 /// current instruction.
477 static MachineInstr *RematerializeCheapDef(
478     unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
479     MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
480     WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
481     const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
482   DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
483   DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
484 
485   unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
486   TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
487   Op.setReg(NewReg);
488   MachineInstr *Clone = &*std::prev(Insert);
489   LIS.InsertMachineInstrInMaps(*Clone);
490   LIS.createAndComputeVirtRegInterval(NewReg);
491   MFI.stackifyVReg(NewReg);
492   ImposeStackOrdering(Clone);
493 
494   DEBUG(dbgs() << " - Cloned to "; Clone->dump());
495 
496   // Shrink the interval.
497   bool IsDead = MRI.use_empty(Reg);
498   if (!IsDead) {
499     LiveInterval &LI = LIS.getInterval(Reg);
500     ShrinkToUses(LI, LIS);
501     IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
502   }
503 
504   // If that was the last use of the original, delete the original.
505   if (IsDead) {
506     DEBUG(dbgs() << " - Deleting original\n");
507     SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
508     LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
509     LIS.removeInterval(Reg);
510     LIS.RemoveMachineInstrFromMaps(Def);
511     Def.eraseFromParent();
512   }
513 
514   return Clone;
515 }
516 
517 /// A multiple-use def in the same block with no intervening memory or register
518 /// dependencies; move the def down, nest it with the current instruction, and
519 /// insert a tee_local to satisfy the rest of the uses. As an illustration,
520 /// rewrite this:
521 ///
522 ///    Reg = INST ...        // Def
523 ///    INST ..., Reg, ...    // Insert
524 ///    INST ..., Reg, ...
525 ///    INST ..., Reg, ...
526 ///
527 /// to this:
528 ///
529 ///    DefReg = INST ...     // Def (to become the new Insert)
530 ///    TeeReg, Reg = TEE_LOCAL_... DefReg
531 ///    INST ..., TeeReg, ... // Insert
532 ///    INST ..., Reg, ...
533 ///    INST ..., Reg, ...
534 ///
535 /// with DefReg and TeeReg stackified. This eliminates a get_local from the
536 /// resulting code.
537 static MachineInstr *MoveAndTeeForMultiUse(
538     unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
539     MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
540     MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
541   DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
542 
543   // Move Def into place.
544   MBB.splice(Insert, &MBB, Def);
545   LIS.handleMove(*Def);
546 
547   // Create the Tee and attach the registers.
548   const auto *RegClass = MRI.getRegClass(Reg);
549   unsigned TeeReg = MRI.createVirtualRegister(RegClass);
550   unsigned DefReg = MRI.createVirtualRegister(RegClass);
551   MachineOperand &DefMO = Def->getOperand(0);
552   MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
553                               TII->get(GetTeeLocalOpcode(RegClass)), TeeReg)
554                           .addReg(Reg, RegState::Define)
555                           .addReg(DefReg, getUndefRegState(DefMO.isDead()));
556   Op.setReg(TeeReg);
557   DefMO.setReg(DefReg);
558   SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
559   SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
560 
561   // Tell LiveIntervals we moved the original vreg def from Def to Tee.
562   LiveInterval &LI = LIS.getInterval(Reg);
563   LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
564   VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
565   I->start = TeeIdx;
566   ValNo->def = TeeIdx;
567   ShrinkToUses(LI, LIS);
568 
569   // Finish stackifying the new regs.
570   LIS.createAndComputeVirtRegInterval(TeeReg);
571   LIS.createAndComputeVirtRegInterval(DefReg);
572   MFI.stackifyVReg(DefReg);
573   MFI.stackifyVReg(TeeReg);
574   ImposeStackOrdering(Def);
575   ImposeStackOrdering(Tee);
576 
577   DEBUG(dbgs() << " - Replaced register: "; Def->dump());
578   DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
579   return Def;
580 }
581 
582 namespace {
583 /// A stack for walking the tree of instructions being built, visiting the
584 /// MachineOperands in DFS order.
585 class TreeWalkerState {
586   typedef MachineInstr::mop_iterator mop_iterator;
587   typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
588   typedef iterator_range<mop_reverse_iterator> RangeTy;
589   SmallVector<RangeTy, 4> Worklist;
590 
591 public:
592   explicit TreeWalkerState(MachineInstr *Insert) {
593     const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
594     if (Range.begin() != Range.end())
595       Worklist.push_back(reverse(Range));
596   }
597 
598   bool Done() const { return Worklist.empty(); }
599 
600   MachineOperand &Pop() {
601     RangeTy &Range = Worklist.back();
602     MachineOperand &Op = *Range.begin();
603     Range = drop_begin(Range, 1);
604     if (Range.begin() == Range.end())
605       Worklist.pop_back();
606     assert((Worklist.empty() ||
607             Worklist.back().begin() != Worklist.back().end()) &&
608            "Empty ranges shouldn't remain in the worklist");
609     return Op;
610   }
611 
612   /// Push Instr's operands onto the stack to be visited.
613   void PushOperands(MachineInstr *Instr) {
614     const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
615     if (Range.begin() != Range.end())
616       Worklist.push_back(reverse(Range));
617   }
618 
619   /// Some of Instr's operands are on the top of the stack; remove them and
620   /// re-insert them starting from the beginning (because we've commuted them).
621   void ResetTopOperands(MachineInstr *Instr) {
622     assert(HasRemainingOperands(Instr) &&
623            "Reseting operands should only be done when the instruction has "
624            "an operand still on the stack");
625     Worklist.back() = reverse(Instr->explicit_uses());
626   }
627 
628   /// Test whether Instr has operands remaining to be visited at the top of
629   /// the stack.
630   bool HasRemainingOperands(const MachineInstr *Instr) const {
631     if (Worklist.empty())
632       return false;
633     const RangeTy &Range = Worklist.back();
634     return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
635   }
636 
637   /// Test whether the given register is present on the stack, indicating an
638   /// operand in the tree that we haven't visited yet. Moving a definition of
639   /// Reg to a point in the tree after that would change its value.
640   ///
641   /// This is needed as a consequence of using implicit get_locals for
642   /// uses and implicit set_locals for defs.
643   bool IsOnStack(unsigned Reg) const {
644     for (const RangeTy &Range : Worklist)
645       for (const MachineOperand &MO : Range)
646         if (MO.isReg() && MO.getReg() == Reg)
647           return true;
648     return false;
649   }
650 };
651 
652 /// State to keep track of whether commuting is in flight or whether it's been
653 /// tried for the current instruction and didn't work.
654 class CommutingState {
655   /// There are effectively three states: the initial state where we haven't
656   /// started commuting anything and we don't know anything yet, the tenative
657   /// state where we've commuted the operands of the current instruction and are
658   /// revisting it, and the declined state where we've reverted the operands
659   /// back to their original order and will no longer commute it further.
660   bool TentativelyCommuting;
661   bool Declined;
662 
663   /// During the tentative state, these hold the operand indices of the commuted
664   /// operands.
665   unsigned Operand0, Operand1;
666 
667 public:
668   CommutingState() : TentativelyCommuting(false), Declined(false) {}
669 
670   /// Stackification for an operand was not successful due to ordering
671   /// constraints. If possible, and if we haven't already tried it and declined
672   /// it, commute Insert's operands and prepare to revisit it.
673   void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
674                     const WebAssemblyInstrInfo *TII) {
675     if (TentativelyCommuting) {
676       assert(!Declined &&
677              "Don't decline commuting until you've finished trying it");
678       // Commuting didn't help. Revert it.
679       TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
680       TentativelyCommuting = false;
681       Declined = true;
682     } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
683       Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
684       Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
685       if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
686         // Tentatively commute the operands and try again.
687         TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
688         TreeWalker.ResetTopOperands(Insert);
689         TentativelyCommuting = true;
690         Declined = false;
691       }
692     }
693   }
694 
695   /// Stackification for some operand was successful. Reset to the default
696   /// state.
697   void Reset() {
698     TentativelyCommuting = false;
699     Declined = false;
700   }
701 };
702 } // end anonymous namespace
703 
704 bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
705   DEBUG(dbgs() << "********** Register Stackifying **********\n"
706                   "********** Function: "
707                << MF.getName() << '\n');
708 
709   bool Changed = false;
710   MachineRegisterInfo &MRI = MF.getRegInfo();
711   WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
712   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
713   const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
714   AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
715   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
716   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
717 
718   // Walk the instructions from the bottom up. Currently we don't look past
719   // block boundaries, and the blocks aren't ordered so the block visitation
720   // order isn't significant, but we may want to change this in the future.
721   for (MachineBasicBlock &MBB : MF) {
722     // Don't use a range-based for loop, because we modify the list as we're
723     // iterating over it and the end iterator may change.
724     for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
725       MachineInstr *Insert = &*MII;
726       // Don't nest anything inside an inline asm, because we don't have
727       // constraints for $push inputs.
728       if (Insert->getOpcode() == TargetOpcode::INLINEASM)
729         continue;
730 
731       // Ignore debugging intrinsics.
732       if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
733         continue;
734 
735       // Iterate through the inputs in reverse order, since we'll be pulling
736       // operands off the stack in LIFO order.
737       CommutingState Commuting;
738       TreeWalkerState TreeWalker(Insert);
739       while (!TreeWalker.Done()) {
740         MachineOperand &Op = TreeWalker.Pop();
741 
742         // We're only interested in explicit virtual register operands.
743         if (!Op.isReg())
744           continue;
745 
746         unsigned Reg = Op.getReg();
747         assert(Op.isUse() && "explicit_uses() should only iterate over uses");
748         assert(!Op.isImplicit() &&
749                "explicit_uses() should only iterate over explicit operands");
750         if (TargetRegisterInfo::isPhysicalRegister(Reg))
751           continue;
752 
753         // Identify the definition for this register at this point. Most
754         // registers are in SSA form here so we try a quick MRI query first.
755         MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
756         if (!Def)
757           continue;
758 
759         // Don't nest an INLINE_ASM def into anything, because we don't have
760         // constraints for $pop outputs.
761         if (Def->getOpcode() == TargetOpcode::INLINEASM)
762           continue;
763 
764         // Argument instructions represent live-in registers and not real
765         // instructions.
766         if (Def->getOpcode() == WebAssembly::ARGUMENT_I32 ||
767             Def->getOpcode() == WebAssembly::ARGUMENT_I64 ||
768             Def->getOpcode() == WebAssembly::ARGUMENT_F32 ||
769             Def->getOpcode() == WebAssembly::ARGUMENT_F64)
770           continue;
771 
772         // Decide which strategy to take. Prefer to move a single-use value
773         // over cloning it, and prefer cloning over introducing a tee_local.
774         // For moving, we require the def to be in the same block as the use;
775         // this makes things simpler (LiveIntervals' handleMove function only
776         // supports intra-block moves) and it's MachineSink's job to catch all
777         // the sinking opportunities anyway.
778         bool SameBlock = Def->getParent() == &MBB;
779         bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, LIS, MRI) &&
780                        !TreeWalker.IsOnStack(Reg);
781         if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
782           Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
783         } else if (ShouldRematerialize(*Def, AA, TII)) {
784           Insert =
785               RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
786                                     LIS, MFI, MRI, TII, TRI);
787         } else if (CanMove &&
788                    OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
789           Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
790                                          MRI, TII);
791         } else {
792           // We failed to stackify the operand. If the problem was ordering
793           // constraints, Commuting may be able to help.
794           if (!CanMove && SameBlock)
795             Commuting.MaybeCommute(Insert, TreeWalker, TII);
796           // Proceed to the next operand.
797           continue;
798         }
799 
800         // We stackified an operand. Add the defining instruction's operands to
801         // the worklist stack now to continue to build an ever deeper tree.
802         Commuting.Reset();
803         TreeWalker.PushOperands(Insert);
804       }
805 
806       // If we stackified any operands, skip over the tree to start looking for
807       // the next instruction we can build a tree on.
808       if (Insert != &*MII) {
809         ImposeStackOrdering(&*MII);
810         MII = std::prev(
811             llvm::make_reverse_iterator(MachineBasicBlock::iterator(Insert)));
812         Changed = true;
813       }
814     }
815   }
816 
817   // If we used EXPR_STACK anywhere, add it to the live-in sets everywhere so
818   // that it never looks like a use-before-def.
819   if (Changed) {
820     MF.getRegInfo().addLiveIn(WebAssembly::EXPR_STACK);
821     for (MachineBasicBlock &MBB : MF)
822       MBB.addLiveIn(WebAssembly::EXPR_STACK);
823   }
824 
825 #ifndef NDEBUG
826   // Verify that pushes and pops are performed in LIFO order.
827   SmallVector<unsigned, 0> Stack;
828   for (MachineBasicBlock &MBB : MF) {
829     for (MachineInstr &MI : MBB) {
830       if (MI.isDebugValue())
831         continue;
832       for (MachineOperand &MO : reverse(MI.explicit_operands())) {
833         if (!MO.isReg())
834           continue;
835         unsigned Reg = MO.getReg();
836 
837         if (MFI.isVRegStackified(Reg)) {
838           if (MO.isDef())
839             Stack.push_back(Reg);
840           else
841             assert(Stack.pop_back_val() == Reg &&
842                    "Register stack pop should be paired with a push");
843         }
844       }
845     }
846     // TODO: Generalize this code to support keeping values on the stack across
847     // basic block boundaries.
848     assert(Stack.empty() &&
849            "Register stack pushes and pops should be balanced");
850   }
851 #endif
852 
853   return Changed;
854 }
855