LLVM  4.0.0
X86FixupBWInsts.cpp
Go to the documentation of this file.
1 //===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
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 /// \file
10 /// This file defines the pass that looks through the machine instructions
11 /// late in the compilation, and finds byte or word instructions that
12 /// can be profitably replaced with 32 bit instructions that give equivalent
13 /// results for the bits of the results that are used. There are two possible
14 /// reasons to do this.
15 ///
16 /// One reason is to avoid false-dependences on the upper portions
17 /// of the registers. Only instructions that have a destination register
18 /// which is not in any of the source registers can be affected by this.
19 /// Any instruction where one of the source registers is also the destination
20 /// register is unaffected, because it has a true dependence on the source
21 /// register already. So, this consideration primarily affects load
22 /// instructions and register-to-register moves. It would
23 /// seem like cmov(s) would also be affected, but because of the way cmov is
24 /// really implemented by most machines as reading both the destination and
25 /// and source regsters, and then "merging" the two based on a condition,
26 /// it really already should be considered as having a true dependence on the
27 /// destination register as well.
28 ///
29 /// The other reason to do this is for potential code size savings. Word
30 /// operations need an extra override byte compared to their 32 bit
31 /// versions. So this can convert many word operations to their larger
32 /// size, saving a byte in encoding. This could introduce partial register
33 /// dependences where none existed however. As an example take:
34 /// orw ax, $0x1000
35 /// addw ax, $3
36 /// now if this were to get transformed into
37 /// orw ax, $1000
38 /// addl eax, $3
39 /// because the addl encodes shorter than the addw, this would introduce
40 /// a use of a register that was only partially written earlier. On older
41 /// Intel processors this can be quite a performance penalty, so this should
42 /// probably only be done when it can be proven that a new partial dependence
43 /// wouldn't be created, or when your know a newer processor is being
44 /// targeted, or when optimizing for minimum code size.
45 ///
46 //===----------------------------------------------------------------------===//
47 
48 #include "X86.h"
49 #include "X86InstrInfo.h"
50 #include "X86Subtarget.h"
51 #include "llvm/ADT/Statistic.h"
57 #include "llvm/CodeGen/Passes.h"
58 #include "llvm/Support/Debug.h"
61 using namespace llvm;
62 
63 #define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
64 #define FIXUPBW_NAME "x86-fixup-bw-insts"
65 
66 #define DEBUG_TYPE FIXUPBW_NAME
67 
68 // Option to allow this optimization pass to have fine-grained control.
69 static cl::opt<bool>
70  FixupBWInsts("fixup-byte-word-insts",
71  cl::desc("Change byte and word instructions to larger sizes"),
72  cl::init(true), cl::Hidden);
73 
74 namespace {
75 class FixupBWInstPass : public MachineFunctionPass {
76  /// Loop over all of the instructions in the basic block replacing applicable
77  /// byte or word instructions with better alternatives.
78  void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
79 
80  /// This sets the \p SuperDestReg to the 32 bit super reg of the original
81  /// destination register of the MachineInstr passed in. It returns true if
82  /// that super register is dead just prior to \p OrigMI, and false if not.
83  bool getSuperRegDestIfDead(MachineInstr *OrigMI,
84  unsigned &SuperDestReg) const;
85 
86  /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
87  /// register if it is safe to do so. Return the replacement instruction if
88  /// OK, otherwise return nullptr.
89  MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
90 
91  /// Change the MachineInstr \p MI into the equivalent 32-bit copy if it is
92  /// safe to do so. Return the replacement instruction if OK, otherwise return
93  /// nullptr.
94  MachineInstr *tryReplaceCopy(MachineInstr *MI) const;
95 
96  // Change the MachineInstr \p MI into an eqivalent 32 bit instruction if
97  // possible. Return the replacement instruction if OK, return nullptr
98  // otherwise. Set WasCandidate to true or false depending on whether the
99  // MI was a candidate for this sort of transformation.
100  MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB,
101  bool &WasCandidate) const;
102 public:
103  static char ID;
104 
105  StringRef getPassName() const override { return FIXUPBW_DESC; }
106 
107  FixupBWInstPass() : MachineFunctionPass(ID) {
109  }
110 
111  void getAnalysisUsage(AnalysisUsage &AU) const override {
112  AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
113  // guide some heuristics.
115  }
116 
117  /// Loop over all of the basic blocks, replacing byte and word instructions by
118  /// equivalent 32 bit instructions where performance or code size can be
119  /// improved.
120  bool runOnMachineFunction(MachineFunction &MF) override;
121 
122  MachineFunctionProperties getRequiredProperties() const override {
125  }
126 
127 private:
128  MachineFunction *MF;
129 
130  /// Machine instruction info used throughout the class.
131  const X86InstrInfo *TII;
132 
133  /// Local member for function's OptForSize attribute.
134  bool OptForSize;
135 
136  /// Machine loop info used for guiding some heruistics.
137  MachineLoopInfo *MLI;
138 
139  /// Register Liveness information after the current instruction.
140  LivePhysRegs LiveRegs;
141 };
142 char FixupBWInstPass::ID = 0;
143 }
144 
145 INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
146 
147 FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
148 
149 bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
150  if (!FixupBWInsts || skipFunction(*MF.getFunction()))
151  return false;
152 
153  this->MF = &MF;
154  TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
155  OptForSize = MF.getFunction()->optForSize();
156  MLI = &getAnalysis<MachineLoopInfo>();
157  LiveRegs.init(TII->getRegisterInfo());
158 
159  DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
160 
161  // Process all basic blocks.
162  for (auto &MBB : MF)
163  processBasicBlock(MF, MBB);
164 
165  DEBUG(dbgs() << "End X86FixupBWInsts\n";);
166 
167  return true;
168 }
169 
170 // TODO: This method of analysis can miss some legal cases, because the
171 // super-register could be live into the address expression for a memory
172 // reference for the instruction, and still be killed/last used by the
173 // instruction. However, the existing query interfaces don't seem to
174 // easily allow that to be checked.
175 //
176 // What we'd really like to know is whether after OrigMI, the
177 // only portion of SuperDestReg that is alive is the portion that
178 // was the destination register of OrigMI.
179 bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
180  unsigned &SuperDestReg) const {
181  auto *TRI = &TII->getRegisterInfo();
182 
183  unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
184  SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
185 
186  const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
187 
188  // Make sure that the sub-register that this instruction has as its
189  // destination is the lowest order sub-register of the super-register.
190  // If it isn't, then the register isn't really dead even if the
191  // super-register is considered dead.
192  if (SubRegIdx == X86::sub_8bit_hi)
193  return false;
194 
195  if (LiveRegs.contains(SuperDestReg))
196  return false;
197 
198  if (SubRegIdx == X86::sub_8bit) {
199  // In the case of byte registers, we also have to check that the upper
200  // byte register is also dead. That is considered to be independent of
201  // whether the super-register is dead.
202  unsigned UpperByteReg =
203  getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true);
204 
205  if (LiveRegs.contains(UpperByteReg))
206  return false;
207  }
208 
209  return true;
210 }
211 
212 MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
213  MachineInstr *MI) const {
214  unsigned NewDestReg;
215 
216  // We are going to try to rewrite this load to a larger zero-extending
217  // load. This is safe if all portions of the 32 bit super-register
218  // of the original destination register, except for the original destination
219  // register are dead. getSuperRegDestIfDead checks that.
220  if (!getSuperRegDestIfDead(MI, NewDestReg))
221  return nullptr;
222 
223  // Safe to change the instruction.
224  MachineInstrBuilder MIB =
225  BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
226 
227  unsigned NumArgs = MI->getNumOperands();
228  for (unsigned i = 1; i < NumArgs; ++i)
229  MIB.addOperand(MI->getOperand(i));
230 
231  MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
232 
233  return MIB;
234 }
235 
236 MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
237  assert(MI->getNumExplicitOperands() == 2);
238  auto &OldDest = MI->getOperand(0);
239  auto &OldSrc = MI->getOperand(1);
240 
241  unsigned NewDestReg;
242  if (!getSuperRegDestIfDead(MI, NewDestReg))
243  return nullptr;
244 
245  unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
246 
247  // This is only correct if we access the same subregister index: otherwise,
248  // we could try to replace "movb %ah, %al" with "movl %eax, %eax".
249  auto *TRI = &TII->getRegisterInfo();
250  if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
251  TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
252  return nullptr;
253 
254  // Safe to change the instruction.
255  // Don't set src flags, as we don't know if we're also killing the superreg.
256  // However, the superregister might not be defined; make it explicit that
257  // we don't care about the higher bits by reading it as Undef, and adding
258  // an imp-use on the original subregister.
259  MachineInstrBuilder MIB =
260  BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg)
261  .addReg(NewSrcReg, RegState::Undef)
262  .addReg(OldSrc.getReg(), RegState::Implicit);
263 
264  // Drop imp-defs/uses that would be redundant with the new def/use.
265  for (auto &Op : MI->implicit_operands())
266  if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
267  MIB.addOperand(Op);
268 
269  return MIB;
270 }
271 
272 MachineInstr *FixupBWInstPass::tryReplaceInstr(
274  bool &WasCandidate) const {
275  MachineInstr *NewMI = nullptr;
276  WasCandidate = false;
277 
278  // See if this is an instruction of the type we are currently looking for.
279  switch (MI->getOpcode()) {
280 
281  case X86::MOV8rm:
282  // Only replace 8 bit loads with the zero extending versions if
283  // in an inner most loop and not optimizing for size. This takes
284  // an extra byte to encode, and provides limited performance upside.
285  if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
286  if (ML->begin() == ML->end() && !OptForSize) {
287  NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI);
288  WasCandidate = true;
289  }
290  }
291  break;
292 
293  case X86::MOV16rm:
294  // Always try to replace 16 bit load with 32 bit zero extending.
295  // Code size is the same, and there is sometimes a perf advantage
296  // from eliminating a false dependence on the upper portion of
297  // the register.
298  NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI);
299  WasCandidate = true;
300  break;
301 
302  case X86::MOV8rr:
303  case X86::MOV16rr:
304  // Always try to replace 8/16 bit copies with a 32 bit copy.
305  // Code size is either less (16) or equal (8), and there is sometimes a
306  // perf advantage from eliminating a false dependence on the upper portion
307  // of the register.
308  NewMI = tryReplaceCopy(MI);
309  WasCandidate = true;
310  break;
311 
312  default:
313  // nothing to do here.
314  break;
315  }
316 
317  return NewMI;
318 }
319 
320 void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
321  MachineBasicBlock &MBB) {
322 
323  // This algorithm doesn't delete the instructions it is replacing
324  // right away. By leaving the existing instructions in place, the
325  // register liveness information doesn't change, and this makes the
326  // analysis that goes on be better than if the replaced instructions
327  // were immediately removed.
328  //
329  // This algorithm always creates a replacement instruction
330  // and notes that and the original in a data structure, until the
331  // whole BB has been analyzed. This keeps the replacement instructions
332  // from making it seem as if the larger register might be live.
334 
335  // Start computing liveness for this block. We iterate from the end to be able
336  // to update this for each instruction.
337  LiveRegs.clear();
338  // We run after PEI, so we need to AddPristinesAndCSRs.
339  LiveRegs.addLiveOuts(MBB);
340 
341  bool WasCandidate = false;
342 
343  for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
344  MachineInstr *MI = &*I;
345 
346  MachineInstr *NewMI = tryReplaceInstr(MI, MBB, WasCandidate);
347 
348  // Add this to replacements if it was a candidate, even if NewMI is
349  // nullptr. We will revisit that in a bit.
350  if (WasCandidate) {
351  MIReplacements.push_back(std::make_pair(MI, NewMI));
352  }
353 
354  // We're done with this instruction, update liveness for the next one.
355  LiveRegs.stepBackward(*MI);
356  }
357 
358  while (!MIReplacements.empty()) {
359  MachineInstr *MI = MIReplacements.back().first;
360  MachineInstr *NewMI = MIReplacements.back().second;
361  MIReplacements.pop_back();
362  if (NewMI) {
363  MBB.insert(MI, NewMI);
364  MBB.erase(MI);
365  }
366  }
367 }
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
#define FIXUPBW_NAME
FunctionPass * createX86FixupBWInsts()
Return a Machine IR pass that selectively replaces certain byte and word instructions by equivalent 3...
size_t i
void initializeFixupBWInstPassPass(PassRegistry &)
#define FIXUPBW_DESC
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:464
AnalysisUsage & addRequired()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:277
const HexagonRegisterInfo & getRegisterInfo() const
HexagonInstrInfo specifics.
MachineBasicBlock * MBB
reverse_iterator rend()
reverse_iterator rbegin()
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:273
mmo_iterator memoperands_end() const
Definition: MachineInstr.h:359
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:279
Represent the analysis usage information of a pass.
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:36
static cl::opt< bool > FixupBWInsts("fixup-byte-word-insts", cl::desc("Change byte and word instructions to larger sizes"), cl::init(true), cl::Hidden)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getX86SubSuperRegister(unsigned, unsigned, bool High=false)
Returns the sub or super register of a specific X86 register.
iterator_range< mop_iterator > implicit_operands()
Definition: MachineInstr.h:315
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:250
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:52
A set of live physical registers with functions to track liveness when walking backward/forward throu...
Definition: LivePhysRegs.h:45
#define I(x, y, z)
Definition: MD5.cpp:54
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const MachineInstrBuilder & addOperand(const MachineOperand &MO) const
#define DEBUG(X)
Definition: Debug.h:100
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd)
Assign this MachineInstr's memory reference descriptor list.
Properties which a MachineFunction may have at a given point in time.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:358