LLVM 24.0.0git
X86OptimizeLEAs.cpp
Go to the documentation of this file.
1//===- X86OptimizeLEAs.cpp - optimize usage of LEA instructions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the pass that performs some optimizations with LEA
10// instructions in order to improve performance and code size.
11// Currently, it does two things:
12// 1) If there are two LEA instructions calculating addresses which only differ
13// by displacement inside a basic block, one of them is removed.
14// 2) Address calculations in load and store instructions are replaced by
15// existing LEA def registers where possible.
16//
17//===----------------------------------------------------------------------===//
18
20#include "X86.h"
21#include "X86InstrInfo.h"
22#include "X86Subtarget.h"
23#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/Hashing.h"
27#include "llvm/ADT/Statistic.h"
42#include "llvm/IR/DebugLoc.h"
43#include "llvm/IR/Function.h"
44#include "llvm/MC/MCInstrDesc.h"
45#include "llvm/Support/Debug.h"
49#include <cassert>
50#include <cstdint>
51#include <iterator>
52
53using namespace llvm;
54
55#define DEBUG_TYPE "x86-optimize-leas"
56
57STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
58STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
59
60/// Returns true if two machine operands are identical and they are not
61/// physical registers.
62static inline bool isIdenticalOp(const MachineOperand &MO1,
63 const MachineOperand &MO2);
64
65/// Returns true if two address displacement operands are of the same
66/// type and use the same symbol/index/address regardless of the offset.
67static bool isSimilarDispOp(const MachineOperand &MO1,
68 const MachineOperand &MO2);
69
70/// Returns true if the instruction is LEA.
71static inline bool isLEA(const MachineInstr &MI);
72
73namespace {
74
75/// A key based on instruction's memory operands.
76class MemOpKey {
77public:
78 MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
79 const MachineOperand *Index, const MachineOperand *Segment,
80 const MachineOperand *Disp)
81 : Disp(Disp) {
82 Operands[0] = Base;
83 Operands[1] = Scale;
84 Operands[2] = Index;
85 Operands[3] = Segment;
86 }
87
88 bool operator==(const MemOpKey &Other) const {
89 // Addresses' bases, scales, indices and segments must be identical.
90 for (int i = 0; i < 4; ++i)
91 if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
92 return false;
93
94 // Addresses' displacements don't have to be exactly the same. It only
95 // matters that they use the same symbol/index/address. Immediates' or
96 // offsets' differences will be taken care of during instruction
97 // substitution.
98 return isSimilarDispOp(*Disp, *Other.Disp);
99 }
100
101 // Address' base, scale, index and segment operands.
102 const MachineOperand *Operands[4];
103
104 // Address' displacement operand.
105 const MachineOperand *Disp;
106};
107
108} // end anonymous namespace
109
110namespace llvm {
111
112/// Provide DenseMapInfo for MemOpKey.
113template <> struct DenseMapInfo<MemOpKey> {
115
116 static unsigned getHashValue(const MemOpKey &Val) {
117 hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
118 *Val.Operands[2], *Val.Operands[3]);
119
120 // If the address displacement is an immediate, it should not affect the
121 // hash so that memory operands which differ only be immediate displacement
122 // would have the same hash. If the address displacement is something else,
123 // we should reflect symbol/index/address in the hash.
124 switch (Val.Disp->getType()) {
126 break;
129 Hash = hash_combine(Hash, Val.Disp->getIndex());
130 break;
132 Hash = hash_combine(Hash, Val.Disp->getSymbolName());
133 break;
135 Hash = hash_combine(Hash, Val.Disp->getGlobal());
136 break;
138 Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
139 break;
141 Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
142 break;
144 Hash = hash_combine(Hash, Val.Disp->getMBB());
145 break;
146 default:
147 llvm_unreachable("Invalid address displacement operand");
148 }
149
150 return (unsigned)Hash;
151 }
152
153 static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
154 return LHS == RHS;
155 }
156};
157
158} // end namespace llvm
159
160/// Returns a hash table key based on memory operands of \p MI. The
161/// number of the first memory operand of \p MI is specified through \p N.
162static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
163 assert((isLEA(MI) || MI.mayLoadOrStore()) &&
164 "The instruction must be a LEA, a load or a store");
165 return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
166 &MI.getOperand(N + X86::AddrScaleAmt),
167 &MI.getOperand(N + X86::AddrIndexReg),
168 &MI.getOperand(N + X86::AddrSegmentReg),
169 &MI.getOperand(N + X86::AddrDisp));
170}
171
172static inline bool isIdenticalOp(const MachineOperand &MO1,
173 const MachineOperand &MO2) {
174 return MO1.isIdenticalTo(MO2) && (!MO1.isReg() || !MO1.getReg().isPhysical());
175}
176
177#ifndef NDEBUG
178static bool isValidDispOp(const MachineOperand &MO) {
179 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
180 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol() || MO.isMBB();
181}
182#endif
183
184static bool isSimilarDispOp(const MachineOperand &MO1,
185 const MachineOperand &MO2) {
186 assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
187 "Address displacement operand is not valid");
188 return (MO1.isImm() && MO2.isImm()) ||
189 (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
190 (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
191 (MO1.isSymbol() && MO2.isSymbol() &&
192 MO1.getSymbolName() == MO2.getSymbolName()) ||
193 (MO1.isGlobal() && MO2.isGlobal() &&
194 MO1.getGlobal() == MO2.getGlobal()) ||
195 (MO1.isBlockAddress() && MO2.isBlockAddress() &&
196 MO1.getBlockAddress() == MO2.getBlockAddress()) ||
197 (MO1.isMCSymbol() && MO2.isMCSymbol() &&
198 MO1.getMCSymbol() == MO2.getMCSymbol()) ||
199 (MO1.isMBB() && MO2.isMBB() && MO1.getMBB() == MO2.getMBB());
200}
201
202static inline bool isLEA(const MachineInstr &MI) {
203 unsigned Opcode = MI.getOpcode();
204 return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
205 Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
206}
207
208namespace {
209
210class X86OptimizeLEAsImpl {
211public:
212 bool runOnMachineFunction(MachineFunction &MF, ProfileSummaryInfo *PSI,
213 MachineBlockFrequencyInfo *MBFI);
214
215private:
216 using MemOpMap = DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>>;
217
218 /// Returns a distance between two instructions inside one basic block.
219 /// Negative result means, that instructions occur in reverse order.
220 int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
221
222 /// Choose the best \p LEA instruction from the \p List to replace
223 /// address calculation in \p MI instruction. Return the address displacement
224 /// and the distance between \p MI and the chosen \p BestLEA in
225 /// \p AddrDispShift and \p Dist.
226 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
227 const MachineInstr &MI, MachineInstr *&BestLEA,
228 int64_t &AddrDispShift, int &Dist);
229
230 /// Returns the difference between addresses' displacements of \p MI1
231 /// and \p MI2. The numbers of the first memory operands for the instructions
232 /// are specified through \p N1 and \p N2.
233 int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
234 const MachineInstr &MI2, unsigned N2) const;
235
236 /// Returns true if the \p Last LEA instruction can be replaced by the
237 /// \p First. The difference between displacements of the addresses calculated
238 /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
239 /// replacement of the \p Last LEA's uses with the \p First's def register.
240 bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
241 int64_t &AddrDispShift) const;
242
243 /// Find all LEA instructions in the basic block. Also, assign position
244 /// numbers to all instructions in the basic block to speed up calculation of
245 /// distance between them.
246 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
247
248 /// Removes redundant address calculations.
249 bool removeRedundantAddrCalc(MemOpMap &LEAs);
250
251 /// Replace debug value MI with a new debug value instruction using register
252 /// VReg with an appropriate offset and DIExpression to incorporate the
253 /// address displacement AddrDispShift. Return new debug value instruction.
254 MachineInstr *replaceDebugValue(MachineInstr &MI, Register OldReg,
255 Register NewReg, int64_t AddrDispShift);
256
257 /// Removes LEAs which calculate similar addresses.
258 bool removeRedundantLEAs(MemOpMap &LEAs);
259
260 DenseMap<const MachineInstr *, unsigned> InstrPos;
261
262 MachineRegisterInfo *MRI = nullptr;
263 const X86InstrInfo *TII = nullptr;
264};
265
266class X86OptimizeLEAsLegacy : public MachineFunctionPass {
267public:
268 X86OptimizeLEAsLegacy() : MachineFunctionPass(ID) {}
269
270 StringRef getPassName() const override { return "X86 LEA Optimize"; }
271
272 /// Loop over all of the basic blocks, replacing address
273 /// calculations in load and store instructions, if it's already
274 /// been calculated by LEA. Also, remove redundant LEAs.
275 bool runOnMachineFunction(MachineFunction &MF) override;
276
277 static char ID;
278
279 void getAnalysisUsage(AnalysisUsage &AU) const override {
280 AU.addRequired<ProfileSummaryInfoWrapperPass>();
281 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
282 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
284 }
285};
286
287} // end anonymous namespace
288
289char X86OptimizeLEAsLegacy::ID = 0;
290
292 return new X86OptimizeLEAsLegacy();
293}
294INITIALIZE_PASS(X86OptimizeLEAsLegacy, DEBUG_TYPE, "X86 optimize LEA pass",
295 false, false)
296
297int X86OptimizeLEAsImpl::calcInstrDist(const MachineInstr &First,
299 // Both instructions must be in the same basic block and they must be
300 // presented in InstrPos.
301 assert(Last.getParent() == First.getParent() &&
302 "Instructions are in different basic blocks");
303 assert(InstrPos.contains(&First) && InstrPos.contains(&Last) &&
304 "Instructions' positions are undefined");
305
306 return InstrPos[&Last] - InstrPos[&First];
307}
308
309// Find the best LEA instruction in the List to replace address recalculation in
310// MI. Such LEA must meet these requirements:
311// 1) The address calculated by the LEA differs only by the displacement from
312// the address used in MI.
313// 2) The register class of the definition of the LEA is compatible with the
314// register class of the address base register of MI.
315// 3) Displacement of the new memory operand should fit in 1 byte if possible.
316// 4) The LEA should be as close to MI as possible, and prior to it if
317// possible.
318bool X86OptimizeLEAsImpl::chooseBestLEA(
320 MachineInstr *&BestLEA, int64_t &AddrDispShift, int &Dist) {
321 const MCInstrDesc &Desc = MI.getDesc();
322 int MemOpNo = X86II::getMemoryOperandIdx(Desc);
323 assert(MemOpNo >= 0 && "Expected a memory operand");
324
325 BestLEA = nullptr;
326
327 // Loop over all LEA instructions.
328 for (auto *DefMI : List) {
329 // Get new address displacement.
330 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
331
332 // Make sure address displacement fits 4 bytes.
333 if (!isInt<32>(AddrDispShiftTemp))
334 continue;
335
336 // Check that LEA def register can be used as MI address base. Some
337 // instructions can use a limited set of registers as address base, for
338 // example MOV8mr_NOREX. We could constrain the register class of the LEA
339 // def to suit MI, however since this case is very rare and hard to
340 // reproduce in a test it's just more reliable to skip the LEA.
341 if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg) !=
343 continue;
344
345 // Choose the closest LEA instruction from the list, prior to MI if
346 // possible. Note that we took into account resulting address displacement
347 // as well. Also note that the list is sorted by the order in which the LEAs
348 // occur, so the break condition is pretty simple.
349 int DistTemp = calcInstrDist(*DefMI, MI);
350 assert(DistTemp != 0 &&
351 "The distance between two different instructions cannot be zero");
352 if (DistTemp > 0 || BestLEA == nullptr) {
353 // Do not update return LEA, if the current one provides a displacement
354 // which fits in 1 byte, while the new candidate does not.
355 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
356 isInt<8>(AddrDispShift))
357 continue;
358
359 BestLEA = DefMI;
360 AddrDispShift = AddrDispShiftTemp;
361 Dist = DistTemp;
362 }
363
364 // FIXME: Maybe we should not always stop at the first LEA after MI.
365 if (DistTemp < 0)
366 break;
367 }
368
369 return BestLEA != nullptr;
370}
371
372// Get the difference between the addresses' displacements of the two
373// instructions \p MI1 and \p MI2. The numbers of the first memory operands are
374// passed through \p N1 and \p N2.
375int64_t X86OptimizeLEAsImpl::getAddrDispShift(const MachineInstr &MI1,
376 unsigned N1,
377 const MachineInstr &MI2,
378 unsigned N2) const {
379 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
380 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
381
382 assert(isSimilarDispOp(Op1, Op2) &&
383 "Address displacement operands are not compatible");
384
385 // After the assert above we can be sure that both operands are of the same
386 // valid type and use the same symbol/index/address, thus displacement shift
387 // calculation is rather simple.
388 if (Op1.isJTI())
389 return 0;
390 return Op1.isImm() ? Op1.getImm() - Op2.getImm()
391 : Op1.getOffset() - Op2.getOffset();
392}
393
394// Check that the Last LEA can be replaced by the First LEA. To be so,
395// these requirements must be met:
396// 1) Addresses calculated by LEAs differ only by displacement.
397// 2) Def registers of LEAs belong to the same class.
398// 3) All uses of the Last LEA def register are replaceable, thus the
399// register is used only as address base.
400bool X86OptimizeLEAsImpl::isReplaceable(const MachineInstr &First,
401 const MachineInstr &Last,
402 int64_t &AddrDispShift) const {
403 assert(isLEA(First) && isLEA(Last) &&
404 "The function works only with LEA instructions");
405
406 // Make sure that LEA def registers belong to the same class. There may be
407 // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
408 // be used as their operands, so we must be sure that replacing one LEA
409 // with another won't lead to putting a wrong register in the instruction.
410 if (MRI->getRegClass(First.getOperand(0).getReg()) !=
411 MRI->getRegClass(Last.getOperand(0).getReg()))
412 return false;
413
414 // Get new address displacement.
415 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
416
417 // Loop over all uses of the Last LEA to check that its def register is
418 // used only as address base for memory accesses. If so, it can be
419 // replaced, otherwise - no.
420 for (auto &MO : MRI->use_nodbg_operands(Last.getOperand(0).getReg())) {
421 MachineInstr &MI = *MO.getParent();
422
423 // Get the number of the first memory operand.
424 int MemOpNo = X86II::getMemoryOperandIdx(MI.getDesc());
425
426 // If the use instruction has no memory operand - the LEA is not
427 // replaceable.
428 if (MemOpNo < 0)
429 return false;
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
453void X86OptimizeLEAsImpl::findLEAs(const MachineBasicBlock &MBB,
454 MemOpMap &LEAs) {
455 unsigned Pos = 0;
456 for (auto &MI : MBB) {
457 // Assign the position number to the instruction. Note that we are going to
458 // move some instructions during the optimization however there will never
459 // be a need to move two instructions before any selected instruction. So to
460 // avoid multiple positions' updates during moves we just increase position
461 // counter by two leaving a free space for instructions which will be moved.
462 InstrPos[&MI] = Pos += 2;
463
464 if (isLEA(MI))
465 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
466 }
467}
468
469// Try to find load and store instructions which recalculate addresses already
470// calculated by some LEA and replace their memory operands with its def
471// register.
472bool X86OptimizeLEAsImpl::removeRedundantAddrCalc(MemOpMap &LEAs) {
473 bool Changed = false;
474
475 assert(!LEAs.empty());
476 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
477
478 // Process all instructions in basic block.
479 for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
480 // Instruction must be load or store.
481 if (!MI.mayLoadOrStore())
482 continue;
483
484 // Get the number of the first memory operand.
485 int MemOpNo = X86II::getMemoryOperandIdx(MI.getDesc());
486
487 // If instruction has no memory operand - skip it.
488 if (MemOpNo < 0)
489 continue;
490
491 // Do not call chooseBestLEA if there was no matching LEA
492 auto Insns = LEAs.find(getMemOpKey(MI, MemOpNo));
493 if (Insns == LEAs.end())
494 continue;
495
496 // Get the best LEA instruction to replace address calculation.
497 MachineInstr *DefMI;
498 int64_t AddrDispShift;
499 int Dist;
500 if (!chooseBestLEA(Insns->second, MI, DefMI, AddrDispShift, Dist))
501 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) {
512 InstrPos[DefMI] = InstrPos[&MI] - 1;
513
514 // Make sure the instructions' position numbers are sane.
515 assert(((InstrPos[DefMI] == 1 &&
517 InstrPos[DefMI] >
518 InstrPos[&*std::prev(MachineBasicBlock::iterator(DefMI))]) &&
519 "Instruction positioning is broken");
520 }
521
522 ++NumSubstLEAs;
523 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
524
525 // Change instruction operands.
526 MI.getOperand(MemOpNo + X86::AddrBaseReg)
527 .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
528 MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
529 MI.getOperand(MemOpNo + X86::AddrIndexReg)
530 .ChangeToRegister(X86::NoRegister, false);
531 MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
532 MI.getOperand(MemOpNo + X86::AddrSegmentReg)
533 .ChangeToRegister(X86::NoRegister, false);
534
535 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
536
537 Changed = true;
538 }
539
540 return Changed;
541}
542
543MachineInstr *X86OptimizeLEAsImpl::replaceDebugValue(MachineInstr &MI,
544 Register OldReg,
545 Register NewReg,
546 int64_t AddrDispShift) {
547 const DIExpression *Expr = MI.getDebugExpression();
548 if (AddrDispShift != 0) {
549 if (MI.isNonListDebugValue()) {
550 Expr =
552 } else {
553 // Update the Expression, appending an offset of `AddrDispShift` to the
554 // Op corresponding to `OldReg`.
556 DIExpression::appendOffset(Ops, AddrDispShift);
557 for (MachineOperand &Op : MI.getDebugOperandsForReg(OldReg)) {
558 unsigned OpIdx = MI.getDebugOperandIndex(&Op);
559 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx);
560 }
561 }
562 }
563
564 // Replace DBG_VALUE instruction with modified version.
565 MachineBasicBlock *MBB = MI.getParent();
566 DebugLoc DL = MI.getDebugLoc();
567 bool IsIndirect = MI.isIndirectDebugValue();
568 const MDNode *Var = MI.getDebugVariable();
569 unsigned Opcode = MI.isNonListDebugValue() ? TargetOpcode::DBG_VALUE
570 : TargetOpcode::DBG_VALUE_LIST;
571 if (IsIndirect)
572 assert(MI.getDebugOffset().getImm() == 0 &&
573 "DBG_VALUE with nonzero offset");
574 SmallVector<MachineOperand, 4> NewOps;
575 // If we encounter an operand using the old register, replace it with an
576 // operand that uses the new register; otherwise keep the old operand.
577 auto replaceOldReg = [OldReg, NewReg](const MachineOperand &Op) {
578 if (Op.isReg() && Op.getReg() == OldReg)
579 return MachineOperand::CreateReg(NewReg, false, false, false, false,
580 false, false, false, false, false,
581 /*IsRenamable*/ true);
582 return Op;
583 };
584 for (const MachineOperand &Op : MI.debug_operands())
585 NewOps.push_back(replaceOldReg(Op));
586 return BuildMI(*MBB, MBB->erase(&MI), DL, TII->get(Opcode), IsIndirect,
587 NewOps, Var, Expr);
588}
589
590// Try to find similar LEAs in the list and replace one with another.
591bool X86OptimizeLEAsImpl::removeRedundantLEAs(MemOpMap &LEAs) {
592 bool Changed = false;
593
594 // Loop over all entries in the table.
595 for (auto &E : LEAs) {
596 auto &List = E.second;
597
598 // Loop over all LEA pairs.
599 auto I1 = List.begin();
600 while (I1 != List.end()) {
601 MachineInstr &First = **I1;
602 auto I2 = std::next(I1);
603 while (I2 != List.end()) {
604 MachineInstr &Last = **I2;
605 int64_t AddrDispShift;
606
607 // LEAs should be in occurrence order in the list, so we can freely
608 // replace later LEAs with earlier ones.
609 assert(calcInstrDist(First, Last) > 0 &&
610 "LEAs must be in occurrence order in the list");
611
612 // Check that the Last LEA instruction can be replaced by the First.
613 if (!isReplaceable(First, Last, AddrDispShift)) {
614 ++I2;
615 continue;
616 }
617
618 // Loop over all uses of the Last LEA and update their operands. Note
619 // that the correctness of this has already been checked in the
620 // isReplaceable function.
621 Register FirstVReg = First.getOperand(0).getReg();
622 Register LastVReg = Last.getOperand(0).getReg();
623 // We use MRI->use_empty here instead of the combination of
624 // llvm::make_early_inc_range and MRI->use_operands because we could
625 // replace two or more uses in a debug instruction in one iteration, and
626 // that would deeply confuse llvm::make_early_inc_range.
627 while (!MRI->use_empty(LastVReg)) {
628 MachineOperand &MO = *MRI->use_begin(LastVReg);
629 MachineInstr &MI = *MO.getParent();
630
631 if (MI.isDebugValue()) {
632 // Replace DBG_VALUE instruction with modified version using the
633 // register from the replacing LEA and the address displacement
634 // between the LEA instructions.
635 replaceDebugValue(MI, LastVReg, FirstVReg, AddrDispShift);
636 continue;
637 }
638
639 // Get the number of the first memory operand.
640 int MemOpNo = X86II::getMemoryOperandIdx(MI.getDesc());
641 assert(MemOpNo >= 0 && "Expected a memory operand");
642
643 // Update address base.
644 MO.setReg(FirstVReg);
645
646 // Update address disp.
647 MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
648 if (Op.isImm())
649 Op.setImm(Op.getImm() + AddrDispShift);
650 else if (!Op.isJTI())
651 Op.setOffset(Op.getOffset() + AddrDispShift);
652 }
653
654 ++NumRedundantLEAs;
655 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: ";
656 Last.dump(););
657
658 // By this moment, all of the Last LEA's uses must be replaced. So we
659 // can freely remove it.
660 assert(MRI->use_empty(LastVReg) &&
661 "The LEA's def register must have no uses");
662 Last.eraseFromParent();
663
664 // Erase removed LEA from the list.
665 I2 = List.erase(I2);
666
667 Changed = true;
668 }
669 ++I1;
670 }
671 }
672
673 return Changed;
674}
675
676bool X86OptimizeLEAsImpl::runOnMachineFunction(
677 MachineFunction &MF, ProfileSummaryInfo *PSI,
678 MachineBlockFrequencyInfo *MBFI) {
679 bool Changed = false;
680
681 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
682 if (ST.getCLOpts().disable_x86_lea_opt)
683 return false;
684
685 MRI = &MF.getRegInfo();
686 TII = ST.getInstrInfo();
687
688 // Process all basic blocks.
689 for (auto &MBB : MF) {
690 MemOpMap LEAs;
691 InstrPos.clear();
692
693 // Find all LEA instructions in basic block.
694 findLEAs(MBB, LEAs);
695
696 // If current basic block has no LEAs, move on to the next one.
697 if (LEAs.empty())
698 continue;
699
700 // Remove redundant LEA instructions.
701 Changed |= removeRedundantLEAs(LEAs);
702
703 // Remove redundant address calculations. Do it only for -Os/-Oz since only
704 // a code size gain is expected from this part of the pass.
705 if (llvm::shouldOptimizeForSize(&MBB, PSI, MBFI))
706 Changed |= removeRedundantAddrCalc(LEAs);
707 }
708
709 return Changed;
710}
711
712bool X86OptimizeLEAsLegacy::runOnMachineFunction(MachineFunction &MF) {
713 if (skipFunction(MF.getFunction()))
714 return false;
715 ProfileSummaryInfo *PSI =
716 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
717 MachineBlockFrequencyInfo *MBFI =
718 (PSI && PSI->hasProfileSummary())
719 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
720 : nullptr;
721 X86OptimizeLEAsImpl PassImpl;
722 return PassImpl.runOnMachineFunction(MF, PSI, MBFI);
723}
724
725PreservedAnalyses
728 ProfileSummaryInfo *PSI =
730 .getCachedResult<ProfileSummaryAnalysis>(
731 *MF.getFunction().getParent());
733 (PSI && PSI->hasProfileSummary())
735 : nullptr;
736 X86OptimizeLEAsImpl PassImpl;
737 bool Changed = PassImpl.runOnMachineFunction(MF, PSI, MBFI);
738 if (!Changed)
739 return PreservedAnalyses::all();
741}
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
SI Fold Operands
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isLEA(unsigned Opcode)
static bool isLEA(const MachineInstr &MI)
Returns true if the instruction is LEA.
static bool isValidDispOp(const MachineOperand &MO)
static MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N)
Returns a hash table key based on memory operands of MI.
static bool isSimilarDispOp(const MachineOperand &MO1, const MachineOperand &MO2)
Returns true if two address displacement operands are of the same type and use the same symbol/index/...
static bool isIdenticalOp(const MachineOperand &MO1, const MachineOperand &MO2)
Returns true if two machine operands are identical and they are not physical registers.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
LLVM_ABI MachineInstr * removeFromParent()
Unlink 'this' from the containing basic block, and return it without deleting it.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
use_iterator use_begin(Register RegNo) const
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
An opaque object representing a hash code.
Definition Hashing.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int getMemoryOperandIdx(const MCInstrDesc &Desc)
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
FunctionPass * createX86OptimizeLEAsLegacyPass()
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
Op::Description Desc
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
DWARFExpression::Operation Op
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
#define N
static unsigned getHashValue(const MemOpKey &Val)
DenseMapInfo< const MachineOperand * > PtrInfo
static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...