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"
52 #include "llvm/CodeGen/LiveVariables.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/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 using namespace llvm;
62 
63 #define DEBUG_TYPE "x86-fixup-bw-insts"
64 
65 // Option to allow this optimization pass to have fine-grained control.
66 // This is turned off by default so as not to affect a large number of
67 // existing lit tests.
68 static cl::opt<bool>
69     FixupBWInsts("fixup-byte-word-insts",
70                  cl::desc("Change byte and word instructions to larger sizes"),
71                  cl::init(false), cl::Hidden);
72 
73 namespace {
74 class FixupBWInstPass : public MachineFunctionPass {
75   static char ID;
76 
77   const char *getPassName() const override {
78     return "X86 Byte/Word Instruction Fixup";
79   }
80 
81   /// \brief Loop over all of the instructions in the basic block
82   /// replacing applicable byte or word instructions with better
83   /// alternatives.
84   void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB) const;
85 
86   /// \brief This sets the \p SuperDestReg to the 32 bit super reg
87   /// of the original destination register of the MachineInstr
88   /// passed in. It returns true if that super register is dead
89   /// just prior to \p OrigMI, and false if not.
90   /// \pre OrigDestSize must be 8 or 16.
91   bool getSuperRegDestIfDead(MachineInstr *OrigMI, unsigned OrigDestSize,
92                              unsigned &SuperDestReg) const;
93 
94   /// \brief Change the MachineInstr \p MI into the equivalent extending load
95   /// to 32 bit register if it is safe to do so.  Return the replacement
96   /// instruction if OK, otherwise return nullptr.
97   /// \pre OrigDestSize must be 8 or 16.
98   MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, unsigned OrigDestSize,
99                                MachineInstr *MI) const;
100 
101 public:
102   FixupBWInstPass() : MachineFunctionPass(ID) {}
103 
104   void getAnalysisUsage(AnalysisUsage &AU) const override {
105     AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
106                                        // guide some heuristics.
107     MachineFunctionPass::getAnalysisUsage(AU);
108   }
109 
110   /// \brief Loop over all of the basic blocks,
111   /// replacing byte and word instructions by equivalent 32 bit instructions
112   /// where performance or code size can be improved.
113   bool runOnMachineFunction(MachineFunction &MF) override;
114 
115 private:
116   MachineFunction *MF;
117 
118   /// Machine instruction info used throughout the class.
119   const X86InstrInfo *TII;
120 
121   /// Local member for function's OptForSize attribute.
122   bool OptForSize;
123 
124   /// Machine loop info used for guiding some heruistics.
125   MachineLoopInfo *MLI;
126 };
127 char FixupBWInstPass::ID = 0;
128 }
129 
130 FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
131 
132 bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
133   if (!FixupBWInsts)
134     return false;
135 
136   this->MF = &MF;
137   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
138   OptForSize = MF.getFunction()->optForSize();
139   MLI = &getAnalysis<MachineLoopInfo>();
140 
141   DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
142 
143   // Process all basic blocks.
144   for (auto &MBB : MF)
145     processBasicBlock(MF, MBB);
146 
147   DEBUG(dbgs() << "End X86FixupBWInsts\n";);
148 
149   return true;
150 }
151 
152 // TODO: This method of analysis can miss some legal cases, because the
153 // super-register could be live into the address expression for a memory
154 // reference for the instruction, and still be killed/last used by the
155 // instruction. However, the existing query interfaces don't seem to
156 // easily allow that to be checked.
157 //
158 // What we'd really like to know is whether after OrigMI, the
159 // only portion of SuperDestReg that is alive is the portion that
160 // was the destination register of OrigMI.
161 bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
162                                             unsigned OrigDestSize,
163                                             unsigned &SuperDestReg) const {
164 
165   unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
166   SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
167 
168   // Make sure that the sub-register that this instruction has as its
169   // destination is the lowest order sub-register of the super-register.
170   // If it isn't, then the register isn't really dead even if the
171   // super-register is considered dead.
172   // This test works because getX86SubSuperRegister returns the low portion
173   // register by default when getting a sub-register, so if that doesn't
174   // match the original destination register, then the original destination
175   // register must not have been the low register portion of that size.
176   if (getX86SubSuperRegister(SuperDestReg, OrigDestSize) != OrigDestReg)
177     return false;
178 
179   MachineBasicBlock::LivenessQueryResult LQR =
180       OrigMI->getParent()->computeRegisterLiveness(&TII->getRegisterInfo(),
181                                                    SuperDestReg, OrigMI);
182 
183   if (LQR != MachineBasicBlock::LQR_Dead)
184     return false;
185 
186   if (OrigDestSize == 8) {
187     // In the case of byte registers, we also have to check that the upper
188     // byte register is also dead. That is considered to be independent of
189     // whether the super-register is dead.
190     unsigned UpperByteReg = getX86SubSuperRegister(SuperDestReg, 8, true);
191 
192     LQR = OrigMI->getParent()->computeRegisterLiveness(&TII->getRegisterInfo(),
193                                                        UpperByteReg, OrigMI);
194     if (LQR != MachineBasicBlock::LQR_Dead)
195       return false;
196   }
197 
198   return true;
199 }
200 
201 MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
202                                               unsigned OrigDestSize,
203                                               MachineInstr *MI) const {
204   unsigned NewDestReg;
205 
206   // We are going to try to rewrite this load to a larger zero-extending
207   // load.  This is safe if all portions of the 32 bit super-register
208   // of the original destination register, except for the original destination
209   // register are dead. getSuperRegDestIfDead checks that.
210   if (!getSuperRegDestIfDead(MI, OrigDestSize, NewDestReg))
211     return nullptr;
212 
213   // Safe to change the instruction.
214   MachineInstrBuilder MIB =
215       BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
216 
217   unsigned NumArgs = MI->getNumOperands();
218   for (unsigned i = 1; i < NumArgs; ++i)
219     MIB.addOperand(MI->getOperand(i));
220 
221   MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
222 
223   return MIB;
224 }
225 
226 void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
227                                         MachineBasicBlock &MBB) const {
228 
229   // This algorithm doesn't delete the instructions it is replacing
230   // right away.  By leaving the existing instructions in place, the
231   // register liveness information doesn't change, and this makes the
232   // analysis that goes on be better than if the replaced instructions
233   // were immediately removed.
234   //
235   // This algorithm always creates a replacement instruction
236   // and notes that and the original in a data structure, until the
237   // whole BB has been analyzed.  This keeps the replacement instructions
238   // from making it seem as if the larger register might be live.
239   SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
240 
241   for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
242     MachineInstr *NewMI = nullptr;
243     MachineInstr *MI = I;
244 
245     // See if this is an instruction of the type we are currently looking for.
246     switch (MI->getOpcode()) {
247 
248     case X86::MOV8rm:
249       // Only replace 8 bit loads with the zero extending versions if
250       // in an inner most loop and not optimizing for size. This takes
251       // an extra byte to encode, and provides limited performance upside.
252       if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
253         if (ML->begin() == ML->end() && !OptForSize)
254           NewMI = tryReplaceLoad(X86::MOVZX32rm8, 8, MI);
255       }
256       break;
257 
258     case X86::MOV16rm:
259       // Always try to replace 16 bit load with 32 bit zero extending.
260       // Code size is the same, and there is sometimes a perf advantage
261       // from eliminating a false dependence on the upper portion of
262       // the register.
263       NewMI = tryReplaceLoad(X86::MOVZX32rm16, 16, MI);
264       break;
265 
266     default:
267       // nothing to do here.
268       break;
269     }
270 
271     if (NewMI)
272       MIReplacements.push_back(std::make_pair(MI, NewMI));
273   }
274 
275   while (!MIReplacements.empty()) {
276     MachineInstr *MI = MIReplacements.back().first;
277     MachineInstr *NewMI = MIReplacements.back().second;
278     MIReplacements.pop_back();
279     MBB.insert(MI, NewMI);
280     MBB.erase(MI);
281   }
282 }
283