blob: 28c0757b2b663e214324be7f46fd2130678f56fa [file] [log] [blame]
Alexey Bataev7cf32472015-12-04 10:53:15 +00001//===-- X86OptimizeLEAs.cpp - optimize usage of LEA 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//
10// This file defines the pass that performs some optimizations with LEA
Andrey Turetskiy45b22a42016-05-19 10:18:29 +000011// instructions in order to improve performance and code size.
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000012// Currently, it does two things:
13// 1) If there are two LEA instructions calculating addresses which only differ
14// by displacement inside a basic block, one of them is removed.
15// 2) Address calculations in load and store instructions are replaced by
Alexey Bataev7cf32472015-12-04 10:53:15 +000016// existing LEA def registers where possible.
17//
18//===----------------------------------------------------------------------===//
19
20#include "X86.h"
21#include "X86InstrInfo.h"
22#include "X86Subtarget.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/CodeGen/LiveVariables.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
Andrey Turetskiy0babd262016-02-20 10:58:28 +000027#include "llvm/CodeGen/MachineOperand.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/Passes.h"
Andrew Ng03e35b62017-04-28 08:44:30 +000030#include "llvm/IR/DebugInfoMetadata.h"
31#include "llvm/IR/DIBuilder.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000032#include "llvm/IR/Function.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetInstrInfo.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE "x86-optimize-LEAs"
40
Andrey Turetskiy9994b882016-02-20 11:11:55 +000041static cl::opt<bool>
42 DisableX86LEAOpt("disable-x86-lea-opt", cl::Hidden,
43 cl::desc("X86: Disable LEA optimizations."),
44 cl::init(false));
Alexey Bataev7b72b652015-12-17 07:34:39 +000045
Alexey Bataev7cf32472015-12-04 10:53:15 +000046STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000047STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
Alexey Bataev7cf32472015-12-04 10:53:15 +000048
Andrey Turetskiybca0f992016-02-04 08:57:03 +000049/// \brief Returns true if two machine operands are identical and they are not
50/// physical registers.
51static inline bool isIdenticalOp(const MachineOperand &MO1,
52 const MachineOperand &MO2);
53
Andrey Turetskiy0babd262016-02-20 10:58:28 +000054/// \brief Returns true if two address displacement operands are of the same
55/// type and use the same symbol/index/address regardless of the offset.
56static bool isSimilarDispOp(const MachineOperand &MO1,
57 const MachineOperand &MO2);
58
Andrey Turetskiybca0f992016-02-04 08:57:03 +000059/// \brief Returns true if the instruction is LEA.
60static inline bool isLEA(const MachineInstr &MI);
61
Benjamin Kramerb7d33112016-08-06 11:13:10 +000062namespace {
Andrey Turetskiybca0f992016-02-04 08:57:03 +000063/// A key based on instruction's memory operands.
64class MemOpKey {
65public:
66 MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
67 const MachineOperand *Index, const MachineOperand *Segment,
68 const MachineOperand *Disp)
69 : Disp(Disp) {
70 Operands[0] = Base;
71 Operands[1] = Scale;
72 Operands[2] = Index;
73 Operands[3] = Segment;
74 }
75
76 bool operator==(const MemOpKey &Other) const {
77 // Addresses' bases, scales, indices and segments must be identical.
78 for (int i = 0; i < 4; ++i)
79 if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
80 return false;
81
Andrey Turetskiy0babd262016-02-20 10:58:28 +000082 // Addresses' displacements don't have to be exactly the same. It only
83 // matters that they use the same symbol/index/address. Immediates' or
84 // offsets' differences will be taken care of during instruction
85 // substitution.
86 return isSimilarDispOp(*Disp, *Other.Disp);
Andrey Turetskiybca0f992016-02-04 08:57:03 +000087 }
88
89 // Address' base, scale, index and segment operands.
90 const MachineOperand *Operands[4];
91
92 // Address' displacement operand.
93 const MachineOperand *Disp;
94};
Benjamin Kramerb7d33112016-08-06 11:13:10 +000095} // end anonymous namespace
Andrey Turetskiybca0f992016-02-04 08:57:03 +000096
97/// Provide DenseMapInfo for MemOpKey.
98namespace llvm {
99template <> struct DenseMapInfo<MemOpKey> {
100 typedef DenseMapInfo<const MachineOperand *> PtrInfo;
101
102 static inline MemOpKey getEmptyKey() {
103 return MemOpKey(PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
104 PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
105 PtrInfo::getEmptyKey());
106 }
107
108 static inline MemOpKey getTombstoneKey() {
109 return MemOpKey(PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
110 PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
111 PtrInfo::getTombstoneKey());
112 }
113
114 static unsigned getHashValue(const MemOpKey &Val) {
115 // Checking any field of MemOpKey is enough to determine if the key is
116 // empty or tombstone.
117 assert(Val.Disp != PtrInfo::getEmptyKey() && "Cannot hash the empty key");
118 assert(Val.Disp != PtrInfo::getTombstoneKey() &&
119 "Cannot hash the tombstone key");
120
121 hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
122 *Val.Operands[2], *Val.Operands[3]);
123
124 // If the address displacement is an immediate, it should not affect the
125 // hash so that memory operands which differ only be immediate displacement
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000126 // would have the same hash. If the address displacement is something else,
127 // we should reflect symbol/index/address in the hash.
128 switch (Val.Disp->getType()) {
129 case MachineOperand::MO_Immediate:
130 break;
131 case MachineOperand::MO_ConstantPoolIndex:
132 case MachineOperand::MO_JumpTableIndex:
133 Hash = hash_combine(Hash, Val.Disp->getIndex());
134 break;
135 case MachineOperand::MO_ExternalSymbol:
136 Hash = hash_combine(Hash, Val.Disp->getSymbolName());
137 break;
138 case MachineOperand::MO_GlobalAddress:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000139 Hash = hash_combine(Hash, Val.Disp->getGlobal());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000140 break;
141 case MachineOperand::MO_BlockAddress:
142 Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
143 break;
144 case MachineOperand::MO_MCSymbol:
145 Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
146 break;
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000147 case MachineOperand::MO_MachineBasicBlock:
148 Hash = hash_combine(Hash, Val.Disp->getMBB());
149 break;
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000150 default:
151 llvm_unreachable("Invalid address displacement operand");
152 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000153
154 return (unsigned)Hash;
155 }
156
157 static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
158 // Checking any field of MemOpKey is enough to determine if the key is
159 // empty or tombstone.
160 if (RHS.Disp == PtrInfo::getEmptyKey())
161 return LHS.Disp == PtrInfo::getEmptyKey();
162 if (RHS.Disp == PtrInfo::getTombstoneKey())
163 return LHS.Disp == PtrInfo::getTombstoneKey();
164 return LHS == RHS;
165 }
166};
167}
168
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000169/// \brief Returns a hash table key based on memory operands of \p MI. The
170/// number of the first memory operand of \p MI is specified through \p N.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000171static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
172 assert((isLEA(MI) || MI.mayLoadOrStore()) &&
173 "The instruction must be a LEA, a load or a store");
174 return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
175 &MI.getOperand(N + X86::AddrScaleAmt),
176 &MI.getOperand(N + X86::AddrIndexReg),
177 &MI.getOperand(N + X86::AddrSegmentReg),
178 &MI.getOperand(N + X86::AddrDisp));
179}
180
181static inline bool isIdenticalOp(const MachineOperand &MO1,
182 const MachineOperand &MO2) {
183 return MO1.isIdenticalTo(MO2) &&
184 (!MO1.isReg() ||
185 !TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
186}
187
Justin Bogner38e52172016-02-24 07:58:02 +0000188#ifndef NDEBUG
189static bool isValidDispOp(const MachineOperand &MO) {
190 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000191 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol() || MO.isMBB();
Justin Bogner38e52172016-02-24 07:58:02 +0000192}
193#endif
194
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000195static bool isSimilarDispOp(const MachineOperand &MO1,
196 const MachineOperand &MO2) {
197 assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
198 "Address displacement operand is not valid");
199 return (MO1.isImm() && MO2.isImm()) ||
200 (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
201 (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
202 (MO1.isSymbol() && MO2.isSymbol() &&
203 MO1.getSymbolName() == MO2.getSymbolName()) ||
204 (MO1.isGlobal() && MO2.isGlobal() &&
205 MO1.getGlobal() == MO2.getGlobal()) ||
206 (MO1.isBlockAddress() && MO2.isBlockAddress() &&
207 MO1.getBlockAddress() == MO2.getBlockAddress()) ||
208 (MO1.isMCSymbol() && MO2.isMCSymbol() &&
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000209 MO1.getMCSymbol() == MO2.getMCSymbol()) ||
210 (MO1.isMBB() && MO2.isMBB() && MO1.getMBB() == MO2.getMBB());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000211}
212
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000213static inline bool isLEA(const MachineInstr &MI) {
214 unsigned Opcode = MI.getOpcode();
215 return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
216 Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
217}
218
Alexey Bataev7cf32472015-12-04 10:53:15 +0000219namespace {
220class OptimizeLEAPass : public MachineFunctionPass {
221public:
222 OptimizeLEAPass() : MachineFunctionPass(ID) {}
223
Mehdi Amini117296c2016-10-01 02:56:57 +0000224 StringRef getPassName() const override { return "X86 LEA Optimize"; }
Alexey Bataev7cf32472015-12-04 10:53:15 +0000225
Andrew Ng03e35b62017-04-28 08:44:30 +0000226 bool doInitialization(Module &M) override;
227
Alexey Bataev7cf32472015-12-04 10:53:15 +0000228 /// \brief Loop over all of the basic blocks, replacing address
229 /// calculations in load and store instructions, if it's already
230 /// been calculated by LEA. Also, remove redundant LEAs.
231 bool runOnMachineFunction(MachineFunction &MF) override;
232
233private:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000234 typedef DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>> MemOpMap;
235
Alexey Bataev7cf32472015-12-04 10:53:15 +0000236 /// \brief Returns a distance between two instructions inside one basic block.
237 /// Negative result means, that instructions occur in reverse order.
238 int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
239
240 /// \brief Choose the best \p LEA instruction from the \p List to replace
241 /// address calculation in \p MI instruction. Return the address displacement
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000242 /// and the distance between \p MI and the chosen \p BestLEA in
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000243 /// \p AddrDispShift and \p Dist.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000244 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000245 const MachineInstr &MI, MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000246 int64_t &AddrDispShift, int &Dist);
247
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000248 /// \brief Returns the difference between addresses' displacements of \p MI1
249 /// and \p MI2. The numbers of the first memory operands for the instructions
250 /// are specified through \p N1 and \p N2.
251 int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
252 const MachineInstr &MI2, unsigned N2) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000253
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000254 /// \brief Returns true if the \p Last LEA instruction can be replaced by the
255 /// \p First. The difference between displacements of the addresses calculated
256 /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
257 /// replacement of the \p Last LEA's uses with the \p First's def register.
258 bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000259 int64_t &AddrDispShift) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000260
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000261 /// \brief Find all LEA instructions in the basic block. Also, assign position
262 /// numbers to all instructions in the basic block to speed up calculation of
263 /// distance between them.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000264 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000265
266 /// \brief Removes redundant address calculations.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000267 bool removeRedundantAddrCalc(MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000268
Andrew Ng03e35b62017-04-28 08:44:30 +0000269 /// Replace debug value MI with a new debug value instruction using register
270 /// VReg with an appropriate offset and DIExpression to incorporate the
271 /// address displacement AddrDispShift. Return new debug value instruction.
272 MachineInstr *replaceDebugValue(MachineInstr &MI, unsigned VReg,
273 int64_t AddrDispShift);
274
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000275 /// \brief Removes LEAs which calculate similar addresses.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000276 bool removeRedundantLEAs(MemOpMap &LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000277
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000278 DenseMap<const MachineInstr *, unsigned> InstrPos;
279
Alexey Bataev7cf32472015-12-04 10:53:15 +0000280 MachineRegisterInfo *MRI;
281 const X86InstrInfo *TII;
282 const X86RegisterInfo *TRI;
Andrew Ng03e35b62017-04-28 08:44:30 +0000283 Module *TheModule;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000284
285 static char ID;
286};
287char OptimizeLEAPass::ID = 0;
288}
289
290FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
291
292int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
293 const MachineInstr &Last) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000294 // Both instructions must be in the same basic block and they must be
295 // presented in InstrPos.
296 assert(Last.getParent() == First.getParent() &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000297 "Instructions are in different basic blocks");
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000298 assert(InstrPos.find(&First) != InstrPos.end() &&
299 InstrPos.find(&Last) != InstrPos.end() &&
300 "Instructions' positions are undefined");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000301
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000302 return InstrPos[&Last] - InstrPos[&First];
Alexey Bataev7cf32472015-12-04 10:53:15 +0000303}
304
305// Find the best LEA instruction in the List to replace address recalculation in
306// MI. Such LEA must meet these requirements:
307// 1) The address calculated by the LEA differs only by the displacement from
308// the address used in MI.
309// 2) The register class of the definition of the LEA is compatible with the
310// register class of the address base register of MI.
311// 3) Displacement of the new memory operand should fit in 1 byte if possible.
312// 4) The LEA should be as close to MI as possible, and prior to it if
313// possible.
314bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000315 const MachineInstr &MI,
316 MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000317 int64_t &AddrDispShift, int &Dist) {
318 const MachineFunction *MF = MI.getParent()->getParent();
319 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000320 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags) +
Alexey Bataev7cf32472015-12-04 10:53:15 +0000321 X86II::getOperandBias(Desc);
322
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000323 BestLEA = nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000324
325 // Loop over all LEA instructions.
326 for (auto DefMI : List) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000327 // Get new address displacement.
328 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000329
330 // Make sure address displacement fits 4 bytes.
331 if (!isInt<32>(AddrDispShiftTemp))
332 continue;
333
334 // Check that LEA def register can be used as MI address base. Some
335 // instructions can use a limited set of registers as address base, for
336 // example MOV8mr_NOREX. We could constrain the register class of the LEA
337 // def to suit MI, however since this case is very rare and hard to
338 // reproduce in a test it's just more reliable to skip the LEA.
339 if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
340 MRI->getRegClass(DefMI->getOperand(0).getReg()))
341 continue;
342
343 // Choose the closest LEA instruction from the list, prior to MI if
344 // possible. Note that we took into account resulting address displacement
345 // as well. Also note that the list is sorted by the order in which the LEAs
346 // occur, so the break condition is pretty simple.
347 int DistTemp = calcInstrDist(*DefMI, MI);
348 assert(DistTemp != 0 &&
349 "The distance between two different instructions cannot be zero");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000350 if (DistTemp > 0 || BestLEA == nullptr) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000351 // Do not update return LEA, if the current one provides a displacement
352 // which fits in 1 byte, while the new candidate does not.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000353 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000354 isInt<8>(AddrDispShift))
355 continue;
356
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000357 BestLEA = DefMI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000358 AddrDispShift = AddrDispShiftTemp;
359 Dist = DistTemp;
360 }
361
362 // FIXME: Maybe we should not always stop at the first LEA after MI.
363 if (DistTemp < 0)
364 break;
365 }
366
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000367 return BestLEA != nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000368}
369
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000370// Get the difference between the addresses' displacements of the two
371// instructions \p MI1 and \p MI2. The numbers of the first memory operands are
372// passed through \p N1 and \p N2.
373int64_t OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1, unsigned N1,
374 const MachineInstr &MI2,
375 unsigned N2) const {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000376 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
377 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000378
379 assert(isSimilarDispOp(Op1, Op2) &&
380 "Address displacement operands are not compatible");
381
382 // After the assert above we can be sure that both operands are of the same
383 // valid type and use the same symbol/index/address, thus displacement shift
384 // calculation is rather simple.
385 if (Op1.isJTI())
386 return 0;
387 return Op1.isImm() ? Op1.getImm() - Op2.getImm()
388 : Op1.getOffset() - Op2.getOffset();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000389}
390
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000391// Check that the Last LEA can be replaced by the First LEA. To be so,
392// these requirements must be met:
393// 1) Addresses calculated by LEAs differ only by displacement.
394// 2) Def registers of LEAs belong to the same class.
395// 3) All uses of the Last LEA def register are replaceable, thus the
396// register is used only as address base.
397bool OptimizeLEAPass::isReplaceable(const MachineInstr &First,
398 const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000399 int64_t &AddrDispShift) const {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000400 assert(isLEA(First) && isLEA(Last) &&
401 "The function works only with LEA instructions");
402
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000403 // Make sure that LEA def registers belong to the same class. There may be
404 // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
405 // be used as their operands, so we must be sure that replacing one LEA
406 // with another won't lead to putting a wrong register in the instruction.
407 if (MRI->getRegClass(First.getOperand(0).getReg()) !=
408 MRI->getRegClass(Last.getOperand(0).getReg()))
409 return false;
410
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000411 // Get new address displacement.
412 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
413
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000414 // Loop over all uses of the Last LEA to check that its def register is
415 // used only as address base for memory accesses. If so, it can be
416 // replaced, otherwise - no.
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000417 for (auto &MO : MRI->use_nodbg_operands(Last.getOperand(0).getReg())) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000418 MachineInstr &MI = *MO.getParent();
419
420 // Get the number of the first memory operand.
421 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000422 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000423
424 // If the use instruction has no memory operand - the LEA is not
425 // replaceable.
426 if (MemOpNo < 0)
427 return false;
428
429 MemOpNo += X86II::getOperandBias(Desc);
430
431 // If the address base of the use instruction is not the LEA def register -
432 // the LEA is not replaceable.
433 if (!isIdenticalOp(MI.getOperand(MemOpNo + X86::AddrBaseReg), MO))
434 return false;
435
436 // If the LEA def register is used as any other operand of the use
437 // instruction - the LEA is not replaceable.
438 for (unsigned i = 0; i < MI.getNumOperands(); i++)
439 if (i != (unsigned)(MemOpNo + X86::AddrBaseReg) &&
440 isIdenticalOp(MI.getOperand(i), MO))
441 return false;
442
443 // Check that the new address displacement will fit 4 bytes.
444 if (MI.getOperand(MemOpNo + X86::AddrDisp).isImm() &&
445 !isInt<32>(MI.getOperand(MemOpNo + X86::AddrDisp).getImm() +
446 AddrDispShift))
447 return false;
448 }
449
450 return true;
451}
452
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000453void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000454 unsigned Pos = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000455 for (auto &MI : MBB) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000456 // Assign the position number to the instruction. Note that we are going to
457 // move some instructions during the optimization however there will never
458 // be a need to move two instructions before any selected instruction. So to
459 // avoid multiple positions' updates during moves we just increase position
460 // counter by two leaving a free space for instructions which will be moved.
461 InstrPos[&MI] = Pos += 2;
462
Alexey Bataev7cf32472015-12-04 10:53:15 +0000463 if (isLEA(MI))
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000464 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
Alexey Bataev7cf32472015-12-04 10:53:15 +0000465 }
466}
467
468// Try to find load and store instructions which recalculate addresses already
469// calculated by some LEA and replace their memory operands with its def
470// register.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000471bool OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000472 bool Changed = false;
473
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000474 assert(!LEAs.empty());
475 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000476
477 // Process all instructions in basic block.
478 for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
479 MachineInstr &MI = *I++;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000480
481 // Instruction must be load or store.
482 if (!MI.mayLoadOrStore())
483 continue;
484
485 // Get the number of the first memory operand.
486 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000487 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000488
489 // If instruction has no memory operand - skip it.
490 if (MemOpNo < 0)
491 continue;
492
493 MemOpNo += X86II::getOperandBias(Desc);
494
495 // Get the best LEA instruction to replace address calculation.
496 MachineInstr *DefMI;
497 int64_t AddrDispShift;
498 int Dist;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000499 if (!chooseBestLEA(LEAs[getMemOpKey(MI, MemOpNo)], MI, DefMI, AddrDispShift,
500 Dist))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000501 continue;
502
503 // If LEA occurs before current instruction, we can freely replace
504 // the instruction. If LEA occurs after, we can lift LEA above the
505 // instruction and this way to be able to replace it. Since LEA and the
506 // instruction have similar memory operands (thus, the same def
507 // instructions for these operands), we can always do that, without
508 // worries of using registers before their defs.
509 if (Dist < 0) {
510 DefMI->removeFromParent();
511 MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000512 InstrPos[DefMI] = InstrPos[&MI] - 1;
513
514 // Make sure the instructions' position numbers are sane.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000515 assert(((InstrPos[DefMI] == 1 &&
516 MachineBasicBlock::iterator(DefMI) == MBB->begin()) ||
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000517 InstrPos[DefMI] >
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000518 InstrPos[&*std::prev(MachineBasicBlock::iterator(DefMI))]) &&
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000519 "Instruction positioning is broken");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000520 }
521
522 // Since we can possibly extend register lifetime, clear kill flags.
523 MRI->clearKillFlags(DefMI->getOperand(0).getReg());
524
525 ++NumSubstLEAs;
526 DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
527
528 // Change instruction operands.
529 MI.getOperand(MemOpNo + X86::AddrBaseReg)
530 .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
531 MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
532 MI.getOperand(MemOpNo + X86::AddrIndexReg)
533 .ChangeToRegister(X86::NoRegister, false);
534 MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
535 MI.getOperand(MemOpNo + X86::AddrSegmentReg)
536 .ChangeToRegister(X86::NoRegister, false);
537
538 DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
539
540 Changed = true;
541 }
542
543 return Changed;
544}
545
Andrew Ng03e35b62017-04-28 08:44:30 +0000546MachineInstr *OptimizeLEAPass::replaceDebugValue(MachineInstr &MI,
547 unsigned VReg,
548 int64_t AddrDispShift) {
549 DIExpression *Expr = const_cast<DIExpression *>(MI.getDebugExpression());
550
551 if (AddrDispShift != 0) {
552 DIBuilder DIB(*TheModule);
553 Expr = DIExpression::prependDIExpr(DIB, Expr, false, AddrDispShift, true);
554 }
555
556 // Replace DBG_VALUE instruction with modified version.
557 MachineBasicBlock *MBB = MI.getParent();
558 DebugLoc DL = MI.getDebugLoc();
559 bool IsIndirect = MI.isIndirectDebugValue();
560 int64_t Offset = IsIndirect ? MI.getOperand(1).getImm() : 0;
561 const MDNode *Var = MI.getDebugVariable();
562 return BuildMI(*MBB, MBB->erase(&MI), DL, TII->get(TargetOpcode::DBG_VALUE),
563 IsIndirect, VReg, Offset, Var, Expr);
564}
565
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000566// Try to find similar LEAs in the list and replace one with another.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000567bool OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000568 bool Changed = false;
569
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000570 // Loop over all entries in the table.
571 for (auto &E : LEAs) {
572 auto &List = E.second;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000573
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000574 // Loop over all LEA pairs.
575 auto I1 = List.begin();
576 while (I1 != List.end()) {
577 MachineInstr &First = **I1;
578 auto I2 = std::next(I1);
579 while (I2 != List.end()) {
580 MachineInstr &Last = **I2;
581 int64_t AddrDispShift;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000582
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000583 // LEAs should be in occurrence order in the list, so we can freely
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000584 // replace later LEAs with earlier ones.
585 assert(calcInstrDist(First, Last) > 0 &&
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000586 "LEAs must be in occurrence order in the list");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000587
588 // Check that the Last LEA instruction can be replaced by the First.
589 if (!isReplaceable(First, Last, AddrDispShift)) {
590 ++I2;
591 continue;
592 }
593
594 // Loop over all uses of the Last LEA and update their operands. Note
595 // that the correctness of this has already been checked in the
596 // isReplaceable function.
Andrew Ng03e35b62017-04-28 08:44:30 +0000597 unsigned FirstVReg = First.getOperand(0).getReg();
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000598 unsigned LastVReg = Last.getOperand(0).getReg();
Andrew Ng03e35b62017-04-28 08:44:30 +0000599 for (auto UI = MRI->use_begin(LastVReg), UE = MRI->use_end();
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000600 UI != UE;) {
601 MachineOperand &MO = *UI++;
602 MachineInstr &MI = *MO.getParent();
603
Andrew Ng03e35b62017-04-28 08:44:30 +0000604 if (MI.isDebugValue()) {
605 // Replace DBG_VALUE instruction with modified version using the
606 // register from the replacing LEA and the address displacement
607 // between the LEA instructions.
608 replaceDebugValue(MI, FirstVReg, AddrDispShift);
609 continue;
610 }
611
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000612 // Get the number of the first memory operand.
613 const MCInstrDesc &Desc = MI.getDesc();
614 int MemOpNo =
Craig Topper477649a2016-04-28 05:58:46 +0000615 X86II::getMemoryOperandNo(Desc.TSFlags) +
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000616 X86II::getOperandBias(Desc);
617
618 // Update address base.
Andrew Ng03e35b62017-04-28 08:44:30 +0000619 MO.setReg(FirstVReg);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000620
621 // Update address disp.
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000622 MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
623 if (Op.isImm())
624 Op.setImm(Op.getImm() + AddrDispShift);
625 else if (!Op.isJTI())
626 Op.setOffset(Op.getOffset() + AddrDispShift);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000627 }
628
629 // Since we can possibly extend register lifetime, clear kill flags.
Andrew Ng03e35b62017-04-28 08:44:30 +0000630 MRI->clearKillFlags(FirstVReg);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000631
632 ++NumRedundantLEAs;
633 DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: "; Last.dump(););
634
635 // By this moment, all of the Last LEA's uses must be replaced. So we
636 // can freely remove it.
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000637 assert(MRI->use_empty(LastVReg) &&
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000638 "The LEA's def register must have no uses");
639 Last.eraseFromParent();
640
641 // Erase removed LEA from the list.
642 I2 = List.erase(I2);
643
644 Changed = true;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000645 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000646 ++I1;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000647 }
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000648 }
649
650 return Changed;
651}
652
Andrew Ng03e35b62017-04-28 08:44:30 +0000653bool OptimizeLEAPass::doInitialization(Module &M) {
654 TheModule = &M;
655 return false;
656}
657
Alexey Bataev7cf32472015-12-04 10:53:15 +0000658bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
659 bool Changed = false;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000660
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000661 if (DisableX86LEAOpt || skipFunction(*MF.getFunction()))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000662 return false;
663
664 MRI = &MF.getRegInfo();
665 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
666 TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
667
668 // Process all basic blocks.
669 for (auto &MBB : MF) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000670 MemOpMap LEAs;
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000671 InstrPos.clear();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000672
673 // Find all LEA instructions in basic block.
674 findLEAs(MBB, LEAs);
675
676 // If current basic block has no LEAs, move on to the next one.
677 if (LEAs.empty())
678 continue;
679
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000680 // Remove redundant LEA instructions.
681 Changed |= removeRedundantLEAs(LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000682
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000683 // Remove redundant address calculations. Do it only for -Os/-Oz since only
684 // a code size gain is expected from this part of the pass.
685 if (MF.getFunction()->optForSize())
686 Changed |= removeRedundantAddrCalc(LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000687 }
688
689 return Changed;
690}