LLVM 24.0.0git
X86FixupLEAs.cpp
Go to the documentation of this file.
1//===-- X86FixupLEAs.cpp - use or replace 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 finds instructions that can be
10// re-written as LEA instructions in order to reduce pipeline delays.
11// It replaces LEAs with ADD/INC/DEC when that is better for size/speed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86InstrInfo.h"
17#include "X86Subtarget.h"
18#include "llvm/ADT/Statistic.h"
24#include "llvm/CodeGen/Passes.h"
26#include "llvm/Support/Debug.h"
28using namespace llvm;
29
30#define FIXUPLEA_DESC "X86 LEA Fixup"
31#define FIXUPLEA_NAME "x86-fixup-leas"
32
33#define DEBUG_TYPE FIXUPLEA_NAME
34
35STATISTIC(NumLEAs, "Number of LEA instructions created");
36
37namespace {
38class FixupLEAsImpl {
39 enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };
40
41 /// Given a machine register, look for the instruction
42 /// which writes it in the current basic block. If found,
43 /// try to replace it with an equivalent LEA instruction.
44 /// If replacement succeeds, then also process the newly created
45 /// instruction.
46 void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,
47 MachineBasicBlock &MBB);
48
49 /// Given a memory access or LEA instruction
50 /// whose address mode uses a base and/or index register, look for
51 /// an opportunity to replace the instruction which sets the base or index
52 /// register with an equivalent LEA instruction.
53 void processInstruction(MachineBasicBlock::iterator &I,
54 MachineBasicBlock &MBB);
55
56 /// Given a LEA instruction which is unprofitable
57 /// on SlowLEA targets try to replace it with an equivalent ADD instruction.
58 void processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
59 MachineBasicBlock &MBB);
60
61 /// Given a LEA instruction which is unprofitable
62 /// on SNB+ try to replace it with other instructions.
63 /// According to Intel's Optimization Reference Manual:
64 /// " For LEA instructions with three source operands and some specific
65 /// situations, instruction latency has increased to 3 cycles, and must
66 /// dispatch via port 1:
67 /// - LEA that has all three source operands: base, index, and offset
68 /// - LEA that uses base and index registers where the base is EBP, RBP,
69 /// or R13
70 /// - LEA that uses RIP relative addressing mode
71 /// - LEA that uses 16-bit addressing mode "
72 /// This function currently handles the first 2 cases only.
73 void processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
74 MachineBasicBlock &MBB, bool OptIncDec);
75
76 /// Build and return the instruction that adds the displacement of the LEA
77 /// MI to its destination, inserted before MI. Requires mayHaveOffset().
78 MachineInstr *buildOffsetAdd(MachineInstr &MI, MachineBasicBlock &MBB,
79 bool OptIncDec) const;
80
81 /// Look for LEAs that are really two address LEAs that we might be able to
82 /// turn into regular ADD instructions.
83 bool optTwoAddrLEA(MachineBasicBlock::iterator &I,
84 MachineBasicBlock &MBB, bool OptIncDec,
85 bool UseLEAForSP) const;
86
87 /// Look for and transform the sequence
88 /// lea (reg1, reg2), reg3
89 /// sub reg3, reg4
90 /// to
91 /// sub reg1, reg4
92 /// sub reg2, reg4
93 /// It can also optimize the sequence lea/add similarly.
94 bool optLEAALU(MachineBasicBlock::iterator &I, MachineBasicBlock &MBB) const;
95
96 /// Step forwards in MBB, looking for an ADD/SUB instruction which uses
97 /// the dest register of LEA instruction I.
99 MachineBasicBlock &MBB) const;
100
101 /// Check instructions between LeaI and AluI (exclusively).
102 /// Set BaseIndexDef to true if base or index register from LeaI is defined.
103 /// Set AluDestRef to true if the dest register of AluI is used or defined.
104 /// *KilledBase is set to the killed base register usage.
105 /// *KilledIndex is set to the killed index register usage.
106 void checkRegUsage(MachineBasicBlock::iterator &LeaI,
107 MachineBasicBlock::iterator &AluI, bool &BaseIndexDef,
108 bool &AluDestRef, MachineOperand **KilledBase,
109 MachineOperand **KilledIndex) const;
110
111 /// Determine if an instruction references a machine register
112 /// and, if so, whether it reads or writes the register.
113 RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);
114
115 /// Step backwards through a basic block, looking
116 /// for an instruction which writes a register within
117 /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
118 MachineBasicBlock::iterator searchBackwards(MachineOperand &p,
120 MachineBasicBlock &MBB);
121
122 /// if an instruction can be converted to an
123 /// equivalent LEA, insert the new instruction into the basic block
124 /// and return a pointer to it. Otherwise, return zero.
125 MachineInstr *postRAConvertToLEA(MachineBasicBlock &MBB,
127
128public:
129 FixupLEAsImpl(ProfileSummaryInfo *PSI, MachineBlockFrequencyInfo *MBFI)
130 : PSI(PSI), MBFI(MBFI) {}
131
132 /// Loop over all of the basic blocks,
133 /// replacing instructions by equivalent LEA instructions
134 /// if needed and when possible.
135 bool runOnMachineFunction(MachineFunction &MF);
136
137private:
138 TargetSchedModel TSM;
139 const X86InstrInfo *TII = nullptr;
140 const X86RegisterInfo *TRI = nullptr;
141 ProfileSummaryInfo *PSI;
142 MachineBlockFrequencyInfo *MBFI;
143};
144
145class FixupLEAsLegacy : public MachineFunctionPass {
146public:
147 static char ID;
148
149 StringRef getPassName() const override { return FIXUPLEA_DESC; }
150
151 FixupLEAsLegacy() : MachineFunctionPass(ID) {}
152
153 bool runOnMachineFunction(MachineFunction &MF) override;
154
155 // This pass runs after regalloc and doesn't support VReg operands.
156 MachineFunctionProperties getRequiredProperties() const override {
157 return MachineFunctionProperties().setNoVRegs();
158 }
159
160 void getAnalysisUsage(AnalysisUsage &AU) const override {
161 AU.addRequired<ProfileSummaryInfoWrapperPass>();
162 AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
164 }
165};
166}
167
168char FixupLEAsLegacy::ID = 0;
169
170INITIALIZE_PASS(FixupLEAsLegacy, FIXUPLEA_NAME, FIXUPLEA_DESC, false, false)
171
173FixupLEAsImpl::postRAConvertToLEA(MachineBasicBlock &MBB,
175 MachineInstr &MI = *MBBI;
176 switch (MI.getOpcode()) {
177 case X86::MOV32rr:
178 case X86::MOV64rr: {
179 const MachineOperand &Src = MI.getOperand(1);
180 const MachineOperand &Dest = MI.getOperand(0);
181 MachineInstr *NewMI =
182 BuildMI(MBB, MBBI, MI.getDebugLoc(),
183 TII->get(MI.getOpcode() == X86::MOV32rr ? X86::LEA32r
184 : X86::LEA64r))
185 .add(Dest)
186 .add(Src)
187 .addImm(1)
188 .addReg(0)
189 .addImm(0)
190 .addReg(0);
191 return NewMI;
192 }
193 }
194
195 if (!MI.isConvertibleTo3Addr())
196 return nullptr;
197
198 switch (MI.getOpcode()) {
199 default:
200 // Only convert instructions that we've verified are safe.
201 return nullptr;
202 case X86::ADD64ri32:
203 case X86::ADD64ri32_DB:
204 case X86::ADD32ri:
205 case X86::ADD32ri_DB:
206 if (!MI.getOperand(2).isImm()) {
207 // convertToThreeAddress will call getImm()
208 // which requires isImm() to be true
209 return nullptr;
210 }
211 break;
212 case X86::SHL64ri:
213 case X86::SHL32ri:
214 case X86::INC64r:
215 case X86::INC32r:
216 case X86::DEC64r:
217 case X86::DEC32r:
218 case X86::ADD64rr:
219 case X86::ADD64rr_DB:
220 case X86::ADD32rr:
221 case X86::ADD32rr_DB:
222 // These instructions are all fine to convert.
223 break;
224 }
225 return TII->convertToThreeAddress(MI, /*LIS=*/nullptr);
226}
227
229 return new FixupLEAsLegacy();
230}
231
232static bool isLEA(unsigned Opcode) {
233 return Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
234 Opcode == X86::LEA64_32r;
235}
236
237bool FixupLEAsImpl::runOnMachineFunction(MachineFunction &MF) {
238 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
239 bool IsSlowLEA = ST.slowLEA();
240 bool IsSlow3OpsLEA = ST.slow3OpsLEA();
241 bool LEAUsesAG = ST.leaUsesAG();
242
243 bool OptIncDec = !ST.slowIncDec() || MF.getFunction().hasOptSize();
244 bool UseLEAForSP = ST.useLeaForSP();
245
246 TSM.init(&ST);
247 TII = ST.getInstrInfo();
248 TRI = ST.getRegisterInfo();
249
250 LLVM_DEBUG(dbgs() << "Start X86FixupLEAs\n";);
251 for (MachineBasicBlock &MBB : MF) {
252 // First pass. Try to remove or optimize existing LEAs.
253 bool OptIncDecPerBB =
254 OptIncDec || llvm::shouldOptimizeForSize(&MBB, PSI, MBFI);
255 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
256 if (!isLEA(I->getOpcode()))
257 continue;
258
259 if (optTwoAddrLEA(I, MBB, OptIncDecPerBB, UseLEAForSP))
260 continue;
261
262 if (IsSlowLEA)
263 processInstructionForSlowLEA(I, MBB);
264 else if (IsSlow3OpsLEA)
265 processInstrForSlow3OpLEA(I, MBB, OptIncDecPerBB);
266 }
267
268 // Second pass for creating LEAs. This may reverse some of the
269 // transformations above.
270 if (LEAUsesAG) {
271 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I)
272 processInstruction(I, MBB);
273 }
274 }
275
276 LLVM_DEBUG(dbgs() << "End X86FixupLEAs\n";);
277
278 return true;
279}
280
281FixupLEAsImpl::RegUsageState
282FixupLEAsImpl::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {
283 RegUsageState RegUsage = RU_NotUsed;
284 MachineInstr &MI = *I;
285
286 for (const MachineOperand &MO : MI.operands()) {
287 if (MO.isReg() && MO.getReg() == p.getReg()) {
288 if (MO.isDef())
289 return RU_Write;
290 RegUsage = RU_Read;
291 }
292 }
293 return RegUsage;
294}
295
296/// getPreviousInstr - Given a reference to an instruction in a basic
297/// block, return a reference to the previous instruction in the block,
298/// wrapping around to the last instruction of the block if the block
299/// branches to itself.
302 if (I == MBB.begin()) {
303 if (MBB.isPredecessor(&MBB)) {
304 I = --MBB.end();
305 return true;
306 } else
307 return false;
308 }
309 --I;
310 return true;
311}
312
313MachineBasicBlock::iterator FixupLEAsImpl::searchBackwards(
314 MachineOperand &p, MachineBasicBlock::iterator &I, MachineBasicBlock &MBB) {
315 int InstrDistance = 1;
317 static const int INSTR_DISTANCE_THRESHOLD = 5;
318
319 CurInst = I;
320 bool Found;
321 Found = getPreviousInstr(CurInst, MBB);
322 while (Found && I != CurInst) {
323 if (CurInst->isCall() || CurInst->isInlineAsm())
324 break;
325 if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
326 break; // too far back to make a difference
327 if (usesRegister(p, CurInst) == RU_Write) {
328 return CurInst;
329 }
330 InstrDistance += TSM.computeInstrLatency(&*CurInst);
331 Found = getPreviousInstr(CurInst, MBB);
332 }
334}
335
336static inline bool isInefficientLEAReg(Register Reg) {
337 return Reg == X86::EBP || Reg == X86::RBP ||
338 Reg == X86::R13D || Reg == X86::R13;
339}
340
341/// Returns true if this LEA uses base and index registers, and the base
342/// register is known to be inefficient for the subtarget.
343// TODO: use a variant scheduling class to model the latency profile
344// of LEA instructions, and implement this logic as a scheduling predicate.
346 const MachineOperand &Index) {
347 return Base.isReg() && isInefficientLEAReg(Base.getReg()) && Index.isReg() &&
348 Index.getReg().isValid();
349}
350
351// Returns true if this operand may have a non-zero offset.
352static inline bool mayHaveOffset(const MachineOperand &Offset) {
353 return !(Offset.isImm() && Offset.getImm() == 0);
354}
355
356static inline unsigned getADDrrFromLEA(unsigned LEAOpcode) {
357 switch (LEAOpcode) {
358 default:
359 llvm_unreachable("Unexpected LEA instruction");
360 case X86::LEA32r:
361 case X86::LEA64_32r:
362 return X86::ADD32rr;
363 case X86::LEA64r:
364 return X86::ADD64rr;
365 }
366}
367
368static inline unsigned getSUBrrFromLEA(unsigned LEAOpcode) {
369 switch (LEAOpcode) {
370 default:
371 llvm_unreachable("Unexpected LEA instruction");
372 case X86::LEA32r:
373 case X86::LEA64_32r:
374 return X86::SUB32rr;
375 case X86::LEA64r:
376 return X86::SUB64rr;
377 }
378}
379
380static inline unsigned getADDriFromLEA(unsigned LEAOpcode,
381 const MachineOperand &Offset) {
382 switch (LEAOpcode) {
383 default:
384 llvm_unreachable("Unexpected LEA instruction");
385 case X86::LEA32r:
386 case X86::LEA64_32r:
387 return X86::ADD32ri;
388 case X86::LEA64r:
389 return X86::ADD64ri32;
390 }
391}
392
393static inline unsigned getSUBriFromLEA(unsigned LEAOpcode) {
394 switch (LEAOpcode) {
395 default:
396 llvm_unreachable("Unexpected LEA instruction");
397 case X86::LEA32r:
398 case X86::LEA64_32r:
399 return X86::SUB32ri;
400 case X86::LEA64r:
401 return X86::SUB64ri32;
402 }
403}
404
405static inline unsigned getINCDECFromLEA(unsigned LEAOpcode, bool IsINC) {
406 switch (LEAOpcode) {
407 default:
408 llvm_unreachable("Unexpected LEA instruction");
409 case X86::LEA32r:
410 case X86::LEA64_32r:
411 return IsINC ? X86::INC32r : X86::DEC32r;
412 case X86::LEA64r:
413 return IsINC ? X86::INC64r : X86::DEC64r;
414 }
415}
416
418FixupLEAsImpl::searchALUInst(MachineBasicBlock::iterator &I,
419 MachineBasicBlock &MBB) const {
420 const X86Subtarget &ST = MBB.getParent()->getSubtarget<X86Subtarget>();
421 unsigned InstrDistance = 1;
422
423 unsigned LEAOpcode = I->getOpcode();
424 unsigned AddOpcode = getADDrrFromLEA(LEAOpcode);
425 unsigned SubOpcode = getSUBrrFromLEA(LEAOpcode);
426 Register DestReg = I->getOperand(0).getReg();
427
428 for (MachineInstr &CurInst : instructionsWithoutDebug(
429 std::next(I), MBB.end(), /*SkipPseudoOp=*/false)) {
430 if (CurInst.isCall() || CurInst.isInlineAsm())
431 break;
432 if (InstrDistance > ST.getCLOpts().fixup_leas_search_distance_threshold)
433 break;
434
435 // Check if the lea dest register is used in an add/sub instruction only.
436 for (unsigned I = 0, E = CurInst.getNumOperands(); I != E; ++I) {
437 MachineOperand &Opnd = CurInst.getOperand(I);
438 if (Opnd.isReg()) {
439 if (Opnd.getReg() == DestReg) {
440 if (Opnd.isDef() || !Opnd.isKill())
442
443 unsigned AluOpcode = CurInst.getOpcode();
444 if (AluOpcode != AddOpcode && AluOpcode != SubOpcode)
446
447 MachineOperand &Opnd2 = CurInst.getOperand(3 - I);
448 MachineOperand AluDest = CurInst.getOperand(0);
449 if (Opnd2.getReg() != AluDest.getReg())
451
452 // X - (Y + Z) may generate different flags than (X - Y) - Z when
453 // there is overflow. So we can't change the alu instruction if the
454 // flags register is live.
455 if (!CurInst.registerDefIsDead(X86::EFLAGS, TRI))
457
458 return CurInst.getIterator();
459 }
460 if (TRI->regsOverlap(DestReg, Opnd.getReg()))
462 }
463 }
464
465 InstrDistance++;
466 }
468}
469
470void FixupLEAsImpl::checkRegUsage(MachineBasicBlock::iterator &LeaI,
472 bool &BaseIndexDef, bool &AluDestRef,
473 MachineOperand **KilledBase,
474 MachineOperand **KilledIndex) const {
475 BaseIndexDef = AluDestRef = false;
476 *KilledBase = *KilledIndex = nullptr;
477 Register BaseReg = LeaI->getOperand(1 + X86::AddrBaseReg).getReg();
478 Register IndexReg = LeaI->getOperand(1 + X86::AddrIndexReg).getReg();
479 Register AluDestReg = AluI->getOperand(0).getReg();
480
481 for (MachineInstr &CurInst : llvm::make_range(std::next(LeaI), AluI)) {
482 for (MachineOperand &Opnd : CurInst.operands()) {
483 if (!Opnd.isReg())
484 continue;
485 Register Reg = Opnd.getReg();
486 if (TRI->regsOverlap(Reg, AluDestReg))
487 AluDestRef = true;
488 if (TRI->regsOverlap(Reg, BaseReg)) {
489 if (Opnd.isDef())
490 BaseIndexDef = true;
491 else if (Opnd.isKill())
492 *KilledBase = &Opnd;
493 }
494 if (TRI->regsOverlap(Reg, IndexReg)) {
495 if (Opnd.isDef())
496 BaseIndexDef = true;
497 else if (Opnd.isKill())
498 *KilledIndex = &Opnd;
499 }
500 }
501 }
502}
503
504bool FixupLEAsImpl::optLEAALU(MachineBasicBlock::iterator &I,
505 MachineBasicBlock &MBB) const {
506 // Look for an add/sub instruction which uses the result of lea.
507 MachineBasicBlock::iterator AluI = searchALUInst(I, MBB);
508 if (AluI == MachineBasicBlock::iterator())
509 return false;
510
511 // Check if there are any related register usage between lea and alu.
512 bool BaseIndexDef, AluDestRef;
513 MachineOperand *KilledBase, *KilledIndex;
514 checkRegUsage(I, AluI, BaseIndexDef, AluDestRef, &KilledBase, &KilledIndex);
515
516 MachineBasicBlock::iterator InsertPos = AluI;
517 if (BaseIndexDef) {
518 if (AluDestRef)
519 return false;
520 InsertPos = I;
521 KilledBase = KilledIndex = nullptr;
522 }
523
524 // Check if there are same registers.
525 Register AluDestReg = AluI->getOperand(0).getReg();
526 Register BaseReg = I->getOperand(1 + X86::AddrBaseReg).getReg();
527 Register IndexReg = I->getOperand(1 + X86::AddrIndexReg).getReg();
528 if (I->getOpcode() == X86::LEA64_32r) {
529 BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
530 IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
531 }
532 if (AluDestReg == IndexReg) {
533 if (BaseReg == IndexReg)
534 return false;
535 std::swap(BaseReg, IndexReg);
536 std::swap(KilledBase, KilledIndex);
537 }
538 if (BaseReg == IndexReg)
539 KilledBase = nullptr;
540
541 // Now it's safe to change instructions.
542 MachineInstr *NewMI1, *NewMI2;
543 unsigned NewOpcode = AluI->getOpcode();
544 NewMI1 = BuildMI(MBB, InsertPos, AluI->getDebugLoc(), TII->get(NewOpcode),
545 AluDestReg)
546 .addReg(AluDestReg, RegState::Kill)
547 .addReg(BaseReg, getKillRegState(KilledBase));
548 NewMI1->addRegisterDead(X86::EFLAGS, TRI);
549 NewMI2 = BuildMI(MBB, InsertPos, AluI->getDebugLoc(), TII->get(NewOpcode),
550 AluDestReg)
551 .addReg(AluDestReg, RegState::Kill)
552 .addReg(IndexReg, getKillRegState(KilledIndex));
553 NewMI2->addRegisterDead(X86::EFLAGS, TRI);
554
555 // Clear the old Kill flags.
556 if (KilledBase)
557 KilledBase->setIsKill(false);
558 if (KilledIndex)
559 KilledIndex->setIsKill(false);
560
561 MBB.getParent()->substituteDebugValuesForInst(*AluI, *NewMI2, 1);
562 MBB.erase(I);
563 MBB.erase(AluI);
564 I = NewMI1;
565 return true;
566}
567
568bool FixupLEAsImpl::optTwoAddrLEA(MachineBasicBlock::iterator &I,
569 MachineBasicBlock &MBB, bool OptIncDec,
570 bool UseLEAForSP) const {
571 MachineInstr &MI = *I;
572
573 const MachineOperand &Base = MI.getOperand(1 + X86::AddrBaseReg);
574 const MachineOperand &Scale = MI.getOperand(1 + X86::AddrScaleAmt);
575 const MachineOperand &Index = MI.getOperand(1 + X86::AddrIndexReg);
576 const MachineOperand &Disp = MI.getOperand(1 + X86::AddrDisp);
577 const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
578
579 if (Segment.getReg().isValid() || !Disp.isImm() || Scale.getImm() > 1 ||
580 MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I) !=
582 return false;
583
584 Register DestReg = MI.getOperand(0).getReg();
585 Register BaseReg = Base.getReg();
586 Register IndexReg = Index.getReg();
587
588 // Don't change stack adjustment LEAs.
589 if (UseLEAForSP && (DestReg == X86::ESP || DestReg == X86::RSP))
590 return false;
591
592 // LEA64_32 has 64-bit operands but 32-bit result.
593 if (MI.getOpcode() == X86::LEA64_32r) {
594 if (BaseReg)
595 BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
596 if (IndexReg)
597 IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
598 }
599
600 MachineInstr *NewMI = nullptr;
601
602 // Case 1.
603 // Look for lea(%reg1, %reg2), %reg1 or lea(%reg2, %reg1), %reg1
604 // which can be turned into add %reg2, %reg1
605 if (BaseReg.isValid() && IndexReg.isValid() && Disp.getImm() == 0 &&
606 (DestReg == BaseReg || DestReg == IndexReg)) {
607 unsigned NewOpcode = getADDrrFromLEA(MI.getOpcode());
608 if (DestReg != BaseReg)
609 std::swap(BaseReg, IndexReg);
610
611 if (MI.getOpcode() == X86::LEA64_32r) {
612 // TODO: Do we need the super register implicit use?
613 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
614 .addReg(BaseReg).addReg(IndexReg)
615 .addReg(Base.getReg(), RegState::Implicit)
616 .addReg(Index.getReg(), RegState::Implicit);
617 } else {
618 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
619 .addReg(BaseReg).addReg(IndexReg);
620 }
621 } else if (DestReg == BaseReg && !IndexReg) {
622 // Case 2.
623 // This is an LEA with only a base register and a displacement,
624 // We can use ADDri or INC/DEC.
625
626 // Does this LEA have one these forms:
627 // lea %reg, 1(%reg)
628 // lea %reg, -1(%reg)
629 if (OptIncDec && (Disp.getImm() == 1 || Disp.getImm() == -1)) {
630 bool IsINC = Disp.getImm() == 1;
631 unsigned NewOpcode = getINCDECFromLEA(MI.getOpcode(), IsINC);
632
633 if (MI.getOpcode() == X86::LEA64_32r) {
634 // TODO: Do we need the super register implicit use?
635 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
636 .addReg(BaseReg).addReg(Base.getReg(), RegState::Implicit);
637 } else {
638 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
639 .addReg(BaseReg);
640 }
641 } else {
642 unsigned NewOpcode = getADDriFromLEA(MI.getOpcode(), Disp);
643 if (MI.getOpcode() == X86::LEA64_32r) {
644 // TODO: Do we need the super register implicit use?
645 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
646 .addReg(BaseReg).addImm(Disp.getImm())
647 .addReg(Base.getReg(), RegState::Implicit);
648 } else {
649 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
650 .addReg(BaseReg).addImm(Disp.getImm());
651 }
652 }
653 } else if (BaseReg.isValid() && IndexReg.isValid() && Disp.getImm() == 0) {
654 // Case 3.
655 // Look for and transform the sequence
656 // lea (reg1, reg2), reg3
657 // sub reg3, reg4
658 return optLEAALU(I, MBB);
659 } else
660 return false;
661
663 MBB.erase(I);
664 I = NewMI;
665 return true;
666}
667
668void FixupLEAsImpl::processInstruction(MachineBasicBlock::iterator &I,
669 MachineBasicBlock &MBB) {
670 // Process a load, store, or LEA instruction.
671 MachineInstr &MI = *I;
672 int AddrOffset = X86II::getMemoryOperandIdx(MI.getDesc());
673 if (AddrOffset >= 0) {
674 MachineOperand &p = MI.getOperand(AddrOffset + X86::AddrBaseReg);
675 if (p.isReg() && p.getReg() != X86::ESP) {
676 seekLEAFixup(p, I, MBB);
677 }
678 MachineOperand &q = MI.getOperand(AddrOffset + X86::AddrIndexReg);
679 if (q.isReg() && q.getReg() != X86::ESP) {
680 seekLEAFixup(q, I, MBB);
681 }
682 }
683}
684
685void FixupLEAsImpl::seekLEAFixup(MachineOperand &p,
687 MachineBasicBlock &MBB) {
688 MachineBasicBlock::iterator MBI = searchBackwards(p, I, MBB);
689 if (MBI != MachineBasicBlock::iterator()) {
690 MachineInstr *NewMI = postRAConvertToLEA(MBB, MBI);
691 if (NewMI) {
692 ++NumLEAs;
693 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI->dump(););
694 // now to replace with an equivalent LEA...
695 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI->dump(););
696 MBB.getParent()->substituteDebugValuesForInst(*MBI, *NewMI, 1);
697 MBB.erase(MBI);
699 static_cast<MachineBasicBlock::iterator>(NewMI);
700 processInstruction(J, MBB);
701 }
702 }
703}
704
705void FixupLEAsImpl::processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
706 MachineBasicBlock &MBB) {
707 MachineInstr &MI = *I;
708 const unsigned Opcode = MI.getOpcode();
709
710 const MachineOperand &Dst = MI.getOperand(0);
711 const MachineOperand &Base = MI.getOperand(1 + X86::AddrBaseReg);
712 const MachineOperand &Scale = MI.getOperand(1 + X86::AddrScaleAmt);
713 const MachineOperand &Index = MI.getOperand(1 + X86::AddrIndexReg);
714 const MachineOperand &Offset = MI.getOperand(1 + X86::AddrDisp);
715 const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
716
717 if (Segment.getReg().isValid() || !Offset.isImm() ||
718 MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I, 4) !=
720 return;
721 const Register DstR = Dst.getReg();
722 const Register SrcR1 = Base.getReg();
723 const Register SrcR2 = Index.getReg();
724 if ((!SrcR1 || SrcR1 != DstR) && (!SrcR2 || SrcR2 != DstR))
725 return;
726 if (Scale.getImm() > 1)
727 return;
728 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump(););
729 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
730 MachineInstr *NewMI = nullptr;
731 // Make ADD instruction for two registers writing to LEA's destination
732 if (SrcR1 && SrcR2) {
733 const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(Opcode));
734 const MachineOperand &Src = SrcR1 == DstR ? Index : Base;
735 NewMI =
736 BuildMI(MBB, I, MI.getDebugLoc(), ADDrr, DstR).addReg(DstR).add(Src);
737 LLVM_DEBUG(NewMI->dump(););
738 }
739 // Make ADD instruction for immediate
740 if (Offset.getImm() != 0) {
741 const MCInstrDesc &ADDri =
742 TII->get(getADDriFromLEA(Opcode, Offset));
743 const MachineOperand &SrcR = SrcR1 == DstR ? Base : Index;
744 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), ADDri, DstR)
745 .add(SrcR)
746 .addImm(Offset.getImm());
747 LLVM_DEBUG(NewMI->dump(););
748 }
749 if (NewMI) {
751 MBB.erase(I);
752 I = NewMI;
753 }
754}
755
756MachineInstr *FixupLEAsImpl::buildOffsetAdd(MachineInstr &MI,
757 MachineBasicBlock &MBB,
758 bool OptIncDec) const {
759 Register DestReg = MI.getOperand(0).getReg();
760 const MachineOperand &Offset = MI.getOperand(1 + X86::AddrDisp);
761 if (OptIncDec && Offset.isImm() &&
762 (Offset.getImm() == 1 || Offset.getImm() == -1)) {
763 unsigned NewOpc = getINCDECFromLEA(MI.getOpcode(), Offset.getImm() == 1);
764 MachineInstr *AddMI =
765 BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
766 .addReg(DestReg);
767 LLVM_DEBUG(AddMI->dump(););
768 return AddMI;
769 }
770 if (Offset.isImm() && Offset.getImm() == 128) {
771 // ADD of +128 needs a 32-bit immediate, while SUB of -128 fits the
772 // sign-extended 8-bit form, three bytes shorter. EFLAGS is dead
773 // (checked by the caller), so the different flag results don't matter.
774 unsigned NewOpc = getSUBriFromLEA(MI.getOpcode());
775 MachineInstr *AddMI =
776 BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
777 .addReg(DestReg)
778 .addImm(-128);
779 LLVM_DEBUG(AddMI->dump(););
780 return AddMI;
781 }
782 unsigned NewOpc = getADDriFromLEA(MI.getOpcode(), Offset);
783 MachineInstr *AddMI =
784 BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
785 .addReg(DestReg)
786 .add(Offset);
787 LLVM_DEBUG(AddMI->dump(););
788 return AddMI;
789}
790
791void FixupLEAsImpl::processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
792 MachineBasicBlock &MBB,
793 bool OptIncDec) {
794 MachineInstr &MI = *I;
795 const unsigned LEAOpcode = MI.getOpcode();
796
797 const MachineOperand &Dest = MI.getOperand(0);
798 const MachineOperand &Base = MI.getOperand(1 + X86::AddrBaseReg);
799 const MachineOperand &Scale = MI.getOperand(1 + X86::AddrScaleAmt);
800 const MachineOperand &Index = MI.getOperand(1 + X86::AddrIndexReg);
801 const MachineOperand &Offset = MI.getOperand(1 + X86::AddrDisp);
802 const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
803
804 if (!(TII->isThreeOperandsLEA(MI) || hasInefficientLEABaseReg(Base, Index)) ||
805 MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I, 4) !=
807 Segment.getReg().isValid())
808 return;
809
810 Register DestReg = Dest.getReg();
811 Register BaseReg = Base.getReg();
812 Register IndexReg = Index.getReg();
813
814 if (MI.getOpcode() == X86::LEA64_32r) {
815 if (BaseReg)
816 BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
817 if (IndexReg)
818 IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
819 }
820
821 bool IsScale1 = Scale.getImm() == 1;
822 bool IsInefficientBase = isInefficientLEAReg(BaseReg);
823 bool IsInefficientIndex = isInefficientLEAReg(IndexReg);
824
825 // Skip these cases since it takes more than 2 instructions
826 // to replace the LEA instruction.
827 if (IsInefficientBase && DestReg == BaseReg && !IsScale1)
828 return;
829
830 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI.dump(););
831 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
832
833 MachineInstr *NewMI = nullptr;
834 bool BaseOrIndexIsDst = DestReg == BaseReg || DestReg == IndexReg;
835 // First try and remove the base while sticking with LEA iff base == index and
836 // scale == 1. We can handle:
837 // 1. lea D(%base,%index,1) -> lea D(,%index,2)
838 // 2. lea D(%r13/%rbp,%index) -> lea D(,%index,2)
839 // Only do this if the LEA would otherwise be split into 2-instruction
840 // (either it has a an Offset or neither base nor index are dst)
841 if (IsScale1 && BaseReg == IndexReg &&
842 (mayHaveOffset(Offset) || (IsInefficientBase && !BaseOrIndexIsDst))) {
843 NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
844 .add(Dest)
845 .addReg(0)
846 .addImm(2)
847 .add(Index)
848 .add(Offset)
849 .add(Segment);
850 LLVM_DEBUG(NewMI->dump(););
851
853 MBB.erase(I);
854 I = NewMI;
855 return;
856 } else if (IsScale1 && BaseOrIndexIsDst) {
857 // Try to replace LEA with one or two (for the 3-op LEA case)
858 // add instructions:
859 // 1.lea (%base,%index,1), %base => add %index,%base
860 // 2.lea (%base,%index,1), %index => add %base,%index
861 if (mayHaveOffset(Offset)) {
862 // lea D(%r,%r,1) is turned into lea D(,%r,2) above; adding D first
863 // here would double it.
864 assert(BaseReg != IndexReg && "lea D(%r,%r,1) is handled above");
865 // 3.lea D(%base,%index,1), %base => add D,%base; add %index,%base
866 // Add D first so only one add waits for the other operand.
867 buildOffsetAdd(MI, MBB, OptIncDec);
868 }
869 unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
870 if (DestReg != BaseReg)
871 std::swap(BaseReg, IndexReg);
872
873 if (MI.getOpcode() == X86::LEA64_32r) {
874 // TODO: Do we need the super register implicit use?
875 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
876 .addReg(BaseReg)
877 .addReg(IndexReg)
878 .addReg(Base.getReg(), RegState::Implicit)
879 .addReg(Index.getReg(), RegState::Implicit);
880 } else {
881 NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
882 .addReg(BaseReg)
883 .addReg(IndexReg);
884 }
885 } else if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) {
886 // If the base is inefficient try switching the index and base operands,
887 // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction:
888 // lea offset(%base,%index,scale),%dst =>
889 // lea (%base,%index,scale); add offset,%dst
890 NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
891 .add(Dest)
892 .add(IsInefficientBase ? Index : Base)
893 .add(Scale)
894 .add(IsInefficientBase ? Base : Index)
895 .addImm(0)
896 .add(Segment);
897 LLVM_DEBUG(NewMI->dump(););
898
900 NewMI = buildOffsetAdd(MI, MBB, OptIncDec);
901 }
902
903 if (NewMI) {
905 MBB.erase(I);
906 I = NewMI;
907 return;
908 }
909
910 // Handle the rest of the cases with inefficient base register:
911 assert(DestReg != BaseReg && "DestReg == BaseReg should be handled already!");
912 assert(IsInefficientBase && "efficient base should be handled already!");
913
914 // FIXME: Handle LEA64_32r.
915 if (LEAOpcode == X86::LEA64_32r)
916 return;
917
918 // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst
919 if (IsScale1 && !mayHaveOffset(Offset)) {
920 bool BIK = Base.isKill() && BaseReg != IndexReg;
921 TII->copyPhysReg(MBB, MI, MI.getDebugLoc(), DestReg, BaseReg, BIK);
922 LLVM_DEBUG(MI.getPrevNode()->dump(););
923
924 unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
925 NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
926 .addReg(DestReg)
927 .add(Index);
928 LLVM_DEBUG(NewMI->dump(););
929
931 MBB.erase(I);
932 I = NewMI;
933 return;
934 }
935
936 // lea offset(%base,%index,scale), %dst =>
937 // lea offset( ,%index,scale), %dst; add %base,%dst
938 NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
939 .add(Dest)
940 .addReg(0)
941 .add(Scale)
942 .add(Index)
943 .add(Offset)
944 .add(Segment);
945 LLVM_DEBUG(NewMI->dump(););
946
947 unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
948 NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
949 .addReg(DestReg)
950 .add(Base);
951 LLVM_DEBUG(NewMI->dump(););
952
954 MBB.erase(I);
955 I = NewMI;
956}
957
958bool FixupLEAsLegacy::runOnMachineFunction(MachineFunction &MF) {
959 if (skipFunction(MF.getFunction()))
960 return false;
961
962 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
963 auto *MBFI = (PSI && PSI->hasProfileSummary())
964 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
965 : nullptr;
966 FixupLEAsImpl PassImpl(PSI, MBFI);
967 return PassImpl.runOnMachineFunction(MF);
968}
969
972 ProfileSummaryInfo *PSI =
974 .getCachedResult<ProfileSummaryAnalysis>(
975 *MF.getFunction().getParent());
976 if (!PSI)
977 report_fatal_error("x86-fixup-leas requires ProfileSummaryAnalysis", false);
980
981 FixupLEAsImpl PassImpl(PSI, MBFI);
982 bool Changed = PassImpl.runOnMachineFunction(MF);
983 if (!Changed)
984 return PreservedAnalyses::all();
987 return PA;
988}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
IRTranslator LLVM IR MI
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static unsigned getINCDECFromLEA(unsigned LEAOpcode, bool IsINC)
static bool isLEA(unsigned Opcode)
static unsigned getSUBriFromLEA(unsigned LEAOpcode)
static bool isInefficientLEAReg(Register Reg)
static bool hasInefficientLEABaseReg(const MachineOperand &Base, const MachineOperand &Index)
Returns true if this LEA uses base and index registers, and the base register is known to be ineffici...
static unsigned getADDriFromLEA(unsigned LEAOpcode, const MachineOperand &Offset)
static bool getPreviousInstr(MachineBasicBlock::iterator &I, MachineBasicBlock &MBB)
getPreviousInstr - Given a reference to an instruction in a basic block, return a reference to the pr...
#define FIXUPLEA_DESC
static unsigned getADDrrFromLEA(unsigned LEAOpcode)
#define FIXUPLEA_NAME
static unsigned getSUBrrFromLEA(unsigned LEAOpcode)
static bool mayHaveOffset(const MachineOperand &Offset)
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
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
@ LQR_Dead
Register is known to be fully dead.
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.
void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New, unsigned MaxOperand=UINT_MAX)
Create substitutions for any tracked values in Old, to point at New.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
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:151
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int getMemoryOperandIdx(const MCInstrDesc &Desc)
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getKillRegState(bool B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
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
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createX86FixupLEAsLegacyPass()
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881