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 registers, 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"
52 #include "llvm/CodeGen/LivePhysRegs.h"
53 #include "llvm/CodeGen/MachineFunctionPass.h"
54 #include "llvm/CodeGen/MachineInstrBuilder.h"
55 #include "llvm/CodeGen/MachineLoopInfo.h"
56 #include "llvm/CodeGen/MachineRegisterInfo.h"
57 #include "llvm/CodeGen/Passes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/raw_ostream.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.
99   MachineInstr *tryReplaceInstr(MachineInstr *MI, MachineBasicBlock &MBB) const;
100 
101 public:
102   static char ID;
103 
getPassName() const104   StringRef getPassName() const override { return FIXUPBW_DESC; }
105 
FixupBWInstPass()106   FixupBWInstPass() : MachineFunctionPass(ID) {
107     initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry());
108   }
109 
getAnalysisUsage(AnalysisUsage & AU) const110   void getAnalysisUsage(AnalysisUsage &AU) const override {
111     AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
112                                        // guide some heuristics.
113     MachineFunctionPass::getAnalysisUsage(AU);
114   }
115 
116   /// Loop over all of the basic blocks, replacing byte and word instructions by
117   /// equivalent 32 bit instructions where performance or code size can be
118   /// improved.
119   bool runOnMachineFunction(MachineFunction &MF) override;
120 
getRequiredProperties() const121   MachineFunctionProperties getRequiredProperties() const override {
122     return MachineFunctionProperties().set(
123         MachineFunctionProperties::Property::NoVRegs);
124   }
125 
126 private:
127   MachineFunction *MF;
128 
129   /// Machine instruction info used throughout the class.
130   const X86InstrInfo *TII;
131 
132   /// Local member for function's OptForSize attribute.
133   bool OptForSize;
134 
135   /// Machine loop info used for guiding some heruistics.
136   MachineLoopInfo *MLI;
137 
138   /// Register Liveness information after the current instruction.
139   LivePhysRegs LiveRegs;
140 };
141 char FixupBWInstPass::ID = 0;
142 }
143 
INITIALIZE_PASS(FixupBWInstPass,FIXUPBW_NAME,FIXUPBW_DESC,false,false)144 INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
145 
146 FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
147 
runOnMachineFunction(MachineFunction & MF)148 bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
149   if (!FixupBWInsts || skipFunction(MF.getFunction()))
150     return false;
151 
152   this->MF = &MF;
153   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
154   OptForSize = MF.getFunction().optForSize();
155   MLI = &getAnalysis<MachineLoopInfo>();
156   LiveRegs.init(TII->getRegisterInfo());
157 
158   LLVM_DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
159 
160   // Process all basic blocks.
161   for (auto &MBB : MF)
162     processBasicBlock(MF, MBB);
163 
164   LLVM_DEBUG(dbgs() << "End X86FixupBWInsts\n";);
165 
166   return true;
167 }
168 
169 /// Check if after \p OrigMI the only portion of super register
170 /// of the destination register of \p OrigMI that is alive is that
171 /// destination register.
172 ///
173 /// If so, return that super register in \p SuperDestReg.
getSuperRegDestIfDead(MachineInstr * OrigMI,unsigned & SuperDestReg) const174 bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
175                                             unsigned &SuperDestReg) const {
176   auto *TRI = &TII->getRegisterInfo();
177 
178   unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
179   SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
180 
181   const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
182 
183   // Make sure that the sub-register that this instruction has as its
184   // destination is the lowest order sub-register of the super-register.
185   // If it isn't, then the register isn't really dead even if the
186   // super-register is considered dead.
187   if (SubRegIdx == X86::sub_8bit_hi)
188     return false;
189 
190   // If neither the destination-super register nor any applicable subregisters
191   // are live after this instruction, then the super register is safe to use.
192   if (!LiveRegs.contains(SuperDestReg)) {
193     // If the original destination register was not the low 8-bit subregister
194     // then the super register check is sufficient.
195     if (SubRegIdx != X86::sub_8bit)
196       return true;
197     // If the original destination register was the low 8-bit subregister and
198     // we also need to check the 16-bit subregister and the high 8-bit
199     // subregister.
200     if (!LiveRegs.contains(getX86SubSuperRegister(OrigDestReg, 16)) &&
201         !LiveRegs.contains(getX86SubSuperRegister(SuperDestReg, 8,
202                                                   /*High=*/true)))
203       return true;
204     // Otherwise, we have a little more checking to do.
205   }
206 
207   // If we get here, the super-register destination (or some part of it) is
208   // marked as live after the original instruction.
209   //
210   // The X86 backend does not have subregister liveness tracking enabled,
211   // so liveness information might be overly conservative. Specifically, the
212   // super register might be marked as live because it is implicitly defined
213   // by the instruction we are examining.
214   //
215   // However, for some specific instructions (this pass only cares about MOVs)
216   // we can produce more precise results by analysing that MOV's operands.
217   //
218   // Indeed, if super-register is not live before the mov it means that it
219   // was originally <read-undef> and so we are free to modify these
220   // undef upper bits. That may happen in case where the use is in another MBB
221   // and the vreg/physreg corresponding to the move has higher width than
222   // necessary (e.g. due to register coalescing with a "truncate" copy).
223   // So, we would like to handle patterns like this:
224   //
225   //   %bb.2: derived from LLVM BB %if.then
226   //   Live Ins: %rdi
227   //   Predecessors according to CFG: %bb.0
228   //   %ax<def> = MOV16rm killed %rdi, 1, %noreg, 0, %noreg, implicit-def %eax
229   //                                 ; No implicit %eax
230   //   Successors according to CFG: %bb.3(?%)
231   //
232   //   %bb.3: derived from LLVM BB %if.end
233   //   Live Ins: %eax                            Only %ax is actually live
234   //   Predecessors according to CFG: %bb.2 %bb.1
235   //   %ax = KILL %ax, implicit killed %eax
236   //   RET 0, %ax
237   unsigned Opc = OrigMI->getOpcode(); (void)Opc;
238   // These are the opcodes currently handled by the pass, if something
239   // else will be added we need to ensure that new opcode has the same
240   // properties.
241   assert((Opc == X86::MOV8rm || Opc == X86::MOV16rm || Opc == X86::MOV8rr ||
242           Opc == X86::MOV16rr) &&
243          "Unexpected opcode.");
244 
245   bool IsDefined = false;
246   for (auto &MO: OrigMI->implicit_operands()) {
247     if (!MO.isReg())
248       continue;
249 
250     assert((MO.isDef() || MO.isUse()) && "Expected Def or Use only!");
251 
252     if (MO.isDef() && TRI->isSuperRegisterEq(OrigDestReg, MO.getReg()))
253         IsDefined = true;
254 
255     // If MO is a use of any part of the destination register but is not equal
256     // to OrigDestReg or one of its subregisters, we cannot use SuperDestReg.
257     // For example, if OrigDestReg is %al then an implicit use of %ah, %ax,
258     // %eax, or %rax will prevent us from using the %eax register.
259     if (MO.isUse() && !TRI->isSubRegisterEq(OrigDestReg, MO.getReg()) &&
260         TRI->regsOverlap(SuperDestReg, MO.getReg()))
261       return false;
262   }
263   // Reg is not Imp-def'ed -> it's live both before/after the instruction.
264   if (!IsDefined)
265     return false;
266 
267   // Otherwise, the Reg is not live before the MI and the MOV can't
268   // make it really live, so it's in fact dead even after the MI.
269   return true;
270 }
271 
tryReplaceLoad(unsigned New32BitOpcode,MachineInstr * MI) const272 MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
273                                               MachineInstr *MI) const {
274   unsigned NewDestReg;
275 
276   // We are going to try to rewrite this load to a larger zero-extending
277   // load.  This is safe if all portions of the 32 bit super-register
278   // of the original destination register, except for the original destination
279   // register are dead. getSuperRegDestIfDead checks that.
280   if (!getSuperRegDestIfDead(MI, NewDestReg))
281     return nullptr;
282 
283   // Safe to change the instruction.
284   MachineInstrBuilder MIB =
285       BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
286 
287   unsigned NumArgs = MI->getNumOperands();
288   for (unsigned i = 1; i < NumArgs; ++i)
289     MIB.add(MI->getOperand(i));
290 
291   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
292 
293   return MIB;
294 }
295 
tryReplaceCopy(MachineInstr * MI) const296 MachineInstr *FixupBWInstPass::tryReplaceCopy(MachineInstr *MI) const {
297   assert(MI->getNumExplicitOperands() == 2);
298   auto &OldDest = MI->getOperand(0);
299   auto &OldSrc = MI->getOperand(1);
300 
301   unsigned NewDestReg;
302   if (!getSuperRegDestIfDead(MI, NewDestReg))
303     return nullptr;
304 
305   unsigned NewSrcReg = getX86SubSuperRegister(OldSrc.getReg(), 32);
306 
307   // This is only correct if we access the same subregister index: otherwise,
308   // we could try to replace "movb %ah, %al" with "movl %eax, %eax".
309   auto *TRI = &TII->getRegisterInfo();
310   if (TRI->getSubRegIndex(NewSrcReg, OldSrc.getReg()) !=
311       TRI->getSubRegIndex(NewDestReg, OldDest.getReg()))
312     return nullptr;
313 
314   // Safe to change the instruction.
315   // Don't set src flags, as we don't know if we're also killing the superreg.
316   // However, the superregister might not be defined; make it explicit that
317   // we don't care about the higher bits by reading it as Undef, and adding
318   // an imp-use on the original subregister.
319   MachineInstrBuilder MIB =
320       BuildMI(*MF, MI->getDebugLoc(), TII->get(X86::MOV32rr), NewDestReg)
321           .addReg(NewSrcReg, RegState::Undef)
322           .addReg(OldSrc.getReg(), RegState::Implicit);
323 
324   // Drop imp-defs/uses that would be redundant with the new def/use.
325   for (auto &Op : MI->implicit_operands())
326     if (Op.getReg() != (Op.isDef() ? NewDestReg : NewSrcReg))
327       MIB.add(Op);
328 
329   return MIB;
330 }
331 
tryReplaceInstr(MachineInstr * MI,MachineBasicBlock & MBB) const332 MachineInstr *FixupBWInstPass::tryReplaceInstr(MachineInstr *MI,
333                                                MachineBasicBlock &MBB) const {
334   // See if this is an instruction of the type we are currently looking for.
335   switch (MI->getOpcode()) {
336 
337   case X86::MOV8rm:
338     // Only replace 8 bit loads with the zero extending versions if
339     // in an inner most loop and not optimizing for size. This takes
340     // an extra byte to encode, and provides limited performance upside.
341     if (MachineLoop *ML = MLI->getLoopFor(&MBB))
342       if (ML->begin() == ML->end() && !OptForSize)
343         return tryReplaceLoad(X86::MOVZX32rm8, MI);
344     break;
345 
346   case X86::MOV16rm:
347     // Always try to replace 16 bit load with 32 bit zero extending.
348     // Code size is the same, and there is sometimes a perf advantage
349     // from eliminating a false dependence on the upper portion of
350     // the register.
351     return tryReplaceLoad(X86::MOVZX32rm16, MI);
352 
353   case X86::MOV8rr:
354   case X86::MOV16rr:
355     // Always try to replace 8/16 bit copies with a 32 bit copy.
356     // Code size is either less (16) or equal (8), and there is sometimes a
357     // perf advantage from eliminating a false dependence on the upper portion
358     // of the register.
359     return tryReplaceCopy(MI);
360 
361   default:
362     // nothing to do here.
363     break;
364   }
365 
366   return nullptr;
367 }
368 
processBasicBlock(MachineFunction & MF,MachineBasicBlock & MBB)369 void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
370                                         MachineBasicBlock &MBB) {
371 
372   // This algorithm doesn't delete the instructions it is replacing
373   // right away.  By leaving the existing instructions in place, the
374   // register liveness information doesn't change, and this makes the
375   // analysis that goes on be better than if the replaced instructions
376   // were immediately removed.
377   //
378   // This algorithm always creates a replacement instruction
379   // and notes that and the original in a data structure, until the
380   // whole BB has been analyzed.  This keeps the replacement instructions
381   // from making it seem as if the larger register might be live.
382   SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
383 
384   // Start computing liveness for this block. We iterate from the end to be able
385   // to update this for each instruction.
386   LiveRegs.clear();
387   // We run after PEI, so we need to AddPristinesAndCSRs.
388   LiveRegs.addLiveOuts(MBB);
389 
390   for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
391     MachineInstr *MI = &*I;
392 
393     if (MachineInstr *NewMI = tryReplaceInstr(MI, MBB))
394       MIReplacements.push_back(std::make_pair(MI, NewMI));
395 
396     // We're done with this instruction, update liveness for the next one.
397     LiveRegs.stepBackward(*MI);
398   }
399 
400   while (!MIReplacements.empty()) {
401     MachineInstr *MI = MIReplacements.back().first;
402     MachineInstr *NewMI = MIReplacements.back().second;
403     MIReplacements.pop_back();
404     MBB.insert(MI, NewMI);
405     MBB.erase(MI);
406   }
407 }
408