1 //===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// \file This file contains a pass that performs load / store related peephole
11 /// optimizations. This pass should be run after register allocation.
13 //===----------------------------------------------------------------------===//
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "ThumbRegisterInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/RegisterClassInfo.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/LivePhysRegs.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
49 #define DEBUG_TYPE "arm-ldst-opt"
51 STATISTIC(NumLDMGened , "Number of ldm instructions generated");
52 STATISTIC(NumSTMGened , "Number of stm instructions generated");
53 STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
54 STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
55 STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
56 STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
57 STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
58 STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
59 STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
60 STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
61 STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
63 /// This switch disables formation of double/multi instructions that could
64 /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
65 /// disabled. This can be used to create libraries that are robust even when
66 /// users provoke undefined behaviour by supplying misaligned pointers.
67 /// \see mayCombineMisaligned()
69 AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
70 cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
72 #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
75 /// Post- register allocation pass the combine load / store instructions to
76 /// form ldm / stm instructions.
77 struct ARMLoadStoreOpt : public MachineFunctionPass {
79 ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
81 const MachineFunction *MF;
82 const TargetInstrInfo *TII;
83 const TargetRegisterInfo *TRI;
84 const ARMSubtarget *STI;
85 const TargetLowering *TL;
87 LivePhysRegs LiveRegs;
88 RegisterClassInfo RegClassInfo;
89 MachineBasicBlock::const_iterator LiveRegPos;
91 bool RegClassInfoValid;
92 bool isThumb1, isThumb2;
94 bool runOnMachineFunction(MachineFunction &Fn) override;
96 MachineFunctionProperties getRequiredProperties() const override {
97 return MachineFunctionProperties().set(
98 MachineFunctionProperties::Property::NoVRegs);
101 StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
104 /// A set of load/store MachineInstrs with same base register sorted by
106 struct MemOpQueueEntry {
108 int Offset; ///< Load/Store offset.
109 unsigned Position; ///< Position as counted from end of basic block.
110 MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
111 : MI(&MI), Offset(Offset), Position(Position) {}
113 typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
115 /// A set of MachineInstrs that fulfill (nearly all) conditions to get
116 /// merged into a LDM/STM.
117 struct MergeCandidate {
118 /// List of instructions ordered by load/store offset.
119 SmallVector<MachineInstr*, 4> Instrs;
120 /// Index in Instrs of the instruction being latest in the schedule.
121 unsigned LatestMIIdx;
122 /// Index in Instrs of the instruction being earliest in the schedule.
123 unsigned EarliestMIIdx;
124 /// Index into the basic block where the merged instruction will be
125 /// inserted. (See MemOpQueueEntry.Position)
127 /// Whether the instructions can be merged into a ldm/stm instruction.
128 bool CanMergeToLSMulti;
129 /// Whether the instructions can be merged into a ldrd/strd instruction.
130 bool CanMergeToLSDouble;
132 SpecificBumpPtrAllocator<MergeCandidate> Allocator;
133 SmallVector<const MergeCandidate*,4> Candidates;
134 SmallVector<MachineInstr*,4> MergeBaseCandidates;
136 void moveLiveRegsBefore(const MachineBasicBlock &MBB,
137 MachineBasicBlock::const_iterator Before);
138 unsigned findFreeReg(const TargetRegisterClass &RegClass);
139 void UpdateBaseRegUses(MachineBasicBlock &MBB,
140 MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
141 unsigned Base, unsigned WordOffset,
142 ARMCC::CondCodes Pred, unsigned PredReg);
143 MachineInstr *CreateLoadStoreMulti(
144 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
145 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
146 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
147 ArrayRef<std::pair<unsigned, bool>> Regs);
148 MachineInstr *CreateLoadStoreDouble(
149 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
150 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
151 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
152 ArrayRef<std::pair<unsigned, bool>> Regs) const;
153 void FormCandidates(const MemOpQueue &MemOps);
154 MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
155 bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
156 MachineBasicBlock::iterator &MBBI);
157 bool MergeBaseUpdateLoadStore(MachineInstr *MI);
158 bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
159 bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
160 bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
161 bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
162 bool CombineMovBx(MachineBasicBlock &MBB);
164 char ARMLoadStoreOpt::ID = 0;
167 INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,
170 static bool definesCPSR(const MachineInstr &MI) {
171 for (const auto &MO : MI.operands()) {
174 if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
175 // If the instruction has live CPSR def, then it's not safe to fold it
176 // into load / store.
183 static int getMemoryOpOffset(const MachineInstr &MI) {
184 unsigned Opcode = MI.getOpcode();
185 bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
186 unsigned NumOperands = MI.getDesc().getNumOperands();
187 unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
189 if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
190 Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
191 Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
192 Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
195 // Thumb1 immediate offsets are scaled by 4
196 if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
197 Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
200 int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
201 : ARM_AM::getAM5Offset(OffField) * 4;
202 ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
203 : ARM_AM::getAM5Op(OffField);
205 if (Op == ARM_AM::sub)
211 static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
212 return MI.getOperand(1);
215 static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
216 return MI.getOperand(0);
219 static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
221 default: llvm_unreachable("Unhandled opcode!");
225 default: llvm_unreachable("Unhandled submode!");
226 case ARM_AM::ia: return ARM::LDMIA;
227 case ARM_AM::da: return ARM::LDMDA;
228 case ARM_AM::db: return ARM::LDMDB;
229 case ARM_AM::ib: return ARM::LDMIB;
234 default: llvm_unreachable("Unhandled submode!");
235 case ARM_AM::ia: return ARM::STMIA;
236 case ARM_AM::da: return ARM::STMDA;
237 case ARM_AM::db: return ARM::STMDB;
238 case ARM_AM::ib: return ARM::STMIB;
242 // tLDMIA is writeback-only - unless the base register is in the input
246 default: llvm_unreachable("Unhandled submode!");
247 case ARM_AM::ia: return ARM::tLDMIA;
251 // There is no non-writeback tSTMIA either.
254 default: llvm_unreachable("Unhandled submode!");
255 case ARM_AM::ia: return ARM::tSTMIA_UPD;
261 default: llvm_unreachable("Unhandled submode!");
262 case ARM_AM::ia: return ARM::t2LDMIA;
263 case ARM_AM::db: return ARM::t2LDMDB;
269 default: llvm_unreachable("Unhandled submode!");
270 case ARM_AM::ia: return ARM::t2STMIA;
271 case ARM_AM::db: return ARM::t2STMDB;
276 default: llvm_unreachable("Unhandled submode!");
277 case ARM_AM::ia: return ARM::VLDMSIA;
278 case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
283 default: llvm_unreachable("Unhandled submode!");
284 case ARM_AM::ia: return ARM::VSTMSIA;
285 case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
290 default: llvm_unreachable("Unhandled submode!");
291 case ARM_AM::ia: return ARM::VLDMDIA;
292 case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
297 default: llvm_unreachable("Unhandled submode!");
298 case ARM_AM::ia: return ARM::VSTMDIA;
299 case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
304 static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
306 default: llvm_unreachable("Unhandled opcode!");
313 case ARM::tLDMIA_UPD:
314 case ARM::tSTMIA_UPD:
315 case ARM::t2LDMIA_RET:
317 case ARM::t2LDMIA_UPD:
319 case ARM::t2STMIA_UPD:
321 case ARM::VLDMSIA_UPD:
323 case ARM::VSTMSIA_UPD:
325 case ARM::VLDMDIA_UPD:
327 case ARM::VSTMDIA_UPD:
341 case ARM::t2LDMDB_UPD:
343 case ARM::t2STMDB_UPD:
344 case ARM::VLDMSDB_UPD:
345 case ARM::VSTMSDB_UPD:
346 case ARM::VLDMDDB_UPD:
347 case ARM::VSTMDDB_UPD:
358 static bool isT1i32Load(unsigned Opc) {
359 return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
362 static bool isT2i32Load(unsigned Opc) {
363 return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
366 static bool isi32Load(unsigned Opc) {
367 return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
370 static bool isT1i32Store(unsigned Opc) {
371 return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
374 static bool isT2i32Store(unsigned Opc) {
375 return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
378 static bool isi32Store(unsigned Opc) {
379 return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
382 static bool isLoadSingle(unsigned Opc) {
383 return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
386 static unsigned getImmScale(unsigned Opc) {
388 default: llvm_unreachable("Unhandled opcode!");
403 static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
404 switch (MI->getOpcode()) {
431 case ARM::tLDMIA_UPD:
432 case ARM::tSTMIA_UPD:
439 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
442 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
446 /// Update future uses of the base register with the offset introduced
447 /// due to writeback. This function only works on Thumb1.
448 void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
449 MachineBasicBlock::iterator MBBI,
450 const DebugLoc &DL, unsigned Base,
452 ARMCC::CondCodes Pred,
454 assert(isThumb1 && "Can only update base register uses for Thumb1!");
455 // Start updating any instructions with immediate offsets. Insert a SUB before
456 // the first non-updateable instruction (if any).
457 for (; MBBI != MBB.end(); ++MBBI) {
458 bool InsertSub = false;
459 unsigned Opc = MBBI->getOpcode();
461 if (MBBI->readsRegister(Base)) {
464 Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
466 Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
468 if (IsLoad || IsStore) {
469 // Loads and stores with immediate offsets can be updated, but only if
470 // the new offset isn't negative.
471 // The MachineOperand containing the offset immediate is the last one
472 // before predicates.
474 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
475 // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
476 Offset = MO.getImm() - WordOffset * getImmScale(Opc);
478 // If storing the base register, it needs to be reset first.
479 unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
481 if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
486 } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
487 !definesCPSR(*MBBI)) {
488 // SUBS/ADDS using this register, with a dead def of the CPSR.
489 // Merge it with the update; if the merged offset is too large,
490 // insert a new sub instead.
492 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
493 Offset = (Opc == ARM::tSUBi8) ?
494 MO.getImm() + WordOffset * 4 :
495 MO.getImm() - WordOffset * 4 ;
496 if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
497 // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
500 // The base register has now been reset, so exit early.
507 // Can't update the instruction.
511 } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
512 // Since SUBS sets the condition flags, we can't place the base reset
513 // after an instruction that has a live CPSR def.
514 // The base register might also contain an argument for a function call.
519 // An instruction above couldn't be updated, so insert a sub.
520 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
521 .add(t1CondCodeOp(true))
523 .addImm(WordOffset * 4)
529 if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
530 // Register got killed. Stop updating.
534 // End of block was reached.
535 if (MBB.succ_size() > 0) {
536 // FIXME: Because of a bug, live registers are sometimes missing from
537 // the successor blocks' live-in sets. This means we can't trust that
538 // information and *always* have to reset at the end of a block.
540 if (MBBI != MBB.end()) --MBBI;
541 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
542 .add(t1CondCodeOp(true))
544 .addImm(WordOffset * 4)
550 /// Return the first register of class \p RegClass that is not in \p Regs.
551 unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
552 if (!RegClassInfoValid) {
553 RegClassInfo.runOnMachineFunction(*MF);
554 RegClassInfoValid = true;
557 for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
558 if (!LiveRegs.contains(Reg))
563 /// Compute live registers just before instruction \p Before (in normal schedule
564 /// direction). Computes backwards so multiple queries in the same block must
565 /// come in reverse order.
566 void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
567 MachineBasicBlock::const_iterator Before) {
568 // Initialize if we never queried in this block.
569 if (!LiveRegsValid) {
571 LiveRegs.addLiveOuts(MBB);
572 LiveRegPos = MBB.end();
573 LiveRegsValid = true;
575 // Move backward just before the "Before" position.
576 while (LiveRegPos != Before) {
578 LiveRegs.stepBackward(*LiveRegPos);
582 static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
584 for (const std::pair<unsigned, bool> &R : Regs)
590 /// Create and insert a LDM or STM with Base as base register and registers in
591 /// Regs as the register operands that would be loaded / stored. It returns
592 /// true if the transformation is done.
593 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
594 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
595 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
596 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
597 ArrayRef<std::pair<unsigned, bool>> Regs) {
598 unsigned NumRegs = Regs.size();
601 // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
602 // Compute liveness information for that register to make the decision.
603 bool SafeToClobberCPSR = !isThumb1 ||
604 (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
605 MachineBasicBlock::LQR_Dead);
607 bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
609 // Exception: If the base register is in the input reglist, Thumb1 LDM is
611 // It's also not possible to merge an STR of the base register in Thumb1.
612 if (isThumb1 && ContainsReg(Regs, Base)) {
613 assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
614 if (Opcode == ARM::tLDRi)
616 else if (Opcode == ARM::tSTRi)
620 ARM_AM::AMSubMode Mode = ARM_AM::ia;
621 // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
622 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
623 bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
625 if (Offset == 4 && haveIBAndDA) {
627 } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
629 } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
630 // VLDM/VSTM do not support DB mode without also updating the base reg.
632 } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
633 // Check if this is a supported opcode before inserting instructions to
634 // calculate a new base register.
635 if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
637 // If starting offset isn't zero, insert a MI to materialize a new base.
638 // But only do so if it is cost effective, i.e. merging more than two
643 // On Thumb1, it's not worth materializing a new base register without
644 // clobbering the CPSR (i.e. not using ADDS/SUBS).
645 if (!SafeToClobberCPSR)
649 if (isi32Load(Opcode)) {
650 // If it is a load, then just use one of the destination registers
651 // as the new base. Will no longer be writeback in Thumb1.
652 NewBase = Regs[NumRegs-1].first;
655 // Find a free register that we can use as scratch register.
656 moveLiveRegsBefore(MBB, InsertBefore);
657 // The merged instruction does not exist yet but will use several Regs if
659 if (!isLoadSingle(Opcode))
660 for (const std::pair<unsigned, bool> &R : Regs)
661 LiveRegs.addReg(R.first);
663 NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
669 isThumb2 ? ARM::t2ADDri :
670 (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
671 (isThumb1 && Offset < 8) ? ARM::tADDi3 :
672 isThumb1 ? ARM::tADDi8 : ARM::ADDri;
677 isThumb2 ? ARM::t2SUBri :
678 (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
679 isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
682 if (!TL->isLegalAddImmediate(Offset))
683 // FIXME: Try add with register operand?
684 return nullptr; // Probably not worth it then.
686 // We can only append a kill flag to the add/sub input if the value is not
687 // used in the register list of the stm as well.
688 bool KillOldBase = BaseKill &&
689 (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
692 // Thumb1: depending on immediate size, use either
693 // ADDS NewBase, Base, #imm3
696 // ADDS NewBase, #imm8.
697 if (Base != NewBase &&
698 (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
699 // Need to insert a MOV to the new base first.
700 if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
702 // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
703 if (Pred != ARMCC::AL)
705 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
706 .addReg(Base, getKillRegState(KillOldBase));
708 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
709 .addReg(Base, getKillRegState(KillOldBase))
710 .add(predOps(Pred, PredReg));
712 // The following ADDS/SUBS becomes an update.
716 if (BaseOpc == ARM::tADDrSPi) {
717 assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
718 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
719 .addReg(Base, getKillRegState(KillOldBase))
721 .add(predOps(Pred, PredReg));
723 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
724 .add(t1CondCodeOp(true))
725 .addReg(Base, getKillRegState(KillOldBase))
727 .add(predOps(Pred, PredReg));
729 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
730 .addReg(Base, getKillRegState(KillOldBase))
732 .add(predOps(Pred, PredReg))
736 BaseKill = true; // New base is always killed straight away.
739 bool isDef = isLoadSingle(Opcode);
741 // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
742 // base register writeback.
743 Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
747 // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
748 // - There is no writeback (LDM of base register),
749 // - the base register is killed by the merged instruction,
750 // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
751 // to reset the base register.
752 // Otherwise, don't merge.
753 // It's safe to return here since the code to materialize a new base register
754 // above is also conditional on SafeToClobberCPSR.
755 if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
758 MachineInstrBuilder MIB;
761 assert(isThumb1 && "expected Writeback only inThumb1");
762 if (Opcode == ARM::tLDMIA) {
763 assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
764 // Update tLDMIA with writeback if necessary.
765 Opcode = ARM::tLDMIA_UPD;
768 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
770 // Thumb1: we might need to set base writeback when building the MI.
771 MIB.addReg(Base, getDefRegState(true))
772 .addReg(Base, getKillRegState(BaseKill));
774 // The base isn't dead after a merged instruction with writeback.
775 // Insert a sub instruction after the newly formed instruction to reset.
777 UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
780 // No writeback, simply build the MachineInstr.
781 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
782 MIB.addReg(Base, getKillRegState(BaseKill));
785 MIB.addImm(Pred).addReg(PredReg);
787 for (const std::pair<unsigned, bool> &R : Regs)
788 MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
790 return MIB.getInstr();
793 MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
794 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
795 int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
796 ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
797 ArrayRef<std::pair<unsigned, bool>> Regs) const {
798 bool IsLoad = isi32Load(Opcode);
799 assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
800 unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
802 assert(Regs.size() == 2);
803 MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
804 TII->get(LoadStoreOpcode));
806 MIB.addReg(Regs[0].first, RegState::Define)
807 .addReg(Regs[1].first, RegState::Define);
809 MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
810 .addReg(Regs[1].first, getKillRegState(Regs[1].second));
812 MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
813 return MIB.getInstr();
816 /// Call MergeOps and update MemOps and merges accordingly on success.
817 MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
818 const MachineInstr *First = Cand.Instrs.front();
819 unsigned Opcode = First->getOpcode();
820 bool IsLoad = isLoadSingle(Opcode);
821 SmallVector<std::pair<unsigned, bool>, 8> Regs;
822 SmallVector<unsigned, 4> ImpDefs;
823 DenseSet<unsigned> KilledRegs;
824 DenseSet<unsigned> UsedRegs;
825 // Determine list of registers and list of implicit super-register defs.
826 for (const MachineInstr *MI : Cand.Instrs) {
827 const MachineOperand &MO = getLoadStoreRegOp(*MI);
828 unsigned Reg = MO.getReg();
829 bool IsKill = MO.isKill();
831 KilledRegs.insert(Reg);
832 Regs.push_back(std::make_pair(Reg, IsKill));
833 UsedRegs.insert(Reg);
836 // Collect any implicit defs of super-registers, after merging we can't
837 // be sure anymore that we properly preserved these live ranges and must
838 // removed these implicit operands.
839 for (const MachineOperand &MO : MI->implicit_operands()) {
840 if (!MO.isReg() || !MO.isDef() || MO.isDead())
842 assert(MO.isImplicit());
843 unsigned DefReg = MO.getReg();
845 if (is_contained(ImpDefs, DefReg))
847 // We can ignore cases where the super-reg is read and written.
848 if (MI->readsRegister(DefReg))
850 ImpDefs.push_back(DefReg);
855 // Attempt the merge.
856 typedef MachineBasicBlock::iterator iterator;
857 MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
858 iterator InsertBefore = std::next(iterator(LatestMI));
859 MachineBasicBlock &MBB = *LatestMI->getParent();
860 unsigned Offset = getMemoryOpOffset(*First);
861 unsigned Base = getLoadStoreBaseOp(*First).getReg();
862 bool BaseKill = LatestMI->killsRegister(Base);
863 unsigned PredReg = 0;
864 ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
865 DebugLoc DL = First->getDebugLoc();
866 MachineInstr *Merged = nullptr;
867 if (Cand.CanMergeToLSDouble)
868 Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
869 Opcode, Pred, PredReg, DL, Regs);
870 if (!Merged && Cand.CanMergeToLSMulti)
871 Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
872 Opcode, Pred, PredReg, DL, Regs);
876 // Determine earliest instruction that will get removed. We then keep an
877 // iterator just above it so the following erases don't invalidated it.
878 iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
879 bool EarliestAtBegin = false;
880 if (EarliestI == MBB.begin()) {
881 EarliestAtBegin = true;
883 EarliestI = std::prev(EarliestI);
886 // Remove instructions which have been merged.
887 for (MachineInstr *MI : Cand.Instrs)
890 // Determine range between the earliest removed instruction and the new one.
892 EarliestI = MBB.begin();
894 EarliestI = std::next(EarliestI);
895 auto FixupRange = make_range(EarliestI, iterator(Merged));
897 if (isLoadSingle(Opcode)) {
898 // If the previous loads defined a super-reg, then we have to mark earlier
899 // operands undef; Replicate the super-reg def on the merged instruction.
900 for (MachineInstr &MI : FixupRange) {
901 for (unsigned &ImpDefReg : ImpDefs) {
902 for (MachineOperand &MO : MI.implicit_operands()) {
903 if (!MO.isReg() || MO.getReg() != ImpDefReg)
913 MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
914 for (unsigned ImpDef : ImpDefs)
915 MIB.addReg(ImpDef, RegState::ImplicitDefine);
917 // Remove kill flags: We are possibly storing the values later now.
918 assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
919 for (MachineInstr &MI : FixupRange) {
920 for (MachineOperand &MO : MI.uses()) {
921 if (!MO.isReg() || !MO.isKill())
923 if (UsedRegs.count(MO.getReg()))
927 assert(ImpDefs.empty());
933 static bool isValidLSDoubleOffset(int Offset) {
934 unsigned Value = abs(Offset);
935 // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
937 return (Value % 4) == 0 && Value < 1024;
940 /// Return true for loads/stores that can be combined to a double/multi
941 /// operation without increasing the requirements for alignment.
942 static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
943 const MachineInstr &MI) {
944 // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
946 unsigned Opcode = MI.getOpcode();
947 if (!isi32Load(Opcode) && !isi32Store(Opcode))
950 // Stack pointer alignment is out of the programmers control so we can trust
951 // SP-relative loads/stores.
952 if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
953 STI.getFrameLowering()->getTransientStackAlignment() >= 4)
958 /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
959 void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
960 const MachineInstr *FirstMI = MemOps[0].MI;
961 unsigned Opcode = FirstMI->getOpcode();
962 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
963 unsigned Size = getLSMultipleTransferSize(FirstMI);
966 unsigned EIndex = MemOps.size();
968 // Look at the first instruction.
969 const MachineInstr *MI = MemOps[SIndex].MI;
970 int Offset = MemOps[SIndex].Offset;
971 const MachineOperand &PMO = getLoadStoreRegOp(*MI);
972 unsigned PReg = PMO.getReg();
973 unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
974 unsigned Latest = SIndex;
975 unsigned Earliest = SIndex;
977 bool CanMergeToLSDouble =
978 STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
979 // ARM errata 602117: LDRD with base in list may result in incorrect base
980 // register when interrupted or faulted.
981 if (STI->isCortexM3() && isi32Load(Opcode) &&
982 PReg == getLoadStoreBaseOp(*MI).getReg())
983 CanMergeToLSDouble = false;
985 bool CanMergeToLSMulti = true;
986 // On swift vldm/vstm starting with an odd register number as that needs
987 // more uops than single vldrs.
988 if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
989 CanMergeToLSMulti = false;
991 // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
992 // deprecated; LDM to PC is fine but cannot happen here.
993 if (PReg == ARM::SP || PReg == ARM::PC)
994 CanMergeToLSMulti = CanMergeToLSDouble = false;
996 // Should we be conservative?
997 if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
998 CanMergeToLSMulti = CanMergeToLSDouble = false;
1000 // Merge following instructions where possible.
1001 for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1002 int NewOffset = MemOps[I].Offset;
1003 if (NewOffset != Offset + (int)Size)
1005 const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
1006 unsigned Reg = MO.getReg();
1007 if (Reg == ARM::SP || Reg == ARM::PC)
1010 // See if the current load/store may be part of a multi load/store.
1011 unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
1012 bool PartOfLSMulti = CanMergeToLSMulti;
1013 if (PartOfLSMulti) {
1014 // Register numbers must be in ascending order.
1015 if (RegNum <= PRegNum)
1016 PartOfLSMulti = false;
1017 // For VFP / NEON load/store multiples, the registers must be
1018 // consecutive and within the limit on the number of registers per
1020 else if (!isNotVFP && RegNum != PRegNum+1)
1021 PartOfLSMulti = false;
1023 // See if the current load/store may be part of a double load/store.
1024 bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1026 if (!PartOfLSMulti && !PartOfLSDouble)
1028 CanMergeToLSMulti &= PartOfLSMulti;
1029 CanMergeToLSDouble &= PartOfLSDouble;
1030 // Track MemOp with latest and earliest position (Positions are
1031 // counted in reverse).
1032 unsigned Position = MemOps[I].Position;
1033 if (Position < MemOps[Latest].Position)
1035 else if (Position > MemOps[Earliest].Position)
1037 // Prepare for next MemOp.
1042 // Form a candidate from the Ops collected so far.
1043 MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1044 for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1045 Candidate->Instrs.push_back(MemOps[C].MI);
1046 Candidate->LatestMIIdx = Latest - SIndex;
1047 Candidate->EarliestMIIdx = Earliest - SIndex;
1048 Candidate->InsertPos = MemOps[Latest].Position;
1050 CanMergeToLSMulti = CanMergeToLSDouble = false;
1051 Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1052 Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1053 Candidates.push_back(Candidate);
1054 // Continue after the chain.
1056 } while (SIndex < EIndex);
1059 static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1060 ARM_AM::AMSubMode Mode) {
1062 default: llvm_unreachable("Unhandled opcode!");
1068 default: llvm_unreachable("Unhandled submode!");
1069 case ARM_AM::ia: return ARM::LDMIA_UPD;
1070 case ARM_AM::ib: return ARM::LDMIB_UPD;
1071 case ARM_AM::da: return ARM::LDMDA_UPD;
1072 case ARM_AM::db: return ARM::LDMDB_UPD;
1079 default: llvm_unreachable("Unhandled submode!");
1080 case ARM_AM::ia: return ARM::STMIA_UPD;
1081 case ARM_AM::ib: return ARM::STMIB_UPD;
1082 case ARM_AM::da: return ARM::STMDA_UPD;
1083 case ARM_AM::db: return ARM::STMDB_UPD;
1088 default: llvm_unreachable("Unhandled submode!");
1089 case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1090 case ARM_AM::db: return ARM::t2LDMDB_UPD;
1095 default: llvm_unreachable("Unhandled submode!");
1096 case ARM_AM::ia: return ARM::t2STMIA_UPD;
1097 case ARM_AM::db: return ARM::t2STMDB_UPD;
1101 default: llvm_unreachable("Unhandled submode!");
1102 case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1103 case ARM_AM::db: return ARM::VLDMSDB_UPD;
1107 default: llvm_unreachable("Unhandled submode!");
1108 case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1109 case ARM_AM::db: return ARM::VLDMDDB_UPD;
1113 default: llvm_unreachable("Unhandled submode!");
1114 case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1115 case ARM_AM::db: return ARM::VSTMSDB_UPD;
1119 default: llvm_unreachable("Unhandled submode!");
1120 case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1121 case ARM_AM::db: return ARM::VSTMDDB_UPD;
1126 /// Check if the given instruction increments or decrements a register and
1127 /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1128 /// generated by the instruction are possibly read as well.
1129 static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
1130 ARMCC::CondCodes Pred, unsigned PredReg) {
1133 switch (MI.getOpcode()) {
1134 case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break;
1135 case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break;
1137 case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break;
1139 case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break;
1140 case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break;
1141 case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1146 if (MI.getOperand(0).getReg() != Reg ||
1147 MI.getOperand(1).getReg() != Reg ||
1148 getInstrPredicate(MI, MIPredReg) != Pred ||
1149 MIPredReg != PredReg)
1152 if (CheckCPSRDef && definesCPSR(MI))
1154 return MI.getOperand(2).getImm() * Scale;
1157 /// Searches for an increment or decrement of \p Reg before \p MBBI.
1158 static MachineBasicBlock::iterator
1159 findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
1160 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1162 MachineBasicBlock &MBB = *MBBI->getParent();
1163 MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1164 MachineBasicBlock::iterator EndMBBI = MBB.end();
1165 if (MBBI == BeginMBBI)
1168 // Skip debug values.
1169 MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1170 while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
1173 Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1174 return Offset == 0 ? EndMBBI : PrevMBBI;
1177 /// Searches for a increment or decrement of \p Reg after \p MBBI.
1178 static MachineBasicBlock::iterator
1179 findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
1180 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1182 MachineBasicBlock &MBB = *MBBI->getParent();
1183 MachineBasicBlock::iterator EndMBBI = MBB.end();
1184 MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1185 // Skip debug values.
1186 while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1188 if (NextMBBI == EndMBBI)
1191 Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1192 return Offset == 0 ? EndMBBI : NextMBBI;
1195 /// Fold proceeding/trailing inc/dec of base register into the
1196 /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1198 /// stmia rn, <ra, rb, rc>
1199 /// rn := rn + 4 * 3;
1201 /// stmia rn!, <ra, rb, rc>
1203 /// rn := rn - 4 * 3;
1204 /// ldmia rn, <ra, rb, rc>
1206 /// ldmdb rn!, <ra, rb, rc>
1207 bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
1208 // Thumb1 is already using updating loads/stores.
1209 if (isThumb1) return false;
1211 const MachineOperand &BaseOP = MI->getOperand(0);
1212 unsigned Base = BaseOP.getReg();
1213 bool BaseKill = BaseOP.isKill();
1214 unsigned PredReg = 0;
1215 ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1216 unsigned Opcode = MI->getOpcode();
1217 DebugLoc DL = MI->getDebugLoc();
1219 // Can't use an updating ld/st if the base register is also a dest
1220 // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1221 for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1222 if (MI->getOperand(i).getReg() == Base)
1225 int Bytes = getLSMultipleTransferSize(MI);
1226 MachineBasicBlock &MBB = *MI->getParent();
1227 MachineBasicBlock::iterator MBBI(MI);
1229 MachineBasicBlock::iterator MergeInstr
1230 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1231 ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1232 if (Mode == ARM_AM::ia && Offset == -Bytes) {
1234 } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1237 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1238 if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1239 ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
1241 // We couldn't find an inc/dec to merge. But if the base is dead, we
1242 // can still change to a writeback form as that will save us 2 bytes
1243 // of code size. It can create WAW hazards though, so only do it if
1244 // we're minimizing code size.
1245 if (!MBB.getParent()->getFunction()->optForMinSize() || !BaseKill)
1248 bool HighRegsUsed = false;
1249 for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
1250 if (MI->getOperand(i).getReg() >= ARM::R8) {
1251 HighRegsUsed = true;
1256 MergeInstr = MBB.end();
1261 if (MergeInstr != MBB.end())
1262 MBB.erase(MergeInstr);
1264 unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1265 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1266 .addReg(Base, getDefRegState(true)) // WB base register
1267 .addReg(Base, getKillRegState(BaseKill))
1268 .addImm(Pred).addReg(PredReg);
1270 // Transfer the rest of operands.
1271 for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
1272 MIB.add(MI->getOperand(OpNum));
1274 // Transfer memoperands.
1275 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
1281 static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1282 ARM_AM::AddrOpc Mode) {
1285 return ARM::LDR_PRE_IMM;
1287 return ARM::STR_PRE_IMM;
1289 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1291 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1293 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1295 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1298 return ARM::t2LDR_PRE;
1301 return ARM::t2STR_PRE;
1302 default: llvm_unreachable("Unhandled opcode!");
1306 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1307 ARM_AM::AddrOpc Mode) {
1310 return ARM::LDR_POST_IMM;
1312 return ARM::STR_POST_IMM;
1314 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1316 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1318 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1320 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
1323 return ARM::t2LDR_POST;
1326 return ARM::t2STR_POST;
1327 default: llvm_unreachable("Unhandled opcode!");
1331 /// Fold proceeding/trailing inc/dec of base register into the
1332 /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
1333 bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
1334 // Thumb1 doesn't have updating LDR/STR.
1335 // FIXME: Use LDM/STM with single register instead.
1336 if (isThumb1) return false;
1338 unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1339 bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
1340 unsigned Opcode = MI->getOpcode();
1341 DebugLoc DL = MI->getDebugLoc();
1342 bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1343 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1344 bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1345 if (isi32Load(Opcode) || isi32Store(Opcode))
1346 if (MI->getOperand(2).getImm() != 0)
1348 if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
1351 // Can't do the merge if the destination register is the same as the would-be
1352 // writeback register.
1353 if (MI->getOperand(0).getReg() == Base)
1356 unsigned PredReg = 0;
1357 ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1358 int Bytes = getLSMultipleTransferSize(MI);
1359 MachineBasicBlock &MBB = *MI->getParent();
1360 MachineBasicBlock::iterator MBBI(MI);
1362 MachineBasicBlock::iterator MergeInstr
1363 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1365 if (!isAM5 && Offset == Bytes) {
1366 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1367 } else if (Offset == -Bytes) {
1368 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1370 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1371 if (Offset == Bytes) {
1372 NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1373 } else if (!isAM5 && Offset == -Bytes) {
1374 NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1378 MBB.erase(MergeInstr);
1380 ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1382 bool isLd = isLoadSingle(Opcode);
1384 // VLDM[SD]_UPD, VSTM[SD]_UPD
1385 // (There are no base-updating versions of VLDR/VSTR instructions, but the
1386 // updating load/store-multiple instructions can be used with only one
1388 MachineOperand &MO = MI->getOperand(0);
1389 BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1390 .addReg(Base, getDefRegState(true)) // WB base register
1391 .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1392 .addImm(Pred).addReg(PredReg)
1393 .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1394 getKillRegState(MO.isKill())));
1397 // LDR_PRE, LDR_POST
1398 if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1399 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1400 .addReg(Base, RegState::Define)
1401 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1403 int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1404 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1405 .addReg(Base, RegState::Define)
1409 .add(predOps(Pred, PredReg));
1412 // t2LDR_PRE, t2LDR_POST
1413 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
1414 .addReg(Base, RegState::Define)
1417 .add(predOps(Pred, PredReg));
1420 MachineOperand &MO = MI->getOperand(0);
1421 // FIXME: post-indexed stores use am2offset_imm, which still encodes
1422 // the vestigal zero-reg offset register. When that's fixed, this clause
1423 // can be removed entirely.
1424 if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1425 int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
1426 // STR_PRE, STR_POST
1427 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1428 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1432 .add(predOps(Pred, PredReg));
1434 // t2STR_PRE, t2STR_POST
1435 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1436 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1439 .add(predOps(Pred, PredReg));
1447 bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1448 unsigned Opcode = MI.getOpcode();
1449 assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1450 "Must have t2STRDi8 or t2LDRDi8");
1451 if (MI.getOperand(3).getImm() != 0)
1454 // Behaviour for writeback is undefined if base register is the same as one
1456 const MachineOperand &BaseOp = MI.getOperand(2);
1457 unsigned Base = BaseOp.getReg();
1458 const MachineOperand &Reg0Op = MI.getOperand(0);
1459 const MachineOperand &Reg1Op = MI.getOperand(1);
1460 if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1464 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1465 MachineBasicBlock::iterator MBBI(MI);
1466 MachineBasicBlock &MBB = *MI.getParent();
1468 MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1471 if (Offset == 8 || Offset == -8) {
1472 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1474 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1475 if (Offset == 8 || Offset == -8) {
1476 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1480 MBB.erase(MergeInstr);
1482 DebugLoc DL = MI.getDebugLoc();
1483 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1484 if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1485 MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1487 assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1488 MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1490 MIB.addReg(BaseOp.getReg(), RegState::Kill)
1491 .addImm(Offset).addImm(Pred).addReg(PredReg);
1492 assert(TII->get(Opcode).getNumOperands() == 6 &&
1493 TII->get(NewOpc).getNumOperands() == 7 &&
1494 "Unexpected number of operands in Opcode specification.");
1496 // Transfer implicit operands.
1497 for (const MachineOperand &MO : MI.implicit_operands())
1499 MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1505 /// Returns true if instruction is a memory operation that this pass is capable
1506 /// of operating on.
1507 static bool isMemoryOp(const MachineInstr &MI) {
1508 unsigned Opcode = MI.getOpcode();
1528 if (!MI.getOperand(1).isReg())
1531 // When no memory operands are present, conservatively assume unaligned,
1532 // volatile, unfoldable.
1533 if (!MI.hasOneMemOperand())
1536 const MachineMemOperand &MMO = **MI.memoperands_begin();
1538 // Don't touch volatile memory accesses - we may be changing their order.
1539 if (MMO.isVolatile())
1542 // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1544 if (MMO.getAlignment() < 4)
1547 // str <undef> could probably be eliminated entirely, but for now we just want
1548 // to avoid making a mess of it.
1549 // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1550 if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1553 // Likewise don't mess with references to undefined addresses.
1554 if (MI.getOperand(1).isUndef())
1560 static void InsertLDR_STR(MachineBasicBlock &MBB,
1561 MachineBasicBlock::iterator &MBBI, int Offset,
1562 bool isDef, const DebugLoc &DL, unsigned NewOpc,
1563 unsigned Reg, bool RegDeadKill, bool RegUndef,
1564 unsigned BaseReg, bool BaseKill, bool BaseUndef,
1565 bool OffKill, bool OffUndef, ARMCC::CondCodes Pred,
1566 unsigned PredReg, const TargetInstrInfo *TII,
1569 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1571 .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
1572 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1573 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1575 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1577 .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1578 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
1579 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1583 bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1584 MachineBasicBlock::iterator &MBBI) {
1585 MachineInstr *MI = &*MBBI;
1586 unsigned Opcode = MI->getOpcode();
1587 if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1590 const MachineOperand &BaseOp = MI->getOperand(2);
1591 unsigned BaseReg = BaseOp.getReg();
1592 unsigned EvenReg = MI->getOperand(0).getReg();
1593 unsigned OddReg = MI->getOperand(1).getReg();
1594 unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1595 unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
1597 // ARM errata 602117: LDRD with base in list may result in incorrect base
1598 // register when interrupted or faulted.
1599 bool Errata602117 = EvenReg == BaseReg &&
1600 (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1601 // ARM LDRD/STRD needs consecutive registers.
1602 bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1603 (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1605 if (!Errata602117 && !NonConsecutiveRegs)
1608 bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1609 bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1610 bool EvenDeadKill = isLd ?
1611 MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1612 bool EvenUndef = MI->getOperand(0).isUndef();
1613 bool OddDeadKill = isLd ?
1614 MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1615 bool OddUndef = MI->getOperand(1).isUndef();
1616 bool BaseKill = BaseOp.isKill();
1617 bool BaseUndef = BaseOp.isUndef();
1618 bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
1619 bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
1620 int OffImm = getMemoryOpOffset(*MI);
1621 unsigned PredReg = 0;
1622 ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1624 if (OddRegNum > EvenRegNum && OffImm == 0) {
1625 // Ascending register numbers and no offset. It's safe to change it to a
1627 unsigned NewOpc = (isLd)
1628 ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1629 : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1631 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1632 .addReg(BaseReg, getKillRegState(BaseKill))
1633 .addImm(Pred).addReg(PredReg)
1634 .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1635 .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill));
1638 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1639 .addReg(BaseReg, getKillRegState(BaseKill))
1640 .addImm(Pred).addReg(PredReg)
1642 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1644 getKillRegState(OddDeadKill) | getUndefRegState(OddUndef));
1648 // Split into two instructions.
1649 unsigned NewOpc = (isLd)
1650 ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1651 : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1652 // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1653 // so adjust and use t2LDRi12 here for that.
1654 unsigned NewOpc2 = (isLd)
1655 ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1656 : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1657 DebugLoc dl = MBBI->getDebugLoc();
1658 // If this is a load and base register is killed, it may have been
1659 // re-defed by the load, make sure the first load does not clobber it.
1661 (BaseKill || OffKill) &&
1662 (TRI->regsOverlap(EvenReg, BaseReg))) {
1663 assert(!TRI->regsOverlap(OddReg, BaseReg));
1664 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1665 OddReg, OddDeadKill, false,
1666 BaseReg, false, BaseUndef, false, OffUndef,
1667 Pred, PredReg, TII, isT2);
1668 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1669 EvenReg, EvenDeadKill, false,
1670 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1671 Pred, PredReg, TII, isT2);
1673 if (OddReg == EvenReg && EvenDeadKill) {
1674 // If the two source operands are the same, the kill marker is
1675 // probably on the first one. e.g.
1676 // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
1677 EvenDeadKill = false;
1680 // Never kill the base register in the first instruction.
1681 if (EvenReg == BaseReg)
1682 EvenDeadKill = false;
1683 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1684 EvenReg, EvenDeadKill, EvenUndef,
1685 BaseReg, false, BaseUndef, false, OffUndef,
1686 Pred, PredReg, TII, isT2);
1687 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1688 OddReg, OddDeadKill, OddUndef,
1689 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1690 Pred, PredReg, TII, isT2);
1698 MBBI = MBB.erase(MBBI);
1702 /// An optimization pass to turn multiple LDR / STR ops of the same base and
1703 /// incrementing offset into LDM / STM ops.
1704 bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1706 unsigned CurrBase = 0;
1707 unsigned CurrOpc = ~0u;
1708 ARMCC::CondCodes CurrPred = ARMCC::AL;
1709 unsigned Position = 0;
1710 assert(Candidates.size() == 0);
1711 assert(MergeBaseCandidates.size() == 0);
1712 LiveRegsValid = false;
1714 for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1716 // The instruction in front of the iterator is the one we look at.
1717 MBBI = std::prev(I);
1718 if (FixInvalidRegPairOp(MBB, MBBI))
1722 if (isMemoryOp(*MBBI)) {
1723 unsigned Opcode = MBBI->getOpcode();
1724 const MachineOperand &MO = MBBI->getOperand(0);
1725 unsigned Reg = MO.getReg();
1726 unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
1727 unsigned PredReg = 0;
1728 ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
1729 int Offset = getMemoryOpOffset(*MBBI);
1730 if (CurrBase == 0) {
1731 // Start of a new chain.
1735 MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1738 // Note: No need to match PredReg in the next if.
1739 if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1741 // r4 := ldr [r0, #8]
1742 // r4 := ldr [r0, #4]
1745 // If a load overrides the base register or a register loaded by
1746 // another load in our chain, we cannot take this instruction.
1747 bool Overlap = false;
1748 if (isLoadSingle(Opcode)) {
1749 Overlap = (Base == Reg);
1751 for (const MemOpQueueEntry &E : MemOps) {
1752 if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1761 // Check offset and sort memory operation into the current chain.
1762 if (Offset > MemOps.back().Offset) {
1763 MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1766 MemOpQueue::iterator MI, ME;
1767 for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1768 if (Offset < MI->Offset) {
1769 // Found a place to insert.
1772 if (Offset == MI->Offset) {
1773 // Collision, abort.
1778 if (MI != MemOps.end()) {
1779 MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1786 // Don't advance the iterator; The op will start a new chain next.
1789 // Fallthrough to look into existing chain.
1790 } else if (MBBI->isDebugValue()) {
1792 } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1793 MBBI->getOpcode() == ARM::t2STRDi8) {
1794 // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1795 // remember them because we may still be able to merge add/sub into them.
1796 MergeBaseCandidates.push_back(&*MBBI);
1800 // If we are here then the chain is broken; Extract candidates for a merge.
1801 if (MemOps.size() > 0) {
1802 FormCandidates(MemOps);
1803 // Reset for the next chain.
1806 CurrPred = ARMCC::AL;
1810 if (MemOps.size() > 0)
1811 FormCandidates(MemOps);
1813 // Sort candidates so they get processed from end to begin of the basic
1814 // block later; This is necessary for liveness calculation.
1815 auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1816 return M0->InsertPos < M1->InsertPos;
1818 std::sort(Candidates.begin(), Candidates.end(), LessThan);
1820 // Go through list of candidates and merge.
1821 bool Changed = false;
1822 for (const MergeCandidate *Candidate : Candidates) {
1823 if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
1824 MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1825 // Merge preceding/trailing base inc/dec into the merged op.
1828 unsigned Opcode = Merged->getOpcode();
1829 if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
1830 MergeBaseUpdateLSDouble(*Merged);
1832 MergeBaseUpdateLSMultiple(Merged);
1834 for (MachineInstr *MI : Candidate->Instrs) {
1835 if (MergeBaseUpdateLoadStore(MI))
1840 assert(Candidate->Instrs.size() == 1);
1841 if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
1846 // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
1847 for (MachineInstr *MI : MergeBaseCandidates)
1848 MergeBaseUpdateLSDouble(*MI);
1849 MergeBaseCandidates.clear();
1854 /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
1855 /// into the preceding stack restore so it directly restore the value of LR
1857 /// ldmfd sp!, {..., lr}
1860 /// ldmfd sp!, {..., lr}
1863 /// ldmfd sp!, {..., pc}
1864 bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
1865 // Thumb1 LDM doesn't allow high registers.
1866 if (isThumb1) return false;
1867 if (MBB.empty()) return false;
1869 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
1870 if (MBBI != MBB.begin() && MBBI != MBB.end() &&
1871 (MBBI->getOpcode() == ARM::BX_RET ||
1872 MBBI->getOpcode() == ARM::tBX_RET ||
1873 MBBI->getOpcode() == ARM::MOVPCLR)) {
1874 MachineBasicBlock::iterator PrevI = std::prev(MBBI);
1875 // Ignore any DBG_VALUE instructions.
1876 while (PrevI->isDebugValue() && PrevI != MBB.begin())
1878 MachineInstr &PrevMI = *PrevI;
1879 unsigned Opcode = PrevMI.getOpcode();
1880 if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
1881 Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
1882 Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
1883 MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
1884 if (MO.getReg() != ARM::LR)
1886 unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
1887 assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
1888 Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
1889 PrevMI.setDesc(TII->get(NewOpc));
1891 PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
1899 bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
1900 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1901 if (MBBI == MBB.begin() || MBBI == MBB.end() ||
1902 MBBI->getOpcode() != ARM::tBX_RET)
1905 MachineBasicBlock::iterator Prev = MBBI;
1907 if (Prev->getOpcode() != ARM::tMOVr || !Prev->definesRegister(ARM::LR))
1910 for (auto Use : Prev->uses())
1912 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
1913 .addReg(Use.getReg(), RegState::Kill)
1914 .add(predOps(ARMCC::AL))
1915 .copyImplicitOps(*MBBI);
1921 llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
1924 bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
1925 if (skipFunction(*Fn.getFunction()))
1929 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1930 TL = STI->getTargetLowering();
1931 AFI = Fn.getInfo<ARMFunctionInfo>();
1932 TII = STI->getInstrInfo();
1933 TRI = STI->getRegisterInfo();
1935 RegClassInfoValid = false;
1936 isThumb2 = AFI->isThumb2Function();
1937 isThumb1 = AFI->isThumbFunction() && !isThumb2;
1939 bool Modified = false;
1940 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1942 MachineBasicBlock &MBB = *MFI;
1943 Modified |= LoadStoreMultipleOpti(MBB);
1944 if (STI->hasV5TOps())
1945 Modified |= MergeReturnIntoLDM(MBB);
1947 Modified |= CombineMovBx(MBB);
1950 Allocator.DestroyAll();
1954 #define ARM_PREALLOC_LOAD_STORE_OPT_NAME \
1955 "ARM pre- register allocation load / store optimization pass"
1958 /// Pre- register allocation pass that move load / stores from consecutive
1959 /// locations close to make it more likely they will be combined later.
1960 struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
1962 ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
1965 const DataLayout *TD;
1966 const TargetInstrInfo *TII;
1967 const TargetRegisterInfo *TRI;
1968 const ARMSubtarget *STI;
1969 MachineRegisterInfo *MRI;
1970 MachineFunction *MF;
1972 bool runOnMachineFunction(MachineFunction &Fn) override;
1974 StringRef getPassName() const override {
1975 return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
1978 virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
1979 AU.addRequired<AAResultsWrapperPass>();
1980 MachineFunctionPass::getAnalysisUsage(AU);
1984 bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1985 unsigned &NewOpc, unsigned &EvenReg,
1986 unsigned &OddReg, unsigned &BaseReg,
1988 unsigned &PredReg, ARMCC::CondCodes &Pred,
1990 bool RescheduleOps(MachineBasicBlock *MBB,
1991 SmallVectorImpl<MachineInstr *> &Ops,
1992 unsigned Base, bool isLd,
1993 DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1994 bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1996 char ARMPreAllocLoadStoreOpt::ID = 0;
1999 INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
2000 ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
2002 bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2003 if (AssumeMisalignedLoadStores || skipFunction(*Fn.getFunction()))
2006 TD = &Fn.getDataLayout();
2007 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
2008 TII = STI->getInstrInfo();
2009 TRI = STI->getRegisterInfo();
2010 MRI = &Fn.getRegInfo();
2012 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2014 bool Modified = false;
2015 for (MachineBasicBlock &MFI : Fn)
2016 Modified |= RescheduleLoadStoreInstrs(&MFI);
2021 static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2022 MachineBasicBlock::iterator I,
2023 MachineBasicBlock::iterator E,
2024 SmallPtrSetImpl<MachineInstr*> &MemOps,
2025 SmallSet<unsigned, 4> &MemRegs,
2026 const TargetRegisterInfo *TRI,
2027 AliasAnalysis *AA) {
2028 // Are there stores / loads / calls between them?
2029 SmallSet<unsigned, 4> AddedRegPressure;
2031 if (I->isDebugValue() || MemOps.count(&*I))
2033 if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2035 if (I->mayStore() || (!isLd && I->mayLoad()))
2036 for (MachineInstr *MemOp : MemOps)
2037 if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false))
2039 for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2040 MachineOperand &MO = I->getOperand(j);
2043 unsigned Reg = MO.getReg();
2044 if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2046 if (Reg != Base && !MemRegs.count(Reg))
2047 AddedRegPressure.insert(Reg);
2051 // Estimate register pressure increase due to the transformation.
2052 if (MemRegs.size() <= 4)
2053 // Ok if we are moving small number of instructions.
2055 return AddedRegPressure.size() <= MemRegs.size() * 2;
2059 ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
2060 DebugLoc &dl, unsigned &NewOpc,
2062 unsigned &SecondReg,
2063 unsigned &BaseReg, int &Offset,
2065 ARMCC::CondCodes &Pred,
2067 // Make sure we're allowed to generate LDRD/STRD.
2068 if (!STI->hasV5TEOps())
2071 // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
2073 unsigned Opcode = Op0->getOpcode();
2074 if (Opcode == ARM::LDRi12) {
2076 } else if (Opcode == ARM::STRi12) {
2078 } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
2079 NewOpc = ARM::t2LDRDi8;
2082 } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2083 NewOpc = ARM::t2STRDi8;
2090 // Make sure the base address satisfies i64 ld / st alignment requirement.
2091 // At the moment, we ignore the memoryoperand's value.
2092 // If we want to use AliasAnalysis, we should check it accordingly.
2093 if (!Op0->hasOneMemOperand() ||
2094 (*Op0->memoperands_begin())->isVolatile())
2097 unsigned Align = (*Op0->memoperands_begin())->getAlignment();
2098 const Function *Func = MF->getFunction();
2099 unsigned ReqAlign = STI->hasV6Ops()
2100 ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
2101 : 8; // Pre-v6 need 8-byte align
2102 if (Align < ReqAlign)
2105 // Then make sure the immediate offset fits.
2106 int OffImm = getMemoryOpOffset(*Op0);
2108 int Limit = (1 << 8) * Scale;
2109 if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2113 ARM_AM::AddrOpc AddSub = ARM_AM::add;
2115 AddSub = ARM_AM::sub;
2118 int Limit = (1 << 8) * Scale;
2119 if (OffImm >= Limit || (OffImm & (Scale-1)))
2121 Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
2123 FirstReg = Op0->getOperand(0).getReg();
2124 SecondReg = Op1->getOperand(0).getReg();
2125 if (FirstReg == SecondReg)
2127 BaseReg = Op0->getOperand(1).getReg();
2128 Pred = getInstrPredicate(*Op0, PredReg);
2129 dl = Op0->getDebugLoc();
2133 bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
2134 SmallVectorImpl<MachineInstr *> &Ops,
2135 unsigned Base, bool isLd,
2136 DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2137 bool RetVal = false;
2139 // Sort by offset (in reverse order).
2140 std::sort(Ops.begin(), Ops.end(),
2141 [](const MachineInstr *LHS, const MachineInstr *RHS) {
2142 int LOffset = getMemoryOpOffset(*LHS);
2143 int ROffset = getMemoryOpOffset(*RHS);
2144 assert(LHS == RHS || LOffset != ROffset);
2145 return LOffset > ROffset;
2148 // The loads / stores of the same base are in order. Scan them from first to
2149 // last and check for the following:
2150 // 1. Any def of base.
2152 while (Ops.size() > 1) {
2153 unsigned FirstLoc = ~0U;
2154 unsigned LastLoc = 0;
2155 MachineInstr *FirstOp = nullptr;
2156 MachineInstr *LastOp = nullptr;
2158 unsigned LastOpcode = 0;
2159 unsigned LastBytes = 0;
2160 unsigned NumMove = 0;
2161 for (int i = Ops.size() - 1; i >= 0; --i) {
2162 // Make sure each operation has the same kind.
2163 MachineInstr *Op = Ops[i];
2165 = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2166 if (LastOpcode && LSMOpcode != LastOpcode)
2169 // Check that we have a continuous set of offsets.
2170 int Offset = getMemoryOpOffset(*Op);
2171 unsigned Bytes = getLSMultipleTransferSize(Op);
2173 if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2177 // Don't try to reschedule too many instructions.
2178 if (NumMove == 8) // FIXME: Tune this limit.
2181 // Found a mergable instruction; save information about it.
2183 LastOffset = Offset;
2185 LastOpcode = LSMOpcode;
2187 unsigned Loc = MI2LocMap[Op];
2188 if (Loc <= FirstLoc) {
2192 if (Loc >= LastLoc) {
2201 SmallPtrSet<MachineInstr*, 4> MemOps;
2202 SmallSet<unsigned, 4> MemRegs;
2203 for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) {
2204 MemOps.insert(Ops[i]);
2205 MemRegs.insert(Ops[i]->getOperand(0).getReg());
2208 // Be conservative, if the instructions are too far apart, don't
2209 // move them. We want to limit the increase of register pressure.
2210 bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2212 DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2213 MemOps, MemRegs, TRI, AA);
2215 for (unsigned i = 0; i != NumMove; ++i)
2218 // This is the new location for the loads / stores.
2219 MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
2220 while (InsertPos != MBB->end() &&
2221 (MemOps.count(&*InsertPos) || InsertPos->isDebugValue()))
2224 // If we are moving a pair of loads / stores, see if it makes sense
2225 // to try to allocate a pair of registers that can form register pairs.
2226 MachineInstr *Op0 = Ops.back();
2227 MachineInstr *Op1 = Ops[Ops.size()-2];
2228 unsigned FirstReg = 0, SecondReg = 0;
2229 unsigned BaseReg = 0, PredReg = 0;
2230 ARMCC::CondCodes Pred = ARMCC::AL;
2232 unsigned NewOpc = 0;
2235 if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
2236 FirstReg, SecondReg, BaseReg,
2237 Offset, PredReg, Pred, isT2)) {
2241 const MCInstrDesc &MCID = TII->get(NewOpc);
2242 const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
2243 MRI->constrainRegClass(FirstReg, TRC);
2244 MRI->constrainRegClass(SecondReg, TRC);
2246 // Form the pair instruction.
2248 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2249 .addReg(FirstReg, RegState::Define)
2250 .addReg(SecondReg, RegState::Define)
2252 // FIXME: We're converting from LDRi12 to an insn that still
2253 // uses addrmode2, so we need an explicit offset reg. It should
2254 // always by reg0 since we're transforming LDRi12s.
2257 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2258 MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2259 DEBUG(dbgs() << "Formed " << *MIB << "\n");
2262 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
2266 // FIXME: We're converting from LDRi12 to an insn that still
2267 // uses addrmode2, so we need an explicit offset reg. It should
2268 // always by reg0 since we're transforming STRi12s.
2271 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2272 MIB.setMemRefs(Op0->mergeMemRefsWith(*Op1));
2273 DEBUG(dbgs() << "Formed " << *MIB << "\n");
2280 // Add register allocation hints to form register pairs.
2281 MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2282 MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);
2285 for (unsigned i = 0; i != NumMove; ++i) {
2286 MachineInstr *Op = Ops.back();
2288 MBB->splice(InsertPos, MBB, Op);
2292 NumLdStMoved += NumMove;
2302 ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2303 bool RetVal = false;
2305 DenseMap<MachineInstr*, unsigned> MI2LocMap;
2306 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2307 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2308 SmallVector<unsigned, 4> LdBases;
2309 SmallVector<unsigned, 4> StBases;
2312 MachineBasicBlock::iterator MBBI = MBB->begin();
2313 MachineBasicBlock::iterator E = MBB->end();
2315 for (; MBBI != E; ++MBBI) {
2316 MachineInstr &MI = *MBBI;
2317 if (MI.isCall() || MI.isTerminator()) {
2318 // Stop at barriers.
2323 if (!MI.isDebugValue())
2324 MI2LocMap[&MI] = ++Loc;
2326 if (!isMemoryOp(MI))
2328 unsigned PredReg = 0;
2329 if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2332 int Opc = MI.getOpcode();
2333 bool isLd = isLoadSingle(Opc);
2334 unsigned Base = MI.getOperand(1).getReg();
2335 int Offset = getMemoryOpOffset(MI);
2337 bool StopHere = false;
2339 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2340 Base2LdsMap.find(Base);
2341 if (BI != Base2LdsMap.end()) {
2342 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2343 if (Offset == getMemoryOpOffset(*BI->second[i])) {
2349 BI->second.push_back(&MI);
2351 Base2LdsMap[Base].push_back(&MI);
2352 LdBases.push_back(Base);
2355 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2356 Base2StsMap.find(Base);
2357 if (BI != Base2StsMap.end()) {
2358 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2359 if (Offset == getMemoryOpOffset(*BI->second[i])) {
2365 BI->second.push_back(&MI);
2367 Base2StsMap[Base].push_back(&MI);
2368 StBases.push_back(Base);
2373 // Found a duplicate (a base+offset combination that's seen earlier).
2380 // Re-schedule loads.
2381 for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2382 unsigned Base = LdBases[i];
2383 SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2385 RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2388 // Re-schedule stores.
2389 for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2390 unsigned Base = StBases[i];
2391 SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2393 RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2397 Base2LdsMap.clear();
2398 Base2StsMap.clear();
2408 /// Returns an instance of the load / store optimization pass.
2409 FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2411 return new ARMPreAllocLoadStoreOpt();
2412 return new ARMLoadStoreOpt();