xref: /src/contrib/llvm-project/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1044eb2f6SDimitry Andric //===- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass -------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
985d8b2bbSDimitry Andric /// \file This file contains a pass that performs load / store related peephole
1085d8b2bbSDimitry Andric /// optimizations. This pass should be run after register allocation.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "ARM.h"
1559850d08SRoman Divacky #include "ARMBaseInstrInfo.h"
1663faed5bSDimitry Andric #include "ARMBaseRegisterInfo.h"
175ca98fd9SDimitry Andric #include "ARMISelLowering.h"
18009b1c42SEd Schouten #include "ARMMachineFunctionInfo.h"
195ca98fd9SDimitry Andric #include "ARMSubtarget.h"
2030815c53SDimitry Andric #include "MCTargetDesc/ARMAddressingModes.h"
21044eb2f6SDimitry Andric #include "MCTargetDesc/ARMBaseInfo.h"
22044eb2f6SDimitry Andric #include "Utils/ARMBaseInfo.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
244a16efa3SDimitry Andric #include "llvm/ADT/DenseMap.h"
25044eb2f6SDimitry Andric #include "llvm/ADT/DenseSet.h"
264a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
27145449b1SDimitry Andric #include "llvm/ADT/SetVector.h"
284a16efa3SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
294a16efa3SDimitry Andric #include "llvm/ADT/SmallSet.h"
304a16efa3SDimitry Andric #include "llvm/ADT/SmallVector.h"
314a16efa3SDimitry Andric #include "llvm/ADT/Statistic.h"
32044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
33044eb2f6SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
34ac9a064cSDimitry Andric #include "llvm/CodeGen/LiveRegUnits.h"
35009b1c42SEd Schouten #include "llvm/CodeGen/MachineBasicBlock.h"
36cfca06d7SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
37145449b1SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
39009b1c42SEd Schouten #include "llvm/CodeGen/MachineFunctionPass.h"
40009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstr.h"
41009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstrBuilder.h"
42044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
43044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
44600c6fa1SEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
45ee8648bdSDimitry Andric #include "llvm/CodeGen/RegisterClassInfo.h"
46044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
47044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
48044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
49044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
50044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
514a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
52044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
534a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
544a16efa3SDimitry Andric #include "llvm/IR/Function.h"
55044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
56cfca06d7SDimitry Andric #include "llvm/InitializePasses.h"
57044eb2f6SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
58044eb2f6SDimitry Andric #include "llvm/Pass.h"
59ee8648bdSDimitry Andric #include "llvm/Support/Allocator.h"
60044eb2f6SDimitry Andric #include "llvm/Support/CommandLine.h"
614a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
624a16efa3SDimitry Andric #include "llvm/Support/ErrorHandling.h"
635a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
64044eb2f6SDimitry Andric #include <algorithm>
65044eb2f6SDimitry Andric #include <cassert>
66044eb2f6SDimitry Andric #include <cstddef>
67044eb2f6SDimitry Andric #include <cstdlib>
68044eb2f6SDimitry Andric #include <iterator>
69044eb2f6SDimitry Andric #include <limits>
70044eb2f6SDimitry Andric #include <utility>
71044eb2f6SDimitry Andric 
72009b1c42SEd Schouten using namespace llvm;
73009b1c42SEd Schouten 
745ca98fd9SDimitry Andric #define DEBUG_TYPE "arm-ldst-opt"
755ca98fd9SDimitry Andric 
76009b1c42SEd Schouten STATISTIC(NumLDMGened , "Number of ldm instructions generated");
77009b1c42SEd Schouten STATISTIC(NumSTMGened , "Number of stm instructions generated");
78907da171SRoman Divacky STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
79907da171SRoman Divacky STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
80600c6fa1SEd Schouten STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
81b2f21fb0SEd Schouten STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
82b2f21fb0SEd Schouten STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
83b2f21fb0SEd Schouten STATISTIC(NumLDRD2LDM,  "Number of ldrd instructions turned back into ldm");
84b2f21fb0SEd Schouten STATISTIC(NumSTRD2STM,  "Number of strd instructions turned back into stm");
85b2f21fb0SEd Schouten STATISTIC(NumLDRD2LDR,  "Number of ldrd instructions turned back into ldr's");
86b2f21fb0SEd Schouten STATISTIC(NumSTRD2STR,  "Number of strd instructions turned back into str's");
87600c6fa1SEd Schouten 
8801095a5dSDimitry Andric /// This switch disables formation of double/multi instructions that could
8901095a5dSDimitry Andric /// potentially lead to (new) alignment traps even with CCR.UNALIGN_TRP
9001095a5dSDimitry Andric /// disabled. This can be used to create libraries that are robust even when
9101095a5dSDimitry Andric /// users provoke undefined behaviour by supplying misaligned pointers.
9201095a5dSDimitry Andric /// \see mayCombineMisaligned()
9301095a5dSDimitry Andric static cl::opt<bool>
9401095a5dSDimitry Andric AssumeMisalignedLoadStores("arm-assume-misaligned-load-store", cl::Hidden,
9501095a5dSDimitry Andric     cl::init(false), cl::desc("Be more conservative in ARM load/store opt"));
96dd58ef01SDimitry Andric 
97dd58ef01SDimitry Andric #define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
98dd58ef01SDimitry Andric 
99009b1c42SEd Schouten namespace {
100044eb2f6SDimitry Andric 
10185d8b2bbSDimitry Andric   /// Post- register allocation pass the combine load / store instructions to
10285d8b2bbSDimitry Andric   /// form ldm / stm instructions.
10336bf506aSRoman Divacky   struct ARMLoadStoreOpt : public MachineFunctionPass {
104009b1c42SEd Schouten     static char ID;
105009b1c42SEd Schouten 
106ee8648bdSDimitry Andric     const MachineFunction *MF;
107009b1c42SEd Schouten     const TargetInstrInfo *TII;
108009b1c42SEd Schouten     const TargetRegisterInfo *TRI;
10963faed5bSDimitry Andric     const ARMSubtarget *STI;
1105ca98fd9SDimitry Andric     const TargetLowering *TL;
111009b1c42SEd Schouten     ARMFunctionInfo *AFI;
112ac9a064cSDimitry Andric     LiveRegUnits LiveRegs;
113ee8648bdSDimitry Andric     RegisterClassInfo RegClassInfo;
114ee8648bdSDimitry Andric     MachineBasicBlock::const_iterator LiveRegPos;
115ee8648bdSDimitry Andric     bool LiveRegsValid;
116ee8648bdSDimitry Andric     bool RegClassInfoValid;
1175ca98fd9SDimitry Andric     bool isThumb1, isThumb2;
118009b1c42SEd Schouten 
ARMLoadStoreOpt__anond192f79a0111::ARMLoadStoreOpt119044eb2f6SDimitry Andric     ARMLoadStoreOpt() : MachineFunctionPass(ID) {}
120044eb2f6SDimitry Andric 
1215ca98fd9SDimitry Andric     bool runOnMachineFunction(MachineFunction &Fn) override;
122009b1c42SEd Schouten 
getRequiredProperties__anond192f79a0111::ARMLoadStoreOpt12301095a5dSDimitry Andric     MachineFunctionProperties getRequiredProperties() const override {
12401095a5dSDimitry Andric       return MachineFunctionProperties().set(
125b915e9e0SDimitry Andric           MachineFunctionProperties::Property::NoVRegs);
12601095a5dSDimitry Andric     }
12701095a5dSDimitry Andric 
getPassName__anond192f79a0111::ARMLoadStoreOpt128b915e9e0SDimitry Andric     StringRef getPassName() const override { return ARM_LOAD_STORE_OPT_NAME; }
129009b1c42SEd Schouten 
130009b1c42SEd Schouten   private:
131ee8648bdSDimitry Andric     /// A set of load/store MachineInstrs with same base register sorted by
132ee8648bdSDimitry Andric     /// offset.
133009b1c42SEd Schouten     struct MemOpQueueEntry {
134ee8648bdSDimitry Andric       MachineInstr *MI;
135ee8648bdSDimitry Andric       int Offset;        ///< Load/Store offset.
136ee8648bdSDimitry Andric       unsigned Position; ///< Position as counted from end of basic block.
137044eb2f6SDimitry Andric 
MemOpQueueEntry__anond192f79a0111::ARMLoadStoreOpt::MemOpQueueEntry13801095a5dSDimitry Andric       MemOpQueueEntry(MachineInstr &MI, int Offset, unsigned Position)
13901095a5dSDimitry Andric           : MI(&MI), Offset(Offset), Position(Position) {}
140009b1c42SEd Schouten     };
141044eb2f6SDimitry Andric     using MemOpQueue = SmallVector<MemOpQueueEntry, 8>;
142009b1c42SEd Schouten 
143ee8648bdSDimitry Andric     /// A set of MachineInstrs that fulfill (nearly all) conditions to get
144ee8648bdSDimitry Andric     /// merged into a LDM/STM.
145ee8648bdSDimitry Andric     struct MergeCandidate {
146ee8648bdSDimitry Andric       /// List of instructions ordered by load/store offset.
147ee8648bdSDimitry Andric       SmallVector<MachineInstr*, 4> Instrs;
148044eb2f6SDimitry Andric 
149ee8648bdSDimitry Andric       /// Index in Instrs of the instruction being latest in the schedule.
150ee8648bdSDimitry Andric       unsigned LatestMIIdx;
151044eb2f6SDimitry Andric 
152ee8648bdSDimitry Andric       /// Index in Instrs of the instruction being earliest in the schedule.
153ee8648bdSDimitry Andric       unsigned EarliestMIIdx;
154044eb2f6SDimitry Andric 
155ee8648bdSDimitry Andric       /// Index into the basic block where the merged instruction will be
156ee8648bdSDimitry Andric       /// inserted. (See MemOpQueueEntry.Position)
157ee8648bdSDimitry Andric       unsigned InsertPos;
158044eb2f6SDimitry Andric 
159ee8648bdSDimitry Andric       /// Whether the instructions can be merged into a ldm/stm instruction.
160ee8648bdSDimitry Andric       bool CanMergeToLSMulti;
161044eb2f6SDimitry Andric 
162ee8648bdSDimitry Andric       /// Whether the instructions can be merged into a ldrd/strd instruction.
163ee8648bdSDimitry Andric       bool CanMergeToLSDouble;
164ee8648bdSDimitry Andric     };
165ee8648bdSDimitry Andric     SpecificBumpPtrAllocator<MergeCandidate> Allocator;
166ee8648bdSDimitry Andric     SmallVector<const MergeCandidate*,4> Candidates;
167dd58ef01SDimitry Andric     SmallVector<MachineInstr*,4> MergeBaseCandidates;
168ee8648bdSDimitry Andric 
169ee8648bdSDimitry Andric     void moveLiveRegsBefore(const MachineBasicBlock &MBB,
170ee8648bdSDimitry Andric                             MachineBasicBlock::const_iterator Before);
171ee8648bdSDimitry Andric     unsigned findFreeReg(const TargetRegisterClass &RegClass);
1725ca98fd9SDimitry Andric     void UpdateBaseRegUses(MachineBasicBlock &MBB,
17301095a5dSDimitry Andric                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
17401095a5dSDimitry Andric                            unsigned Base, unsigned WordOffset,
1755ca98fd9SDimitry Andric                            ARMCC::CondCodes Pred, unsigned PredReg);
17601095a5dSDimitry Andric     MachineInstr *CreateLoadStoreMulti(
17701095a5dSDimitry Andric         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
17801095a5dSDimitry Andric         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
17901095a5dSDimitry Andric         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
180e6d15924SDimitry Andric         ArrayRef<std::pair<unsigned, bool>> Regs,
181e6d15924SDimitry Andric         ArrayRef<MachineInstr*> Instrs);
18201095a5dSDimitry Andric     MachineInstr *CreateLoadStoreDouble(
18301095a5dSDimitry Andric         MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
18401095a5dSDimitry Andric         int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
18501095a5dSDimitry Andric         ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
186e6d15924SDimitry Andric         ArrayRef<std::pair<unsigned, bool>> Regs,
187e6d15924SDimitry Andric         ArrayRef<MachineInstr*> Instrs) const;
188ee8648bdSDimitry Andric     void FormCandidates(const MemOpQueue &MemOps);
189ee8648bdSDimitry Andric     MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
190b2f21fb0SEd Schouten     bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
191b2f21fb0SEd Schouten                              MachineBasicBlock::iterator &MBBI);
192ee8648bdSDimitry Andric     bool MergeBaseUpdateLoadStore(MachineInstr *MI);
193ee8648bdSDimitry Andric     bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
194dd58ef01SDimitry Andric     bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
195009b1c42SEd Schouten     bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
196009b1c42SEd Schouten     bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
197dd58ef01SDimitry Andric     bool CombineMovBx(MachineBasicBlock &MBB);
198009b1c42SEd Schouten   };
199044eb2f6SDimitry Andric 
200044eb2f6SDimitry Andric } // end anonymous namespace
201044eb2f6SDimitry Andric 
202009b1c42SEd Schouten char ARMLoadStoreOpt::ID = 0;
203009b1c42SEd Schouten 
20401095a5dSDimitry Andric INITIALIZE_PASS(ARMLoadStoreOpt, "arm-ldst-opt", ARM_LOAD_STORE_OPT_NAME, false,
20501095a5dSDimitry Andric                 false)
206dd58ef01SDimitry Andric 
definesCPSR(const MachineInstr & MI)20701095a5dSDimitry Andric static bool definesCPSR(const MachineInstr &MI) {
20801095a5dSDimitry Andric   for (const auto &MO : MI.operands()) {
20967c32a98SDimitry Andric     if (!MO.isReg())
21067c32a98SDimitry Andric       continue;
21167c32a98SDimitry Andric     if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
21267c32a98SDimitry Andric       // If the instruction has live CPSR def, then it's not safe to fold it
21367c32a98SDimitry Andric       // into load / store.
21467c32a98SDimitry Andric       return true;
21567c32a98SDimitry Andric   }
21667c32a98SDimitry Andric 
21767c32a98SDimitry Andric   return false;
21867c32a98SDimitry Andric }
21967c32a98SDimitry Andric 
getMemoryOpOffset(const MachineInstr & MI)22001095a5dSDimitry Andric static int getMemoryOpOffset(const MachineInstr &MI) {
22101095a5dSDimitry Andric   unsigned Opcode = MI.getOpcode();
22267c32a98SDimitry Andric   bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
22301095a5dSDimitry Andric   unsigned NumOperands = MI.getDesc().getNumOperands();
22401095a5dSDimitry Andric   unsigned OffField = MI.getOperand(NumOperands - 3).getImm();
22567c32a98SDimitry Andric 
22667c32a98SDimitry Andric   if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
22767c32a98SDimitry Andric       Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
22867c32a98SDimitry Andric       Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
22967c32a98SDimitry Andric       Opcode == ARM::LDRi12   || Opcode == ARM::STRi12)
23067c32a98SDimitry Andric     return OffField;
23167c32a98SDimitry Andric 
23267c32a98SDimitry Andric   // Thumb1 immediate offsets are scaled by 4
2335a5ac124SDimitry Andric   if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
2345a5ac124SDimitry Andric       Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
23567c32a98SDimitry Andric     return OffField * 4;
23667c32a98SDimitry Andric 
23767c32a98SDimitry Andric   int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
23867c32a98SDimitry Andric     : ARM_AM::getAM5Offset(OffField) * 4;
23967c32a98SDimitry Andric   ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
24067c32a98SDimitry Andric     : ARM_AM::getAM5Op(OffField);
24167c32a98SDimitry Andric 
24267c32a98SDimitry Andric   if (Op == ARM_AM::sub)
24367c32a98SDimitry Andric     return -Offset;
24467c32a98SDimitry Andric 
24567c32a98SDimitry Andric   return Offset;
24667c32a98SDimitry Andric }
24767c32a98SDimitry Andric 
getLoadStoreBaseOp(const MachineInstr & MI)248ee8648bdSDimitry Andric static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
249ee8648bdSDimitry Andric   return MI.getOperand(1);
250ee8648bdSDimitry Andric }
251ee8648bdSDimitry Andric 
getLoadStoreRegOp(const MachineInstr & MI)252ee8648bdSDimitry Andric static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
253ee8648bdSDimitry Andric   return MI.getOperand(0);
254ee8648bdSDimitry Andric }
255ee8648bdSDimitry Andric 
getLoadStoreMultipleOpcode(unsigned Opcode,ARM_AM::AMSubMode Mode)2565a5ac124SDimitry Andric static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
257009b1c42SEd Schouten   switch (Opcode) {
258cf099d11SDimitry Andric   default: llvm_unreachable("Unhandled opcode!");
259cf099d11SDimitry Andric   case ARM::LDRi12:
26066e41e3cSRoman Divacky     ++NumLDMGened;
261cf099d11SDimitry Andric     switch (Mode) {
262cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
263cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::LDMIA;
264cf099d11SDimitry Andric     case ARM_AM::da: return ARM::LDMDA;
265cf099d11SDimitry Andric     case ARM_AM::db: return ARM::LDMDB;
266cf099d11SDimitry Andric     case ARM_AM::ib: return ARM::LDMIB;
267cf099d11SDimitry Andric     }
268cf099d11SDimitry Andric   case ARM::STRi12:
26966e41e3cSRoman Divacky     ++NumSTMGened;
270cf099d11SDimitry Andric     switch (Mode) {
271cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
272cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::STMIA;
273cf099d11SDimitry Andric     case ARM_AM::da: return ARM::STMDA;
274cf099d11SDimitry Andric     case ARM_AM::db: return ARM::STMDB;
275cf099d11SDimitry Andric     case ARM_AM::ib: return ARM::STMIB;
276cf099d11SDimitry Andric     }
2775ca98fd9SDimitry Andric   case ARM::tLDRi:
2785a5ac124SDimitry Andric   case ARM::tLDRspi:
2795ca98fd9SDimitry Andric     // tLDMIA is writeback-only - unless the base register is in the input
2805ca98fd9SDimitry Andric     // reglist.
2815ca98fd9SDimitry Andric     ++NumLDMGened;
2825ca98fd9SDimitry Andric     switch (Mode) {
2835ca98fd9SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
2845ca98fd9SDimitry Andric     case ARM_AM::ia: return ARM::tLDMIA;
2855ca98fd9SDimitry Andric     }
2865ca98fd9SDimitry Andric   case ARM::tSTRi:
2875a5ac124SDimitry Andric   case ARM::tSTRspi:
2885ca98fd9SDimitry Andric     // There is no non-writeback tSTMIA either.
2895ca98fd9SDimitry Andric     ++NumSTMGened;
2905ca98fd9SDimitry Andric     switch (Mode) {
2915ca98fd9SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
2925ca98fd9SDimitry Andric     case ARM_AM::ia: return ARM::tSTMIA_UPD;
2935ca98fd9SDimitry Andric     }
29459850d08SRoman Divacky   case ARM::t2LDRi8:
29559850d08SRoman Divacky   case ARM::t2LDRi12:
29666e41e3cSRoman Divacky     ++NumLDMGened;
297cf099d11SDimitry Andric     switch (Mode) {
298cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
299cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::t2LDMIA;
300cf099d11SDimitry Andric     case ARM_AM::db: return ARM::t2LDMDB;
301cf099d11SDimitry Andric     }
30259850d08SRoman Divacky   case ARM::t2STRi8:
30359850d08SRoman Divacky   case ARM::t2STRi12:
30466e41e3cSRoman Divacky     ++NumSTMGened;
305cf099d11SDimitry Andric     switch (Mode) {
306cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
307cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::t2STMIA;
308cf099d11SDimitry Andric     case ARM_AM::db: return ARM::t2STMDB;
309cf099d11SDimitry Andric     }
310907da171SRoman Divacky   case ARM::VLDRS:
31166e41e3cSRoman Divacky     ++NumVLDMGened;
312cf099d11SDimitry Andric     switch (Mode) {
313cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
314cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VLDMSIA;
3156b943ff3SDimitry Andric     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
316cf099d11SDimitry Andric     }
317907da171SRoman Divacky   case ARM::VSTRS:
31866e41e3cSRoman Divacky     ++NumVSTMGened;
319cf099d11SDimitry Andric     switch (Mode) {
320cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
321cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VSTMSIA;
3226b943ff3SDimitry Andric     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
323cf099d11SDimitry Andric     }
324907da171SRoman Divacky   case ARM::VLDRD:
32566e41e3cSRoman Divacky     ++NumVLDMGened;
326cf099d11SDimitry Andric     switch (Mode) {
327cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
328cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VLDMDIA;
3296b943ff3SDimitry Andric     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
330cf099d11SDimitry Andric     }
331907da171SRoman Divacky   case ARM::VSTRD:
33266e41e3cSRoman Divacky     ++NumVSTMGened;
333cf099d11SDimitry Andric     switch (Mode) {
334cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
335cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VSTMDIA;
3366b943ff3SDimitry Andric     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
337009b1c42SEd Schouten     }
338cf099d11SDimitry Andric   }
339009b1c42SEd Schouten }
340009b1c42SEd Schouten 
getLoadStoreMultipleSubMode(unsigned Opcode)34185d8b2bbSDimitry Andric static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
342cf099d11SDimitry Andric   switch (Opcode) {
343cf099d11SDimitry Andric   default: llvm_unreachable("Unhandled opcode!");
344cf099d11SDimitry Andric   case ARM::LDMIA_RET:
345cf099d11SDimitry Andric   case ARM::LDMIA:
346cf099d11SDimitry Andric   case ARM::LDMIA_UPD:
347cf099d11SDimitry Andric   case ARM::STMIA:
348cf099d11SDimitry Andric   case ARM::STMIA_UPD:
3495ca98fd9SDimitry Andric   case ARM::tLDMIA:
3505ca98fd9SDimitry Andric   case ARM::tLDMIA_UPD:
3515ca98fd9SDimitry Andric   case ARM::tSTMIA_UPD:
352cf099d11SDimitry Andric   case ARM::t2LDMIA_RET:
353cf099d11SDimitry Andric   case ARM::t2LDMIA:
354cf099d11SDimitry Andric   case ARM::t2LDMIA_UPD:
355cf099d11SDimitry Andric   case ARM::t2STMIA:
356cf099d11SDimitry Andric   case ARM::t2STMIA_UPD:
357cf099d11SDimitry Andric   case ARM::VLDMSIA:
358cf099d11SDimitry Andric   case ARM::VLDMSIA_UPD:
359cf099d11SDimitry Andric   case ARM::VSTMSIA:
360cf099d11SDimitry Andric   case ARM::VSTMSIA_UPD:
361cf099d11SDimitry Andric   case ARM::VLDMDIA:
362cf099d11SDimitry Andric   case ARM::VLDMDIA_UPD:
363cf099d11SDimitry Andric   case ARM::VSTMDIA:
364cf099d11SDimitry Andric   case ARM::VSTMDIA_UPD:
365cf099d11SDimitry Andric     return ARM_AM::ia;
366cf099d11SDimitry Andric 
367cf099d11SDimitry Andric   case ARM::LDMDA:
368cf099d11SDimitry Andric   case ARM::LDMDA_UPD:
369cf099d11SDimitry Andric   case ARM::STMDA:
370cf099d11SDimitry Andric   case ARM::STMDA_UPD:
371cf099d11SDimitry Andric     return ARM_AM::da;
372cf099d11SDimitry Andric 
373cf099d11SDimitry Andric   case ARM::LDMDB:
374cf099d11SDimitry Andric   case ARM::LDMDB_UPD:
375cf099d11SDimitry Andric   case ARM::STMDB:
376cf099d11SDimitry Andric   case ARM::STMDB_UPD:
377cf099d11SDimitry Andric   case ARM::t2LDMDB:
378cf099d11SDimitry Andric   case ARM::t2LDMDB_UPD:
379cf099d11SDimitry Andric   case ARM::t2STMDB:
380cf099d11SDimitry Andric   case ARM::t2STMDB_UPD:
381cf099d11SDimitry Andric   case ARM::VLDMSDB_UPD:
382cf099d11SDimitry Andric   case ARM::VSTMSDB_UPD:
383cf099d11SDimitry Andric   case ARM::VLDMDDB_UPD:
384cf099d11SDimitry Andric   case ARM::VSTMDDB_UPD:
385cf099d11SDimitry Andric     return ARM_AM::db;
386cf099d11SDimitry Andric 
387cf099d11SDimitry Andric   case ARM::LDMIB:
388cf099d11SDimitry Andric   case ARM::LDMIB_UPD:
389cf099d11SDimitry Andric   case ARM::STMIB:
390cf099d11SDimitry Andric   case ARM::STMIB_UPD:
391cf099d11SDimitry Andric     return ARM_AM::ib;
392cf099d11SDimitry Andric   }
393cf099d11SDimitry Andric }
394cf099d11SDimitry Andric 
isT1i32Load(unsigned Opc)3955ca98fd9SDimitry Andric static bool isT1i32Load(unsigned Opc) {
3965a5ac124SDimitry Andric   return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
3975ca98fd9SDimitry Andric }
3985ca98fd9SDimitry Andric 
isT2i32Load(unsigned Opc)39959850d08SRoman Divacky static bool isT2i32Load(unsigned Opc) {
40059850d08SRoman Divacky   return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
40159850d08SRoman Divacky }
40259850d08SRoman Divacky 
isi32Load(unsigned Opc)40359850d08SRoman Divacky static bool isi32Load(unsigned Opc) {
4045ca98fd9SDimitry Andric   return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
4055ca98fd9SDimitry Andric }
4065ca98fd9SDimitry Andric 
isT1i32Store(unsigned Opc)4075ca98fd9SDimitry Andric static bool isT1i32Store(unsigned Opc) {
4085a5ac124SDimitry Andric   return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
40959850d08SRoman Divacky }
41059850d08SRoman Divacky 
isT2i32Store(unsigned Opc)41159850d08SRoman Divacky static bool isT2i32Store(unsigned Opc) {
41259850d08SRoman Divacky   return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
41359850d08SRoman Divacky }
41459850d08SRoman Divacky 
isi32Store(unsigned Opc)41559850d08SRoman Divacky static bool isi32Store(unsigned Opc) {
4165ca98fd9SDimitry Andric   return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
4175ca98fd9SDimitry Andric }
4185ca98fd9SDimitry Andric 
isLoadSingle(unsigned Opc)419ee8648bdSDimitry Andric static bool isLoadSingle(unsigned Opc) {
420ee8648bdSDimitry Andric   return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
421ee8648bdSDimitry Andric }
422ee8648bdSDimitry Andric 
getImmScale(unsigned Opc)4235ca98fd9SDimitry Andric static unsigned getImmScale(unsigned Opc) {
4245ca98fd9SDimitry Andric   switch (Opc) {
4255ca98fd9SDimitry Andric   default: llvm_unreachable("Unhandled opcode!");
4265ca98fd9SDimitry Andric   case ARM::tLDRi:
4275ca98fd9SDimitry Andric   case ARM::tSTRi:
4285a5ac124SDimitry Andric   case ARM::tLDRspi:
4295a5ac124SDimitry Andric   case ARM::tSTRspi:
4305ca98fd9SDimitry Andric     return 1;
4315ca98fd9SDimitry Andric   case ARM::tLDRHi:
4325ca98fd9SDimitry Andric   case ARM::tSTRHi:
4335ca98fd9SDimitry Andric     return 2;
4345ca98fd9SDimitry Andric   case ARM::tLDRBi:
4355ca98fd9SDimitry Andric   case ARM::tSTRBi:
4365ca98fd9SDimitry Andric     return 4;
4375ca98fd9SDimitry Andric   }
4385ca98fd9SDimitry Andric }
4395ca98fd9SDimitry Andric 
getLSMultipleTransferSize(const MachineInstr * MI)440ee8648bdSDimitry Andric static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
441009b1c42SEd Schouten   switch (MI->getOpcode()) {
442009b1c42SEd Schouten   default: return 0;
443cf099d11SDimitry Andric   case ARM::LDRi12:
444cf099d11SDimitry Andric   case ARM::STRi12:
4455ca98fd9SDimitry Andric   case ARM::tLDRi:
4465ca98fd9SDimitry Andric   case ARM::tSTRi:
4475a5ac124SDimitry Andric   case ARM::tLDRspi:
4485a5ac124SDimitry Andric   case ARM::tSTRspi:
44959850d08SRoman Divacky   case ARM::t2LDRi8:
45059850d08SRoman Divacky   case ARM::t2LDRi12:
45159850d08SRoman Divacky   case ARM::t2STRi8:
45259850d08SRoman Divacky   case ARM::t2STRi12:
453907da171SRoman Divacky   case ARM::VLDRS:
454907da171SRoman Divacky   case ARM::VSTRS:
455009b1c42SEd Schouten     return 4;
456907da171SRoman Divacky   case ARM::VLDRD:
457907da171SRoman Divacky   case ARM::VSTRD:
458009b1c42SEd Schouten     return 8;
459cf099d11SDimitry Andric   case ARM::LDMIA:
460cf099d11SDimitry Andric   case ARM::LDMDA:
461cf099d11SDimitry Andric   case ARM::LDMDB:
462cf099d11SDimitry Andric   case ARM::LDMIB:
463cf099d11SDimitry Andric   case ARM::STMIA:
464cf099d11SDimitry Andric   case ARM::STMDA:
465cf099d11SDimitry Andric   case ARM::STMDB:
466cf099d11SDimitry Andric   case ARM::STMIB:
4675ca98fd9SDimitry Andric   case ARM::tLDMIA:
4685ca98fd9SDimitry Andric   case ARM::tLDMIA_UPD:
4695ca98fd9SDimitry Andric   case ARM::tSTMIA_UPD:
470cf099d11SDimitry Andric   case ARM::t2LDMIA:
471cf099d11SDimitry Andric   case ARM::t2LDMDB:
472cf099d11SDimitry Andric   case ARM::t2STMIA:
473cf099d11SDimitry Andric   case ARM::t2STMDB:
474cf099d11SDimitry Andric   case ARM::VLDMSIA:
475cf099d11SDimitry Andric   case ARM::VSTMSIA:
476cf099d11SDimitry Andric     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
477cf099d11SDimitry Andric   case ARM::VLDMDIA:
478cf099d11SDimitry Andric   case ARM::VSTMDIA:
479cf099d11SDimitry Andric     return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
480009b1c42SEd Schouten   }
481009b1c42SEd Schouten }
482009b1c42SEd Schouten 
483ee8648bdSDimitry Andric /// Update future uses of the base register with the offset introduced
484ee8648bdSDimitry Andric /// due to writeback. This function only works on Thumb1.
UpdateBaseRegUses(MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,unsigned Base,unsigned WordOffset,ARMCC::CondCodes Pred,unsigned PredReg)48501095a5dSDimitry Andric void ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
486ee8648bdSDimitry Andric                                         MachineBasicBlock::iterator MBBI,
48701095a5dSDimitry Andric                                         const DebugLoc &DL, unsigned Base,
488ee8648bdSDimitry Andric                                         unsigned WordOffset,
48901095a5dSDimitry Andric                                         ARMCC::CondCodes Pred,
49001095a5dSDimitry Andric                                         unsigned PredReg) {
491ee8648bdSDimitry Andric   assert(isThumb1 && "Can only update base register uses for Thumb1!");
492ee8648bdSDimitry Andric   // Start updating any instructions with immediate offsets. Insert a SUB before
493ee8648bdSDimitry Andric   // the first non-updateable instruction (if any).
494ee8648bdSDimitry Andric   for (; MBBI != MBB.end(); ++MBBI) {
495ee8648bdSDimitry Andric     bool InsertSub = false;
496ee8648bdSDimitry Andric     unsigned Opc = MBBI->getOpcode();
497ee8648bdSDimitry Andric 
498ac9a064cSDimitry Andric     if (MBBI->readsRegister(Base, /*TRI=*/nullptr)) {
499ee8648bdSDimitry Andric       int Offset;
500ee8648bdSDimitry Andric       bool IsLoad =
501ee8648bdSDimitry Andric         Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
502ee8648bdSDimitry Andric       bool IsStore =
503ee8648bdSDimitry Andric         Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
504ee8648bdSDimitry Andric 
505ee8648bdSDimitry Andric       if (IsLoad || IsStore) {
506ee8648bdSDimitry Andric         // Loads and stores with immediate offsets can be updated, but only if
507ee8648bdSDimitry Andric         // the new offset isn't negative.
508ee8648bdSDimitry Andric         // The MachineOperand containing the offset immediate is the last one
509ee8648bdSDimitry Andric         // before predicates.
510ee8648bdSDimitry Andric         MachineOperand &MO =
511ee8648bdSDimitry Andric           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
512ee8648bdSDimitry Andric         // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
513ee8648bdSDimitry Andric         Offset = MO.getImm() - WordOffset * getImmScale(Opc);
514ee8648bdSDimitry Andric 
515ee8648bdSDimitry Andric         // If storing the base register, it needs to be reset first.
5161d5ae102SDimitry Andric         Register InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
517ee8648bdSDimitry Andric 
518ee8648bdSDimitry Andric         if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
519ee8648bdSDimitry Andric           MO.setImm(Offset);
520ee8648bdSDimitry Andric         else
521ee8648bdSDimitry Andric           InsertSub = true;
522ee8648bdSDimitry Andric       } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
52301095a5dSDimitry Andric                  !definesCPSR(*MBBI)) {
524ee8648bdSDimitry Andric         // SUBS/ADDS using this register, with a dead def of the CPSR.
525ee8648bdSDimitry Andric         // Merge it with the update; if the merged offset is too large,
526ee8648bdSDimitry Andric         // insert a new sub instead.
527ee8648bdSDimitry Andric         MachineOperand &MO =
528ee8648bdSDimitry Andric           MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
529ee8648bdSDimitry Andric         Offset = (Opc == ARM::tSUBi8) ?
530ee8648bdSDimitry Andric           MO.getImm() + WordOffset * 4 :
531ee8648bdSDimitry Andric           MO.getImm() - WordOffset * 4 ;
532ee8648bdSDimitry Andric         if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
533ee8648bdSDimitry Andric           // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
534ee8648bdSDimitry Andric           // Offset == 0.
535ee8648bdSDimitry Andric           MO.setImm(Offset);
536ee8648bdSDimitry Andric           // The base register has now been reset, so exit early.
537ee8648bdSDimitry Andric           return;
538ee8648bdSDimitry Andric         } else {
539ee8648bdSDimitry Andric           InsertSub = true;
540ee8648bdSDimitry Andric         }
541ee8648bdSDimitry Andric       } else {
542ee8648bdSDimitry Andric         // Can't update the instruction.
543ee8648bdSDimitry Andric         InsertSub = true;
544ee8648bdSDimitry Andric       }
54501095a5dSDimitry Andric     } else if (definesCPSR(*MBBI) || MBBI->isCall() || MBBI->isBranch()) {
546ee8648bdSDimitry Andric       // Since SUBS sets the condition flags, we can't place the base reset
547ee8648bdSDimitry Andric       // after an instruction that has a live CPSR def.
548ee8648bdSDimitry Andric       // The base register might also contain an argument for a function call.
549ee8648bdSDimitry Andric       InsertSub = true;
550ee8648bdSDimitry Andric     }
551ee8648bdSDimitry Andric 
552ee8648bdSDimitry Andric     if (InsertSub) {
553ee8648bdSDimitry Andric       // An instruction above couldn't be updated, so insert a sub.
55471d5a254SDimitry Andric       BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
55571d5a254SDimitry Andric           .add(t1CondCodeOp(true))
55671d5a254SDimitry Andric           .addReg(Base)
55771d5a254SDimitry Andric           .addImm(WordOffset * 4)
55871d5a254SDimitry Andric           .addImm(Pred)
55971d5a254SDimitry Andric           .addReg(PredReg);
560ee8648bdSDimitry Andric       return;
561ee8648bdSDimitry Andric     }
562ee8648bdSDimitry Andric 
563ac9a064cSDimitry Andric     if (MBBI->killsRegister(Base, /*TRI=*/nullptr) ||
564ac9a064cSDimitry Andric         MBBI->definesRegister(Base, /*TRI=*/nullptr))
565ee8648bdSDimitry Andric       // Register got killed. Stop updating.
566ee8648bdSDimitry Andric       return;
567ee8648bdSDimitry Andric   }
568ee8648bdSDimitry Andric 
569ee8648bdSDimitry Andric   // End of block was reached.
570c0981da4SDimitry Andric   if (!MBB.succ_empty()) {
571ee8648bdSDimitry Andric     // FIXME: Because of a bug, live registers are sometimes missing from
572ee8648bdSDimitry Andric     // the successor blocks' live-in sets. This means we can't trust that
573ee8648bdSDimitry Andric     // information and *always* have to reset at the end of a block.
574ee8648bdSDimitry Andric     // See PR21029.
575ee8648bdSDimitry Andric     if (MBBI != MBB.end()) --MBBI;
57671d5a254SDimitry Andric     BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base)
57771d5a254SDimitry Andric         .add(t1CondCodeOp(true))
57871d5a254SDimitry Andric         .addReg(Base)
57971d5a254SDimitry Andric         .addImm(WordOffset * 4)
58071d5a254SDimitry Andric         .addImm(Pred)
58171d5a254SDimitry Andric         .addReg(PredReg);
582ee8648bdSDimitry Andric   }
583ee8648bdSDimitry Andric }
584ee8648bdSDimitry Andric 
585ee8648bdSDimitry Andric /// Return the first register of class \p RegClass that is not in \p Regs.
findFreeReg(const TargetRegisterClass & RegClass)586ee8648bdSDimitry Andric unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
587ee8648bdSDimitry Andric   if (!RegClassInfoValid) {
588ee8648bdSDimitry Andric     RegClassInfo.runOnMachineFunction(*MF);
589ee8648bdSDimitry Andric     RegClassInfoValid = true;
590ee8648bdSDimitry Andric   }
591ee8648bdSDimitry Andric 
592ee8648bdSDimitry Andric   for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
593ac9a064cSDimitry Andric     if (LiveRegs.available(Reg) && !MF->getRegInfo().isReserved(Reg))
594ee8648bdSDimitry Andric       return Reg;
595ee8648bdSDimitry Andric   return 0;
596ee8648bdSDimitry Andric }
597ee8648bdSDimitry Andric 
598ee8648bdSDimitry Andric /// Compute live registers just before instruction \p Before (in normal schedule
599ee8648bdSDimitry Andric /// direction). Computes backwards so multiple queries in the same block must
600ee8648bdSDimitry Andric /// come in reverse order.
moveLiveRegsBefore(const MachineBasicBlock & MBB,MachineBasicBlock::const_iterator Before)601ee8648bdSDimitry Andric void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
602ee8648bdSDimitry Andric     MachineBasicBlock::const_iterator Before) {
603ee8648bdSDimitry Andric   // Initialize if we never queried in this block.
604ee8648bdSDimitry Andric   if (!LiveRegsValid) {
605b915e9e0SDimitry Andric     LiveRegs.init(*TRI);
60601095a5dSDimitry Andric     LiveRegs.addLiveOuts(MBB);
607ee8648bdSDimitry Andric     LiveRegPos = MBB.end();
608ee8648bdSDimitry Andric     LiveRegsValid = true;
609ee8648bdSDimitry Andric   }
610ee8648bdSDimitry Andric   // Move backward just before the "Before" position.
611ee8648bdSDimitry Andric   while (LiveRegPos != Before) {
612ee8648bdSDimitry Andric     --LiveRegPos;
613ee8648bdSDimitry Andric     LiveRegs.stepBackward(*LiveRegPos);
614ee8648bdSDimitry Andric   }
615ee8648bdSDimitry Andric }
616ee8648bdSDimitry Andric 
ContainsReg(const ArrayRef<std::pair<unsigned,bool>> & Regs,unsigned Reg)617ee8648bdSDimitry Andric static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
618ee8648bdSDimitry Andric                         unsigned Reg) {
619ee8648bdSDimitry Andric   for (const std::pair<unsigned, bool> &R : Regs)
620ee8648bdSDimitry Andric     if (R.first == Reg)
621ee8648bdSDimitry Andric       return true;
622ee8648bdSDimitry Andric   return false;
623ee8648bdSDimitry Andric }
624ee8648bdSDimitry Andric 
625ee8648bdSDimitry Andric /// Create and insert a LDM or STM with Base as base register and registers in
626ee8648bdSDimitry Andric /// Regs as the register operands that would be loaded / stored.  It returns
627ee8648bdSDimitry Andric /// true if the transformation is done.
CreateLoadStoreMulti(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,int Offset,unsigned Base,bool BaseKill,unsigned Opcode,ARMCC::CondCodes Pred,unsigned PredReg,const DebugLoc & DL,ArrayRef<std::pair<unsigned,bool>> Regs,ArrayRef<MachineInstr * > Instrs)62801095a5dSDimitry Andric MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(
62901095a5dSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
63001095a5dSDimitry Andric     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
63101095a5dSDimitry Andric     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
632e6d15924SDimitry Andric     ArrayRef<std::pair<unsigned, bool>> Regs,
633e6d15924SDimitry Andric     ArrayRef<MachineInstr*> Instrs) {
634ee8648bdSDimitry Andric   unsigned NumRegs = Regs.size();
635ee8648bdSDimitry Andric   assert(NumRegs > 1);
636ee8648bdSDimitry Andric 
637ee8648bdSDimitry Andric   // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
638ee8648bdSDimitry Andric   // Compute liveness information for that register to make the decision.
639ee8648bdSDimitry Andric   bool SafeToClobberCPSR = !isThumb1 ||
640ee8648bdSDimitry Andric     (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
641ee8648bdSDimitry Andric      MachineBasicBlock::LQR_Dead);
642ee8648bdSDimitry Andric 
643ee8648bdSDimitry Andric   bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
644ee8648bdSDimitry Andric 
645ee8648bdSDimitry Andric   // Exception: If the base register is in the input reglist, Thumb1 LDM is
646ee8648bdSDimitry Andric   // non-writeback.
647ee8648bdSDimitry Andric   // It's also not possible to merge an STR of the base register in Thumb1.
64871d5a254SDimitry Andric   if (isThumb1 && ContainsReg(Regs, Base)) {
649ee8648bdSDimitry Andric     assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
65071d5a254SDimitry Andric     if (Opcode == ARM::tLDRi)
651ee8648bdSDimitry Andric       Writeback = false;
65271d5a254SDimitry Andric     else if (Opcode == ARM::tSTRi)
653ee8648bdSDimitry Andric       return nullptr;
654ee8648bdSDimitry Andric   }
655ee8648bdSDimitry Andric 
656ee8648bdSDimitry Andric   ARM_AM::AMSubMode Mode = ARM_AM::ia;
657ee8648bdSDimitry Andric   // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
658ee8648bdSDimitry Andric   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
659ee8648bdSDimitry Andric   bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
660ee8648bdSDimitry Andric 
661ee8648bdSDimitry Andric   if (Offset == 4 && haveIBAndDA) {
662ee8648bdSDimitry Andric     Mode = ARM_AM::ib;
663ee8648bdSDimitry Andric   } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
664ee8648bdSDimitry Andric     Mode = ARM_AM::da;
665ee8648bdSDimitry Andric   } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
666ee8648bdSDimitry Andric     // VLDM/VSTM do not support DB mode without also updating the base reg.
667ee8648bdSDimitry Andric     Mode = ARM_AM::db;
668ee8648bdSDimitry Andric   } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
669ee8648bdSDimitry Andric     // Check if this is a supported opcode before inserting instructions to
670ee8648bdSDimitry Andric     // calculate a new base register.
671ee8648bdSDimitry Andric     if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
672ee8648bdSDimitry Andric 
673ee8648bdSDimitry Andric     // If starting offset isn't zero, insert a MI to materialize a new base.
674ee8648bdSDimitry Andric     // But only do so if it is cost effective, i.e. merging more than two
675ee8648bdSDimitry Andric     // loads / stores.
676ee8648bdSDimitry Andric     if (NumRegs <= 2)
677ee8648bdSDimitry Andric       return nullptr;
678ee8648bdSDimitry Andric 
679ee8648bdSDimitry Andric     // On Thumb1, it's not worth materializing a new base register without
680ee8648bdSDimitry Andric     // clobbering the CPSR (i.e. not using ADDS/SUBS).
681ee8648bdSDimitry Andric     if (!SafeToClobberCPSR)
682ee8648bdSDimitry Andric       return nullptr;
683ee8648bdSDimitry Andric 
684ee8648bdSDimitry Andric     unsigned NewBase;
685ee8648bdSDimitry Andric     if (isi32Load(Opcode)) {
686dd58ef01SDimitry Andric       // If it is a load, then just use one of the destination registers
687dd58ef01SDimitry Andric       // as the new base. Will no longer be writeback in Thumb1.
688ee8648bdSDimitry Andric       NewBase = Regs[NumRegs-1].first;
689dd58ef01SDimitry Andric       Writeback = false;
690ee8648bdSDimitry Andric     } else {
691ee8648bdSDimitry Andric       // Find a free register that we can use as scratch register.
692ee8648bdSDimitry Andric       moveLiveRegsBefore(MBB, InsertBefore);
693ee8648bdSDimitry Andric       // The merged instruction does not exist yet but will use several Regs if
694ee8648bdSDimitry Andric       // it is a Store.
695ee8648bdSDimitry Andric       if (!isLoadSingle(Opcode))
696ee8648bdSDimitry Andric         for (const std::pair<unsigned, bool> &R : Regs)
697ee8648bdSDimitry Andric           LiveRegs.addReg(R.first);
698ee8648bdSDimitry Andric 
699ee8648bdSDimitry Andric       NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
700ee8648bdSDimitry Andric       if (NewBase == 0)
701ee8648bdSDimitry Andric         return nullptr;
702ee8648bdSDimitry Andric     }
703ee8648bdSDimitry Andric 
704706b4fc4SDimitry Andric     int BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2ADDspImm
705706b4fc4SDimitry Andric                                                           : ARM::t2ADDri)
706706b4fc4SDimitry Andric                            : (isThumb1 && Base == ARM::SP)
707706b4fc4SDimitry Andric                                  ? ARM::tADDrSPi
708706b4fc4SDimitry Andric                                  : (isThumb1 && Offset < 8)
709706b4fc4SDimitry Andric                                        ? ARM::tADDi3
710706b4fc4SDimitry Andric                                        : isThumb1 ? ARM::tADDi8 : ARM::ADDri;
711ee8648bdSDimitry Andric 
712ee8648bdSDimitry Andric     if (Offset < 0) {
713706b4fc4SDimitry Andric       // FIXME: There are no Thumb1 load/store instructions with negative
714706b4fc4SDimitry Andric       // offsets. So the Base != ARM::SP might be unnecessary.
715ee8648bdSDimitry Andric       Offset = -Offset;
716706b4fc4SDimitry Andric       BaseOpc = isThumb2 ? (BaseKill && Base == ARM::SP ? ARM::t2SUBspImm
717706b4fc4SDimitry Andric                                                         : ARM::t2SUBri)
718706b4fc4SDimitry Andric                          : (isThumb1 && Offset < 8 && Base != ARM::SP)
719706b4fc4SDimitry Andric                                ? ARM::tSUBi3
720706b4fc4SDimitry Andric                                : isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
721ee8648bdSDimitry Andric     }
722ee8648bdSDimitry Andric 
723ee8648bdSDimitry Andric     if (!TL->isLegalAddImmediate(Offset))
724ee8648bdSDimitry Andric       // FIXME: Try add with register operand?
725ee8648bdSDimitry Andric       return nullptr; // Probably not worth it then.
726ee8648bdSDimitry Andric 
727ee8648bdSDimitry Andric     // We can only append a kill flag to the add/sub input if the value is not
728ee8648bdSDimitry Andric     // used in the register list of the stm as well.
729ee8648bdSDimitry Andric     bool KillOldBase = BaseKill &&
730ee8648bdSDimitry Andric       (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
731ee8648bdSDimitry Andric 
732ee8648bdSDimitry Andric     if (isThumb1) {
733ee8648bdSDimitry Andric       // Thumb1: depending on immediate size, use either
734ee8648bdSDimitry Andric       //   ADDS NewBase, Base, #imm3
735ee8648bdSDimitry Andric       // or
736ee8648bdSDimitry Andric       //   MOV  NewBase, Base
737ee8648bdSDimitry Andric       //   ADDS NewBase, #imm8.
738ee8648bdSDimitry Andric       if (Base != NewBase &&
739ee8648bdSDimitry Andric           (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
740ee8648bdSDimitry Andric         // Need to insert a MOV to the new base first.
741ee8648bdSDimitry Andric         if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
742ee8648bdSDimitry Andric             !STI->hasV6Ops()) {
743ee8648bdSDimitry Andric           // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
744ee8648bdSDimitry Andric           if (Pred != ARMCC::AL)
745ee8648bdSDimitry Andric             return nullptr;
746ee8648bdSDimitry Andric           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
747ee8648bdSDimitry Andric             .addReg(Base, getKillRegState(KillOldBase));
748ee8648bdSDimitry Andric         } else
749ee8648bdSDimitry Andric           BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
750ee8648bdSDimitry Andric               .addReg(Base, getKillRegState(KillOldBase))
75171d5a254SDimitry Andric               .add(predOps(Pred, PredReg));
752ee8648bdSDimitry Andric 
753ee8648bdSDimitry Andric         // The following ADDS/SUBS becomes an update.
754ee8648bdSDimitry Andric         Base = NewBase;
755ee8648bdSDimitry Andric         KillOldBase = true;
756ee8648bdSDimitry Andric       }
757ee8648bdSDimitry Andric       if (BaseOpc == ARM::tADDrSPi) {
758ee8648bdSDimitry Andric         assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
759ee8648bdSDimitry Andric         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
76071d5a254SDimitry Andric             .addReg(Base, getKillRegState(KillOldBase))
76171d5a254SDimitry Andric             .addImm(Offset / 4)
76271d5a254SDimitry Andric             .add(predOps(Pred, PredReg));
763ee8648bdSDimitry Andric       } else
76471d5a254SDimitry Andric         BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
76571d5a254SDimitry Andric             .add(t1CondCodeOp(true))
76671d5a254SDimitry Andric             .addReg(Base, getKillRegState(KillOldBase))
76771d5a254SDimitry Andric             .addImm(Offset)
76871d5a254SDimitry Andric             .add(predOps(Pred, PredReg));
769ee8648bdSDimitry Andric     } else {
770ee8648bdSDimitry Andric       BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
77171d5a254SDimitry Andric           .addReg(Base, getKillRegState(KillOldBase))
77271d5a254SDimitry Andric           .addImm(Offset)
77371d5a254SDimitry Andric           .add(predOps(Pred, PredReg))
77471d5a254SDimitry Andric           .add(condCodeOp());
775ee8648bdSDimitry Andric     }
776ee8648bdSDimitry Andric     Base = NewBase;
777ee8648bdSDimitry Andric     BaseKill = true; // New base is always killed straight away.
778ee8648bdSDimitry Andric   }
779ee8648bdSDimitry Andric 
780ee8648bdSDimitry Andric   bool isDef = isLoadSingle(Opcode);
781ee8648bdSDimitry Andric 
782ee8648bdSDimitry Andric   // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
783ee8648bdSDimitry Andric   // base register writeback.
784ee8648bdSDimitry Andric   Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
785ee8648bdSDimitry Andric   if (!Opcode)
786ee8648bdSDimitry Andric     return nullptr;
787ee8648bdSDimitry Andric 
788ee8648bdSDimitry Andric   // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
789ee8648bdSDimitry Andric   // - There is no writeback (LDM of base register),
790ee8648bdSDimitry Andric   // - the base register is killed by the merged instruction,
791ee8648bdSDimitry Andric   // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
792ee8648bdSDimitry Andric   //   to reset the base register.
793ee8648bdSDimitry Andric   // Otherwise, don't merge.
794ee8648bdSDimitry Andric   // It's safe to return here since the code to materialize a new base register
795ee8648bdSDimitry Andric   // above is also conditional on SafeToClobberCPSR.
796ee8648bdSDimitry Andric   if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
797ee8648bdSDimitry Andric     return nullptr;
798ee8648bdSDimitry Andric 
799ee8648bdSDimitry Andric   MachineInstrBuilder MIB;
800ee8648bdSDimitry Andric 
801ee8648bdSDimitry Andric   if (Writeback) {
802dd58ef01SDimitry Andric     assert(isThumb1 && "expected Writeback only inThumb1");
803dd58ef01SDimitry Andric     if (Opcode == ARM::tLDMIA) {
804dd58ef01SDimitry Andric       assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
805ee8648bdSDimitry Andric       // Update tLDMIA with writeback if necessary.
806ee8648bdSDimitry Andric       Opcode = ARM::tLDMIA_UPD;
807dd58ef01SDimitry Andric     }
808ee8648bdSDimitry Andric 
809ee8648bdSDimitry Andric     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
810ee8648bdSDimitry Andric 
811ee8648bdSDimitry Andric     // Thumb1: we might need to set base writeback when building the MI.
812ee8648bdSDimitry Andric     MIB.addReg(Base, getDefRegState(true))
813ee8648bdSDimitry Andric        .addReg(Base, getKillRegState(BaseKill));
814ee8648bdSDimitry Andric 
815ee8648bdSDimitry Andric     // The base isn't dead after a merged instruction with writeback.
816ee8648bdSDimitry Andric     // Insert a sub instruction after the newly formed instruction to reset.
817ee8648bdSDimitry Andric     if (!BaseKill)
818ee8648bdSDimitry Andric       UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
819ee8648bdSDimitry Andric   } else {
820ee8648bdSDimitry Andric     // No writeback, simply build the MachineInstr.
821ee8648bdSDimitry Andric     MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
822ee8648bdSDimitry Andric     MIB.addReg(Base, getKillRegState(BaseKill));
823ee8648bdSDimitry Andric   }
824ee8648bdSDimitry Andric 
825ee8648bdSDimitry Andric   MIB.addImm(Pred).addReg(PredReg);
826ee8648bdSDimitry Andric 
827ee8648bdSDimitry Andric   for (const std::pair<unsigned, bool> &R : Regs)
828ee8648bdSDimitry Andric     MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
829ee8648bdSDimitry Andric 
830e6d15924SDimitry Andric   MIB.cloneMergedMemRefs(Instrs);
831e6d15924SDimitry Andric 
832ee8648bdSDimitry Andric   return MIB.getInstr();
833ee8648bdSDimitry Andric }
834ee8648bdSDimitry Andric 
CreateLoadStoreDouble(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,int Offset,unsigned Base,bool BaseKill,unsigned Opcode,ARMCC::CondCodes Pred,unsigned PredReg,const DebugLoc & DL,ArrayRef<std::pair<unsigned,bool>> Regs,ArrayRef<MachineInstr * > Instrs) const83501095a5dSDimitry Andric MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(
83601095a5dSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
83701095a5dSDimitry Andric     int Offset, unsigned Base, bool BaseKill, unsigned Opcode,
83801095a5dSDimitry Andric     ARMCC::CondCodes Pred, unsigned PredReg, const DebugLoc &DL,
839e6d15924SDimitry Andric     ArrayRef<std::pair<unsigned, bool>> Regs,
840e6d15924SDimitry Andric     ArrayRef<MachineInstr*> Instrs) const {
841ee8648bdSDimitry Andric   bool IsLoad = isi32Load(Opcode);
842ee8648bdSDimitry Andric   assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
843ee8648bdSDimitry Andric   unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
844ee8648bdSDimitry Andric 
845ee8648bdSDimitry Andric   assert(Regs.size() == 2);
846ee8648bdSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
847ee8648bdSDimitry Andric                                     TII->get(LoadStoreOpcode));
848ee8648bdSDimitry Andric   if (IsLoad) {
849ee8648bdSDimitry Andric     MIB.addReg(Regs[0].first, RegState::Define)
850ee8648bdSDimitry Andric        .addReg(Regs[1].first, RegState::Define);
851ee8648bdSDimitry Andric   } else {
852ee8648bdSDimitry Andric     MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
853ee8648bdSDimitry Andric        .addReg(Regs[1].first, getKillRegState(Regs[1].second));
854ee8648bdSDimitry Andric   }
855ee8648bdSDimitry Andric   MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
856e6d15924SDimitry Andric   MIB.cloneMergedMemRefs(Instrs);
857ee8648bdSDimitry Andric   return MIB.getInstr();
858ee8648bdSDimitry Andric }
859ee8648bdSDimitry Andric 
860ee8648bdSDimitry Andric /// Call MergeOps and update MemOps and merges accordingly on success.
MergeOpsUpdate(const MergeCandidate & Cand)861ee8648bdSDimitry Andric MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
862ee8648bdSDimitry Andric   const MachineInstr *First = Cand.Instrs.front();
863ee8648bdSDimitry Andric   unsigned Opcode = First->getOpcode();
864ee8648bdSDimitry Andric   bool IsLoad = isLoadSingle(Opcode);
865ee8648bdSDimitry Andric   SmallVector<std::pair<unsigned, bool>, 8> Regs;
866ee8648bdSDimitry Andric   SmallVector<unsigned, 4> ImpDefs;
867ee8648bdSDimitry Andric   DenseSet<unsigned> KilledRegs;
868dd58ef01SDimitry Andric   DenseSet<unsigned> UsedRegs;
869ee8648bdSDimitry Andric   // Determine list of registers and list of implicit super-register defs.
870ee8648bdSDimitry Andric   for (const MachineInstr *MI : Cand.Instrs) {
871ee8648bdSDimitry Andric     const MachineOperand &MO = getLoadStoreRegOp(*MI);
8721d5ae102SDimitry Andric     Register Reg = MO.getReg();
873ee8648bdSDimitry Andric     bool IsKill = MO.isKill();
874ee8648bdSDimitry Andric     if (IsKill)
875ee8648bdSDimitry Andric       KilledRegs.insert(Reg);
876ee8648bdSDimitry Andric     Regs.push_back(std::make_pair(Reg, IsKill));
877dd58ef01SDimitry Andric     UsedRegs.insert(Reg);
878ee8648bdSDimitry Andric 
879ee8648bdSDimitry Andric     if (IsLoad) {
880ee8648bdSDimitry Andric       // Collect any implicit defs of super-registers, after merging we can't
881ee8648bdSDimitry Andric       // be sure anymore that we properly preserved these live ranges and must
882ee8648bdSDimitry Andric       // removed these implicit operands.
883ee8648bdSDimitry Andric       for (const MachineOperand &MO : MI->implicit_operands()) {
884ee8648bdSDimitry Andric         if (!MO.isReg() || !MO.isDef() || MO.isDead())
885ee8648bdSDimitry Andric           continue;
886ee8648bdSDimitry Andric         assert(MO.isImplicit());
8871d5ae102SDimitry Andric         Register DefReg = MO.getReg();
888ee8648bdSDimitry Andric 
889b915e9e0SDimitry Andric         if (is_contained(ImpDefs, DefReg))
890ee8648bdSDimitry Andric           continue;
891ee8648bdSDimitry Andric         // We can ignore cases where the super-reg is read and written.
892ac9a064cSDimitry Andric         if (MI->readsRegister(DefReg, /*TRI=*/nullptr))
893ee8648bdSDimitry Andric           continue;
894ee8648bdSDimitry Andric         ImpDefs.push_back(DefReg);
895ee8648bdSDimitry Andric       }
896ee8648bdSDimitry Andric     }
897ee8648bdSDimitry Andric   }
898ee8648bdSDimitry Andric 
899ee8648bdSDimitry Andric   // Attempt the merge.
900044eb2f6SDimitry Andric   using iterator = MachineBasicBlock::iterator;
901044eb2f6SDimitry Andric 
902ee8648bdSDimitry Andric   MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
903ee8648bdSDimitry Andric   iterator InsertBefore = std::next(iterator(LatestMI));
904ee8648bdSDimitry Andric   MachineBasicBlock &MBB = *LatestMI->getParent();
90501095a5dSDimitry Andric   unsigned Offset = getMemoryOpOffset(*First);
9061d5ae102SDimitry Andric   Register Base = getLoadStoreBaseOp(*First).getReg();
907ac9a064cSDimitry Andric   bool BaseKill = LatestMI->killsRegister(Base, /*TRI=*/nullptr);
908cfca06d7SDimitry Andric   Register PredReg;
90901095a5dSDimitry Andric   ARMCC::CondCodes Pred = getInstrPredicate(*First, PredReg);
910ee8648bdSDimitry Andric   DebugLoc DL = First->getDebugLoc();
911ee8648bdSDimitry Andric   MachineInstr *Merged = nullptr;
912ee8648bdSDimitry Andric   if (Cand.CanMergeToLSDouble)
913ee8648bdSDimitry Andric     Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
914e6d15924SDimitry Andric                                    Opcode, Pred, PredReg, DL, Regs,
915e6d15924SDimitry Andric                                    Cand.Instrs);
916ee8648bdSDimitry Andric   if (!Merged && Cand.CanMergeToLSMulti)
917ee8648bdSDimitry Andric     Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
918e6d15924SDimitry Andric                                   Opcode, Pred, PredReg, DL, Regs, Cand.Instrs);
919ee8648bdSDimitry Andric   if (!Merged)
920ee8648bdSDimitry Andric     return nullptr;
921ee8648bdSDimitry Andric 
922ee8648bdSDimitry Andric   // Determine earliest instruction that will get removed. We then keep an
923ee8648bdSDimitry Andric   // iterator just above it so the following erases don't invalidated it.
924ee8648bdSDimitry Andric   iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
925ee8648bdSDimitry Andric   bool EarliestAtBegin = false;
926ee8648bdSDimitry Andric   if (EarliestI == MBB.begin()) {
927ee8648bdSDimitry Andric     EarliestAtBegin = true;
928ee8648bdSDimitry Andric   } else {
929ee8648bdSDimitry Andric     EarliestI = std::prev(EarliestI);
930ee8648bdSDimitry Andric   }
931ee8648bdSDimitry Andric 
932ee8648bdSDimitry Andric   // Remove instructions which have been merged.
933ee8648bdSDimitry Andric   for (MachineInstr *MI : Cand.Instrs)
934ee8648bdSDimitry Andric     MBB.erase(MI);
935ee8648bdSDimitry Andric 
936ee8648bdSDimitry Andric   // Determine range between the earliest removed instruction and the new one.
937ee8648bdSDimitry Andric   if (EarliestAtBegin)
938ee8648bdSDimitry Andric     EarliestI = MBB.begin();
939ee8648bdSDimitry Andric   else
940ee8648bdSDimitry Andric     EarliestI = std::next(EarliestI);
941ee8648bdSDimitry Andric   auto FixupRange = make_range(EarliestI, iterator(Merged));
942ee8648bdSDimitry Andric 
943ee8648bdSDimitry Andric   if (isLoadSingle(Opcode)) {
944ee8648bdSDimitry Andric     // If the previous loads defined a super-reg, then we have to mark earlier
945ee8648bdSDimitry Andric     // operands undef; Replicate the super-reg def on the merged instruction.
946ee8648bdSDimitry Andric     for (MachineInstr &MI : FixupRange) {
947ee8648bdSDimitry Andric       for (unsigned &ImpDefReg : ImpDefs) {
948ee8648bdSDimitry Andric         for (MachineOperand &MO : MI.implicit_operands()) {
949ee8648bdSDimitry Andric           if (!MO.isReg() || MO.getReg() != ImpDefReg)
950ee8648bdSDimitry Andric             continue;
951ee8648bdSDimitry Andric           if (MO.readsReg())
952ee8648bdSDimitry Andric             MO.setIsUndef();
953ee8648bdSDimitry Andric           else if (MO.isDef())
954ee8648bdSDimitry Andric             ImpDefReg = 0;
955ee8648bdSDimitry Andric         }
956ee8648bdSDimitry Andric       }
957ee8648bdSDimitry Andric     }
958ee8648bdSDimitry Andric 
959ee8648bdSDimitry Andric     MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
960ee8648bdSDimitry Andric     for (unsigned ImpDef : ImpDefs)
961ee8648bdSDimitry Andric       MIB.addReg(ImpDef, RegState::ImplicitDefine);
962ee8648bdSDimitry Andric   } else {
963ee8648bdSDimitry Andric     // Remove kill flags: We are possibly storing the values later now.
964ee8648bdSDimitry Andric     assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
965ee8648bdSDimitry Andric     for (MachineInstr &MI : FixupRange) {
966ee8648bdSDimitry Andric       for (MachineOperand &MO : MI.uses()) {
967ee8648bdSDimitry Andric         if (!MO.isReg() || !MO.isKill())
968ee8648bdSDimitry Andric           continue;
969dd58ef01SDimitry Andric         if (UsedRegs.count(MO.getReg()))
970ee8648bdSDimitry Andric           MO.setIsKill(false);
971ee8648bdSDimitry Andric       }
972ee8648bdSDimitry Andric     }
973ee8648bdSDimitry Andric     assert(ImpDefs.empty());
974ee8648bdSDimitry Andric   }
975ee8648bdSDimitry Andric 
976ee8648bdSDimitry Andric   return Merged;
977ee8648bdSDimitry Andric }
978ee8648bdSDimitry Andric 
isValidLSDoubleOffset(int Offset)979ee8648bdSDimitry Andric static bool isValidLSDoubleOffset(int Offset) {
980ee8648bdSDimitry Andric   unsigned Value = abs(Offset);
981ee8648bdSDimitry Andric   // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
982ee8648bdSDimitry Andric   // multiplied by 4.
983ee8648bdSDimitry Andric   return (Value % 4) == 0 && Value < 1024;
984ee8648bdSDimitry Andric }
985ee8648bdSDimitry Andric 
98601095a5dSDimitry Andric /// Return true for loads/stores that can be combined to a double/multi
98701095a5dSDimitry Andric /// operation without increasing the requirements for alignment.
mayCombineMisaligned(const TargetSubtargetInfo & STI,const MachineInstr & MI)98801095a5dSDimitry Andric static bool mayCombineMisaligned(const TargetSubtargetInfo &STI,
98901095a5dSDimitry Andric                                  const MachineInstr &MI) {
99001095a5dSDimitry Andric   // vldr/vstr trap on misaligned pointers anyway, forming vldm makes no
99101095a5dSDimitry Andric   // difference.
99201095a5dSDimitry Andric   unsigned Opcode = MI.getOpcode();
99301095a5dSDimitry Andric   if (!isi32Load(Opcode) && !isi32Store(Opcode))
99401095a5dSDimitry Andric     return true;
99501095a5dSDimitry Andric 
99601095a5dSDimitry Andric   // Stack pointer alignment is out of the programmers control so we can trust
99701095a5dSDimitry Andric   // SP-relative loads/stores.
99801095a5dSDimitry Andric   if (getLoadStoreBaseOp(MI).getReg() == ARM::SP &&
999cfca06d7SDimitry Andric       STI.getFrameLowering()->getTransientStackAlign() >= Align(4))
100001095a5dSDimitry Andric     return true;
100101095a5dSDimitry Andric   return false;
100201095a5dSDimitry Andric }
100301095a5dSDimitry Andric 
1004ee8648bdSDimitry Andric /// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
FormCandidates(const MemOpQueue & MemOps)1005ee8648bdSDimitry Andric void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
1006ee8648bdSDimitry Andric   const MachineInstr *FirstMI = MemOps[0].MI;
1007ee8648bdSDimitry Andric   unsigned Opcode = FirstMI->getOpcode();
1008ee8648bdSDimitry Andric   bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
1009ee8648bdSDimitry Andric   unsigned Size = getLSMultipleTransferSize(FirstMI);
1010ee8648bdSDimitry Andric 
1011ee8648bdSDimitry Andric   unsigned SIndex = 0;
1012ee8648bdSDimitry Andric   unsigned EIndex = MemOps.size();
1013ee8648bdSDimitry Andric   do {
1014ee8648bdSDimitry Andric     // Look at the first instruction.
1015ee8648bdSDimitry Andric     const MachineInstr *MI = MemOps[SIndex].MI;
1016ee8648bdSDimitry Andric     int Offset = MemOps[SIndex].Offset;
1017ee8648bdSDimitry Andric     const MachineOperand &PMO = getLoadStoreRegOp(*MI);
10181d5ae102SDimitry Andric     Register PReg = PMO.getReg();
1019044eb2f6SDimitry Andric     unsigned PRegNum = PMO.isUndef() ? std::numeric_limits<unsigned>::max()
1020044eb2f6SDimitry Andric                                      : TRI->getEncodingValue(PReg);
1021ee8648bdSDimitry Andric     unsigned Latest = SIndex;
1022ee8648bdSDimitry Andric     unsigned Earliest = SIndex;
1023ee8648bdSDimitry Andric     unsigned Count = 1;
1024ee8648bdSDimitry Andric     bool CanMergeToLSDouble =
1025ee8648bdSDimitry Andric       STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
1026ee8648bdSDimitry Andric     // ARM errata 602117: LDRD with base in list may result in incorrect base
1027ee8648bdSDimitry Andric     // register when interrupted or faulted.
1028ee8648bdSDimitry Andric     if (STI->isCortexM3() && isi32Load(Opcode) &&
1029ee8648bdSDimitry Andric         PReg == getLoadStoreBaseOp(*MI).getReg())
1030ee8648bdSDimitry Andric       CanMergeToLSDouble = false;
1031ee8648bdSDimitry Andric 
1032ee8648bdSDimitry Andric     bool CanMergeToLSMulti = true;
1033ee8648bdSDimitry Andric     // On swift vldm/vstm starting with an odd register number as that needs
1034ee8648bdSDimitry Andric     // more uops than single vldrs.
103501095a5dSDimitry Andric     if (STI->hasSlowOddRegister() && !isNotVFP && (PRegNum % 2) == 1)
1036ee8648bdSDimitry Andric       CanMergeToLSMulti = false;
1037ee8648bdSDimitry Andric 
103869156b4cSDimitry Andric     // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
103969156b4cSDimitry Andric     // deprecated; LDM to PC is fine but cannot happen here.
104069156b4cSDimitry Andric     if (PReg == ARM::SP || PReg == ARM::PC)
104169156b4cSDimitry Andric       CanMergeToLSMulti = CanMergeToLSDouble = false;
104269156b4cSDimitry Andric 
104301095a5dSDimitry Andric     // Should we be conservative?
104401095a5dSDimitry Andric     if (AssumeMisalignedLoadStores && !mayCombineMisaligned(*STI, *MI))
104501095a5dSDimitry Andric       CanMergeToLSMulti = CanMergeToLSDouble = false;
104601095a5dSDimitry Andric 
1047d8e91e46SDimitry Andric     // vldm / vstm limit are 32 for S variants, 16 for D variants.
1048d8e91e46SDimitry Andric     unsigned Limit;
1049d8e91e46SDimitry Andric     switch (Opcode) {
1050d8e91e46SDimitry Andric     default:
1051d8e91e46SDimitry Andric       Limit = UINT_MAX;
1052d8e91e46SDimitry Andric       break;
1053d8e91e46SDimitry Andric     case ARM::VLDRD:
1054d8e91e46SDimitry Andric     case ARM::VSTRD:
1055d8e91e46SDimitry Andric       Limit = 16;
1056d8e91e46SDimitry Andric       break;
1057d8e91e46SDimitry Andric     }
1058d8e91e46SDimitry Andric 
1059ee8648bdSDimitry Andric     // Merge following instructions where possible.
1060ee8648bdSDimitry Andric     for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
1061ee8648bdSDimitry Andric       int NewOffset = MemOps[I].Offset;
1062ee8648bdSDimitry Andric       if (NewOffset != Offset + (int)Size)
1063ee8648bdSDimitry Andric         break;
1064ee8648bdSDimitry Andric       const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
10651d5ae102SDimitry Andric       Register Reg = MO.getReg();
106669156b4cSDimitry Andric       if (Reg == ARM::SP || Reg == ARM::PC)
106769156b4cSDimitry Andric         break;
1068d8e91e46SDimitry Andric       if (Count == Limit)
1069d8e91e46SDimitry Andric         break;
1070ee8648bdSDimitry Andric 
1071ee8648bdSDimitry Andric       // See if the current load/store may be part of a multi load/store.
1072044eb2f6SDimitry Andric       unsigned RegNum = MO.isUndef() ? std::numeric_limits<unsigned>::max()
1073044eb2f6SDimitry Andric                                      : TRI->getEncodingValue(Reg);
1074ee8648bdSDimitry Andric       bool PartOfLSMulti = CanMergeToLSMulti;
1075ee8648bdSDimitry Andric       if (PartOfLSMulti) {
1076ee8648bdSDimitry Andric         // Register numbers must be in ascending order.
107769156b4cSDimitry Andric         if (RegNum <= PRegNum)
1078ee8648bdSDimitry Andric           PartOfLSMulti = false;
1079ee8648bdSDimitry Andric         // For VFP / NEON load/store multiples, the registers must be
1080ee8648bdSDimitry Andric         // consecutive and within the limit on the number of registers per
1081ee8648bdSDimitry Andric         // instruction.
1082ee8648bdSDimitry Andric         else if (!isNotVFP && RegNum != PRegNum+1)
1083ee8648bdSDimitry Andric           PartOfLSMulti = false;
1084ee8648bdSDimitry Andric       }
1085ee8648bdSDimitry Andric       // See if the current load/store may be part of a double load/store.
1086ee8648bdSDimitry Andric       bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
1087ee8648bdSDimitry Andric 
1088ee8648bdSDimitry Andric       if (!PartOfLSMulti && !PartOfLSDouble)
1089ee8648bdSDimitry Andric         break;
1090ee8648bdSDimitry Andric       CanMergeToLSMulti &= PartOfLSMulti;
1091ee8648bdSDimitry Andric       CanMergeToLSDouble &= PartOfLSDouble;
1092ee8648bdSDimitry Andric       // Track MemOp with latest and earliest position (Positions are
1093ee8648bdSDimitry Andric       // counted in reverse).
1094ee8648bdSDimitry Andric       unsigned Position = MemOps[I].Position;
1095ee8648bdSDimitry Andric       if (Position < MemOps[Latest].Position)
1096ee8648bdSDimitry Andric         Latest = I;
1097ee8648bdSDimitry Andric       else if (Position > MemOps[Earliest].Position)
1098ee8648bdSDimitry Andric         Earliest = I;
1099ee8648bdSDimitry Andric       // Prepare for next MemOp.
1100ee8648bdSDimitry Andric       Offset += Size;
1101ee8648bdSDimitry Andric       PRegNum = RegNum;
1102ee8648bdSDimitry Andric     }
1103ee8648bdSDimitry Andric 
1104ee8648bdSDimitry Andric     // Form a candidate from the Ops collected so far.
1105ee8648bdSDimitry Andric     MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
1106ee8648bdSDimitry Andric     for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1107ee8648bdSDimitry Andric       Candidate->Instrs.push_back(MemOps[C].MI);
1108ee8648bdSDimitry Andric     Candidate->LatestMIIdx = Latest - SIndex;
1109ee8648bdSDimitry Andric     Candidate->EarliestMIIdx = Earliest - SIndex;
1110ee8648bdSDimitry Andric     Candidate->InsertPos = MemOps[Latest].Position;
1111ee8648bdSDimitry Andric     if (Count == 1)
1112ee8648bdSDimitry Andric       CanMergeToLSMulti = CanMergeToLSDouble = false;
1113ee8648bdSDimitry Andric     Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1114ee8648bdSDimitry Andric     Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
1115ee8648bdSDimitry Andric     Candidates.push_back(Candidate);
1116ee8648bdSDimitry Andric     // Continue after the chain.
1117ee8648bdSDimitry Andric     SIndex += Count;
1118ee8648bdSDimitry Andric   } while (SIndex < EIndex);
1119ee8648bdSDimitry Andric }
1120ee8648bdSDimitry Andric 
getUpdatingLSMultipleOpcode(unsigned Opc,ARM_AM::AMSubMode Mode)1121cf099d11SDimitry Andric static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1122cf099d11SDimitry Andric                                             ARM_AM::AMSubMode Mode) {
1123c6910277SRoman Divacky   switch (Opc) {
1124c6910277SRoman Divacky   default: llvm_unreachable("Unhandled opcode!");
1125cf099d11SDimitry Andric   case ARM::LDMIA:
1126cf099d11SDimitry Andric   case ARM::LDMDA:
1127cf099d11SDimitry Andric   case ARM::LDMDB:
1128cf099d11SDimitry Andric   case ARM::LDMIB:
1129cf099d11SDimitry Andric     switch (Mode) {
1130cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1131cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::LDMIA_UPD;
1132cf099d11SDimitry Andric     case ARM_AM::ib: return ARM::LDMIB_UPD;
1133cf099d11SDimitry Andric     case ARM_AM::da: return ARM::LDMDA_UPD;
1134cf099d11SDimitry Andric     case ARM_AM::db: return ARM::LDMDB_UPD;
1135c6910277SRoman Divacky     }
1136cf099d11SDimitry Andric   case ARM::STMIA:
1137cf099d11SDimitry Andric   case ARM::STMDA:
1138cf099d11SDimitry Andric   case ARM::STMDB:
1139cf099d11SDimitry Andric   case ARM::STMIB:
1140cf099d11SDimitry Andric     switch (Mode) {
1141cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1142cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::STMIA_UPD;
1143cf099d11SDimitry Andric     case ARM_AM::ib: return ARM::STMIB_UPD;
1144cf099d11SDimitry Andric     case ARM_AM::da: return ARM::STMDA_UPD;
1145cf099d11SDimitry Andric     case ARM_AM::db: return ARM::STMDB_UPD;
1146cf099d11SDimitry Andric     }
1147cf099d11SDimitry Andric   case ARM::t2LDMIA:
1148cf099d11SDimitry Andric   case ARM::t2LDMDB:
1149cf099d11SDimitry Andric     switch (Mode) {
1150cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1151cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1152cf099d11SDimitry Andric     case ARM_AM::db: return ARM::t2LDMDB_UPD;
1153cf099d11SDimitry Andric     }
1154cf099d11SDimitry Andric   case ARM::t2STMIA:
1155cf099d11SDimitry Andric   case ARM::t2STMDB:
1156cf099d11SDimitry Andric     switch (Mode) {
1157cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1158cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::t2STMIA_UPD;
1159cf099d11SDimitry Andric     case ARM_AM::db: return ARM::t2STMDB_UPD;
1160cf099d11SDimitry Andric     }
1161cf099d11SDimitry Andric   case ARM::VLDMSIA:
1162cf099d11SDimitry Andric     switch (Mode) {
1163cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1164cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1165cf099d11SDimitry Andric     case ARM_AM::db: return ARM::VLDMSDB_UPD;
1166cf099d11SDimitry Andric     }
1167cf099d11SDimitry Andric   case ARM::VLDMDIA:
1168cf099d11SDimitry Andric     switch (Mode) {
1169cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1170cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1171cf099d11SDimitry Andric     case ARM_AM::db: return ARM::VLDMDDB_UPD;
1172cf099d11SDimitry Andric     }
1173cf099d11SDimitry Andric   case ARM::VSTMSIA:
1174cf099d11SDimitry Andric     switch (Mode) {
1175cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1176cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1177cf099d11SDimitry Andric     case ARM_AM::db: return ARM::VSTMSDB_UPD;
1178cf099d11SDimitry Andric     }
1179cf099d11SDimitry Andric   case ARM::VSTMDIA:
1180cf099d11SDimitry Andric     switch (Mode) {
1181cf099d11SDimitry Andric     default: llvm_unreachable("Unhandled submode!");
1182cf099d11SDimitry Andric     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1183cf099d11SDimitry Andric     case ARM_AM::db: return ARM::VSTMDDB_UPD;
1184cf099d11SDimitry Andric     }
1185cf099d11SDimitry Andric   }
1186c6910277SRoman Divacky }
1187c6910277SRoman Divacky 
1188dd58ef01SDimitry Andric /// Check if the given instruction increments or decrements a register and
1189dd58ef01SDimitry Andric /// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1190dd58ef01SDimitry Andric /// generated by the instruction are possibly read as well.
isIncrementOrDecrement(const MachineInstr & MI,Register Reg,ARMCC::CondCodes Pred,Register PredReg)1191cfca06d7SDimitry Andric static int isIncrementOrDecrement(const MachineInstr &MI, Register Reg,
1192cfca06d7SDimitry Andric                                   ARMCC::CondCodes Pred, Register PredReg) {
1193dd58ef01SDimitry Andric   bool CheckCPSRDef;
1194dd58ef01SDimitry Andric   int Scale;
1195dd58ef01SDimitry Andric   switch (MI.getOpcode()) {
1196dd58ef01SDimitry Andric   case ARM::tADDi8:  Scale =  4; CheckCPSRDef = true; break;
1197dd58ef01SDimitry Andric   case ARM::tSUBi8:  Scale = -4; CheckCPSRDef = true; break;
1198dd58ef01SDimitry Andric   case ARM::t2SUBri:
1199706b4fc4SDimitry Andric   case ARM::t2SUBspImm:
1200dd58ef01SDimitry Andric   case ARM::SUBri:   Scale = -1; CheckCPSRDef = true; break;
1201dd58ef01SDimitry Andric   case ARM::t2ADDri:
1202706b4fc4SDimitry Andric   case ARM::t2ADDspImm:
1203dd58ef01SDimitry Andric   case ARM::ADDri:   Scale =  1; CheckCPSRDef = true; break;
1204dd58ef01SDimitry Andric   case ARM::tADDspi: Scale =  4; CheckCPSRDef = false; break;
1205dd58ef01SDimitry Andric   case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1206dd58ef01SDimitry Andric   default: return 0;
1207dd58ef01SDimitry Andric   }
1208dd58ef01SDimitry Andric 
1209cfca06d7SDimitry Andric   Register MIPredReg;
1210dd58ef01SDimitry Andric   if (MI.getOperand(0).getReg() != Reg ||
1211dd58ef01SDimitry Andric       MI.getOperand(1).getReg() != Reg ||
121201095a5dSDimitry Andric       getInstrPredicate(MI, MIPredReg) != Pred ||
1213dd58ef01SDimitry Andric       MIPredReg != PredReg)
1214dd58ef01SDimitry Andric     return 0;
1215dd58ef01SDimitry Andric 
121601095a5dSDimitry Andric   if (CheckCPSRDef && definesCPSR(MI))
1217dd58ef01SDimitry Andric     return 0;
1218dd58ef01SDimitry Andric   return MI.getOperand(2).getImm() * Scale;
1219dd58ef01SDimitry Andric }
1220dd58ef01SDimitry Andric 
1221dd58ef01SDimitry Andric /// Searches for an increment or decrement of \p Reg before \p MBBI.
1222dd58ef01SDimitry Andric static MachineBasicBlock::iterator
findIncDecBefore(MachineBasicBlock::iterator MBBI,Register Reg,ARMCC::CondCodes Pred,Register PredReg,int & Offset)1223cfca06d7SDimitry Andric findIncDecBefore(MachineBasicBlock::iterator MBBI, Register Reg,
1224cfca06d7SDimitry Andric                  ARMCC::CondCodes Pred, Register PredReg, int &Offset) {
1225dd58ef01SDimitry Andric   Offset = 0;
1226dd58ef01SDimitry Andric   MachineBasicBlock &MBB = *MBBI->getParent();
1227dd58ef01SDimitry Andric   MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1228dd58ef01SDimitry Andric   MachineBasicBlock::iterator EndMBBI = MBB.end();
1229dd58ef01SDimitry Andric   if (MBBI == BeginMBBI)
1230dd58ef01SDimitry Andric     return EndMBBI;
1231dd58ef01SDimitry Andric 
1232dd58ef01SDimitry Andric   // Skip debug values.
1233dd58ef01SDimitry Andric   MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1234eb11fae6SDimitry Andric   while (PrevMBBI->isDebugInstr() && PrevMBBI != BeginMBBI)
1235dd58ef01SDimitry Andric     --PrevMBBI;
1236dd58ef01SDimitry Andric 
1237dd58ef01SDimitry Andric   Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1238dd58ef01SDimitry Andric   return Offset == 0 ? EndMBBI : PrevMBBI;
1239dd58ef01SDimitry Andric }
1240dd58ef01SDimitry Andric 
1241dd58ef01SDimitry Andric /// Searches for a increment or decrement of \p Reg after \p MBBI.
1242dd58ef01SDimitry Andric static MachineBasicBlock::iterator
findIncDecAfter(MachineBasicBlock::iterator MBBI,Register Reg,ARMCC::CondCodes Pred,Register PredReg,int & Offset,const TargetRegisterInfo * TRI)1243cfca06d7SDimitry Andric findIncDecAfter(MachineBasicBlock::iterator MBBI, Register Reg,
1244344a3780SDimitry Andric                 ARMCC::CondCodes Pred, Register PredReg, int &Offset,
1245344a3780SDimitry Andric                 const TargetRegisterInfo *TRI) {
1246dd58ef01SDimitry Andric   Offset = 0;
1247dd58ef01SDimitry Andric   MachineBasicBlock &MBB = *MBBI->getParent();
1248dd58ef01SDimitry Andric   MachineBasicBlock::iterator EndMBBI = MBB.end();
1249dd58ef01SDimitry Andric   MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1250344a3780SDimitry Andric   while (NextMBBI != EndMBBI) {
1251dd58ef01SDimitry Andric     // Skip debug values.
1252eb11fae6SDimitry Andric     while (NextMBBI != EndMBBI && NextMBBI->isDebugInstr())
1253dd58ef01SDimitry Andric       ++NextMBBI;
1254dd58ef01SDimitry Andric     if (NextMBBI == EndMBBI)
1255dd58ef01SDimitry Andric       return EndMBBI;
1256dd58ef01SDimitry Andric 
1257344a3780SDimitry Andric     unsigned Off = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1258344a3780SDimitry Andric     if (Off) {
1259344a3780SDimitry Andric       Offset = Off;
1260344a3780SDimitry Andric       return NextMBBI;
1261344a3780SDimitry Andric     }
1262344a3780SDimitry Andric 
1263344a3780SDimitry Andric     // SP can only be combined if it is the next instruction after the original
1264344a3780SDimitry Andric     // MBBI, otherwise we may be incrementing the stack pointer (invalidating
1265344a3780SDimitry Andric     // anything below the new pointer) when its frame elements are still in
1266344a3780SDimitry Andric     // use. Other registers can attempt to look further, until a different use
1267344a3780SDimitry Andric     // or def of the register is found.
1268344a3780SDimitry Andric     if (Reg == ARM::SP || NextMBBI->readsRegister(Reg, TRI) ||
1269344a3780SDimitry Andric         NextMBBI->definesRegister(Reg, TRI))
1270344a3780SDimitry Andric       return EndMBBI;
1271344a3780SDimitry Andric 
1272344a3780SDimitry Andric     ++NextMBBI;
1273344a3780SDimitry Andric   }
1274344a3780SDimitry Andric   return EndMBBI;
1275dd58ef01SDimitry Andric }
1276dd58ef01SDimitry Andric 
127785d8b2bbSDimitry Andric /// Fold proceeding/trailing inc/dec of base register into the
127885d8b2bbSDimitry Andric /// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
1279009b1c42SEd Schouten ///
1280009b1c42SEd Schouten /// stmia rn, <ra, rb, rc>
1281009b1c42SEd Schouten /// rn := rn + 4 * 3;
1282009b1c42SEd Schouten /// =>
1283009b1c42SEd Schouten /// stmia rn!, <ra, rb, rc>
1284009b1c42SEd Schouten ///
1285009b1c42SEd Schouten /// rn := rn - 4 * 3;
1286009b1c42SEd Schouten /// ldmia rn, <ra, rb, rc>
1287009b1c42SEd Schouten /// =>
1288009b1c42SEd Schouten /// ldmdb rn!, <ra, rb, rc>
MergeBaseUpdateLSMultiple(MachineInstr * MI)1289ee8648bdSDimitry Andric bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
12905ca98fd9SDimitry Andric   // Thumb1 is already using updating loads/stores.
12915ca98fd9SDimitry Andric   if (isThumb1) return false;
1292b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
12935ca98fd9SDimitry Andric 
1294ee8648bdSDimitry Andric   const MachineOperand &BaseOP = MI->getOperand(0);
12951d5ae102SDimitry Andric   Register Base = BaseOP.getReg();
1296ee8648bdSDimitry Andric   bool BaseKill = BaseOP.isKill();
1297cfca06d7SDimitry Andric   Register PredReg;
129801095a5dSDimitry Andric   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
12995a5ac124SDimitry Andric   unsigned Opcode = MI->getOpcode();
1300ee8648bdSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
1301c6910277SRoman Divacky 
1302c6910277SRoman Divacky   // Can't use an updating ld/st if the base register is also a dest
1303009b1c42SEd Schouten   // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
1304f65dcba8SDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1305f65dcba8SDimitry Andric     if (MO.getReg() == Base)
1306009b1c42SEd Schouten       return false;
1307cf099d11SDimitry Andric 
1308dd58ef01SDimitry Andric   int Bytes = getLSMultipleTransferSize(MI);
130969156b4cSDimitry Andric   MachineBasicBlock &MBB = *MI->getParent();
131069156b4cSDimitry Andric   MachineBasicBlock::iterator MBBI(MI);
1311dd58ef01SDimitry Andric   int Offset;
1312dd58ef01SDimitry Andric   MachineBasicBlock::iterator MergeInstr
1313dd58ef01SDimitry Andric     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1314dd58ef01SDimitry Andric   ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1315dd58ef01SDimitry Andric   if (Mode == ARM_AM::ia && Offset == -Bytes) {
1316c6910277SRoman Divacky     Mode = ARM_AM::db;
1317dd58ef01SDimitry Andric   } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1318c6910277SRoman Divacky     Mode = ARM_AM::da;
1319dd58ef01SDimitry Andric   } else {
1320344a3780SDimitry Andric     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1321dd58ef01SDimitry Andric     if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
132201095a5dSDimitry Andric         ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes)) {
132301095a5dSDimitry Andric 
132401095a5dSDimitry Andric       // We couldn't find an inc/dec to merge. But if the base is dead, we
132501095a5dSDimitry Andric       // can still change to a writeback form as that will save us 2 bytes
132601095a5dSDimitry Andric       // of code size. It can create WAW hazards though, so only do it if
132701095a5dSDimitry Andric       // we're minimizing code size.
1328e6d15924SDimitry Andric       if (!STI->hasMinSize() || !BaseKill)
132901095a5dSDimitry Andric         return false;
133001095a5dSDimitry Andric 
133101095a5dSDimitry Andric       bool HighRegsUsed = false;
1332f65dcba8SDimitry Andric       for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
1333f65dcba8SDimitry Andric         if (MO.getReg() >= ARM::R8) {
133401095a5dSDimitry Andric           HighRegsUsed = true;
133501095a5dSDimitry Andric           break;
133601095a5dSDimitry Andric         }
133701095a5dSDimitry Andric 
133801095a5dSDimitry Andric       if (!HighRegsUsed)
133901095a5dSDimitry Andric         MergeInstr = MBB.end();
134001095a5dSDimitry Andric       else
134169156b4cSDimitry Andric         return false;
1342dd58ef01SDimitry Andric     }
134301095a5dSDimitry Andric   }
1344b60736ecSDimitry Andric   if (MergeInstr != MBB.end()) {
1345b60736ecSDimitry Andric     LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1346dd58ef01SDimitry Andric     MBB.erase(MergeInstr);
1347b60736ecSDimitry Andric   }
1348c6910277SRoman Divacky 
1349cf099d11SDimitry Andric   unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
1350ee8648bdSDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
1351c6910277SRoman Divacky     .addReg(Base, getDefRegState(true)) // WB base register
1352d39c594dSDimitry Andric     .addReg(Base, getKillRegState(BaseKill))
1353c6910277SRoman Divacky     .addImm(Pred).addReg(PredReg);
1354cf099d11SDimitry Andric 
1355c6910277SRoman Divacky   // Transfer the rest of operands.
1356f65dcba8SDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 3))
1357f65dcba8SDimitry Andric     MIB.add(MO);
1358cf099d11SDimitry Andric 
1359c6910277SRoman Divacky   // Transfer memoperands.
1360d8e91e46SDimitry Andric   MIB.setMemRefs(MI->memoperands());
1361c6910277SRoman Divacky 
1362b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "  Added new load/store: " << *MIB);
1363c6910277SRoman Divacky   MBB.erase(MBBI);
1364c6910277SRoman Divacky   return true;
1365009b1c42SEd Schouten }
1366009b1c42SEd Schouten 
getPreIndexedLoadStoreOpcode(unsigned Opc,ARM_AM::AddrOpc Mode)1367cf099d11SDimitry Andric static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1368cf099d11SDimitry Andric                                              ARM_AM::AddrOpc Mode) {
1369009b1c42SEd Schouten   switch (Opc) {
1370cf099d11SDimitry Andric   case ARM::LDRi12:
137130815c53SDimitry Andric     return ARM::LDR_PRE_IMM;
1372cf099d11SDimitry Andric   case ARM::STRi12:
137330815c53SDimitry Andric     return ARM::STR_PRE_IMM;
1374cf099d11SDimitry Andric   case ARM::VLDRS:
1375cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1376cf099d11SDimitry Andric   case ARM::VLDRD:
1377cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1378cf099d11SDimitry Andric   case ARM::VSTRS:
1379cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1380cf099d11SDimitry Andric   case ARM::VSTRD:
1381cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
138259850d08SRoman Divacky   case ARM::t2LDRi8:
138359850d08SRoman Divacky   case ARM::t2LDRi12:
138459850d08SRoman Divacky     return ARM::t2LDR_PRE;
138559850d08SRoman Divacky   case ARM::t2STRi8:
138659850d08SRoman Divacky   case ARM::t2STRi12:
138759850d08SRoman Divacky     return ARM::t2STR_PRE;
138859850d08SRoman Divacky   default: llvm_unreachable("Unhandled opcode!");
1389009b1c42SEd Schouten   }
1390009b1c42SEd Schouten }
1391009b1c42SEd Schouten 
getPostIndexedLoadStoreOpcode(unsigned Opc,ARM_AM::AddrOpc Mode)1392cf099d11SDimitry Andric static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1393cf099d11SDimitry Andric                                               ARM_AM::AddrOpc Mode) {
1394009b1c42SEd Schouten   switch (Opc) {
1395cf099d11SDimitry Andric   case ARM::LDRi12:
139630815c53SDimitry Andric     return ARM::LDR_POST_IMM;
1397cf099d11SDimitry Andric   case ARM::STRi12:
139830815c53SDimitry Andric     return ARM::STR_POST_IMM;
1399cf099d11SDimitry Andric   case ARM::VLDRS:
1400cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1401cf099d11SDimitry Andric   case ARM::VLDRD:
1402cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1403cf099d11SDimitry Andric   case ARM::VSTRS:
1404cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1405cf099d11SDimitry Andric   case ARM::VSTRD:
1406cf099d11SDimitry Andric     return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
140759850d08SRoman Divacky   case ARM::t2LDRi8:
140859850d08SRoman Divacky   case ARM::t2LDRi12:
140959850d08SRoman Divacky     return ARM::t2LDR_POST;
1410b60736ecSDimitry Andric   case ARM::t2LDRBi8:
1411b60736ecSDimitry Andric   case ARM::t2LDRBi12:
1412b60736ecSDimitry Andric     return ARM::t2LDRB_POST;
1413b60736ecSDimitry Andric   case ARM::t2LDRSBi8:
1414b60736ecSDimitry Andric   case ARM::t2LDRSBi12:
1415b60736ecSDimitry Andric     return ARM::t2LDRSB_POST;
1416b60736ecSDimitry Andric   case ARM::t2LDRHi8:
1417b60736ecSDimitry Andric   case ARM::t2LDRHi12:
1418b60736ecSDimitry Andric     return ARM::t2LDRH_POST;
1419b60736ecSDimitry Andric   case ARM::t2LDRSHi8:
1420b60736ecSDimitry Andric   case ARM::t2LDRSHi12:
1421b60736ecSDimitry Andric     return ARM::t2LDRSH_POST;
142259850d08SRoman Divacky   case ARM::t2STRi8:
142359850d08SRoman Divacky   case ARM::t2STRi12:
142459850d08SRoman Divacky     return ARM::t2STR_POST;
1425b60736ecSDimitry Andric   case ARM::t2STRBi8:
1426b60736ecSDimitry Andric   case ARM::t2STRBi12:
1427b60736ecSDimitry Andric     return ARM::t2STRB_POST;
1428b60736ecSDimitry Andric   case ARM::t2STRHi8:
1429b60736ecSDimitry Andric   case ARM::t2STRHi12:
1430b60736ecSDimitry Andric     return ARM::t2STRH_POST;
1431cfca06d7SDimitry Andric 
1432cfca06d7SDimitry Andric   case ARM::MVE_VLDRBS16:
1433cfca06d7SDimitry Andric     return ARM::MVE_VLDRBS16_post;
1434cfca06d7SDimitry Andric   case ARM::MVE_VLDRBS32:
1435cfca06d7SDimitry Andric     return ARM::MVE_VLDRBS32_post;
1436cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU16:
1437cfca06d7SDimitry Andric     return ARM::MVE_VLDRBU16_post;
1438cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU32:
1439cfca06d7SDimitry Andric     return ARM::MVE_VLDRBU32_post;
1440cfca06d7SDimitry Andric   case ARM::MVE_VLDRHS32:
1441cfca06d7SDimitry Andric     return ARM::MVE_VLDRHS32_post;
1442cfca06d7SDimitry Andric   case ARM::MVE_VLDRHU32:
1443cfca06d7SDimitry Andric     return ARM::MVE_VLDRHU32_post;
1444cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU8:
1445cfca06d7SDimitry Andric     return ARM::MVE_VLDRBU8_post;
1446cfca06d7SDimitry Andric   case ARM::MVE_VLDRHU16:
1447cfca06d7SDimitry Andric     return ARM::MVE_VLDRHU16_post;
1448cfca06d7SDimitry Andric   case ARM::MVE_VLDRWU32:
1449cfca06d7SDimitry Andric     return ARM::MVE_VLDRWU32_post;
1450cfca06d7SDimitry Andric   case ARM::MVE_VSTRB16:
1451cfca06d7SDimitry Andric     return ARM::MVE_VSTRB16_post;
1452cfca06d7SDimitry Andric   case ARM::MVE_VSTRB32:
1453cfca06d7SDimitry Andric     return ARM::MVE_VSTRB32_post;
1454cfca06d7SDimitry Andric   case ARM::MVE_VSTRH32:
1455cfca06d7SDimitry Andric     return ARM::MVE_VSTRH32_post;
1456cfca06d7SDimitry Andric   case ARM::MVE_VSTRBU8:
1457cfca06d7SDimitry Andric     return ARM::MVE_VSTRBU8_post;
1458cfca06d7SDimitry Andric   case ARM::MVE_VSTRHU16:
1459cfca06d7SDimitry Andric     return ARM::MVE_VSTRHU16_post;
1460cfca06d7SDimitry Andric   case ARM::MVE_VSTRWU32:
1461cfca06d7SDimitry Andric     return ARM::MVE_VSTRWU32_post;
1462cfca06d7SDimitry Andric 
146359850d08SRoman Divacky   default: llvm_unreachable("Unhandled opcode!");
1464009b1c42SEd Schouten   }
1465009b1c42SEd Schouten }
1466009b1c42SEd Schouten 
146785d8b2bbSDimitry Andric /// Fold proceeding/trailing inc/dec of base register into the
146885d8b2bbSDimitry Andric /// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
MergeBaseUpdateLoadStore(MachineInstr * MI)1469ee8648bdSDimitry Andric bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
14705ca98fd9SDimitry Andric   // Thumb1 doesn't have updating LDR/STR.
14715ca98fd9SDimitry Andric   // FIXME: Use LDM/STM with single register instead.
14725ca98fd9SDimitry Andric   if (isThumb1) return false;
1473b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << *MI);
14745ca98fd9SDimitry Andric 
14751d5ae102SDimitry Andric   Register Base = getLoadStoreBaseOp(*MI).getReg();
1476ee8648bdSDimitry Andric   bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
14775a5ac124SDimitry Andric   unsigned Opcode = MI->getOpcode();
1478ee8648bdSDimitry Andric   DebugLoc DL = MI->getDebugLoc();
1479c6910277SRoman Divacky   bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1480c6910277SRoman Divacky                 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
1481cf099d11SDimitry Andric   bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1482cf099d11SDimitry Andric   if (isi32Load(Opcode) || isi32Store(Opcode))
1483cf099d11SDimitry Andric     if (MI->getOperand(2).getImm() != 0)
148459850d08SRoman Divacky       return false;
1485c6910277SRoman Divacky   if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
148659850d08SRoman Divacky     return false;
1487009b1c42SEd Schouten 
1488009b1c42SEd Schouten   // Can't do the merge if the destination register is the same as the would-be
1489009b1c42SEd Schouten   // writeback register.
14904a16efa3SDimitry Andric   if (MI->getOperand(0).getReg() == Base)
1491009b1c42SEd Schouten     return false;
1492009b1c42SEd Schouten 
1493cfca06d7SDimitry Andric   Register PredReg;
149401095a5dSDimitry Andric   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1495dd58ef01SDimitry Andric   int Bytes = getLSMultipleTransferSize(MI);
1496ee8648bdSDimitry Andric   MachineBasicBlock &MBB = *MI->getParent();
1497ee8648bdSDimitry Andric   MachineBasicBlock::iterator MBBI(MI);
1498dd58ef01SDimitry Andric   int Offset;
1499dd58ef01SDimitry Andric   MachineBasicBlock::iterator MergeInstr
1500dd58ef01SDimitry Andric     = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1501dd58ef01SDimitry Andric   unsigned NewOpc;
1502dd58ef01SDimitry Andric   if (!isAM5 && Offset == Bytes) {
1503dd58ef01SDimitry Andric     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1504dd58ef01SDimitry Andric   } else if (Offset == -Bytes) {
1505dd58ef01SDimitry Andric     NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1506dd58ef01SDimitry Andric   } else {
1507344a3780SDimitry Andric     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1508344a3780SDimitry Andric     if (MergeInstr == MBB.end())
150969156b4cSDimitry Andric       return false;
1510344a3780SDimitry Andric 
1511344a3780SDimitry Andric     NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1512344a3780SDimitry Andric     if ((isAM5 && Offset != Bytes) ||
1513344a3780SDimitry Andric         (!isAM5 && !isLegalAddressImm(NewOpc, Offset, TII))) {
1514344a3780SDimitry Andric       NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1515344a3780SDimitry Andric       if (isAM5 || !isLegalAddressImm(NewOpc, Offset, TII))
1516344a3780SDimitry Andric         return false;
1517344a3780SDimitry Andric     }
1518dd58ef01SDimitry Andric   }
1519b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1520dd58ef01SDimitry Andric   MBB.erase(MergeInstr);
152169156b4cSDimitry Andric 
1522dd58ef01SDimitry Andric   ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
1523dd58ef01SDimitry Andric 
1524dd58ef01SDimitry Andric   bool isLd = isLoadSingle(Opcode);
1525c6910277SRoman Divacky   if (isAM5) {
15265ca98fd9SDimitry Andric     // VLDM[SD]_UPD, VSTM[SD]_UPD
1527d39c594dSDimitry Andric     // (There are no base-updating versions of VLDR/VSTR instructions, but the
1528d39c594dSDimitry Andric     // updating load/store-multiple instructions can be used with only one
1529d39c594dSDimitry Andric     // register.)
1530c6910277SRoman Divacky     MachineOperand &MO = MI->getOperand(0);
1531b60736ecSDimitry Andric     auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
153259850d08SRoman Divacky                    .addReg(Base, getDefRegState(true)) // WB base register
1533c6910277SRoman Divacky                    .addReg(Base, getKillRegState(isLd ? BaseKill : false))
1534b60736ecSDimitry Andric                    .addImm(Pred)
1535b60736ecSDimitry Andric                    .addReg(PredReg)
1536b60736ecSDimitry Andric                    .addReg(MO.getReg(), (isLd ? getDefRegState(true)
1537b60736ecSDimitry Andric                                               : getKillRegState(MO.isKill())))
1538e6d15924SDimitry Andric                    .cloneMemRefs(*MI);
1539b60736ecSDimitry Andric     (void)MIB;
1540b60736ecSDimitry Andric     LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1541c6910277SRoman Divacky   } else if (isLd) {
154230815c53SDimitry Andric     if (isAM2) {
154330815c53SDimitry Andric       // LDR_PRE, LDR_POST
154430815c53SDimitry Andric       if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
1545b60736ecSDimitry Andric         auto MIB =
1546ee8648bdSDimitry Andric             BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
154759850d08SRoman Divacky                 .addReg(Base, RegState::Define)
1548b60736ecSDimitry Andric                 .addReg(Base)
1549b60736ecSDimitry Andric                 .addImm(Offset)
1550b60736ecSDimitry Andric                 .addImm(Pred)
1551b60736ecSDimitry Andric                 .addReg(PredReg)
1552e6d15924SDimitry Andric                 .cloneMemRefs(*MI);
1553b60736ecSDimitry Andric         (void)MIB;
1554b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1555009b1c42SEd Schouten       } else {
1556344a3780SDimitry Andric         int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);
1557b60736ecSDimitry Andric         auto MIB =
1558ee8648bdSDimitry Andric             BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
155930815c53SDimitry Andric                 .addReg(Base, RegState::Define)
156071d5a254SDimitry Andric                 .addReg(Base)
156171d5a254SDimitry Andric                 .addReg(0)
156271d5a254SDimitry Andric                 .addImm(Imm)
1563e6d15924SDimitry Andric                 .add(predOps(Pred, PredReg))
1564e6d15924SDimitry Andric                 .cloneMemRefs(*MI);
1565b60736ecSDimitry Andric         (void)MIB;
1566b60736ecSDimitry Andric         LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
156730815c53SDimitry Andric       }
156830815c53SDimitry Andric     } else {
156930815c53SDimitry Andric       // t2LDR_PRE, t2LDR_POST
1570b60736ecSDimitry Andric       auto MIB =
1571ee8648bdSDimitry Andric           BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
157230815c53SDimitry Andric               .addReg(Base, RegState::Define)
157371d5a254SDimitry Andric               .addReg(Base)
157471d5a254SDimitry Andric               .addImm(Offset)
1575e6d15924SDimitry Andric               .add(predOps(Pred, PredReg))
1576e6d15924SDimitry Andric               .cloneMemRefs(*MI);
1577b60736ecSDimitry Andric       (void)MIB;
1578b60736ecSDimitry Andric       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
157930815c53SDimitry Andric     }
158030815c53SDimitry Andric   } else {
1581009b1c42SEd Schouten     MachineOperand &MO = MI->getOperand(0);
158230815c53SDimitry Andric     // FIXME: post-indexed stores use am2offset_imm, which still encodes
158330815c53SDimitry Andric     // the vestigal zero-reg offset register. When that's fixed, this clause
158430815c53SDimitry Andric     // can be removed entirely.
158530815c53SDimitry Andric     if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
1586344a3780SDimitry Andric       int Imm = ARM_AM::getAM2Opc(AddSub, abs(Offset), ARM_AM::no_shift);
158759850d08SRoman Divacky       // STR_PRE, STR_POST
1588b60736ecSDimitry Andric       auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
1589f4fe016fSEd Schouten                      .addReg(MO.getReg(), getKillRegState(MO.isKill()))
159071d5a254SDimitry Andric                      .addReg(Base)
159171d5a254SDimitry Andric                      .addReg(0)
159271d5a254SDimitry Andric                      .addImm(Imm)
1593e6d15924SDimitry Andric                      .add(predOps(Pred, PredReg))
1594e6d15924SDimitry Andric                      .cloneMemRefs(*MI);
1595b60736ecSDimitry Andric       (void)MIB;
1596b60736ecSDimitry Andric       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
159730815c53SDimitry Andric     } else {
159859850d08SRoman Divacky       // t2STR_PRE, t2STR_POST
1599b60736ecSDimitry Andric       auto MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
160059850d08SRoman Divacky                      .addReg(MO.getReg(), getKillRegState(MO.isKill()))
160171d5a254SDimitry Andric                      .addReg(Base)
160271d5a254SDimitry Andric                      .addImm(Offset)
1603e6d15924SDimitry Andric                      .add(predOps(Pred, PredReg))
1604e6d15924SDimitry Andric                      .cloneMemRefs(*MI);
1605b60736ecSDimitry Andric       (void)MIB;
1606b60736ecSDimitry Andric       LLVM_DEBUG(dbgs() << "  Added new instruction: " << *MIB);
1607009b1c42SEd Schouten     }
160830815c53SDimitry Andric   }
1609009b1c42SEd Schouten   MBB.erase(MBBI);
1610009b1c42SEd Schouten 
1611009b1c42SEd Schouten   return true;
1612009b1c42SEd Schouten }
1613009b1c42SEd Schouten 
MergeBaseUpdateLSDouble(MachineInstr & MI) const1614dd58ef01SDimitry Andric bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1615dd58ef01SDimitry Andric   unsigned Opcode = MI.getOpcode();
1616dd58ef01SDimitry Andric   assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1617dd58ef01SDimitry Andric          "Must have t2STRDi8 or t2LDRDi8");
1618dd58ef01SDimitry Andric   if (MI.getOperand(3).getImm() != 0)
1619dd58ef01SDimitry Andric     return false;
1620b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "Attempting to merge update of: " << MI);
1621dd58ef01SDimitry Andric 
1622dd58ef01SDimitry Andric   // Behaviour for writeback is undefined if base register is the same as one
1623dd58ef01SDimitry Andric   // of the others.
1624dd58ef01SDimitry Andric   const MachineOperand &BaseOp = MI.getOperand(2);
16251d5ae102SDimitry Andric   Register Base = BaseOp.getReg();
1626dd58ef01SDimitry Andric   const MachineOperand &Reg0Op = MI.getOperand(0);
1627dd58ef01SDimitry Andric   const MachineOperand &Reg1Op = MI.getOperand(1);
1628dd58ef01SDimitry Andric   if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1629dd58ef01SDimitry Andric     return false;
1630dd58ef01SDimitry Andric 
1631cfca06d7SDimitry Andric   Register PredReg;
163201095a5dSDimitry Andric   ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1633dd58ef01SDimitry Andric   MachineBasicBlock::iterator MBBI(MI);
1634dd58ef01SDimitry Andric   MachineBasicBlock &MBB = *MI.getParent();
1635dd58ef01SDimitry Andric   int Offset;
1636dd58ef01SDimitry Andric   MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1637dd58ef01SDimitry Andric                                                             PredReg, Offset);
1638dd58ef01SDimitry Andric   unsigned NewOpc;
1639dd58ef01SDimitry Andric   if (Offset == 8 || Offset == -8) {
1640dd58ef01SDimitry Andric     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1641dd58ef01SDimitry Andric   } else {
1642344a3780SDimitry Andric     MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset, TRI);
1643344a3780SDimitry Andric     if (MergeInstr == MBB.end())
1644344a3780SDimitry Andric       return false;
1645dd58ef01SDimitry Andric     NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1646344a3780SDimitry Andric     if (!isLegalAddressImm(NewOpc, Offset, TII))
1647dd58ef01SDimitry Andric       return false;
1648dd58ef01SDimitry Andric   }
1649b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "  Erasing old increment: " << *MergeInstr);
1650dd58ef01SDimitry Andric   MBB.erase(MergeInstr);
1651dd58ef01SDimitry Andric 
1652dd58ef01SDimitry Andric   DebugLoc DL = MI.getDebugLoc();
1653dd58ef01SDimitry Andric   MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1654dd58ef01SDimitry Andric   if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
165571d5a254SDimitry Andric     MIB.add(Reg0Op).add(Reg1Op).addReg(BaseOp.getReg(), RegState::Define);
1656dd58ef01SDimitry Andric   } else {
1657dd58ef01SDimitry Andric     assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
165871d5a254SDimitry Andric     MIB.addReg(BaseOp.getReg(), RegState::Define).add(Reg0Op).add(Reg1Op);
1659dd58ef01SDimitry Andric   }
1660dd58ef01SDimitry Andric   MIB.addReg(BaseOp.getReg(), RegState::Kill)
1661dd58ef01SDimitry Andric      .addImm(Offset).addImm(Pred).addReg(PredReg);
1662dd58ef01SDimitry Andric   assert(TII->get(Opcode).getNumOperands() == 6 &&
1663dd58ef01SDimitry Andric          TII->get(NewOpc).getNumOperands() == 7 &&
1664dd58ef01SDimitry Andric          "Unexpected number of operands in Opcode specification.");
1665dd58ef01SDimitry Andric 
1666dd58ef01SDimitry Andric   // Transfer implicit operands.
1667dd58ef01SDimitry Andric   for (const MachineOperand &MO : MI.implicit_operands())
166871d5a254SDimitry Andric     MIB.add(MO);
1669e6d15924SDimitry Andric   MIB.cloneMemRefs(MI);
1670dd58ef01SDimitry Andric 
1671b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "  Added new load/store: " << *MIB);
1672dd58ef01SDimitry Andric   MBB.erase(MBBI);
1673dd58ef01SDimitry Andric   return true;
1674dd58ef01SDimitry Andric }
1675dd58ef01SDimitry Andric 
167685d8b2bbSDimitry Andric /// Returns true if instruction is a memory operation that this pass is capable
167785d8b2bbSDimitry Andric /// of operating on.
isMemoryOp(const MachineInstr & MI)1678dd58ef01SDimitry Andric static bool isMemoryOp(const MachineInstr &MI) {
1679dd58ef01SDimitry Andric   unsigned Opcode = MI.getOpcode();
1680009b1c42SEd Schouten   switch (Opcode) {
1681907da171SRoman Divacky   case ARM::VLDRS:
1682907da171SRoman Divacky   case ARM::VSTRS:
1683907da171SRoman Divacky   case ARM::VLDRD:
1684907da171SRoman Divacky   case ARM::VSTRD:
1685cf099d11SDimitry Andric   case ARM::LDRi12:
1686cf099d11SDimitry Andric   case ARM::STRi12:
16875ca98fd9SDimitry Andric   case ARM::tLDRi:
16885ca98fd9SDimitry Andric   case ARM::tSTRi:
16895a5ac124SDimitry Andric   case ARM::tLDRspi:
16905a5ac124SDimitry Andric   case ARM::tSTRspi:
169159850d08SRoman Divacky   case ARM::t2LDRi8:
169259850d08SRoman Divacky   case ARM::t2LDRi12:
169359850d08SRoman Divacky   case ARM::t2STRi8:
169459850d08SRoman Divacky   case ARM::t2STRi12:
1695dd58ef01SDimitry Andric     break;
1696dd58ef01SDimitry Andric   default:
1697009b1c42SEd Schouten     return false;
1698009b1c42SEd Schouten   }
1699dd58ef01SDimitry Andric   if (!MI.getOperand(1).isReg())
1700dd58ef01SDimitry Andric     return false;
1701dd58ef01SDimitry Andric 
1702dd58ef01SDimitry Andric   // When no memory operands are present, conservatively assume unaligned,
1703dd58ef01SDimitry Andric   // volatile, unfoldable.
1704dd58ef01SDimitry Andric   if (!MI.hasOneMemOperand())
1705dd58ef01SDimitry Andric     return false;
1706dd58ef01SDimitry Andric 
1707dd58ef01SDimitry Andric   const MachineMemOperand &MMO = **MI.memoperands_begin();
1708dd58ef01SDimitry Andric 
1709dd58ef01SDimitry Andric   // Don't touch volatile memory accesses - we may be changing their order.
1710e6d15924SDimitry Andric   // TODO: We could allow unordered and monotonic atomics here, but we need to
1711e6d15924SDimitry Andric   // make sure the resulting ldm/stm is correctly marked as atomic.
1712e6d15924SDimitry Andric   if (MMO.isVolatile() || MMO.isAtomic())
1713dd58ef01SDimitry Andric     return false;
1714dd58ef01SDimitry Andric 
1715dd58ef01SDimitry Andric   // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1716dd58ef01SDimitry Andric   // not.
1717cfca06d7SDimitry Andric   if (MMO.getAlign() < Align(4))
1718dd58ef01SDimitry Andric     return false;
1719dd58ef01SDimitry Andric 
1720dd58ef01SDimitry Andric   // str <undef> could probably be eliminated entirely, but for now we just want
1721dd58ef01SDimitry Andric   // to avoid making a mess of it.
1722dd58ef01SDimitry Andric   // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1723dd58ef01SDimitry Andric   if (MI.getOperand(0).isReg() && MI.getOperand(0).isUndef())
1724dd58ef01SDimitry Andric     return false;
1725dd58ef01SDimitry Andric 
1726dd58ef01SDimitry Andric   // Likewise don't mess with references to undefined addresses.
1727dd58ef01SDimitry Andric   if (MI.getOperand(1).isUndef())
1728dd58ef01SDimitry Andric     return false;
1729dd58ef01SDimitry Andric 
1730dd58ef01SDimitry Andric   return true;
1731dd58ef01SDimitry Andric }
1732009b1c42SEd Schouten 
InsertLDR_STR(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,int Offset,bool isDef,unsigned NewOpc,unsigned Reg,bool RegDeadKill,bool RegUndef,unsigned BaseReg,bool BaseKill,bool BaseUndef,ARMCC::CondCodes Pred,unsigned PredReg,const TargetInstrInfo * TII,MachineInstr * MI)1733b2f21fb0SEd Schouten static void InsertLDR_STR(MachineBasicBlock &MBB,
173401095a5dSDimitry Andric                           MachineBasicBlock::iterator &MBBI, int Offset,
1735044eb2f6SDimitry Andric                           bool isDef, unsigned NewOpc, unsigned Reg,
1736044eb2f6SDimitry Andric                           bool RegDeadKill, bool RegUndef, unsigned BaseReg,
1737044eb2f6SDimitry Andric                           bool BaseKill, bool BaseUndef, ARMCC::CondCodes Pred,
1738e6d15924SDimitry Andric                           unsigned PredReg, const TargetInstrInfo *TII,
1739e6d15924SDimitry Andric                           MachineInstr *MI) {
174059850d08SRoman Divacky   if (isDef) {
174159850d08SRoman Divacky     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
174259850d08SRoman Divacky                                       TII->get(NewOpc))
1743b2f21fb0SEd Schouten       .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
174459850d08SRoman Divacky       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
174559850d08SRoman Divacky     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1746e6d15924SDimitry Andric     // FIXME: This is overly conservative; the new instruction accesses 4
1747e6d15924SDimitry Andric     // bytes, not 8.
1748e6d15924SDimitry Andric     MIB.cloneMemRefs(*MI);
174959850d08SRoman Divacky   } else {
175059850d08SRoman Divacky     MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
175159850d08SRoman Divacky                                       TII->get(NewOpc))
175259850d08SRoman Divacky       .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
175359850d08SRoman Divacky       .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
175459850d08SRoman Divacky     MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1755e6d15924SDimitry Andric     // FIXME: This is overly conservative; the new instruction accesses 4
1756e6d15924SDimitry Andric     // bytes, not 8.
1757e6d15924SDimitry Andric     MIB.cloneMemRefs(*MI);
175859850d08SRoman Divacky   }
1759b2f21fb0SEd Schouten }
1760b2f21fb0SEd Schouten 
FixInvalidRegPairOp(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI)1761b2f21fb0SEd Schouten bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1762b2f21fb0SEd Schouten                                           MachineBasicBlock::iterator &MBBI) {
1763b2f21fb0SEd Schouten   MachineInstr *MI = &*MBBI;
1764b2f21fb0SEd Schouten   unsigned Opcode = MI->getOpcode();
1765044eb2f6SDimitry Andric   // FIXME: Code/comments below check Opcode == t2STRDi8, but this check returns
1766044eb2f6SDimitry Andric   // if we see this opcode.
17671a82d4c0SDimitry Andric   if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
17681a82d4c0SDimitry Andric     return false;
17691a82d4c0SDimitry Andric 
177063faed5bSDimitry Andric   const MachineOperand &BaseOp = MI->getOperand(2);
17711d5ae102SDimitry Andric   Register BaseReg = BaseOp.getReg();
17721d5ae102SDimitry Andric   Register EvenReg = MI->getOperand(0).getReg();
17731d5ae102SDimitry Andric   Register OddReg = MI->getOperand(1).getReg();
1774b2f21fb0SEd Schouten   unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1775b2f21fb0SEd Schouten   unsigned OddRegNum  = TRI->getDwarfRegNum(OddReg, false);
17761a82d4c0SDimitry Andric 
177763faed5bSDimitry Andric   // ARM errata 602117: LDRD with base in list may result in incorrect base
177863faed5bSDimitry Andric   // register when interrupted or faulted.
17791a82d4c0SDimitry Andric   bool Errata602117 = EvenReg == BaseReg &&
17801a82d4c0SDimitry Andric     (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
17811a82d4c0SDimitry Andric   // ARM LDRD/STRD needs consecutive registers.
17821a82d4c0SDimitry Andric   bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
17831a82d4c0SDimitry Andric     (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
17841a82d4c0SDimitry Andric 
17851a82d4c0SDimitry Andric   if (!Errata602117 && !NonConsecutiveRegs)
1786b2f21fb0SEd Schouten     return false;
1787b2f21fb0SEd Schouten 
178859850d08SRoman Divacky   bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
178959850d08SRoman Divacky   bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1790b2f21fb0SEd Schouten   bool EvenDeadKill = isLd ?
1791b2f21fb0SEd Schouten     MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
179259850d08SRoman Divacky   bool EvenUndef = MI->getOperand(0).isUndef();
1793b2f21fb0SEd Schouten   bool OddDeadKill  = isLd ?
1794b2f21fb0SEd Schouten     MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
179559850d08SRoman Divacky   bool OddUndef = MI->getOperand(1).isUndef();
1796b2f21fb0SEd Schouten   bool BaseKill = BaseOp.isKill();
179759850d08SRoman Divacky   bool BaseUndef = BaseOp.isUndef();
1798044eb2f6SDimitry Andric   assert((isT2 || MI->getOperand(3).getReg() == ARM::NoRegister) &&
1799044eb2f6SDimitry Andric          "register offset not handled below");
180001095a5dSDimitry Andric   int OffImm = getMemoryOpOffset(*MI);
1801cfca06d7SDimitry Andric   Register PredReg;
180201095a5dSDimitry Andric   ARMCC::CondCodes Pred = getInstrPredicate(*MI, PredReg);
1803b2f21fb0SEd Schouten 
1804cf099d11SDimitry Andric   if (OddRegNum > EvenRegNum && OffImm == 0) {
1805b2f21fb0SEd Schouten     // Ascending register numbers and no offset. It's safe to change it to a
1806b2f21fb0SEd Schouten     // ldm or stm.
180759850d08SRoman Divacky     unsigned NewOpc = (isLd)
1808cf099d11SDimitry Andric       ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1809cf099d11SDimitry Andric       : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1810b2f21fb0SEd Schouten     if (isLd) {
1811b2f21fb0SEd Schouten       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1812b2f21fb0SEd Schouten         .addReg(BaseReg, getKillRegState(BaseKill))
1813b2f21fb0SEd Schouten         .addImm(Pred).addReg(PredReg)
1814b2f21fb0SEd Schouten         .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1815e6d15924SDimitry Andric         .addReg(OddReg,  getDefRegState(isLd) | getDeadRegState(OddDeadKill))
1816e6d15924SDimitry Andric         .cloneMemRefs(*MI);
1817b2f21fb0SEd Schouten       ++NumLDRD2LDM;
1818b2f21fb0SEd Schouten     } else {
1819b2f21fb0SEd Schouten       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1820b2f21fb0SEd Schouten         .addReg(BaseReg, getKillRegState(BaseKill))
1821b2f21fb0SEd Schouten         .addImm(Pred).addReg(PredReg)
182259850d08SRoman Divacky         .addReg(EvenReg,
182359850d08SRoman Divacky                 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
182459850d08SRoman Divacky         .addReg(OddReg,
1825e6d15924SDimitry Andric                 getKillRegState(OddDeadKill)  | getUndefRegState(OddUndef))
1826e6d15924SDimitry Andric         .cloneMemRefs(*MI);
1827b2f21fb0SEd Schouten       ++NumSTRD2STM;
1828b2f21fb0SEd Schouten     }
1829b2f21fb0SEd Schouten   } else {
1830b2f21fb0SEd Schouten     // Split into two instructions.
183159850d08SRoman Divacky     unsigned NewOpc = (isLd)
1832cf099d11SDimitry Andric       ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1833cf099d11SDimitry Andric       : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
183463faed5bSDimitry Andric     // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
183563faed5bSDimitry Andric     // so adjust and use t2LDRi12 here for that.
183663faed5bSDimitry Andric     unsigned NewOpc2 = (isLd)
183763faed5bSDimitry Andric       ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
183863faed5bSDimitry Andric       : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1839044eb2f6SDimitry Andric     // If this is a load, make sure the first load does not clobber the base
1840044eb2f6SDimitry Andric     // register before the second load reads it.
1841044eb2f6SDimitry Andric     if (isLd && TRI->regsOverlap(EvenReg, BaseReg)) {
1842cf099d11SDimitry Andric       assert(!TRI->regsOverlap(OddReg, BaseReg));
1843044eb2f6SDimitry Andric       InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1844e6d15924SDimitry Andric                     false, BaseReg, false, BaseUndef, Pred, PredReg, TII, MI);
1845044eb2f6SDimitry Andric       InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1846e6d15924SDimitry Andric                     false, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1847e6d15924SDimitry Andric                     MI);
1848b2f21fb0SEd Schouten     } else {
1849907da171SRoman Divacky       if (OddReg == EvenReg && EvenDeadKill) {
185066e41e3cSRoman Divacky         // If the two source operands are the same, the kill marker is
185166e41e3cSRoman Divacky         // probably on the first one. e.g.
1852044eb2f6SDimitry Andric         // t2STRDi8 killed %r5, %r5, killed %r9, 0, 14, %reg0
1853907da171SRoman Divacky         EvenDeadKill = false;
1854907da171SRoman Divacky         OddDeadKill = true;
1855907da171SRoman Divacky       }
185663faed5bSDimitry Andric       // Never kill the base register in the first instruction.
185763faed5bSDimitry Andric       if (EvenReg == BaseReg)
185863faed5bSDimitry Andric         EvenDeadKill = false;
1859044eb2f6SDimitry Andric       InsertLDR_STR(MBB, MBBI, OffImm, isLd, NewOpc, EvenReg, EvenDeadKill,
1860e6d15924SDimitry Andric                     EvenUndef, BaseReg, false, BaseUndef, Pred, PredReg, TII,
1861e6d15924SDimitry Andric                     MI);
1862044eb2f6SDimitry Andric       InsertLDR_STR(MBB, MBBI, OffImm + 4, isLd, NewOpc2, OddReg, OddDeadKill,
1863e6d15924SDimitry Andric                     OddUndef, BaseReg, BaseKill, BaseUndef, Pred, PredReg, TII,
1864e6d15924SDimitry Andric                     MI);
1865b2f21fb0SEd Schouten     }
1866b2f21fb0SEd Schouten     if (isLd)
1867b2f21fb0SEd Schouten       ++NumLDRD2LDR;
1868b2f21fb0SEd Schouten     else
1869b2f21fb0SEd Schouten       ++NumSTRD2STR;
1870b2f21fb0SEd Schouten   }
1871b2f21fb0SEd Schouten 
1872ee8648bdSDimitry Andric   MBBI = MBB.erase(MBBI);
187366e41e3cSRoman Divacky   return true;
1874b2f21fb0SEd Schouten }
1875b2f21fb0SEd Schouten 
187685d8b2bbSDimitry Andric /// An optimization pass to turn multiple LDR / STR ops of the same base and
187785d8b2bbSDimitry Andric /// incrementing offset into LDM / STM ops.
LoadStoreMultipleOpti(MachineBasicBlock & MBB)1878009b1c42SEd Schouten bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
1879009b1c42SEd Schouten   MemOpQueue MemOps;
1880009b1c42SEd Schouten   unsigned CurrBase = 0;
18815a5ac124SDimitry Andric   unsigned CurrOpc = ~0u;
1882009b1c42SEd Schouten   ARMCC::CondCodes CurrPred = ARMCC::AL;
1883009b1c42SEd Schouten   unsigned Position = 0;
1884ee8648bdSDimitry Andric   assert(Candidates.size() == 0);
1885dd58ef01SDimitry Andric   assert(MergeBaseCandidates.size() == 0);
1886ee8648bdSDimitry Andric   LiveRegsValid = false;
1887009b1c42SEd Schouten 
1888ee8648bdSDimitry Andric   for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1889ee8648bdSDimitry Andric        I = MBBI) {
1890ee8648bdSDimitry Andric     // The instruction in front of the iterator is the one we look at.
1891ee8648bdSDimitry Andric     MBBI = std::prev(I);
1892b2f21fb0SEd Schouten     if (FixInvalidRegPairOp(MBB, MBBI))
1893b2f21fb0SEd Schouten       continue;
1894ee8648bdSDimitry Andric     ++Position;
1895b2f21fb0SEd Schouten 
1896dd58ef01SDimitry Andric     if (isMemoryOp(*MBBI)) {
18975a5ac124SDimitry Andric       unsigned Opcode = MBBI->getOpcode();
189866e41e3cSRoman Divacky       const MachineOperand &MO = MBBI->getOperand(0);
18991d5ae102SDimitry Andric       Register Reg = MO.getReg();
19001d5ae102SDimitry Andric       Register Base = getLoadStoreBaseOp(*MBBI).getReg();
1901cfca06d7SDimitry Andric       Register PredReg;
190201095a5dSDimitry Andric       ARMCC::CondCodes Pred = getInstrPredicate(*MBBI, PredReg);
190301095a5dSDimitry Andric       int Offset = getMemoryOpOffset(*MBBI);
1904ee8648bdSDimitry Andric       if (CurrBase == 0) {
1905ee8648bdSDimitry Andric         // Start of a new chain.
1906ee8648bdSDimitry Andric         CurrBase = Base;
1907ee8648bdSDimitry Andric         CurrOpc  = Opcode;
1908ee8648bdSDimitry Andric         CurrPred = Pred;
190901095a5dSDimitry Andric         MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1910ee8648bdSDimitry Andric         continue;
1911ee8648bdSDimitry Andric       }
1912ee8648bdSDimitry Andric       // Note: No need to match PredReg in the next if.
1913ee8648bdSDimitry Andric       if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
191459d6cff9SDimitry Andric         // Watch out for:
191559d6cff9SDimitry Andric         //   r4 := ldr [r0, #8]
191659d6cff9SDimitry Andric         //   r4 := ldr [r0, #4]
1917ee8648bdSDimitry Andric         // or
1918ee8648bdSDimitry Andric         //   r0 := ldr [r0]
1919ee8648bdSDimitry Andric         // If a load overrides the base register or a register loaded by
1920ee8648bdSDimitry Andric         // another load in our chain, we cannot take this instruction.
192159d6cff9SDimitry Andric         bool Overlap = false;
1922ee8648bdSDimitry Andric         if (isLoadSingle(Opcode)) {
1923ee8648bdSDimitry Andric           Overlap = (Base == Reg);
1924ee8648bdSDimitry Andric           if (!Overlap) {
1925ee8648bdSDimitry Andric             for (const MemOpQueueEntry &E : MemOps) {
1926ee8648bdSDimitry Andric               if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
192759d6cff9SDimitry Andric                 Overlap = true;
192859d6cff9SDimitry Andric                 break;
192959d6cff9SDimitry Andric               }
193059d6cff9SDimitry Andric             }
1931ee8648bdSDimitry Andric           }
1932009b1c42SEd Schouten         }
1933009b1c42SEd Schouten 
1934ee8648bdSDimitry Andric         if (!Overlap) {
1935ee8648bdSDimitry Andric           // Check offset and sort memory operation into the current chain.
1936009b1c42SEd Schouten           if (Offset > MemOps.back().Offset) {
193701095a5dSDimitry Andric             MemOps.push_back(MemOpQueueEntry(*MBBI, Offset, Position));
1938ee8648bdSDimitry Andric             continue;
1939009b1c42SEd Schouten           } else {
1940ee8648bdSDimitry Andric             MemOpQueue::iterator MI, ME;
1941ee8648bdSDimitry Andric             for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1942ee8648bdSDimitry Andric               if (Offset < MI->Offset) {
1943ee8648bdSDimitry Andric                 // Found a place to insert.
1944009b1c42SEd Schouten                 break;
1945ee8648bdSDimitry Andric               }
1946ee8648bdSDimitry Andric               if (Offset == MI->Offset) {
1947ee8648bdSDimitry Andric                 // Collision, abort.
1948ee8648bdSDimitry Andric                 MI = ME;
1949009b1c42SEd Schouten                 break;
1950009b1c42SEd Schouten               }
1951009b1c42SEd Schouten             }
1952ee8648bdSDimitry Andric             if (MI != MemOps.end()) {
195301095a5dSDimitry Andric               MemOps.insert(MI, MemOpQueueEntry(*MBBI, Offset, Position));
1954ee8648bdSDimitry Andric               continue;
1955009b1c42SEd Schouten             }
1956009b1c42SEd Schouten           }
1957009b1c42SEd Schouten         }
1958009b1c42SEd Schouten       }
1959009b1c42SEd Schouten 
1960ee8648bdSDimitry Andric       // Don't advance the iterator; The op will start a new chain next.
1961ee8648bdSDimitry Andric       MBBI = I;
1962ee8648bdSDimitry Andric       --Position;
1963ee8648bdSDimitry Andric       // Fallthrough to look into existing chain.
1964eb11fae6SDimitry Andric     } else if (MBBI->isDebugInstr()) {
1965ee8648bdSDimitry Andric       continue;
1966dd58ef01SDimitry Andric     } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1967dd58ef01SDimitry Andric                MBBI->getOpcode() == ARM::t2STRDi8) {
1968dd58ef01SDimitry Andric       // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1969dd58ef01SDimitry Andric       // remember them because we may still be able to merge add/sub into them.
197001095a5dSDimitry Andric       MergeBaseCandidates.push_back(&*MBBI);
1971dd58ef01SDimitry Andric     }
1972dd58ef01SDimitry Andric 
1973ee8648bdSDimitry Andric     // If we are here then the chain is broken; Extract candidates for a merge.
1974ee8648bdSDimitry Andric     if (MemOps.size() > 0) {
1975ee8648bdSDimitry Andric       FormCandidates(MemOps);
1976ee8648bdSDimitry Andric       // Reset for the next chain.
1977009b1c42SEd Schouten       CurrBase = 0;
19785a5ac124SDimitry Andric       CurrOpc = ~0u;
1979009b1c42SEd Schouten       CurrPred = ARMCC::AL;
1980009b1c42SEd Schouten       MemOps.clear();
1981009b1c42SEd Schouten     }
1982ee8648bdSDimitry Andric   }
1983ee8648bdSDimitry Andric   if (MemOps.size() > 0)
1984ee8648bdSDimitry Andric     FormCandidates(MemOps);
1985009b1c42SEd Schouten 
1986ee8648bdSDimitry Andric   // Sort candidates so they get processed from end to begin of the basic
1987ee8648bdSDimitry Andric   // block later; This is necessary for liveness calculation.
1988ee8648bdSDimitry Andric   auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1989ee8648bdSDimitry Andric     return M0->InsertPos < M1->InsertPos;
1990ee8648bdSDimitry Andric   };
1991d8e91e46SDimitry Andric   llvm::sort(Candidates, LessThan);
1992ee8648bdSDimitry Andric 
1993ee8648bdSDimitry Andric   // Go through list of candidates and merge.
1994ee8648bdSDimitry Andric   bool Changed = false;
1995ee8648bdSDimitry Andric   for (const MergeCandidate *Candidate : Candidates) {
1996ee8648bdSDimitry Andric     if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
1997ee8648bdSDimitry Andric       MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1998ee8648bdSDimitry Andric       // Merge preceding/trailing base inc/dec into the merged op.
1999ee8648bdSDimitry Andric       if (Merged) {
2000ee8648bdSDimitry Andric         Changed = true;
2001ee8648bdSDimitry Andric         unsigned Opcode = Merged->getOpcode();
2002dd58ef01SDimitry Andric         if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
2003dd58ef01SDimitry Andric           MergeBaseUpdateLSDouble(*Merged);
2004dd58ef01SDimitry Andric         else
2005ee8648bdSDimitry Andric           MergeBaseUpdateLSMultiple(Merged);
2006ee8648bdSDimitry Andric       } else {
2007ee8648bdSDimitry Andric         for (MachineInstr *MI : Candidate->Instrs) {
2008ee8648bdSDimitry Andric           if (MergeBaseUpdateLoadStore(MI))
2009ee8648bdSDimitry Andric             Changed = true;
2010009b1c42SEd Schouten         }
2011009b1c42SEd Schouten       }
2012ee8648bdSDimitry Andric     } else {
2013ee8648bdSDimitry Andric       assert(Candidate->Instrs.size() == 1);
2014ee8648bdSDimitry Andric       if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
2015ee8648bdSDimitry Andric         Changed = true;
2016009b1c42SEd Schouten     }
2017ee8648bdSDimitry Andric   }
2018ee8648bdSDimitry Andric   Candidates.clear();
2019dd58ef01SDimitry Andric   // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
2020dd58ef01SDimitry Andric   for (MachineInstr *MI : MergeBaseCandidates)
2021dd58ef01SDimitry Andric     MergeBaseUpdateLSDouble(*MI);
2022dd58ef01SDimitry Andric   MergeBaseCandidates.clear();
2023ee8648bdSDimitry Andric 
2024ee8648bdSDimitry Andric   return Changed;
2025009b1c42SEd Schouten }
2026009b1c42SEd Schouten 
202785d8b2bbSDimitry Andric /// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
202885d8b2bbSDimitry Andric /// into the preceding stack restore so it directly restore the value of LR
202985d8b2bbSDimitry Andric /// into pc.
20302f12f10aSRoman Divacky ///   ldmfd sp!, {..., lr}
2031009b1c42SEd Schouten ///   bx lr
20322f12f10aSRoman Divacky /// or
20332f12f10aSRoman Divacky ///   ldmfd sp!, {..., lr}
20342f12f10aSRoman Divacky ///   mov pc, lr
2035009b1c42SEd Schouten /// =>
20362f12f10aSRoman Divacky ///   ldmfd sp!, {..., pc}
MergeReturnIntoLDM(MachineBasicBlock & MBB)2037009b1c42SEd Schouten bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
20385ca98fd9SDimitry Andric   // Thumb1 LDM doesn't allow high registers.
20395ca98fd9SDimitry Andric   if (isThumb1) return false;
2040009b1c42SEd Schouten   if (MBB.empty()) return false;
2041009b1c42SEd Schouten 
2042cf099d11SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
2043b915e9e0SDimitry Andric   if (MBBI != MBB.begin() && MBBI != MBB.end() &&
20442f12f10aSRoman Divacky       (MBBI->getOpcode() == ARM::BX_RET ||
20452f12f10aSRoman Divacky        MBBI->getOpcode() == ARM::tBX_RET ||
20462f12f10aSRoman Divacky        MBBI->getOpcode() == ARM::MOVPCLR)) {
2047dd58ef01SDimitry Andric     MachineBasicBlock::iterator PrevI = std::prev(MBBI);
2048eb11fae6SDimitry Andric     // Ignore any debug instructions.
2049eb11fae6SDimitry Andric     while (PrevI->isDebugInstr() && PrevI != MBB.begin())
2050dd58ef01SDimitry Andric       --PrevI;
205101095a5dSDimitry Andric     MachineInstr &PrevMI = *PrevI;
205201095a5dSDimitry Andric     unsigned Opcode = PrevMI.getOpcode();
2053cf099d11SDimitry Andric     if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
2054cf099d11SDimitry Andric         Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
2055cf099d11SDimitry Andric         Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
205601095a5dSDimitry Andric       MachineOperand &MO = PrevMI.getOperand(PrevMI.getNumOperands() - 1);
205759850d08SRoman Divacky       if (MO.getReg() != ARM::LR)
205859850d08SRoman Divacky         return false;
2059cf099d11SDimitry Andric       unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
2060cf099d11SDimitry Andric       assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
2061cf099d11SDimitry Andric               Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
206201095a5dSDimitry Andric       PrevMI.setDesc(TII->get(NewOpc));
2063009b1c42SEd Schouten       MO.setReg(ARM::PC);
206401095a5dSDimitry Andric       PrevMI.copyImplicitOps(*MBB.getParent(), *MBBI);
2065009b1c42SEd Schouten       MBB.erase(MBBI);
2066009b1c42SEd Schouten       return true;
2067009b1c42SEd Schouten     }
2068009b1c42SEd Schouten   }
2069009b1c42SEd Schouten   return false;
2070009b1c42SEd Schouten }
2071009b1c42SEd Schouten 
CombineMovBx(MachineBasicBlock & MBB)2072dd58ef01SDimitry Andric bool ARMLoadStoreOpt::CombineMovBx(MachineBasicBlock &MBB) {
2073dd58ef01SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
2074dd58ef01SDimitry Andric   if (MBBI == MBB.begin() || MBBI == MBB.end() ||
2075dd58ef01SDimitry Andric       MBBI->getOpcode() != ARM::tBX_RET)
2076dd58ef01SDimitry Andric     return false;
2077dd58ef01SDimitry Andric 
2078dd58ef01SDimitry Andric   MachineBasicBlock::iterator Prev = MBBI;
2079dd58ef01SDimitry Andric   --Prev;
2080ac9a064cSDimitry Andric   if (Prev->getOpcode() != ARM::tMOVr ||
2081ac9a064cSDimitry Andric       !Prev->definesRegister(ARM::LR, /*TRI=*/nullptr))
2082dd58ef01SDimitry Andric     return false;
2083dd58ef01SDimitry Andric 
2084dd58ef01SDimitry Andric   for (auto Use : Prev->uses())
2085dd58ef01SDimitry Andric     if (Use.isKill()) {
2086edad5bcbSDimitry Andric       assert(STI->hasV4TOps());
208771d5a254SDimitry Andric       BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(ARM::tBX))
208871d5a254SDimitry Andric           .addReg(Use.getReg(), RegState::Kill)
208971d5a254SDimitry Andric           .add(predOps(ARMCC::AL))
209001095a5dSDimitry Andric           .copyImplicitOps(*MBBI);
2091dd58ef01SDimitry Andric       MBB.erase(MBBI);
2092dd58ef01SDimitry Andric       MBB.erase(Prev);
2093dd58ef01SDimitry Andric       return true;
2094dd58ef01SDimitry Andric     }
2095dd58ef01SDimitry Andric 
2096dd58ef01SDimitry Andric   llvm_unreachable("tMOVr doesn't kill a reg before tBX_RET?");
2097dd58ef01SDimitry Andric }
2098dd58ef01SDimitry Andric 
runOnMachineFunction(MachineFunction & Fn)2099009b1c42SEd Schouten bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2100044eb2f6SDimitry Andric   if (skipFunction(Fn.getFunction()))
210101095a5dSDimitry Andric     return false;
210201095a5dSDimitry Andric 
2103ee8648bdSDimitry Andric   MF = &Fn;
2104145449b1SDimitry Andric   STI = &Fn.getSubtarget<ARMSubtarget>();
21055a5ac124SDimitry Andric   TL = STI->getTargetLowering();
2106009b1c42SEd Schouten   AFI = Fn.getInfo<ARMFunctionInfo>();
21075a5ac124SDimitry Andric   TII = STI->getInstrInfo();
21085a5ac124SDimitry Andric   TRI = STI->getRegisterInfo();
2109dd58ef01SDimitry Andric 
2110ee8648bdSDimitry Andric   RegClassInfoValid = false;
211159850d08SRoman Divacky   isThumb2 = AFI->isThumb2Function();
21125ca98fd9SDimitry Andric   isThumb1 = AFI->isThumbFunction() && !isThumb2;
21135ca98fd9SDimitry Andric 
2114ac9a064cSDimitry Andric   bool Modified = false, ModifiedLDMReturn = false;
2115f65dcba8SDimitry Andric   for (MachineBasicBlock &MBB : Fn) {
2116009b1c42SEd Schouten     Modified |= LoadStoreMultipleOpti(MBB);
211777fc4c14SDimitry Andric     if (STI->hasV5TOps() && !AFI->shouldSignReturnAddress())
2118ac9a064cSDimitry Andric       ModifiedLDMReturn |= MergeReturnIntoLDM(MBB);
2119dd58ef01SDimitry Andric     if (isThumb1)
2120dd58ef01SDimitry Andric       Modified |= CombineMovBx(MBB);
2121009b1c42SEd Schouten   }
2122ac9a064cSDimitry Andric   Modified |= ModifiedLDMReturn;
2123ac9a064cSDimitry Andric 
2124ac9a064cSDimitry Andric   // If we merged a BX instruction into an LDM, we need to re-calculate whether
2125ac9a064cSDimitry Andric   // LR is restored. This check needs to consider the whole function, not just
2126ac9a064cSDimitry Andric   // the instruction(s) we changed, because there may be other BX returns which
2127ac9a064cSDimitry Andric   // still need LR to be restored.
2128ac9a064cSDimitry Andric   if (ModifiedLDMReturn)
2129ac9a064cSDimitry Andric     ARMFrameLowering::updateLRRestored(Fn);
2130009b1c42SEd Schouten 
2131ee8648bdSDimitry Andric   Allocator.DestroyAll();
2132009b1c42SEd Schouten   return Modified;
2133009b1c42SEd Schouten }
2134600c6fa1SEd Schouten 
2135dd58ef01SDimitry Andric #define ARM_PREALLOC_LOAD_STORE_OPT_NAME                                       \
2136dd58ef01SDimitry Andric   "ARM pre- register allocation load / store optimization pass"
2137dd58ef01SDimitry Andric 
2138600c6fa1SEd Schouten namespace {
2139044eb2f6SDimitry Andric 
214085d8b2bbSDimitry Andric   /// Pre- register allocation pass that move load / stores from consecutive
214185d8b2bbSDimitry Andric   /// locations close to make it more likely they will be combined later.
214236bf506aSRoman Divacky   struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
2143600c6fa1SEd Schouten     static char ID;
2144600c6fa1SEd Schouten 
214571d5a254SDimitry Andric     AliasAnalysis *AA;
2146522600a2SDimitry Andric     const DataLayout *TD;
2147600c6fa1SEd Schouten     const TargetInstrInfo *TII;
2148600c6fa1SEd Schouten     const TargetRegisterInfo *TRI;
2149b2f21fb0SEd Schouten     const ARMSubtarget *STI;
2150600c6fa1SEd Schouten     MachineRegisterInfo *MRI;
2151cfca06d7SDimitry Andric     MachineDominatorTree *DT;
215259850d08SRoman Divacky     MachineFunction *MF;
2153600c6fa1SEd Schouten 
ARMPreAllocLoadStoreOpt__anond192f79a0311::ARMPreAllocLoadStoreOpt2154044eb2f6SDimitry Andric     ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {}
2155044eb2f6SDimitry Andric 
21565ca98fd9SDimitry Andric     bool runOnMachineFunction(MachineFunction &Fn) override;
2157600c6fa1SEd Schouten 
getPassName__anond192f79a0311::ARMPreAllocLoadStoreOpt2158b915e9e0SDimitry Andric     StringRef getPassName() const override {
2159dd58ef01SDimitry Andric       return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
2160600c6fa1SEd Schouten     }
2161600c6fa1SEd Schouten 
getAnalysisUsage__anond192f79a0311::ARMPreAllocLoadStoreOpt2162044eb2f6SDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
216371d5a254SDimitry Andric       AU.addRequired<AAResultsWrapperPass>();
2164ac9a064cSDimitry Andric       AU.addRequired<MachineDominatorTreeWrapperPass>();
2165ac9a064cSDimitry Andric       AU.addPreserved<MachineDominatorTreeWrapperPass>();
216671d5a254SDimitry Andric       MachineFunctionPass::getAnalysisUsage(AU);
216771d5a254SDimitry Andric     }
216871d5a254SDimitry Andric 
2169600c6fa1SEd Schouten   private:
2170b2f21fb0SEd Schouten     bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
2171cfca06d7SDimitry Andric                           unsigned &NewOpc, Register &EvenReg, Register &OddReg,
2172cfca06d7SDimitry Andric                           Register &BaseReg, int &Offset, Register &PredReg,
2173cfca06d7SDimitry Andric                           ARMCC::CondCodes &Pred, bool &isT2);
21747fa27ce4SDimitry Andric     bool RescheduleOps(
21757fa27ce4SDimitry Andric         MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops,
21767fa27ce4SDimitry Andric         unsigned Base, bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,
21777fa27ce4SDimitry Andric         SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap);
2178600c6fa1SEd Schouten     bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
2179cfca06d7SDimitry Andric     bool DistributeIncrements();
2180cfca06d7SDimitry Andric     bool DistributeIncrements(Register Base);
2181600c6fa1SEd Schouten   };
2182044eb2f6SDimitry Andric 
2183044eb2f6SDimitry Andric } // end anonymous namespace
2184044eb2f6SDimitry Andric 
2185600c6fa1SEd Schouten char ARMPreAllocLoadStoreOpt::ID = 0;
2186600c6fa1SEd Schouten 
2187cfca06d7SDimitry Andric INITIALIZE_PASS_BEGIN(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
2188cfca06d7SDimitry Andric                       ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
2189ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
2190cfca06d7SDimitry Andric INITIALIZE_PASS_END(ARMPreAllocLoadStoreOpt, "arm-prera-ldst-opt",
2191dd58ef01SDimitry Andric                     ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
2192dd58ef01SDimitry Andric 
2193e6d15924SDimitry Andric // Limit the number of instructions to be rescheduled.
2194e6d15924SDimitry Andric // FIXME: tune this limit, and/or come up with some better heuristics.
2195e6d15924SDimitry Andric static cl::opt<unsigned> InstReorderLimit("arm-prera-ldst-opt-reorder-limit",
2196e6d15924SDimitry Andric                                           cl::init(8), cl::Hidden);
2197e6d15924SDimitry Andric 
runOnMachineFunction(MachineFunction & Fn)2198600c6fa1SEd Schouten bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2199044eb2f6SDimitry Andric   if (AssumeMisalignedLoadStores || skipFunction(Fn.getFunction()))
220001095a5dSDimitry Andric     return false;
220101095a5dSDimitry Andric 
2202dd58ef01SDimitry Andric   TD = &Fn.getDataLayout();
2203145449b1SDimitry Andric   STI = &Fn.getSubtarget<ARMSubtarget>();
22045a5ac124SDimitry Andric   TII = STI->getInstrInfo();
22055a5ac124SDimitry Andric   TRI = STI->getRegisterInfo();
2206600c6fa1SEd Schouten   MRI = &Fn.getRegInfo();
2207ac9a064cSDimitry Andric   DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
220859850d08SRoman Divacky   MF  = &Fn;
220971d5a254SDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2210600c6fa1SEd Schouten 
2211cfca06d7SDimitry Andric   bool Modified = DistributeIncrements();
2212dd58ef01SDimitry Andric   for (MachineBasicBlock &MFI : Fn)
2213dd58ef01SDimitry Andric     Modified |= RescheduleLoadStoreInstrs(&MFI);
2214600c6fa1SEd Schouten 
2215600c6fa1SEd Schouten   return Modified;
2216600c6fa1SEd Schouten }
2217600c6fa1SEd Schouten 
IsSafeAndProfitableToMove(bool isLd,unsigned Base,MachineBasicBlock::iterator I,MachineBasicBlock::iterator E,SmallPtrSetImpl<MachineInstr * > & MemOps,SmallSet<unsigned,4> & MemRegs,const TargetRegisterInfo * TRI,AliasAnalysis * AA)2218b2f21fb0SEd Schouten static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
2219600c6fa1SEd Schouten                                       MachineBasicBlock::iterator I,
2220600c6fa1SEd Schouten                                       MachineBasicBlock::iterator E,
222167c32a98SDimitry Andric                                       SmallPtrSetImpl<MachineInstr*> &MemOps,
2222b2f21fb0SEd Schouten                                       SmallSet<unsigned, 4> &MemRegs,
222371d5a254SDimitry Andric                                       const TargetRegisterInfo *TRI,
222471d5a254SDimitry Andric                                       AliasAnalysis *AA) {
2225600c6fa1SEd Schouten   // Are there stores / loads / calls between them?
2226b2f21fb0SEd Schouten   SmallSet<unsigned, 4> AddedRegPressure;
2227600c6fa1SEd Schouten   while (++I != E) {
2228eb11fae6SDimitry Andric     if (I->isDebugInstr() || MemOps.count(&*I))
2229b2f21fb0SEd Schouten       continue;
223063faed5bSDimitry Andric     if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
2231600c6fa1SEd Schouten       return false;
223271d5a254SDimitry Andric     if (I->mayStore() || (!isLd && I->mayLoad()))
223371d5a254SDimitry Andric       for (MachineInstr *MemOp : MemOps)
223471d5a254SDimitry Andric         if (I->mayAlias(AA, *MemOp, /*UseTBAA*/ false))
2235600c6fa1SEd Schouten           return false;
2236600c6fa1SEd Schouten     for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
2237600c6fa1SEd Schouten       MachineOperand &MO = I->getOperand(j);
2238b2f21fb0SEd Schouten       if (!MO.isReg())
2239b2f21fb0SEd Schouten         continue;
22401d5ae102SDimitry Andric       Register Reg = MO.getReg();
2241b2f21fb0SEd Schouten       if (MO.isDef() && TRI->regsOverlap(Reg, Base))
2242600c6fa1SEd Schouten         return false;
2243b2f21fb0SEd Schouten       if (Reg != Base && !MemRegs.count(Reg))
2244b2f21fb0SEd Schouten         AddedRegPressure.insert(Reg);
2245600c6fa1SEd Schouten     }
2246600c6fa1SEd Schouten   }
2247b2f21fb0SEd Schouten 
2248b2f21fb0SEd Schouten   // Estimate register pressure increase due to the transformation.
2249b2f21fb0SEd Schouten   if (MemRegs.size() <= 4)
2250b2f21fb0SEd Schouten     // Ok if we are moving small number of instructions.
2251b2f21fb0SEd Schouten     return true;
2252b2f21fb0SEd Schouten   return AddedRegPressure.size() <= MemRegs.size() * 2;
2253b2f21fb0SEd Schouten }
2254b2f21fb0SEd Schouten 
CanFormLdStDWord(MachineInstr * Op0,MachineInstr * Op1,DebugLoc & dl,unsigned & NewOpc,Register & FirstReg,Register & SecondReg,Register & BaseReg,int & Offset,Register & PredReg,ARMCC::CondCodes & Pred,bool & isT2)2255cfca06d7SDimitry Andric bool ARMPreAllocLoadStoreOpt::CanFormLdStDWord(
2256cfca06d7SDimitry Andric     MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl, unsigned &NewOpc,
2257cfca06d7SDimitry Andric     Register &FirstReg, Register &SecondReg, Register &BaseReg, int &Offset,
2258cfca06d7SDimitry Andric     Register &PredReg, ARMCC::CondCodes &Pred, bool &isT2) {
225959850d08SRoman Divacky   // Make sure we're allowed to generate LDRD/STRD.
226059850d08SRoman Divacky   if (!STI->hasV5TEOps())
226159850d08SRoman Divacky     return false;
226259850d08SRoman Divacky 
2263907da171SRoman Divacky   // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
226459850d08SRoman Divacky   unsigned Scale = 1;
2265b2f21fb0SEd Schouten   unsigned Opcode = Op0->getOpcode();
22665ca98fd9SDimitry Andric   if (Opcode == ARM::LDRi12) {
2267b2f21fb0SEd Schouten     NewOpc = ARM::LDRD;
22685ca98fd9SDimitry Andric   } else if (Opcode == ARM::STRi12) {
2269b2f21fb0SEd Schouten     NewOpc = ARM::STRD;
22705ca98fd9SDimitry Andric   } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
227159850d08SRoman Divacky     NewOpc = ARM::t2LDRDi8;
227259850d08SRoman Divacky     Scale = 4;
227359850d08SRoman Divacky     isT2 = true;
227459850d08SRoman Divacky   } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
227559850d08SRoman Divacky     NewOpc = ARM::t2STRDi8;
227659850d08SRoman Divacky     Scale = 4;
227759850d08SRoman Divacky     isT2 = true;
22785ca98fd9SDimitry Andric   } else {
227959850d08SRoman Divacky     return false;
22805ca98fd9SDimitry Andric   }
228159850d08SRoman Divacky 
2282cf099d11SDimitry Andric   // Make sure the base address satisfies i64 ld / st alignment requirement.
2283f8af5cf6SDimitry Andric   // At the moment, we ignore the memoryoperand's value.
2284f8af5cf6SDimitry Andric   // If we want to use AliasAnalysis, we should check it accordingly.
2285b2f21fb0SEd Schouten   if (!Op0->hasOneMemOperand() ||
2286e6d15924SDimitry Andric       (*Op0->memoperands_begin())->isVolatile() ||
2287e6d15924SDimitry Andric       (*Op0->memoperands_begin())->isAtomic())
2288b2f21fb0SEd Schouten     return false;
2289b2f21fb0SEd Schouten 
2290cfca06d7SDimitry Andric   Align Alignment = (*Op0->memoperands_begin())->getAlign();
22917fa27ce4SDimitry Andric   Align ReqAlign = STI->getDualLoadStoreAlignment();
2292cfca06d7SDimitry Andric   if (Alignment < ReqAlign)
2293b2f21fb0SEd Schouten     return false;
2294b2f21fb0SEd Schouten 
2295b2f21fb0SEd Schouten   // Then make sure the immediate offset fits.
229601095a5dSDimitry Andric   int OffImm = getMemoryOpOffset(*Op0);
229759850d08SRoman Divacky   if (isT2) {
229859850d08SRoman Divacky     int Limit = (1 << 8) * Scale;
22996b943ff3SDimitry Andric     if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
230059850d08SRoman Divacky       return false;
230159850d08SRoman Divacky     Offset = OffImm;
230259850d08SRoman Divacky   } else {
2303b2f21fb0SEd Schouten     ARM_AM::AddrOpc AddSub = ARM_AM::add;
2304b2f21fb0SEd Schouten     if (OffImm < 0) {
2305b2f21fb0SEd Schouten       AddSub = ARM_AM::sub;
2306b2f21fb0SEd Schouten       OffImm = - OffImm;
2307b2f21fb0SEd Schouten     }
230859850d08SRoman Divacky     int Limit = (1 << 8) * Scale;
230959850d08SRoman Divacky     if (OffImm >= Limit || (OffImm & (Scale-1)))
2310b2f21fb0SEd Schouten       return false;
2311b2f21fb0SEd Schouten     Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
231259850d08SRoman Divacky   }
231385d8b2bbSDimitry Andric   FirstReg = Op0->getOperand(0).getReg();
231485d8b2bbSDimitry Andric   SecondReg = Op1->getOperand(0).getReg();
231585d8b2bbSDimitry Andric   if (FirstReg == SecondReg)
2316b2f21fb0SEd Schouten     return false;
2317b2f21fb0SEd Schouten   BaseReg = Op0->getOperand(1).getReg();
231801095a5dSDimitry Andric   Pred = getInstrPredicate(*Op0, PredReg);
2319b2f21fb0SEd Schouten   dl = Op0->getDebugLoc();
2320600c6fa1SEd Schouten   return true;
2321600c6fa1SEd Schouten }
2322600c6fa1SEd Schouten 
RescheduleOps(MachineBasicBlock * MBB,SmallVectorImpl<MachineInstr * > & Ops,unsigned Base,bool isLd,DenseMap<MachineInstr *,unsigned> & MI2LocMap,SmallDenseMap<Register,SmallVector<MachineInstr * >,8> & RegisterMap)23237fa27ce4SDimitry Andric bool ARMPreAllocLoadStoreOpt::RescheduleOps(
23247fa27ce4SDimitry Andric     MachineBasicBlock *MBB, SmallVectorImpl<MachineInstr *> &Ops, unsigned Base,
23257fa27ce4SDimitry Andric     bool isLd, DenseMap<MachineInstr *, unsigned> &MI2LocMap,
23267fa27ce4SDimitry Andric     SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap) {
2327600c6fa1SEd Schouten   bool RetVal = false;
2328600c6fa1SEd Schouten 
2329600c6fa1SEd Schouten   // Sort by offset (in reverse order).
2330d8e91e46SDimitry Andric   llvm::sort(Ops, [](const MachineInstr *LHS, const MachineInstr *RHS) {
233101095a5dSDimitry Andric     int LOffset = getMemoryOpOffset(*LHS);
233201095a5dSDimitry Andric     int ROffset = getMemoryOpOffset(*RHS);
23335ca98fd9SDimitry Andric     assert(LHS == RHS || LOffset != ROffset);
23345ca98fd9SDimitry Andric     return LOffset > ROffset;
23355ca98fd9SDimitry Andric   });
2336600c6fa1SEd Schouten 
2337600c6fa1SEd Schouten   // The loads / stores of the same base are in order. Scan them from first to
233866e41e3cSRoman Divacky   // last and check for the following:
2339600c6fa1SEd Schouten   // 1. Any def of base.
2340600c6fa1SEd Schouten   // 2. Any gaps.
2341600c6fa1SEd Schouten   while (Ops.size() > 1) {
2342600c6fa1SEd Schouten     unsigned FirstLoc = ~0U;
2343600c6fa1SEd Schouten     unsigned LastLoc = 0;
23445ca98fd9SDimitry Andric     MachineInstr *FirstOp = nullptr;
23455ca98fd9SDimitry Andric     MachineInstr *LastOp = nullptr;
2346600c6fa1SEd Schouten     int LastOffset = 0;
2347b2f21fb0SEd Schouten     unsigned LastOpcode = 0;
2348600c6fa1SEd Schouten     unsigned LastBytes = 0;
2349600c6fa1SEd Schouten     unsigned NumMove = 0;
235077fc4c14SDimitry Andric     for (MachineInstr *Op : llvm::reverse(Ops)) {
235171d5a254SDimitry Andric       // Make sure each operation has the same kind.
235271d5a254SDimitry Andric       unsigned LSMOpcode
235371d5a254SDimitry Andric         = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
235471d5a254SDimitry Andric       if (LastOpcode && LSMOpcode != LastOpcode)
235571d5a254SDimitry Andric         break;
235671d5a254SDimitry Andric 
235771d5a254SDimitry Andric       // Check that we have a continuous set of offsets.
235871d5a254SDimitry Andric       int Offset = getMemoryOpOffset(*Op);
235971d5a254SDimitry Andric       unsigned Bytes = getLSMultipleTransferSize(Op);
236071d5a254SDimitry Andric       if (LastBytes) {
236171d5a254SDimitry Andric         if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
236271d5a254SDimitry Andric           break;
236371d5a254SDimitry Andric       }
236471d5a254SDimitry Andric 
236571d5a254SDimitry Andric       // Don't try to reschedule too many instructions.
2366e6d15924SDimitry Andric       if (NumMove == InstReorderLimit)
236771d5a254SDimitry Andric         break;
236871d5a254SDimitry Andric 
236971d5a254SDimitry Andric       // Found a mergable instruction; save information about it.
237071d5a254SDimitry Andric       ++NumMove;
237171d5a254SDimitry Andric       LastOffset = Offset;
237271d5a254SDimitry Andric       LastBytes = Bytes;
237371d5a254SDimitry Andric       LastOpcode = LSMOpcode;
237471d5a254SDimitry Andric 
2375600c6fa1SEd Schouten       unsigned Loc = MI2LocMap[Op];
2376600c6fa1SEd Schouten       if (Loc <= FirstLoc) {
2377600c6fa1SEd Schouten         FirstLoc = Loc;
2378600c6fa1SEd Schouten         FirstOp = Op;
2379600c6fa1SEd Schouten       }
2380600c6fa1SEd Schouten       if (Loc >= LastLoc) {
2381600c6fa1SEd Schouten         LastLoc = Loc;
2382600c6fa1SEd Schouten         LastOp = Op;
2383600c6fa1SEd Schouten       }
2384600c6fa1SEd Schouten     }
2385600c6fa1SEd Schouten 
2386600c6fa1SEd Schouten     if (NumMove <= 1)
2387600c6fa1SEd Schouten       Ops.pop_back();
2388600c6fa1SEd Schouten     else {
2389b2f21fb0SEd Schouten       SmallPtrSet<MachineInstr*, 4> MemOps;
2390b2f21fb0SEd Schouten       SmallSet<unsigned, 4> MemRegs;
239171d5a254SDimitry Andric       for (size_t i = Ops.size() - NumMove, e = Ops.size(); i != e; ++i) {
2392b2f21fb0SEd Schouten         MemOps.insert(Ops[i]);
2393b2f21fb0SEd Schouten         MemRegs.insert(Ops[i]->getOperand(0).getReg());
2394b2f21fb0SEd Schouten       }
2395600c6fa1SEd Schouten 
2396600c6fa1SEd Schouten       // Be conservative, if the instructions are too far apart, don't
2397600c6fa1SEd Schouten       // move them. We want to limit the increase of register pressure.
2398b2f21fb0SEd Schouten       bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
2399600c6fa1SEd Schouten       if (DoMove)
2400b2f21fb0SEd Schouten         DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
240171d5a254SDimitry Andric                                            MemOps, MemRegs, TRI, AA);
2402600c6fa1SEd Schouten       if (!DoMove) {
2403600c6fa1SEd Schouten         for (unsigned i = 0; i != NumMove; ++i)
2404600c6fa1SEd Schouten           Ops.pop_back();
2405600c6fa1SEd Schouten       } else {
2406600c6fa1SEd Schouten         // This is the new location for the loads / stores.
2407600c6fa1SEd Schouten         MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
240801095a5dSDimitry Andric         while (InsertPos != MBB->end() &&
2409eb11fae6SDimitry Andric                (MemOps.count(&*InsertPos) || InsertPos->isDebugInstr()))
2410600c6fa1SEd Schouten           ++InsertPos;
2411b2f21fb0SEd Schouten 
2412b2f21fb0SEd Schouten         // If we are moving a pair of loads / stores, see if it makes sense
2413b2f21fb0SEd Schouten         // to try to allocate a pair of registers that can form register pairs.
2414b2f21fb0SEd Schouten         MachineInstr *Op0 = Ops.back();
2415b2f21fb0SEd Schouten         MachineInstr *Op1 = Ops[Ops.size()-2];
2416cfca06d7SDimitry Andric         Register FirstReg, SecondReg;
2417cfca06d7SDimitry Andric         Register BaseReg, PredReg;
2418b2f21fb0SEd Schouten         ARMCC::CondCodes Pred = ARMCC::AL;
241959850d08SRoman Divacky         bool isT2 = false;
2420b2f21fb0SEd Schouten         unsigned NewOpc = 0;
242159850d08SRoman Divacky         int Offset = 0;
2422b2f21fb0SEd Schouten         DebugLoc dl;
2423b2f21fb0SEd Schouten         if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
242485d8b2bbSDimitry Andric                                              FirstReg, SecondReg, BaseReg,
242559850d08SRoman Divacky                                              Offset, PredReg, Pred, isT2)) {
2426b2f21fb0SEd Schouten           Ops.pop_back();
2427b2f21fb0SEd Schouten           Ops.pop_back();
2428b2f21fb0SEd Schouten 
2429411bd29eSDimitry Andric           const MCInstrDesc &MCID = TII->get(NewOpc);
243058b69754SDimitry Andric           const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
243185d8b2bbSDimitry Andric           MRI->constrainRegClass(FirstReg, TRC);
243285d8b2bbSDimitry Andric           MRI->constrainRegClass(SecondReg, TRC);
243356fe8f14SDimitry Andric 
2434b2f21fb0SEd Schouten           // Form the pair instruction.
2435b2f21fb0SEd Schouten           if (isLd) {
2436411bd29eSDimitry Andric             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
243785d8b2bbSDimitry Andric               .addReg(FirstReg, RegState::Define)
243885d8b2bbSDimitry Andric               .addReg(SecondReg, RegState::Define)
243959850d08SRoman Divacky               .addReg(BaseReg);
2440cf099d11SDimitry Andric             // FIXME: We're converting from LDRi12 to an insn that still
2441cf099d11SDimitry Andric             // uses addrmode2, so we need an explicit offset reg. It should
2442cf099d11SDimitry Andric             // always by reg0 since we're transforming LDRi12s.
244359850d08SRoman Divacky             if (!isT2)
2444cf099d11SDimitry Andric               MIB.addReg(0);
244559850d08SRoman Divacky             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2446d8e91e46SDimitry Andric             MIB.cloneMergedMemRefs({Op0, Op1});
2447eb11fae6SDimitry Andric             LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2448b2f21fb0SEd Schouten             ++NumLDRDFormed;
2449b2f21fb0SEd Schouten           } else {
2450411bd29eSDimitry Andric             MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
245185d8b2bbSDimitry Andric               .addReg(FirstReg)
245285d8b2bbSDimitry Andric               .addReg(SecondReg)
245359850d08SRoman Divacky               .addReg(BaseReg);
2454cf099d11SDimitry Andric             // FIXME: We're converting from LDRi12 to an insn that still
2455cf099d11SDimitry Andric             // uses addrmode2, so we need an explicit offset reg. It should
2456cf099d11SDimitry Andric             // always by reg0 since we're transforming STRi12s.
245759850d08SRoman Divacky             if (!isT2)
2458cf099d11SDimitry Andric               MIB.addReg(0);
245959850d08SRoman Divacky             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
2460d8e91e46SDimitry Andric             MIB.cloneMergedMemRefs({Op0, Op1});
2461eb11fae6SDimitry Andric             LLVM_DEBUG(dbgs() << "Formed " << *MIB << "\n");
2462b2f21fb0SEd Schouten             ++NumSTRDFormed;
2463b2f21fb0SEd Schouten           }
2464b2f21fb0SEd Schouten           MBB->erase(Op0);
2465b2f21fb0SEd Schouten           MBB->erase(Op1);
2466b2f21fb0SEd Schouten 
246785d8b2bbSDimitry Andric           if (!isT2) {
2468b2f21fb0SEd Schouten             // Add register allocation hints to form register pairs.
246985d8b2bbSDimitry Andric             MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
247085d8b2bbSDimitry Andric             MRI->setRegAllocationHint(SecondReg,  ARMRI::RegPairOdd, FirstReg);
247185d8b2bbSDimitry Andric           }
2472b2f21fb0SEd Schouten         } else {
2473600c6fa1SEd Schouten           for (unsigned i = 0; i != NumMove; ++i) {
2474c0981da4SDimitry Andric             MachineInstr *Op = Ops.pop_back_val();
24757fa27ce4SDimitry Andric             if (isLd) {
24767fa27ce4SDimitry Andric               // Populate RegisterMap with all Registers defined by loads.
24777fa27ce4SDimitry Andric               Register Reg = Op->getOperand(0).getReg();
24787fa27ce4SDimitry Andric               RegisterMap[Reg];
24797fa27ce4SDimitry Andric             }
24807fa27ce4SDimitry Andric 
2481600c6fa1SEd Schouten             MBB->splice(InsertPos, MBB, Op);
2482600c6fa1SEd Schouten           }
2483b2f21fb0SEd Schouten         }
2484600c6fa1SEd Schouten 
2485600c6fa1SEd Schouten         NumLdStMoved += NumMove;
2486600c6fa1SEd Schouten         RetVal = true;
2487600c6fa1SEd Schouten       }
2488600c6fa1SEd Schouten     }
2489600c6fa1SEd Schouten   }
2490600c6fa1SEd Schouten 
2491600c6fa1SEd Schouten   return RetVal;
2492600c6fa1SEd Schouten }
2493600c6fa1SEd Schouten 
forEachDbgRegOperand(MachineInstr * MI,std::function<void (MachineOperand &)> Fn)24947fa27ce4SDimitry Andric static void forEachDbgRegOperand(MachineInstr *MI,
24957fa27ce4SDimitry Andric                                  std::function<void(MachineOperand &)> Fn) {
24967fa27ce4SDimitry Andric   if (MI->isNonListDebugValue()) {
24977fa27ce4SDimitry Andric     auto &Op = MI->getOperand(0);
24987fa27ce4SDimitry Andric     if (Op.isReg())
24997fa27ce4SDimitry Andric       Fn(Op);
25007fa27ce4SDimitry Andric   } else {
25017fa27ce4SDimitry Andric     for (unsigned I = 2; I < MI->getNumOperands(); I++) {
25027fa27ce4SDimitry Andric       auto &Op = MI->getOperand(I);
25037fa27ce4SDimitry Andric       if (Op.isReg())
25047fa27ce4SDimitry Andric         Fn(Op);
25057fa27ce4SDimitry Andric     }
25067fa27ce4SDimitry Andric   }
25077fa27ce4SDimitry Andric }
25087fa27ce4SDimitry Andric 
25097fa27ce4SDimitry Andric // Update the RegisterMap with the instruction that was moved because a
25107fa27ce4SDimitry Andric // DBG_VALUE_LIST may need to be moved again.
updateRegisterMapForDbgValueListAfterMove(SmallDenseMap<Register,SmallVector<MachineInstr * >,8> & RegisterMap,MachineInstr * DbgValueListInstr,MachineInstr * InstrToReplace)25117fa27ce4SDimitry Andric static void updateRegisterMapForDbgValueListAfterMove(
25127fa27ce4SDimitry Andric     SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> &RegisterMap,
25137fa27ce4SDimitry Andric     MachineInstr *DbgValueListInstr, MachineInstr *InstrToReplace) {
25147fa27ce4SDimitry Andric 
25157fa27ce4SDimitry Andric   forEachDbgRegOperand(DbgValueListInstr, [&](MachineOperand &Op) {
25167fa27ce4SDimitry Andric     auto RegIt = RegisterMap.find(Op.getReg());
25177fa27ce4SDimitry Andric     if (RegIt == RegisterMap.end())
25187fa27ce4SDimitry Andric       return;
25197fa27ce4SDimitry Andric     auto &InstrVec = RegIt->getSecond();
25207fa27ce4SDimitry Andric     for (unsigned I = 0; I < InstrVec.size(); I++)
25217fa27ce4SDimitry Andric       if (InstrVec[I] == InstrToReplace)
25227fa27ce4SDimitry Andric         InstrVec[I] = DbgValueListInstr;
25237fa27ce4SDimitry Andric   });
25247fa27ce4SDimitry Andric }
25257fa27ce4SDimitry Andric 
createDebugVariableFromMachineInstr(MachineInstr * MI)25267fa27ce4SDimitry Andric static DebugVariable createDebugVariableFromMachineInstr(MachineInstr *MI) {
25277fa27ce4SDimitry Andric   auto DbgVar = DebugVariable(MI->getDebugVariable(), MI->getDebugExpression(),
25287fa27ce4SDimitry Andric                               MI->getDebugLoc()->getInlinedAt());
25297fa27ce4SDimitry Andric   return DbgVar;
25307fa27ce4SDimitry Andric }
25317fa27ce4SDimitry Andric 
2532600c6fa1SEd Schouten bool
RescheduleLoadStoreInstrs(MachineBasicBlock * MBB)2533600c6fa1SEd Schouten ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2534600c6fa1SEd Schouten   bool RetVal = false;
2535600c6fa1SEd Schouten 
2536600c6fa1SEd Schouten   DenseMap<MachineInstr*, unsigned> MI2LocMap;
2537e6d15924SDimitry Andric   using MapIt = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>::iterator;
2538e6d15924SDimitry Andric   using Base2InstMap = DenseMap<unsigned, SmallVector<MachineInstr *, 4>>;
2539e6d15924SDimitry Andric   using BaseVec = SmallVector<unsigned, 4>;
2540e6d15924SDimitry Andric   Base2InstMap Base2LdsMap;
2541e6d15924SDimitry Andric   Base2InstMap Base2StsMap;
2542e6d15924SDimitry Andric   BaseVec LdBases;
2543e6d15924SDimitry Andric   BaseVec StBases;
25447fa27ce4SDimitry Andric   // This map is used to track the relationship between the virtual
25457fa27ce4SDimitry Andric   // register that is the result of a load that is moved and the DBG_VALUE
25467fa27ce4SDimitry Andric   // MachineInstr pointer that uses that virtual register.
25477fa27ce4SDimitry Andric   SmallDenseMap<Register, SmallVector<MachineInstr *>, 8> RegisterMap;
2548600c6fa1SEd Schouten 
2549600c6fa1SEd Schouten   unsigned Loc = 0;
2550600c6fa1SEd Schouten   MachineBasicBlock::iterator MBBI = MBB->begin();
2551600c6fa1SEd Schouten   MachineBasicBlock::iterator E = MBB->end();
2552600c6fa1SEd Schouten   while (MBBI != E) {
2553600c6fa1SEd Schouten     for (; MBBI != E; ++MBBI) {
255401095a5dSDimitry Andric       MachineInstr &MI = *MBBI;
255501095a5dSDimitry Andric       if (MI.isCall() || MI.isTerminator()) {
2556600c6fa1SEd Schouten         // Stop at barriers.
2557600c6fa1SEd Schouten         ++MBBI;
2558600c6fa1SEd Schouten         break;
2559600c6fa1SEd Schouten       }
2560600c6fa1SEd Schouten 
2561eb11fae6SDimitry Andric       if (!MI.isDebugInstr())
256201095a5dSDimitry Andric         MI2LocMap[&MI] = ++Loc;
256366e41e3cSRoman Divacky 
256401095a5dSDimitry Andric       if (!isMemoryOp(MI))
2565600c6fa1SEd Schouten         continue;
2566cfca06d7SDimitry Andric       Register PredReg;
256763faed5bSDimitry Andric       if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
2568600c6fa1SEd Schouten         continue;
2569600c6fa1SEd Schouten 
257001095a5dSDimitry Andric       int Opc = MI.getOpcode();
2571ee8648bdSDimitry Andric       bool isLd = isLoadSingle(Opc);
25721d5ae102SDimitry Andric       Register Base = MI.getOperand(1).getReg();
2573600c6fa1SEd Schouten       int Offset = getMemoryOpOffset(MI);
2574600c6fa1SEd Schouten       bool StopHere = false;
2575e6d15924SDimitry Andric       auto FindBases = [&] (Base2InstMap &Base2Ops, BaseVec &Bases) {
2576e6d15924SDimitry Andric         MapIt BI = Base2Ops.find(Base);
2577e6d15924SDimitry Andric         if (BI == Base2Ops.end()) {
2578e6d15924SDimitry Andric           Base2Ops[Base].push_back(&MI);
2579e6d15924SDimitry Andric           Bases.push_back(Base);
2580e6d15924SDimitry Andric           return;
2581e6d15924SDimitry Andric         }
2582ac9a064cSDimitry Andric         for (const MachineInstr *MI : BI->second) {
2583ac9a064cSDimitry Andric           if (Offset == getMemoryOpOffset(*MI)) {
2584600c6fa1SEd Schouten             StopHere = true;
2585600c6fa1SEd Schouten             break;
2586600c6fa1SEd Schouten           }
2587600c6fa1SEd Schouten         }
2588600c6fa1SEd Schouten         if (!StopHere)
258901095a5dSDimitry Andric           BI->second.push_back(&MI);
2590e6d15924SDimitry Andric       };
2591e6d15924SDimitry Andric 
2592e6d15924SDimitry Andric       if (isLd)
2593e6d15924SDimitry Andric         FindBases(Base2LdsMap, LdBases);
2594e6d15924SDimitry Andric       else
2595e6d15924SDimitry Andric         FindBases(Base2StsMap, StBases);
2596600c6fa1SEd Schouten 
2597600c6fa1SEd Schouten       if (StopHere) {
2598b2f21fb0SEd Schouten         // Found a duplicate (a base+offset combination that's seen earlier).
2599b2f21fb0SEd Schouten         // Backtrack.
2600600c6fa1SEd Schouten         --Loc;
2601600c6fa1SEd Schouten         break;
2602600c6fa1SEd Schouten       }
2603600c6fa1SEd Schouten     }
2604600c6fa1SEd Schouten 
2605600c6fa1SEd Schouten     // Re-schedule loads.
260699aabd70SDimitry Andric     for (unsigned Base : LdBases) {
2607f8af5cf6SDimitry Andric       SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
2608600c6fa1SEd Schouten       if (Lds.size() > 1)
26097fa27ce4SDimitry Andric         RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap, RegisterMap);
2610600c6fa1SEd Schouten     }
2611600c6fa1SEd Schouten 
2612600c6fa1SEd Schouten     // Re-schedule stores.
261399aabd70SDimitry Andric     for (unsigned Base : StBases) {
2614f8af5cf6SDimitry Andric       SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
2615600c6fa1SEd Schouten       if (Sts.size() > 1)
26167fa27ce4SDimitry Andric         RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap, RegisterMap);
2617600c6fa1SEd Schouten     }
2618600c6fa1SEd Schouten 
2619600c6fa1SEd Schouten     if (MBBI != E) {
2620600c6fa1SEd Schouten       Base2LdsMap.clear();
2621600c6fa1SEd Schouten       Base2StsMap.clear();
2622600c6fa1SEd Schouten       LdBases.clear();
2623600c6fa1SEd Schouten       StBases.clear();
2624600c6fa1SEd Schouten     }
2625600c6fa1SEd Schouten   }
2626600c6fa1SEd Schouten 
26277fa27ce4SDimitry Andric   // Reschedule DBG_VALUEs to match any loads that were moved. When a load is
26287fa27ce4SDimitry Andric   // sunk beyond a DBG_VALUE that is referring to it, the DBG_VALUE becomes a
26297fa27ce4SDimitry Andric   // use-before-def, resulting in a loss of debug info.
26307fa27ce4SDimitry Andric 
26317fa27ce4SDimitry Andric   // Example:
26327fa27ce4SDimitry Andric   // Before the Pre Register Allocation Load Store Pass
26337fa27ce4SDimitry Andric   // inst_a
26347fa27ce4SDimitry Andric   // %2 = ld ...
26357fa27ce4SDimitry Andric   // inst_b
26367fa27ce4SDimitry Andric   // DBG_VALUE %2, "x", ...
26377fa27ce4SDimitry Andric   // %3 = ld ...
26387fa27ce4SDimitry Andric 
26397fa27ce4SDimitry Andric   // After the Pass:
26407fa27ce4SDimitry Andric   // inst_a
26417fa27ce4SDimitry Andric   // inst_b
26427fa27ce4SDimitry Andric   // DBG_VALUE %2, "x", ...
26437fa27ce4SDimitry Andric   // %2 = ld ...
26447fa27ce4SDimitry Andric   // %3 = ld ...
26457fa27ce4SDimitry Andric 
26467fa27ce4SDimitry Andric   // The code below addresses this by moving the DBG_VALUE to the position
26477fa27ce4SDimitry Andric   // immediately after the load.
26487fa27ce4SDimitry Andric 
26497fa27ce4SDimitry Andric   // Example:
26507fa27ce4SDimitry Andric   // After the code below:
26517fa27ce4SDimitry Andric   // inst_a
26527fa27ce4SDimitry Andric   // inst_b
26537fa27ce4SDimitry Andric   // %2 = ld ...
26547fa27ce4SDimitry Andric   // DBG_VALUE %2, "x", ...
26557fa27ce4SDimitry Andric   // %3 = ld ...
26567fa27ce4SDimitry Andric 
26577fa27ce4SDimitry Andric   // The algorithm works in two phases: First RescheduleOps() populates the
26587fa27ce4SDimitry Andric   // RegisterMap with registers that were moved as keys, there is no value
26597fa27ce4SDimitry Andric   // inserted. In the next phase, every MachineInstr in a basic block is
26607fa27ce4SDimitry Andric   // iterated over. If it is a valid DBG_VALUE or DBG_VALUE_LIST and it uses one
26617fa27ce4SDimitry Andric   // or more registers in the RegisterMap, the RegisterMap and InstrMap are
26627fa27ce4SDimitry Andric   // populated with the MachineInstr. If the DBG_VALUE or DBG_VALUE_LIST
26637fa27ce4SDimitry Andric   // describes debug information for a variable that already exists in the
26647fa27ce4SDimitry Andric   // DbgValueSinkCandidates, the MachineInstr in the DbgValueSinkCandidates must
26657fa27ce4SDimitry Andric   // be set to undef. If the current MachineInstr is a load that was moved,
26667fa27ce4SDimitry Andric   // undef the corresponding DBG_VALUE or DBG_VALUE_LIST and clone it to below
26677fa27ce4SDimitry Andric   // the load.
26687fa27ce4SDimitry Andric 
26697fa27ce4SDimitry Andric   // To illustrate the above algorithm visually let's take this example.
26707fa27ce4SDimitry Andric 
26717fa27ce4SDimitry Andric   // Before the Pre Register Allocation Load Store Pass:
26727fa27ce4SDimitry Andric   // %2 = ld ...
26737fa27ce4SDimitry Andric   // DBG_VALUE %2, A, .... # X
26747fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
26757fa27ce4SDimitry Andric   // %3 = ld ...
26767fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
26777fa27ce4SDimitry Andric   // %4 = ld ...
26787fa27ce4SDimitry Andric 
26797fa27ce4SDimitry Andric   // After Pre Register Allocation Load Store Pass:
26807fa27ce4SDimitry Andric   // DBG_VALUE %2, A, .... # X
26817fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
26827fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
26837fa27ce4SDimitry Andric   // %2 = ld ...
26847fa27ce4SDimitry Andric   // %3 = ld ...
26857fa27ce4SDimitry Andric   // %4 = ld ...
26867fa27ce4SDimitry Andric 
26877fa27ce4SDimitry Andric   // The algorithm below does the following:
26887fa27ce4SDimitry Andric 
26897fa27ce4SDimitry Andric   // In the beginning, the RegisterMap will have been populated with the virtual
26907fa27ce4SDimitry Andric   // registers %2, and %3, the DbgValueSinkCandidates and the InstrMap will be
26917fa27ce4SDimitry Andric   // empty. DbgValueSinkCandidates = {}, RegisterMap = {2 -> {}, 3 -> {}},
26927fa27ce4SDimitry Andric   // InstrMap {}
26937fa27ce4SDimitry Andric   // -> DBG_VALUE %2, A, .... # X
26947fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
26957fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
26967fa27ce4SDimitry Andric   // %2 = ld ...
26977fa27ce4SDimitry Andric   // %3 = ld ...
26987fa27ce4SDimitry Andric   // %4 = ld ...
26997fa27ce4SDimitry Andric 
27007fa27ce4SDimitry Andric   // After the first DBG_VALUE (denoted with an X) is processed, the
27017fa27ce4SDimitry Andric   // DbgValueSinkCandidates and InstrMap will be populated and the RegisterMap
27027fa27ce4SDimitry Andric   // entry for %2 will be populated as well. DbgValueSinkCandidates = {A -> X},
27037fa27ce4SDimitry Andric   // RegisterMap = {2 -> {X}, 3 -> {}}, InstrMap {X -> 2}
27047fa27ce4SDimitry Andric   // DBG_VALUE %2, A, .... # X
27057fa27ce4SDimitry Andric   // -> DBG_VALUE 0, A, ... # Y
27067fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
27077fa27ce4SDimitry Andric   // %2 = ld ...
27087fa27ce4SDimitry Andric   // %3 = ld ...
27097fa27ce4SDimitry Andric   // %4 = ld ...
27107fa27ce4SDimitry Andric 
27117fa27ce4SDimitry Andric   // After the DBG_VALUE Y is processed, the DbgValueSinkCandidates is updated
27127fa27ce4SDimitry Andric   // to now hold Y for A and the RegisterMap is also updated to remove X from
27137fa27ce4SDimitry Andric   // %2, this is because both X and Y describe the same debug variable A. X is
27147fa27ce4SDimitry Andric   // also updated to have a $noreg as the first operand.
27157fa27ce4SDimitry Andric   // DbgValueSinkCandidates = {A -> {Y}}, RegisterMap = {2 -> {}, 3 -> {}},
27167fa27ce4SDimitry Andric   // InstrMap = {X-> 2}
27177fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, .... # X
27187fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
27197fa27ce4SDimitry Andric   // -> DBG_VALUE %3, A, ..., # Z
27207fa27ce4SDimitry Andric   // %2 = ld ...
27217fa27ce4SDimitry Andric   // %3 = ld ...
27227fa27ce4SDimitry Andric   // %4 = ld ...
27237fa27ce4SDimitry Andric 
27247fa27ce4SDimitry Andric   // After DBG_VALUE Z is processed, the DbgValueSinkCandidates is updated to
27257fa27ce4SDimitry Andric   // hold Z fr A, the RegisterMap is updated to hold Z for %3, and the InstrMap
27267fa27ce4SDimitry Andric   // is updated to have Z mapped to %3. This is again because Z describes the
27277fa27ce4SDimitry Andric   // debug variable A, Y is not updated to have $noreg as first operand because
27287fa27ce4SDimitry Andric   // its first operand is an immediate, not a register.
27297fa27ce4SDimitry Andric   // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
27307fa27ce4SDimitry Andric   // InstrMap = {X -> 2, Z -> 3}
27317fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, .... # X
27327fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
27337fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
27347fa27ce4SDimitry Andric   // -> %2 = ld ...
27357fa27ce4SDimitry Andric   // %3 = ld ...
27367fa27ce4SDimitry Andric   // %4 = ld ...
27377fa27ce4SDimitry Andric 
27387fa27ce4SDimitry Andric   // Nothing happens here since the RegisterMap for %2 contains no value.
27397fa27ce4SDimitry Andric   // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
27407fa27ce4SDimitry Andric   // InstrMap = {X -> 2, Z -> 3}
27417fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, .... # X
27427fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
27437fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
27447fa27ce4SDimitry Andric   // %2 = ld ...
27457fa27ce4SDimitry Andric   // -> %3 = ld ...
27467fa27ce4SDimitry Andric   // %4 = ld ...
27477fa27ce4SDimitry Andric 
27487fa27ce4SDimitry Andric   // Since the RegisterMap contains Z as a value for %3, the MachineInstr
27497fa27ce4SDimitry Andric   // pointer Z is copied to come after the load for %3 and the old Z's first
27507fa27ce4SDimitry Andric   // operand is changed to $noreg the Basic Block iterator is moved to after the
27517fa27ce4SDimitry Andric   // DBG_VALUE Z's new position.
27527fa27ce4SDimitry Andric   // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
27537fa27ce4SDimitry Andric   // InstrMap = {X -> 2, Z -> 3}
27547fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, .... # X
27557fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
27567fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, ..., # Old Z
27577fa27ce4SDimitry Andric   // %2 = ld ...
27587fa27ce4SDimitry Andric   // %3 = ld ...
27597fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
27607fa27ce4SDimitry Andric   // -> %4 = ld ...
27617fa27ce4SDimitry Andric 
27627fa27ce4SDimitry Andric   // Nothing happens for %4 and the algorithm exits having processed the entire
27637fa27ce4SDimitry Andric   // Basic Block.
27647fa27ce4SDimitry Andric   // DbgValueSinkCandidates = {A -> {Z}}, RegisterMap = {2 -> {}, 3 -> {Z}},
27657fa27ce4SDimitry Andric   // InstrMap = {X -> 2, Z -> 3}
27667fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, .... # X
27677fa27ce4SDimitry Andric   // DBG_VALUE 0, A, ... # Y
27687fa27ce4SDimitry Andric   // DBG_VALUE $noreg, A, ..., # Old Z
27697fa27ce4SDimitry Andric   // %2 = ld ...
27707fa27ce4SDimitry Andric   // %3 = ld ...
27717fa27ce4SDimitry Andric   // DBG_VALUE %3, A, ..., # Z
27727fa27ce4SDimitry Andric   // %4 = ld ...
27737fa27ce4SDimitry Andric 
27747fa27ce4SDimitry Andric   // This map is used to track the relationship between
27757fa27ce4SDimitry Andric   // a Debug Variable and the DBG_VALUE MachineInstr pointer that describes the
27767fa27ce4SDimitry Andric   // debug information for that Debug Variable.
27777fa27ce4SDimitry Andric   SmallDenseMap<DebugVariable, MachineInstr *, 8> DbgValueSinkCandidates;
27787fa27ce4SDimitry Andric   // This map is used to track the relationship between a DBG_VALUE or
27797fa27ce4SDimitry Andric   // DBG_VALUE_LIST MachineInstr pointer and Registers that it uses.
27807fa27ce4SDimitry Andric   SmallDenseMap<MachineInstr *, SmallVector<Register>, 8> InstrMap;
27817fa27ce4SDimitry Andric   for (MBBI = MBB->begin(), E = MBB->end(); MBBI != E; ++MBBI) {
27827fa27ce4SDimitry Andric     MachineInstr &MI = *MBBI;
27837fa27ce4SDimitry Andric 
27847fa27ce4SDimitry Andric     auto PopulateRegisterAndInstrMapForDebugInstr = [&](Register Reg) {
27857fa27ce4SDimitry Andric       auto RegIt = RegisterMap.find(Reg);
27867fa27ce4SDimitry Andric       if (RegIt == RegisterMap.end())
27877fa27ce4SDimitry Andric         return;
27887fa27ce4SDimitry Andric       auto &InstrVec = RegIt->getSecond();
27897fa27ce4SDimitry Andric       InstrVec.push_back(&MI);
27907fa27ce4SDimitry Andric       InstrMap[&MI].push_back(Reg);
27917fa27ce4SDimitry Andric     };
27927fa27ce4SDimitry Andric 
27937fa27ce4SDimitry Andric     if (MI.isDebugValue()) {
27947fa27ce4SDimitry Andric       assert(MI.getDebugVariable() &&
27957fa27ce4SDimitry Andric              "DBG_VALUE or DBG_VALUE_LIST must contain a DILocalVariable");
27967fa27ce4SDimitry Andric 
27977fa27ce4SDimitry Andric       auto DbgVar = createDebugVariableFromMachineInstr(&MI);
27987fa27ce4SDimitry Andric       // If the first operand is a register and it exists in the RegisterMap, we
27997fa27ce4SDimitry Andric       // know this is a DBG_VALUE that uses the result of a load that was moved,
28007fa27ce4SDimitry Andric       // and is therefore a candidate to also be moved, add it to the
28017fa27ce4SDimitry Andric       // RegisterMap and InstrMap.
28027fa27ce4SDimitry Andric       forEachDbgRegOperand(&MI, [&](MachineOperand &Op) {
28037fa27ce4SDimitry Andric         PopulateRegisterAndInstrMapForDebugInstr(Op.getReg());
28047fa27ce4SDimitry Andric       });
28057fa27ce4SDimitry Andric 
28067fa27ce4SDimitry Andric       // If the current DBG_VALUE describes the same variable as one of the
28077fa27ce4SDimitry Andric       // in-flight DBG_VALUEs, remove the candidate from the list and set it to
28087fa27ce4SDimitry Andric       // undef. Moving one DBG_VALUE past another would result in the variable's
28097fa27ce4SDimitry Andric       // value going back in time when stepping through the block in the
28107fa27ce4SDimitry Andric       // debugger.
28117fa27ce4SDimitry Andric       auto InstrIt = DbgValueSinkCandidates.find(DbgVar);
28127fa27ce4SDimitry Andric       if (InstrIt != DbgValueSinkCandidates.end()) {
28137fa27ce4SDimitry Andric         auto *Instr = InstrIt->getSecond();
28147fa27ce4SDimitry Andric         auto RegIt = InstrMap.find(Instr);
28157fa27ce4SDimitry Andric         if (RegIt != InstrMap.end()) {
28167fa27ce4SDimitry Andric           const auto &RegVec = RegIt->getSecond();
28177fa27ce4SDimitry Andric           // For every Register in the RegVec, remove the MachineInstr in the
28187fa27ce4SDimitry Andric           // RegisterMap that describes the DbgVar.
28197fa27ce4SDimitry Andric           for (auto &Reg : RegVec) {
28207fa27ce4SDimitry Andric             auto RegIt = RegisterMap.find(Reg);
28217fa27ce4SDimitry Andric             if (RegIt == RegisterMap.end())
28227fa27ce4SDimitry Andric               continue;
28237fa27ce4SDimitry Andric             auto &InstrVec = RegIt->getSecond();
28247fa27ce4SDimitry Andric             auto IsDbgVar = [&](MachineInstr *I) -> bool {
28257fa27ce4SDimitry Andric               auto Var = createDebugVariableFromMachineInstr(I);
28267fa27ce4SDimitry Andric               return Var == DbgVar;
28277fa27ce4SDimitry Andric             };
28287fa27ce4SDimitry Andric 
2829b1c73532SDimitry Andric             llvm::erase_if(InstrVec, IsDbgVar);
28307fa27ce4SDimitry Andric           }
28317fa27ce4SDimitry Andric           forEachDbgRegOperand(Instr,
28327fa27ce4SDimitry Andric                                [&](MachineOperand &Op) { Op.setReg(0); });
28337fa27ce4SDimitry Andric         }
28347fa27ce4SDimitry Andric       }
28357fa27ce4SDimitry Andric       DbgValueSinkCandidates[DbgVar] = &MI;
28367fa27ce4SDimitry Andric     } else {
28377fa27ce4SDimitry Andric       // If the first operand of a load matches with a DBG_VALUE in RegisterMap,
28387fa27ce4SDimitry Andric       // then move that DBG_VALUE to below the load.
28397fa27ce4SDimitry Andric       auto Opc = MI.getOpcode();
28407fa27ce4SDimitry Andric       if (!isLoadSingle(Opc))
28417fa27ce4SDimitry Andric         continue;
28427fa27ce4SDimitry Andric       auto Reg = MI.getOperand(0).getReg();
28437fa27ce4SDimitry Andric       auto RegIt = RegisterMap.find(Reg);
28447fa27ce4SDimitry Andric       if (RegIt == RegisterMap.end())
28457fa27ce4SDimitry Andric         continue;
28467fa27ce4SDimitry Andric       auto &DbgInstrVec = RegIt->getSecond();
28477fa27ce4SDimitry Andric       if (!DbgInstrVec.size())
28487fa27ce4SDimitry Andric         continue;
28497fa27ce4SDimitry Andric       for (auto *DbgInstr : DbgInstrVec) {
28507fa27ce4SDimitry Andric         MachineBasicBlock::iterator InsertPos = std::next(MBBI);
28517fa27ce4SDimitry Andric         auto *ClonedMI = MI.getMF()->CloneMachineInstr(DbgInstr);
28527fa27ce4SDimitry Andric         MBB->insert(InsertPos, ClonedMI);
28537fa27ce4SDimitry Andric         MBBI++;
28547fa27ce4SDimitry Andric         //  Erase the entry into the DbgValueSinkCandidates for the DBG_VALUE
28557fa27ce4SDimitry Andric         //  that was moved.
28567fa27ce4SDimitry Andric         auto DbgVar = createDebugVariableFromMachineInstr(DbgInstr);
28577fa27ce4SDimitry Andric         auto DbgIt = DbgValueSinkCandidates.find(DbgVar);
28587fa27ce4SDimitry Andric         // If the instruction is a DBG_VALUE_LIST, it may have already been
28597fa27ce4SDimitry Andric         // erased from the DbgValueSinkCandidates. Only erase if it exists in
28607fa27ce4SDimitry Andric         // the DbgValueSinkCandidates.
28617fa27ce4SDimitry Andric         if (DbgIt != DbgValueSinkCandidates.end())
28627fa27ce4SDimitry Andric           DbgValueSinkCandidates.erase(DbgIt);
28637fa27ce4SDimitry Andric         // Zero out original dbg instr
28647fa27ce4SDimitry Andric         forEachDbgRegOperand(DbgInstr,
28657fa27ce4SDimitry Andric                              [&](MachineOperand &Op) { Op.setReg(0); });
28667fa27ce4SDimitry Andric         // Update RegisterMap with ClonedMI because it might have to be moved
28677fa27ce4SDimitry Andric         // again.
28687fa27ce4SDimitry Andric         if (DbgInstr->isDebugValueList())
28697fa27ce4SDimitry Andric           updateRegisterMapForDbgValueListAfterMove(RegisterMap, ClonedMI,
28707fa27ce4SDimitry Andric                                                     DbgInstr);
28717fa27ce4SDimitry Andric       }
28727fa27ce4SDimitry Andric     }
28737fa27ce4SDimitry Andric   }
2874600c6fa1SEd Schouten   return RetVal;
2875600c6fa1SEd Schouten }
2876600c6fa1SEd Schouten 
2877cfca06d7SDimitry Andric // Get the Base register operand index from the memory access MachineInst if we
2878cfca06d7SDimitry Andric // should attempt to distribute postinc on it. Return -1 if not of a valid
2879cfca06d7SDimitry Andric // instruction type. If it returns an index, it is assumed that instruction is a
2880cfca06d7SDimitry Andric // r+i indexing mode, and getBaseOperandIndex() + 1 is the Offset index.
getBaseOperandIndex(MachineInstr & MI)2881cfca06d7SDimitry Andric static int getBaseOperandIndex(MachineInstr &MI) {
2882cfca06d7SDimitry Andric   switch (MI.getOpcode()) {
2883cfca06d7SDimitry Andric   case ARM::MVE_VLDRBS16:
2884cfca06d7SDimitry Andric   case ARM::MVE_VLDRBS32:
2885cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU16:
2886cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU32:
2887cfca06d7SDimitry Andric   case ARM::MVE_VLDRHS32:
2888cfca06d7SDimitry Andric   case ARM::MVE_VLDRHU32:
2889cfca06d7SDimitry Andric   case ARM::MVE_VLDRBU8:
2890cfca06d7SDimitry Andric   case ARM::MVE_VLDRHU16:
2891cfca06d7SDimitry Andric   case ARM::MVE_VLDRWU32:
2892cfca06d7SDimitry Andric   case ARM::MVE_VSTRB16:
2893cfca06d7SDimitry Andric   case ARM::MVE_VSTRB32:
2894cfca06d7SDimitry Andric   case ARM::MVE_VSTRH32:
2895cfca06d7SDimitry Andric   case ARM::MVE_VSTRBU8:
2896cfca06d7SDimitry Andric   case ARM::MVE_VSTRHU16:
2897cfca06d7SDimitry Andric   case ARM::MVE_VSTRWU32:
2898b60736ecSDimitry Andric   case ARM::t2LDRHi8:
2899b60736ecSDimitry Andric   case ARM::t2LDRHi12:
2900b60736ecSDimitry Andric   case ARM::t2LDRSHi8:
2901b60736ecSDimitry Andric   case ARM::t2LDRSHi12:
2902b60736ecSDimitry Andric   case ARM::t2LDRBi8:
2903b60736ecSDimitry Andric   case ARM::t2LDRBi12:
2904b60736ecSDimitry Andric   case ARM::t2LDRSBi8:
2905b60736ecSDimitry Andric   case ARM::t2LDRSBi12:
2906b60736ecSDimitry Andric   case ARM::t2STRBi8:
2907b60736ecSDimitry Andric   case ARM::t2STRBi12:
2908b60736ecSDimitry Andric   case ARM::t2STRHi8:
2909b60736ecSDimitry Andric   case ARM::t2STRHi12:
2910cfca06d7SDimitry Andric     return 1;
2911b60736ecSDimitry Andric   case ARM::MVE_VLDRBS16_post:
2912b60736ecSDimitry Andric   case ARM::MVE_VLDRBS32_post:
2913b60736ecSDimitry Andric   case ARM::MVE_VLDRBU16_post:
2914b60736ecSDimitry Andric   case ARM::MVE_VLDRBU32_post:
2915b60736ecSDimitry Andric   case ARM::MVE_VLDRHS32_post:
2916b60736ecSDimitry Andric   case ARM::MVE_VLDRHU32_post:
2917b60736ecSDimitry Andric   case ARM::MVE_VLDRBU8_post:
2918b60736ecSDimitry Andric   case ARM::MVE_VLDRHU16_post:
2919b60736ecSDimitry Andric   case ARM::MVE_VLDRWU32_post:
2920b60736ecSDimitry Andric   case ARM::MVE_VSTRB16_post:
2921b60736ecSDimitry Andric   case ARM::MVE_VSTRB32_post:
2922b60736ecSDimitry Andric   case ARM::MVE_VSTRH32_post:
2923b60736ecSDimitry Andric   case ARM::MVE_VSTRBU8_post:
2924b60736ecSDimitry Andric   case ARM::MVE_VSTRHU16_post:
2925b60736ecSDimitry Andric   case ARM::MVE_VSTRWU32_post:
2926b60736ecSDimitry Andric   case ARM::MVE_VLDRBS16_pre:
2927b60736ecSDimitry Andric   case ARM::MVE_VLDRBS32_pre:
2928b60736ecSDimitry Andric   case ARM::MVE_VLDRBU16_pre:
2929b60736ecSDimitry Andric   case ARM::MVE_VLDRBU32_pre:
2930b60736ecSDimitry Andric   case ARM::MVE_VLDRHS32_pre:
2931b60736ecSDimitry Andric   case ARM::MVE_VLDRHU32_pre:
2932b60736ecSDimitry Andric   case ARM::MVE_VLDRBU8_pre:
2933b60736ecSDimitry Andric   case ARM::MVE_VLDRHU16_pre:
2934b60736ecSDimitry Andric   case ARM::MVE_VLDRWU32_pre:
2935b60736ecSDimitry Andric   case ARM::MVE_VSTRB16_pre:
2936b60736ecSDimitry Andric   case ARM::MVE_VSTRB32_pre:
2937b60736ecSDimitry Andric   case ARM::MVE_VSTRH32_pre:
2938b60736ecSDimitry Andric   case ARM::MVE_VSTRBU8_pre:
2939b60736ecSDimitry Andric   case ARM::MVE_VSTRHU16_pre:
2940b60736ecSDimitry Andric   case ARM::MVE_VSTRWU32_pre:
2941b60736ecSDimitry Andric     return 2;
2942cfca06d7SDimitry Andric   }
2943cfca06d7SDimitry Andric   return -1;
2944cfca06d7SDimitry Andric }
2945cfca06d7SDimitry Andric 
isPostIndex(MachineInstr & MI)2946b60736ecSDimitry Andric static bool isPostIndex(MachineInstr &MI) {
2947b60736ecSDimitry Andric   switch (MI.getOpcode()) {
2948b60736ecSDimitry Andric   case ARM::MVE_VLDRBS16_post:
2949b60736ecSDimitry Andric   case ARM::MVE_VLDRBS32_post:
2950b60736ecSDimitry Andric   case ARM::MVE_VLDRBU16_post:
2951b60736ecSDimitry Andric   case ARM::MVE_VLDRBU32_post:
2952b60736ecSDimitry Andric   case ARM::MVE_VLDRHS32_post:
2953b60736ecSDimitry Andric   case ARM::MVE_VLDRHU32_post:
2954b60736ecSDimitry Andric   case ARM::MVE_VLDRBU8_post:
2955b60736ecSDimitry Andric   case ARM::MVE_VLDRHU16_post:
2956b60736ecSDimitry Andric   case ARM::MVE_VLDRWU32_post:
2957b60736ecSDimitry Andric   case ARM::MVE_VSTRB16_post:
2958b60736ecSDimitry Andric   case ARM::MVE_VSTRB32_post:
2959b60736ecSDimitry Andric   case ARM::MVE_VSTRH32_post:
2960b60736ecSDimitry Andric   case ARM::MVE_VSTRBU8_post:
2961b60736ecSDimitry Andric   case ARM::MVE_VSTRHU16_post:
2962b60736ecSDimitry Andric   case ARM::MVE_VSTRWU32_post:
2963b60736ecSDimitry Andric     return true;
2964b60736ecSDimitry Andric   }
2965b60736ecSDimitry Andric   return false;
2966b60736ecSDimitry Andric }
2967b60736ecSDimitry Andric 
isPreIndex(MachineInstr & MI)2968b60736ecSDimitry Andric static bool isPreIndex(MachineInstr &MI) {
2969b60736ecSDimitry Andric   switch (MI.getOpcode()) {
2970b60736ecSDimitry Andric   case ARM::MVE_VLDRBS16_pre:
2971b60736ecSDimitry Andric   case ARM::MVE_VLDRBS32_pre:
2972b60736ecSDimitry Andric   case ARM::MVE_VLDRBU16_pre:
2973b60736ecSDimitry Andric   case ARM::MVE_VLDRBU32_pre:
2974b60736ecSDimitry Andric   case ARM::MVE_VLDRHS32_pre:
2975b60736ecSDimitry Andric   case ARM::MVE_VLDRHU32_pre:
2976b60736ecSDimitry Andric   case ARM::MVE_VLDRBU8_pre:
2977b60736ecSDimitry Andric   case ARM::MVE_VLDRHU16_pre:
2978b60736ecSDimitry Andric   case ARM::MVE_VLDRWU32_pre:
2979b60736ecSDimitry Andric   case ARM::MVE_VSTRB16_pre:
2980b60736ecSDimitry Andric   case ARM::MVE_VSTRB32_pre:
2981b60736ecSDimitry Andric   case ARM::MVE_VSTRH32_pre:
2982b60736ecSDimitry Andric   case ARM::MVE_VSTRBU8_pre:
2983b60736ecSDimitry Andric   case ARM::MVE_VSTRHU16_pre:
2984b60736ecSDimitry Andric   case ARM::MVE_VSTRWU32_pre:
2985b60736ecSDimitry Andric     return true;
2986b60736ecSDimitry Andric   }
2987b60736ecSDimitry Andric   return false;
2988b60736ecSDimitry Andric }
2989b60736ecSDimitry Andric 
2990b60736ecSDimitry Andric // Given a memory access Opcode, check that the give Imm would be a valid Offset
2991b60736ecSDimitry Andric // for this instruction (same as isLegalAddressImm), Or if the instruction
2992b60736ecSDimitry Andric // could be easily converted to one where that was valid. For example converting
2993b60736ecSDimitry Andric // t2LDRi12 to t2LDRi8 for negative offsets. Works in conjunction with
2994b60736ecSDimitry Andric // AdjustBaseAndOffset below.
isLegalOrConvertableAddressImm(unsigned Opcode,int Imm,const TargetInstrInfo * TII,int & CodesizeEstimate)2995b60736ecSDimitry Andric static bool isLegalOrConvertableAddressImm(unsigned Opcode, int Imm,
2996b60736ecSDimitry Andric                                            const TargetInstrInfo *TII,
2997b60736ecSDimitry Andric                                            int &CodesizeEstimate) {
2998b60736ecSDimitry Andric   if (isLegalAddressImm(Opcode, Imm, TII))
2999b60736ecSDimitry Andric     return true;
3000b60736ecSDimitry Andric 
3001f65dcba8SDimitry Andric   // We can convert AddrModeT2_i12 to AddrModeT2_i8neg.
3002b60736ecSDimitry Andric   const MCInstrDesc &Desc = TII->get(Opcode);
3003b60736ecSDimitry Andric   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
3004b60736ecSDimitry Andric   switch (AddrMode) {
3005b60736ecSDimitry Andric   case ARMII::AddrModeT2_i12:
3006b60736ecSDimitry Andric     CodesizeEstimate += 1;
3007f65dcba8SDimitry Andric     return Imm < 0 && -Imm < ((1 << 8) * 1);
3008b60736ecSDimitry Andric   }
3009b60736ecSDimitry Andric   return false;
3010b60736ecSDimitry Andric }
3011b60736ecSDimitry Andric 
3012b60736ecSDimitry Andric // Given an MI adjust its address BaseReg to use NewBaseReg and address offset
3013b60736ecSDimitry Andric // by -Offset. This can either happen in-place or be a replacement as MI is
3014b60736ecSDimitry Andric // converted to another instruction type.
AdjustBaseAndOffset(MachineInstr * MI,Register NewBaseReg,int Offset,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)3015b60736ecSDimitry Andric static void AdjustBaseAndOffset(MachineInstr *MI, Register NewBaseReg,
3016344a3780SDimitry Andric                                 int Offset, const TargetInstrInfo *TII,
3017344a3780SDimitry Andric                                 const TargetRegisterInfo *TRI) {
3018344a3780SDimitry Andric   // Set the Base reg
3019b60736ecSDimitry Andric   unsigned BaseOp = getBaseOperandIndex(*MI);
3020b60736ecSDimitry Andric   MI->getOperand(BaseOp).setReg(NewBaseReg);
3021344a3780SDimitry Andric   // and constrain the reg class to that required by the instruction.
3022344a3780SDimitry Andric   MachineFunction *MF = MI->getMF();
3023344a3780SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
3024344a3780SDimitry Andric   const MCInstrDesc &MCID = TII->get(MI->getOpcode());
3025344a3780SDimitry Andric   const TargetRegisterClass *TRC = TII->getRegClass(MCID, BaseOp, TRI, *MF);
3026344a3780SDimitry Andric   MRI.constrainRegClass(NewBaseReg, TRC);
3027344a3780SDimitry Andric 
3028b60736ecSDimitry Andric   int OldOffset = MI->getOperand(BaseOp + 1).getImm();
3029b60736ecSDimitry Andric   if (isLegalAddressImm(MI->getOpcode(), OldOffset - Offset, TII))
3030b60736ecSDimitry Andric     MI->getOperand(BaseOp + 1).setImm(OldOffset - Offset);
3031b60736ecSDimitry Andric   else {
3032b60736ecSDimitry Andric     unsigned ConvOpcode;
3033b60736ecSDimitry Andric     switch (MI->getOpcode()) {
3034b60736ecSDimitry Andric     case ARM::t2LDRHi12:
3035b60736ecSDimitry Andric       ConvOpcode = ARM::t2LDRHi8;
3036b60736ecSDimitry Andric       break;
3037b60736ecSDimitry Andric     case ARM::t2LDRSHi12:
3038b60736ecSDimitry Andric       ConvOpcode = ARM::t2LDRSHi8;
3039b60736ecSDimitry Andric       break;
3040b60736ecSDimitry Andric     case ARM::t2LDRBi12:
3041b60736ecSDimitry Andric       ConvOpcode = ARM::t2LDRBi8;
3042b60736ecSDimitry Andric       break;
3043b60736ecSDimitry Andric     case ARM::t2LDRSBi12:
3044b60736ecSDimitry Andric       ConvOpcode = ARM::t2LDRSBi8;
3045b60736ecSDimitry Andric       break;
3046b60736ecSDimitry Andric     case ARM::t2STRHi12:
3047b60736ecSDimitry Andric       ConvOpcode = ARM::t2STRHi8;
3048b60736ecSDimitry Andric       break;
3049b60736ecSDimitry Andric     case ARM::t2STRBi12:
3050b60736ecSDimitry Andric       ConvOpcode = ARM::t2STRBi8;
3051b60736ecSDimitry Andric       break;
3052b60736ecSDimitry Andric     default:
3053b60736ecSDimitry Andric       llvm_unreachable("Unhandled convertable opcode");
3054b60736ecSDimitry Andric     }
3055b60736ecSDimitry Andric     assert(isLegalAddressImm(ConvOpcode, OldOffset - Offset, TII) &&
3056b60736ecSDimitry Andric            "Illegal Address Immediate after convert!");
3057b60736ecSDimitry Andric 
3058b60736ecSDimitry Andric     const MCInstrDesc &MCID = TII->get(ConvOpcode);
3059b60736ecSDimitry Andric     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3060b60736ecSDimitry Andric         .add(MI->getOperand(0))
3061b60736ecSDimitry Andric         .add(MI->getOperand(1))
3062b60736ecSDimitry Andric         .addImm(OldOffset - Offset)
3063b60736ecSDimitry Andric         .add(MI->getOperand(3))
3064b60736ecSDimitry Andric         .add(MI->getOperand(4))
3065b60736ecSDimitry Andric         .cloneMemRefs(*MI);
3066b60736ecSDimitry Andric     MI->eraseFromParent();
3067b60736ecSDimitry Andric   }
3068b60736ecSDimitry Andric }
3069b60736ecSDimitry Andric 
createPostIncLoadStore(MachineInstr * MI,int Offset,Register NewReg,const TargetInstrInfo * TII,const TargetRegisterInfo * TRI)3070cfca06d7SDimitry Andric static MachineInstr *createPostIncLoadStore(MachineInstr *MI, int Offset,
3071cfca06d7SDimitry Andric                                             Register NewReg,
3072cfca06d7SDimitry Andric                                             const TargetInstrInfo *TII,
3073cfca06d7SDimitry Andric                                             const TargetRegisterInfo *TRI) {
3074cfca06d7SDimitry Andric   MachineFunction *MF = MI->getMF();
3075cfca06d7SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
3076cfca06d7SDimitry Andric 
3077cfca06d7SDimitry Andric   unsigned NewOpcode = getPostIndexedLoadStoreOpcode(
3078cfca06d7SDimitry Andric       MI->getOpcode(), Offset > 0 ? ARM_AM::add : ARM_AM::sub);
3079cfca06d7SDimitry Andric 
3080cfca06d7SDimitry Andric   const MCInstrDesc &MCID = TII->get(NewOpcode);
3081cfca06d7SDimitry Andric   // Constrain the def register class
3082cfca06d7SDimitry Andric   const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
3083cfca06d7SDimitry Andric   MRI.constrainRegClass(NewReg, TRC);
3084cfca06d7SDimitry Andric   // And do the same for the base operand
3085cfca06d7SDimitry Andric   TRC = TII->getRegClass(MCID, 2, TRI, *MF);
3086cfca06d7SDimitry Andric   MRI.constrainRegClass(MI->getOperand(1).getReg(), TRC);
3087cfca06d7SDimitry Andric 
3088b60736ecSDimitry Andric   unsigned AddrMode = (MCID.TSFlags & ARMII::AddrModeMask);
3089b60736ecSDimitry Andric   switch (AddrMode) {
3090b60736ecSDimitry Andric   case ARMII::AddrModeT2_i7:
3091b60736ecSDimitry Andric   case ARMII::AddrModeT2_i7s2:
3092b60736ecSDimitry Andric   case ARMII::AddrModeT2_i7s4:
3093b60736ecSDimitry Andric     // Any MVE load/store
3094b60736ecSDimitry Andric     return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3095b60736ecSDimitry Andric         .addReg(NewReg, RegState::Define)
3096b60736ecSDimitry Andric         .add(MI->getOperand(0))
3097b60736ecSDimitry Andric         .add(MI->getOperand(1))
3098b60736ecSDimitry Andric         .addImm(Offset)
3099b60736ecSDimitry Andric         .add(MI->getOperand(3))
3100b60736ecSDimitry Andric         .add(MI->getOperand(4))
3101c0981da4SDimitry Andric         .add(MI->getOperand(5))
3102b60736ecSDimitry Andric         .cloneMemRefs(*MI);
3103b60736ecSDimitry Andric   case ARMII::AddrModeT2_i8:
3104b60736ecSDimitry Andric     if (MI->mayLoad()) {
3105b60736ecSDimitry Andric       return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3106b60736ecSDimitry Andric           .add(MI->getOperand(0))
3107b60736ecSDimitry Andric           .addReg(NewReg, RegState::Define)
3108b60736ecSDimitry Andric           .add(MI->getOperand(1))
3109b60736ecSDimitry Andric           .addImm(Offset)
3110b60736ecSDimitry Andric           .add(MI->getOperand(3))
3111b60736ecSDimitry Andric           .add(MI->getOperand(4))
3112b60736ecSDimitry Andric           .cloneMemRefs(*MI);
3113b60736ecSDimitry Andric     } else {
3114cfca06d7SDimitry Andric       return BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), MCID)
3115cfca06d7SDimitry Andric           .addReg(NewReg, RegState::Define)
3116cfca06d7SDimitry Andric           .add(MI->getOperand(0))
3117cfca06d7SDimitry Andric           .add(MI->getOperand(1))
3118cfca06d7SDimitry Andric           .addImm(Offset)
3119cfca06d7SDimitry Andric           .add(MI->getOperand(3))
3120cfca06d7SDimitry Andric           .add(MI->getOperand(4))
3121cfca06d7SDimitry Andric           .cloneMemRefs(*MI);
3122cfca06d7SDimitry Andric     }
3123b60736ecSDimitry Andric   default:
3124b60736ecSDimitry Andric     llvm_unreachable("Unhandled createPostIncLoadStore");
3125b60736ecSDimitry Andric   }
3126b60736ecSDimitry Andric }
3127cfca06d7SDimitry Andric 
3128cfca06d7SDimitry Andric // Given a Base Register, optimise the load/store uses to attempt to create more
3129b60736ecSDimitry Andric // post-inc accesses and less register moves. We do this by taking zero offset
3130b60736ecSDimitry Andric // loads/stores with an add, and convert them to a postinc load/store of the
3131b60736ecSDimitry Andric // same type. Any subsequent accesses will be adjusted to use and account for
3132b60736ecSDimitry Andric // the post-inc value.
3133cfca06d7SDimitry Andric // For example:
3134cfca06d7SDimitry Andric // LDR #0            LDR_POSTINC #16
3135cfca06d7SDimitry Andric // LDR #4            LDR #-12
3136cfca06d7SDimitry Andric // LDR #8            LDR #-8
3137cfca06d7SDimitry Andric // LDR #12           LDR #-4
3138cfca06d7SDimitry Andric // ADD #16
3139b60736ecSDimitry Andric //
3140b60736ecSDimitry Andric // At the same time if we do not find an increment but do find an existing
3141b60736ecSDimitry Andric // pre/post inc instruction, we can still adjust the offsets of subsequent
3142b60736ecSDimitry Andric // instructions to save the register move that would otherwise be needed for the
3143b60736ecSDimitry Andric // in-place increment.
DistributeIncrements(Register Base)3144cfca06d7SDimitry Andric bool ARMPreAllocLoadStoreOpt::DistributeIncrements(Register Base) {
3145cfca06d7SDimitry Andric   // We are looking for:
3146cfca06d7SDimitry Andric   // One zero offset load/store that can become postinc
3147cfca06d7SDimitry Andric   MachineInstr *BaseAccess = nullptr;
3148b60736ecSDimitry Andric   MachineInstr *PrePostInc = nullptr;
3149cfca06d7SDimitry Andric   // An increment that can be folded in
3150cfca06d7SDimitry Andric   MachineInstr *Increment = nullptr;
3151cfca06d7SDimitry Andric   // Other accesses after BaseAccess that will need to be updated to use the
3152b60736ecSDimitry Andric   // postinc value.
3153cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr *, 8> OtherAccesses;
3154cfca06d7SDimitry Andric   for (auto &Use : MRI->use_nodbg_instructions(Base)) {
3155cfca06d7SDimitry Andric     if (!Increment && getAddSubImmediate(Use) != 0) {
3156cfca06d7SDimitry Andric       Increment = &Use;
3157cfca06d7SDimitry Andric       continue;
3158cfca06d7SDimitry Andric     }
3159cfca06d7SDimitry Andric 
3160cfca06d7SDimitry Andric     int BaseOp = getBaseOperandIndex(Use);
3161cfca06d7SDimitry Andric     if (BaseOp == -1)
3162cfca06d7SDimitry Andric       return false;
3163cfca06d7SDimitry Andric 
3164cfca06d7SDimitry Andric     if (!Use.getOperand(BaseOp).isReg() ||
3165cfca06d7SDimitry Andric         Use.getOperand(BaseOp).getReg() != Base)
3166cfca06d7SDimitry Andric       return false;
3167b60736ecSDimitry Andric     if (isPreIndex(Use) || isPostIndex(Use))
3168b60736ecSDimitry Andric       PrePostInc = &Use;
3169b60736ecSDimitry Andric     else if (Use.getOperand(BaseOp + 1).getImm() == 0)
3170cfca06d7SDimitry Andric       BaseAccess = &Use;
3171cfca06d7SDimitry Andric     else
3172cfca06d7SDimitry Andric       OtherAccesses.insert(&Use);
3173cfca06d7SDimitry Andric   }
3174cfca06d7SDimitry Andric 
3175b60736ecSDimitry Andric   int IncrementOffset;
3176b60736ecSDimitry Andric   Register NewBaseReg;
3177b60736ecSDimitry Andric   if (BaseAccess && Increment) {
3178b60736ecSDimitry Andric     if (PrePostInc || BaseAccess->getParent() != Increment->getParent())
3179cfca06d7SDimitry Andric       return false;
3180cfca06d7SDimitry Andric     Register PredReg;
3181ac9a064cSDimitry Andric     if (Increment->definesRegister(ARM::CPSR, /*TRI=*/nullptr) ||
3182cfca06d7SDimitry Andric         getInstrPredicate(*Increment, PredReg) != ARMCC::AL)
3183cfca06d7SDimitry Andric       return false;
3184cfca06d7SDimitry Andric 
3185cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on VirtualReg "
3186cfca06d7SDimitry Andric                       << Base.virtRegIndex() << "\n");
3187cfca06d7SDimitry Andric 
3188145449b1SDimitry Andric     // Make sure that Increment has no uses before BaseAccess that are not PHI
3189145449b1SDimitry Andric     // uses.
3190cfca06d7SDimitry Andric     for (MachineInstr &Use :
3191cfca06d7SDimitry Andric         MRI->use_nodbg_instructions(Increment->getOperand(0).getReg())) {
3192145449b1SDimitry Andric       if (&Use == BaseAccess || (Use.getOpcode() != TargetOpcode::PHI &&
3193145449b1SDimitry Andric                                  !DT->dominates(BaseAccess, &Use))) {
3194cfca06d7SDimitry Andric         LLVM_DEBUG(dbgs() << "  BaseAccess doesn't dominate use of increment\n");
3195cfca06d7SDimitry Andric         return false;
3196cfca06d7SDimitry Andric       }
3197cfca06d7SDimitry Andric     }
3198cfca06d7SDimitry Andric 
3199cfca06d7SDimitry Andric     // Make sure that Increment can be folded into Base
3200b60736ecSDimitry Andric     IncrementOffset = getAddSubImmediate(*Increment);
3201cfca06d7SDimitry Andric     unsigned NewPostIncOpcode = getPostIndexedLoadStoreOpcode(
3202cfca06d7SDimitry Andric         BaseAccess->getOpcode(), IncrementOffset > 0 ? ARM_AM::add : ARM_AM::sub);
3203cfca06d7SDimitry Andric     if (!isLegalAddressImm(NewPostIncOpcode, IncrementOffset, TII)) {
3204cfca06d7SDimitry Andric       LLVM_DEBUG(dbgs() << "  Illegal addressing mode immediate on postinc\n");
3205cfca06d7SDimitry Andric       return false;
3206cfca06d7SDimitry Andric     }
3207b60736ecSDimitry Andric   }
3208b60736ecSDimitry Andric   else if (PrePostInc) {
3209b60736ecSDimitry Andric     // If we already have a pre/post index load/store then set BaseAccess,
3210b60736ecSDimitry Andric     // IncrementOffset and NewBaseReg to the values it already produces,
3211b60736ecSDimitry Andric     // allowing us to update and subsequent uses of BaseOp reg with the
3212b60736ecSDimitry Andric     // incremented value.
3213b60736ecSDimitry Andric     if (Increment)
3214b60736ecSDimitry Andric       return false;
3215b60736ecSDimitry Andric 
3216b60736ecSDimitry Andric     LLVM_DEBUG(dbgs() << "\nAttempting to distribute increments on already "
3217b60736ecSDimitry Andric                       << "indexed VirtualReg " << Base.virtRegIndex() << "\n");
3218b60736ecSDimitry Andric     int BaseOp = getBaseOperandIndex(*PrePostInc);
3219b60736ecSDimitry Andric     IncrementOffset = PrePostInc->getOperand(BaseOp+1).getImm();
3220b60736ecSDimitry Andric     BaseAccess = PrePostInc;
3221b60736ecSDimitry Andric     NewBaseReg = PrePostInc->getOperand(0).getReg();
3222b60736ecSDimitry Andric   }
3223b60736ecSDimitry Andric   else
3224b60736ecSDimitry Andric     return false;
3225cfca06d7SDimitry Andric 
3226cfca06d7SDimitry Andric   // And make sure that the negative value of increment can be added to all
3227cfca06d7SDimitry Andric   // other offsets after the BaseAccess. We rely on either
3228cfca06d7SDimitry Andric   // dominates(BaseAccess, OtherAccess) or dominates(OtherAccess, BaseAccess)
3229cfca06d7SDimitry Andric   // to keep things simple.
3230b60736ecSDimitry Andric   // This also adds a simple codesize metric, to detect if an instruction (like
3231b60736ecSDimitry Andric   // t2LDRBi12) which can often be shrunk to a thumb1 instruction (tLDRBi)
3232b60736ecSDimitry Andric   // cannot because it is converted to something else (t2LDRBi8). We start this
3233b60736ecSDimitry Andric   // at -1 for the gain from removing the increment.
3234cfca06d7SDimitry Andric   SmallPtrSet<MachineInstr *, 4> SuccessorAccesses;
3235b60736ecSDimitry Andric   int CodesizeEstimate = -1;
3236cfca06d7SDimitry Andric   for (auto *Use : OtherAccesses) {
3237cfca06d7SDimitry Andric     if (DT->dominates(BaseAccess, Use)) {
3238cfca06d7SDimitry Andric       SuccessorAccesses.insert(Use);
3239cfca06d7SDimitry Andric       unsigned BaseOp = getBaseOperandIndex(*Use);
3240b60736ecSDimitry Andric       if (!isLegalOrConvertableAddressImm(Use->getOpcode(),
3241b60736ecSDimitry Andric                                           Use->getOperand(BaseOp + 1).getImm() -
3242b60736ecSDimitry Andric                                               IncrementOffset,
3243b60736ecSDimitry Andric                                           TII, CodesizeEstimate)) {
3244cfca06d7SDimitry Andric         LLVM_DEBUG(dbgs() << "  Illegal addressing mode immediate on use\n");
3245cfca06d7SDimitry Andric         return false;
3246cfca06d7SDimitry Andric       }
3247cfca06d7SDimitry Andric     } else if (!DT->dominates(Use, BaseAccess)) {
3248cfca06d7SDimitry Andric       LLVM_DEBUG(
3249cfca06d7SDimitry Andric           dbgs() << "  Unknown dominance relation between Base and Use\n");
3250cfca06d7SDimitry Andric       return false;
3251cfca06d7SDimitry Andric     }
3252cfca06d7SDimitry Andric   }
3253b60736ecSDimitry Andric   if (STI->hasMinSize() && CodesizeEstimate > 0) {
3254b60736ecSDimitry Andric     LLVM_DEBUG(dbgs() << "  Expected to grow instructions under minsize\n");
3255b60736ecSDimitry Andric     return false;
3256b60736ecSDimitry Andric   }
3257cfca06d7SDimitry Andric 
3258b60736ecSDimitry Andric   if (!PrePostInc) {
3259cfca06d7SDimitry Andric     // Replace BaseAccess with a post inc
3260cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "Changing: "; BaseAccess->dump());
3261cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "  And   : "; Increment->dump());
3262b60736ecSDimitry Andric     NewBaseReg = Increment->getOperand(0).getReg();
3263cfca06d7SDimitry Andric     MachineInstr *BaseAccessPost =
3264cfca06d7SDimitry Andric         createPostIncLoadStore(BaseAccess, IncrementOffset, NewBaseReg, TII, TRI);
3265cfca06d7SDimitry Andric     BaseAccess->eraseFromParent();
3266cfca06d7SDimitry Andric     Increment->eraseFromParent();
3267cfca06d7SDimitry Andric     (void)BaseAccessPost;
3268cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "  To    : "; BaseAccessPost->dump());
3269b60736ecSDimitry Andric   }
3270cfca06d7SDimitry Andric 
3271cfca06d7SDimitry Andric   for (auto *Use : SuccessorAccesses) {
3272cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "Changing: "; Use->dump());
3273344a3780SDimitry Andric     AdjustBaseAndOffset(Use, NewBaseReg, IncrementOffset, TII, TRI);
3274cfca06d7SDimitry Andric     LLVM_DEBUG(dbgs() << "  To    : "; Use->dump());
3275cfca06d7SDimitry Andric   }
3276cfca06d7SDimitry Andric 
3277cfca06d7SDimitry Andric   // Remove the kill flag from all uses of NewBaseReg, in case any old uses
3278cfca06d7SDimitry Andric   // remain.
3279cfca06d7SDimitry Andric   for (MachineOperand &Op : MRI->use_nodbg_operands(NewBaseReg))
3280cfca06d7SDimitry Andric     Op.setIsKill(false);
3281cfca06d7SDimitry Andric   return true;
3282cfca06d7SDimitry Andric }
3283cfca06d7SDimitry Andric 
DistributeIncrements()3284cfca06d7SDimitry Andric bool ARMPreAllocLoadStoreOpt::DistributeIncrements() {
3285cfca06d7SDimitry Andric   bool Changed = false;
3286cfca06d7SDimitry Andric   SmallSetVector<Register, 4> Visited;
3287cfca06d7SDimitry Andric   for (auto &MBB : *MF) {
3288cfca06d7SDimitry Andric     for (auto &MI : MBB) {
3289cfca06d7SDimitry Andric       int BaseOp = getBaseOperandIndex(MI);
3290cfca06d7SDimitry Andric       if (BaseOp == -1 || !MI.getOperand(BaseOp).isReg())
3291cfca06d7SDimitry Andric         continue;
3292cfca06d7SDimitry Andric 
3293cfca06d7SDimitry Andric       Register Base = MI.getOperand(BaseOp).getReg();
3294cfca06d7SDimitry Andric       if (!Base.isVirtual() || Visited.count(Base))
3295cfca06d7SDimitry Andric         continue;
3296cfca06d7SDimitry Andric 
3297cfca06d7SDimitry Andric       Visited.insert(Base);
3298cfca06d7SDimitry Andric     }
3299cfca06d7SDimitry Andric   }
3300cfca06d7SDimitry Andric 
3301cfca06d7SDimitry Andric   for (auto Base : Visited)
3302cfca06d7SDimitry Andric     Changed |= DistributeIncrements(Base);
3303cfca06d7SDimitry Andric 
3304cfca06d7SDimitry Andric   return Changed;
3305cfca06d7SDimitry Andric }
3306cfca06d7SDimitry Andric 
330785d8b2bbSDimitry Andric /// Returns an instance of the load / store optimization pass.
createARMLoadStoreOptimizationPass(bool PreAlloc)3308600c6fa1SEd Schouten FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
3309600c6fa1SEd Schouten   if (PreAlloc)
3310600c6fa1SEd Schouten     return new ARMPreAllocLoadStoreOpt();
3311600c6fa1SEd Schouten   return new ARMLoadStoreOpt();
3312600c6fa1SEd Schouten }
3313