LLVM  7.0.0
WebAssemblyStoreResults.cpp
Go to the documentation of this file.
1 //===-- WebAssemblyStoreResults.cpp - Optimize using store result values --===//
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 /// This file implements an optimization pass using store result values.
12 ///
13 /// WebAssembly's store instructions return the stored value. This is to enable
14 /// an optimization wherein uses of the stored value can be replaced by uses of
15 /// the store's result value, making the stored value register more likely to
16 /// be single-use, thus more likely to be useful to register stackifying, and
17 /// potentially also exposing the store to register stackifying. These both can
18 /// reduce get_local/set_local traffic.
19 ///
20 /// This pass also performs this optimization for memcpy, memmove, and memset
21 /// calls, since the LLVM intrinsics for these return void so they can't use the
22 /// returned attribute and consequently aren't handled by the OptimizeReturned
23 /// pass.
24 ///
25 //===----------------------------------------------------------------------===//
26 
28 #include "WebAssembly.h"
30 #include "WebAssemblySubtarget.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/Support/Debug.h"
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "wasm-store-results"
42 
43 namespace {
44 class WebAssemblyStoreResults final : public MachineFunctionPass {
45 public:
46  static char ID; // Pass identification, replacement for typeid
47  WebAssemblyStoreResults() : MachineFunctionPass(ID) {}
48 
49  StringRef getPassName() const override { return "WebAssembly Store Results"; }
50 
51  void getAnalysisUsage(AnalysisUsage &AU) const override {
52  AU.setPreservesCFG();
62  }
63 
64  bool runOnMachineFunction(MachineFunction &MF) override;
65 
66 private:
67 };
68 } // end anonymous namespace
69 
71 INITIALIZE_PASS(WebAssemblyStoreResults, DEBUG_TYPE,
72  "Optimize store result values for WebAssembly", false, false)
73 
75  return new WebAssemblyStoreResults();
76 }
77 
78 // Replace uses of FromReg with ToReg if they are dominated by MI.
80  unsigned FromReg, unsigned ToReg,
81  const MachineRegisterInfo &MRI,
83  LiveIntervals &LIS) {
84  bool Changed = false;
85 
86  LiveInterval *FromLI = &LIS.getInterval(FromReg);
87  LiveInterval *ToLI = &LIS.getInterval(ToReg);
88 
89  SlotIndex FromIdx = LIS.getInstructionIndex(MI).getRegSlot();
90  VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
91 
93 
94  for (auto I = MRI.use_nodbg_begin(FromReg), E = MRI.use_nodbg_end(); I != E;) {
95  MachineOperand &O = *I++;
96  MachineInstr *Where = O.getParent();
97 
98  // Check that MI dominates the instruction in the normal way.
99  if (&MI == Where || !MDT.dominates(&MI, Where))
100  continue;
101 
102  // If this use gets a different value, skip it.
103  SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
104  VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
105  if (WhereVNI && WhereVNI != FromVNI)
106  continue;
107 
108  // Make sure ToReg isn't clobbered before it gets there.
109  VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
110  if (ToVNI && ToVNI != FromVNI)
111  continue;
112 
113  Changed = true;
114  LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
115  << MI << "\n");
116  O.setReg(ToReg);
117 
118  // If the store's def was previously dead, it is no longer.
119  if (!O.isUndef()) {
120  MI.getOperand(0).setIsDead(false);
121 
122  Indices.push_back(WhereIdx.getRegSlot());
123  }
124  }
125 
126  if (Changed) {
127  // Extend ToReg's liveness.
128  LIS.extendToIndices(*ToLI, Indices);
129 
130  // Shrink FromReg's liveness.
131  LIS.shrinkToUses(FromLI);
132 
133  // If we replaced all dominated uses, FromReg is now killed at MI.
134  if (!FromLI->liveAt(FromIdx.getDeadSlot()))
135  MI.addRegisterKilled(FromReg,
137  .getRegisterInfo());
138  }
139 
140  return Changed;
141 }
142 
144  const MachineRegisterInfo &MRI,
146  LiveIntervals &LIS,
147  const WebAssemblyTargetLowering &TLI,
148  const TargetLibraryInfo &LibInfo) {
149  MachineOperand &Op1 = MI.getOperand(1);
150  if (!Op1.isSymbol())
151  return false;
152 
154  bool callReturnsInput = Name == TLI.getLibcallName(RTLIB::MEMCPY) ||
155  Name == TLI.getLibcallName(RTLIB::MEMMOVE) ||
156  Name == TLI.getLibcallName(RTLIB::MEMSET);
157  if (!callReturnsInput)
158  return false;
159 
160  LibFunc Func;
161  if (!LibInfo.getLibFunc(Name, Func))
162  return false;
163 
164  unsigned FromReg = MI.getOperand(2).getReg();
165  unsigned ToReg = MI.getOperand(0).getReg();
166  if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
167  report_fatal_error("Store results: call to builtin function with wrong "
168  "signature, from/to mismatch");
169  return ReplaceDominatedUses(MBB, MI, FromReg, ToReg, MRI, MDT, LIS);
170 }
171 
172 bool WebAssemblyStoreResults::runOnMachineFunction(MachineFunction &MF) {
173  LLVM_DEBUG({
174  dbgs() << "********** Store Results **********\n"
175  << "********** Function: " << MF.getName() << '\n';
176  });
177 
179  MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
180  const WebAssemblyTargetLowering &TLI =
181  *MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();
182  const auto &LibInfo = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
183  LiveIntervals &LIS = getAnalysis<LiveIntervals>();
184  bool Changed = false;
185 
186  // We don't preserve SSA form.
187  MRI.leaveSSA();
188 
189  assert(MRI.tracksLiveness() && "StoreResults expects liveness tracking");
190 
191  for (auto &MBB : MF) {
192  LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
193  for (auto &MI : MBB)
194  switch (MI.getOpcode()) {
195  default:
196  break;
197  case WebAssembly::CALL_I32:
198  case WebAssembly::CALL_I64:
199  Changed |= optimizeCall(MBB, MI, MRI, MDT, LIS, TLI, LibInfo);
200  break;
201  }
202  }
203 
204  return Changed;
205 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static bool optimizeCall(MachineBasicBlock &MBB, MachineInstr &MI, const MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS, const WebAssemblyTargetLowering &TLI, const TargetLibraryInfo &LibInfo)
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:119
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:638
unsigned getReg() const
getReg - Returns the register number.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
void setIsDead(bool Val=true)
VNInfo - Value Number Information.
Definition: LiveInterval.h:53
use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
static use_nodbg_iterator use_nodbg_end()
AnalysisUsage & addRequired()
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
Definition: SlotIndexes.h:260
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const char * getSymbolName() const
void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
SlotIndexes pass.
Definition: SlotIndexes.h:331
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
Definition: SlotIndexes.h:255
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:409
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool liveAt(SlotIndex index) const
Definition: LiveInterval.h:389
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides WebAssembly-specific target descriptions.
Represent the analysis usage information of a pass.
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr *> *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
FunctionPass * createWebAssemblyStoreResults()
This file declares the WebAssembly-specific subclass of TargetSubtarget.
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
Provides information about what library functions are available for the current target.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
LiveInterval & getInterval(unsigned Reg)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:60
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static bool ReplaceDominatedUses(MachineBasicBlock &MBB, MachineInstr &MI, unsigned FromReg, unsigned ToReg, const MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
INITIALIZE_PASS(WebAssemblyStoreResults, DEBUG_TYPE, "Optimize store result values for WebAssembly", false, false) FunctionPass *llvm
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares WebAssembly-specific per-machine-function information.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define DEBUG_TYPE
bool addRegisterKilled(unsigned IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
#define LLVM_DEBUG(X)
Definition: Debug.h:119
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:316
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:84
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.