LLVM  8.0.1
WebAssemblyMemIntrinsicResults.cpp
Go to the documentation of this file.
1 //== WebAssemblyMemIntrinsicResults.cpp - Optimize memory intrinsic results ==//
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 memory intrinsic results.
12 ///
13 /// Calls to memory intrinsics (memcpy, memmove, memset) return the destination
14 /// address. They are in the form of
15 /// %dst_new = call @memcpy %dst, %src, %len
16 /// where %dst and %dst_new registers contain the same value.
17 ///
18 /// This is to enable an optimization wherein uses of the %dst register used in
19 /// the parameter can be replaced by uses of the %dst_new register used in the
20 /// result, making the %dst register more likely to be single-use, thus more
21 /// likely to be useful to register stackifying, and potentially also exposing
22 /// the call instruction itself to register stackifying. These both can reduce
23 /// local.get/local.set traffic.
24 ///
25 /// The LLVM intrinsics for these return void so they can't use the returned
26 /// attribute and consequently aren't handled by the OptimizeReturned pass.
27 ///
28 //===----------------------------------------------------------------------===//
29 
31 #include "WebAssembly.h"
33 #include "WebAssemblySubtarget.h"
39 #include "llvm/CodeGen/Passes.h"
40 #include "llvm/Support/Debug.h"
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "wasm-mem-intrinsic-results"
45 
46 namespace {
47 class WebAssemblyMemIntrinsicResults final : public MachineFunctionPass {
48 public:
49  static char ID; // Pass identification, replacement for typeid
50  WebAssemblyMemIntrinsicResults() : MachineFunctionPass(ID) {}
51 
52  StringRef getPassName() const override {
53  return "WebAssembly Memory Intrinsic Results";
54  }
55 
56  void getAnalysisUsage(AnalysisUsage &AU) const override {
57  AU.setPreservesCFG();
67  }
68 
69  bool runOnMachineFunction(MachineFunction &MF) override;
70 
71 private:
72 };
73 } // end anonymous namespace
74 
76 INITIALIZE_PASS(WebAssemblyMemIntrinsicResults, DEBUG_TYPE,
77  "Optimize memory intrinsic result values for WebAssembly",
78  false, false)
79 
81  return new WebAssemblyMemIntrinsicResults();
82 }
83 
84 // Replace uses of FromReg with ToReg if they are dominated by MI.
86  unsigned FromReg, unsigned ToReg,
87  const MachineRegisterInfo &MRI,
89  LiveIntervals &LIS) {
90  bool Changed = false;
91 
92  LiveInterval *FromLI = &LIS.getInterval(FromReg);
93  LiveInterval *ToLI = &LIS.getInterval(ToReg);
94 
95  SlotIndex FromIdx = LIS.getInstructionIndex(MI).getRegSlot();
96  VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
97 
99 
100  for (auto I = MRI.use_nodbg_begin(FromReg), E = MRI.use_nodbg_end();
101  I != E;) {
102  MachineOperand &O = *I++;
103  MachineInstr *Where = O.getParent();
104 
105  // Check that MI dominates the instruction in the normal way.
106  if (&MI == Where || !MDT.dominates(&MI, Where))
107  continue;
108 
109  // If this use gets a different value, skip it.
110  SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
111  VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
112  if (WhereVNI && WhereVNI != FromVNI)
113  continue;
114 
115  // Make sure ToReg isn't clobbered before it gets there.
116  VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
117  if (ToVNI && ToVNI != FromVNI)
118  continue;
119 
120  Changed = true;
121  LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
122  << MI << "\n");
123  O.setReg(ToReg);
124 
125  // If the store's def was previously dead, it is no longer.
126  if (!O.isUndef()) {
127  MI.getOperand(0).setIsDead(false);
128 
129  Indices.push_back(WhereIdx.getRegSlot());
130  }
131  }
132 
133  if (Changed) {
134  // Extend ToReg's liveness.
135  LIS.extendToIndices(*ToLI, Indices);
136 
137  // Shrink FromReg's liveness.
138  LIS.shrinkToUses(FromLI);
139 
140  // If we replaced all dominated uses, FromReg is now killed at MI.
141  if (!FromLI->liveAt(FromIdx.getDeadSlot()))
142  MI.addRegisterKilled(FromReg, MBB.getParent()
144  .getRegisterInfo());
145  }
146 
147  return Changed;
148 }
149 
151  const MachineRegisterInfo &MRI,
153  const WebAssemblyTargetLowering &TLI,
154  const TargetLibraryInfo &LibInfo) {
155  MachineOperand &Op1 = MI.getOperand(1);
156  if (!Op1.isSymbol())
157  return false;
158 
160  bool callReturnsInput = Name == TLI.getLibcallName(RTLIB::MEMCPY) ||
161  Name == TLI.getLibcallName(RTLIB::MEMMOVE) ||
162  Name == TLI.getLibcallName(RTLIB::MEMSET);
163  if (!callReturnsInput)
164  return false;
165 
166  LibFunc Func;
167  if (!LibInfo.getLibFunc(Name, Func))
168  return false;
169 
170  unsigned FromReg = MI.getOperand(2).getReg();
171  unsigned ToReg = MI.getOperand(0).getReg();
172  if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
173  report_fatal_error("Memory Intrinsic results: call to builtin function "
174  "with wrong signature, from/to mismatch");
175  return ReplaceDominatedUses(MBB, MI, FromReg, ToReg, MRI, MDT, LIS);
176 }
177 
178 bool WebAssemblyMemIntrinsicResults::runOnMachineFunction(MachineFunction &MF) {
179  LLVM_DEBUG({
180  dbgs() << "********** Memory Intrinsic Results **********\n"
181  << "********** Function: " << MF.getName() << '\n';
182  });
183 
185  MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
186  const WebAssemblyTargetLowering &TLI =
187  *MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();
188  const auto &LibInfo = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
189  LiveIntervals &LIS = getAnalysis<LiveIntervals>();
190  bool Changed = false;
191 
192  // We don't preserve SSA form.
193  MRI.leaveSSA();
194 
195  assert(MRI.tracksLiveness() &&
196  "MemIntrinsicResults expects liveness tracking");
197 
198  for (auto &MBB : MF) {
199  LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
200  for (auto &MI : MBB)
201  switch (MI.getOpcode()) {
202  default:
203  break;
204  case WebAssembly::CALL_I32:
205  case WebAssembly::CALL_I64:
206  Changed |= optimizeCall(MBB, MI, MRI, MDT, LIS, TLI, LibInfo);
207  break;
208  }
209  }
210 
211  return Changed;
212 }
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.
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:140
This class represents lattice values for constants.
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)
INITIALIZE_PASS(WebAssemblyMemIntrinsicResults, DEBUG_TYPE, "Optimize memory intrinsic result values for WebAssembly", false, false) FunctionPass *llvm
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()
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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.
static bool ReplaceDominatedUses(MachineBasicBlock &MBB, MachineInstr &MI, unsigned FromReg, unsigned ToReg, const MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
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
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)
static bool optimizeCall(MachineBasicBlock &MBB, MachineInstr &MI, const MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS, const WebAssemblyTargetLowering &TLI, const TargetLibraryInfo &LibInfo)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
FunctionPass * createWebAssemblyMemIntrinsicResults()
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:64
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
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())
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:123
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:414
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.