blob: 520376921859b348da87688e114d908d26c627bf [file] [log] [blame]
Kevin B. Smith6a833502016-02-11 19:43:04 +00001//===-- 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"
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +000052#include "llvm/CodeGen/LivePhysRegs.h"
Kevin B. Smith6a833502016-02-11 19:43:04 +000053#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"
61using 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.
68static cl::opt<bool>
69 FixupBWInsts("fixup-byte-word-insts",
70 cl::desc("Change byte and word instructions to larger sizes"),
Kevin B. Smithe0a6fc32016-04-08 18:58:29 +000071 cl::init(true), cl::Hidden);
Kevin B. Smith6a833502016-02-11 19:43:04 +000072
73namespace {
74class 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.
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +000084 void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
Kevin B. Smith6a833502016-02-11 19:43:04 +000085
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
101public:
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
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000115 MachineFunctionProperties getRequiredProperties() const override {
116 return MachineFunctionProperties().set(
117 MachineFunctionProperties::Property::AllVRegsAllocated);
118 }
119
Kevin B. Smith6a833502016-02-11 19:43:04 +0000120private:
121 MachineFunction *MF;
122
123 /// Machine instruction info used throughout the class.
124 const X86InstrInfo *TII;
125
126 /// Local member for function's OptForSize attribute.
127 bool OptForSize;
128
129 /// Machine loop info used for guiding some heruistics.
130 MachineLoopInfo *MLI;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000131
132 /// Register Liveness information after the current instruction.
133 LivePhysRegs LiveRegs;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000134};
135char FixupBWInstPass::ID = 0;
136}
137
138FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
139
140bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor2bee5ef2016-04-26 21:44:24 +0000141 if (!FixupBWInsts || skipFunction(*MF.getFunction()))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000142 return false;
143
144 this->MF = &MF;
145 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
146 OptForSize = MF.getFunction()->optForSize();
147 MLI = &getAnalysis<MachineLoopInfo>();
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000148 LiveRegs.init(&TII->getRegisterInfo());
Kevin B. Smith6a833502016-02-11 19:43:04 +0000149
150 DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
151
152 // Process all basic blocks.
153 for (auto &MBB : MF)
154 processBasicBlock(MF, MBB);
155
156 DEBUG(dbgs() << "End X86FixupBWInsts\n";);
157
158 return true;
159}
160
161// TODO: This method of analysis can miss some legal cases, because the
162// super-register could be live into the address expression for a memory
163// reference for the instruction, and still be killed/last used by the
164// instruction. However, the existing query interfaces don't seem to
165// easily allow that to be checked.
166//
167// What we'd really like to know is whether after OrigMI, the
168// only portion of SuperDestReg that is alive is the portion that
169// was the destination register of OrigMI.
170bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
171 unsigned OrigDestSize,
172 unsigned &SuperDestReg) const {
173
174 unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
175 SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
176
177 // Make sure that the sub-register that this instruction has as its
178 // destination is the lowest order sub-register of the super-register.
179 // If it isn't, then the register isn't really dead even if the
180 // super-register is considered dead.
181 // This test works because getX86SubSuperRegister returns the low portion
182 // register by default when getting a sub-register, so if that doesn't
183 // match the original destination register, then the original destination
184 // register must not have been the low register portion of that size.
185 if (getX86SubSuperRegister(SuperDestReg, OrigDestSize) != OrigDestReg)
186 return false;
187
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000188 if (LiveRegs.contains(SuperDestReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000189 return false;
190
191 if (OrigDestSize == 8) {
192 // In the case of byte registers, we also have to check that the upper
193 // byte register is also dead. That is considered to be independent of
194 // whether the super-register is dead.
195 unsigned UpperByteReg = getX86SubSuperRegister(SuperDestReg, 8, true);
196
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000197 if (LiveRegs.contains(UpperByteReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000198 return false;
199 }
200
201 return true;
202}
203
204MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
205 unsigned OrigDestSize,
206 MachineInstr *MI) const {
207 unsigned NewDestReg;
208
209 // We are going to try to rewrite this load to a larger zero-extending
210 // load. This is safe if all portions of the 32 bit super-register
211 // of the original destination register, except for the original destination
212 // register are dead. getSuperRegDestIfDead checks that.
213 if (!getSuperRegDestIfDead(MI, OrigDestSize, NewDestReg))
214 return nullptr;
215
216 // Safe to change the instruction.
217 MachineInstrBuilder MIB =
218 BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
219
220 unsigned NumArgs = MI->getNumOperands();
221 for (unsigned i = 1; i < NumArgs; ++i)
222 MIB.addOperand(MI->getOperand(i));
223
224 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
225
226 return MIB;
227}
228
229void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000230 MachineBasicBlock &MBB) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000231
232 // This algorithm doesn't delete the instructions it is replacing
233 // right away. By leaving the existing instructions in place, the
234 // register liveness information doesn't change, and this makes the
235 // analysis that goes on be better than if the replaced instructions
236 // were immediately removed.
237 //
238 // This algorithm always creates a replacement instruction
239 // and notes that and the original in a data structure, until the
240 // whole BB has been analyzed. This keeps the replacement instructions
241 // from making it seem as if the larger register might be live.
242 SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
243
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000244 // Start computing liveness for this block. We iterate from the end to be able
245 // to update this for each instruction.
246 LiveRegs.clear();
247 LiveRegs.addLiveOuts(&MBB);
248
249 for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000250 MachineInstr *NewMI = nullptr;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000251 MachineInstr *MI = &*I;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000252
253 // See if this is an instruction of the type we are currently looking for.
254 switch (MI->getOpcode()) {
255
256 case X86::MOV8rm:
257 // Only replace 8 bit loads with the zero extending versions if
258 // in an inner most loop and not optimizing for size. This takes
259 // an extra byte to encode, and provides limited performance upside.
260 if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
261 if (ML->begin() == ML->end() && !OptForSize)
262 NewMI = tryReplaceLoad(X86::MOVZX32rm8, 8, MI);
263 }
264 break;
265
266 case X86::MOV16rm:
267 // Always try to replace 16 bit load with 32 bit zero extending.
268 // Code size is the same, and there is sometimes a perf advantage
269 // from eliminating a false dependence on the upper portion of
270 // the register.
271 NewMI = tryReplaceLoad(X86::MOVZX32rm16, 16, MI);
272 break;
273
274 default:
275 // nothing to do here.
276 break;
277 }
278
279 if (NewMI)
280 MIReplacements.push_back(std::make_pair(MI, NewMI));
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000281
282 // We're done with this instruction, update liveness for the next one.
283 LiveRegs.stepBackward(*MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000284 }
285
286 while (!MIReplacements.empty()) {
287 MachineInstr *MI = MIReplacements.back().first;
288 MachineInstr *NewMI = MIReplacements.back().second;
289 MIReplacements.pop_back();
290 MBB.insert(MI, NewMI);
291 MBB.erase(MI);
292 }
293}