blob: d0cd9efc29abdedeffb9fd4758b5d88c11a737ce [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ------------===//
Evan Cheng10043e22007-01-19 07:51:42 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Evan Cheng10043e22007-01-19 07:51:42 +00007//
8//===----------------------------------------------------------------------===//
9//
Matthias Braunec50fa62015-06-01 21:26:23 +000010/// \file This file contains a pass that performs load / store related peephole
11/// optimizations. This pass should be run after register allocation.
Evan Cheng10043e22007-01-19 07:51:42 +000012//
13//===----------------------------------------------------------------------===//
14
Evan Cheng10043e22007-01-19 07:51:42 +000015#include "ARM.h"
Evan Cheng2aa91cc2009-08-08 03:20:32 +000016#include "ARMBaseInstrInfo.h"
Craig Topper5fa0caa2012-03-26 00:45:15 +000017#include "ARMBaseRegisterInfo.h"
James Molloy556763d2014-05-16 14:14:30 +000018#include "ARMISelLowering.h"
Evan Chengf030f2d2007-03-07 20:30:36 +000019#include "ARMMachineFunctionInfo.h"
Craig Toppera9253262014-03-22 23:51:00 +000020#include "ARMSubtarget.h"
Evan Chenga20cde32011-07-20 23:34:39 +000021#include "MCTargetDesc/ARMAddressingModes.h"
Eric Christopherae326492015-03-12 22:48:50 +000022#include "ThumbRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
Evan Cheng10043e22007-01-19 07:51:42 +000029#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng185c9ef2009-06-13 09:12:55 +000033#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000034#include "llvm/CodeGen/RegisterClassInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000035#include "llvm/CodeGen/SelectionDAGNodes.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000036#include "llvm/CodeGen/LivePhysRegs.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/DerivedTypes.h"
39#include "llvm/IR/Function.h"
Matthias Brauna4a3182d2015-07-10 18:08:49 +000040#include "llvm/Support/Allocator.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000043#include "llvm/Support/raw_ostream.h"
Evan Cheng10043e22007-01-19 07:51:42 +000044#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetMachine.h"
Evan Cheng1283c6a2009-06-15 08:28:29 +000046#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng10043e22007-01-19 07:51:42 +000047using namespace llvm;
48
Chandler Carruth84e68b22014-04-22 02:41:26 +000049#define DEBUG_TYPE "arm-ldst-opt"
50
Evan Cheng10043e22007-01-19 07:51:42 +000051STATISTIC(NumLDMGened , "Number of ldm instructions generated");
52STATISTIC(NumSTMGened , "Number of stm instructions generated");
Jim Grosbachd7cf55c2009-11-09 00:11:35 +000053STATISTIC(NumVLDMGened, "Number of vldm instructions generated");
54STATISTIC(NumVSTMGened, "Number of vstm instructions generated");
Evan Cheng185c9ef2009-06-13 09:12:55 +000055STATISTIC(NumLdStMoved, "Number of load / store instructions moved");
Evan Cheng0e796032009-06-18 02:04:01 +000056STATISTIC(NumLDRDFormed,"Number of ldrd created before allocation");
57STATISTIC(NumSTRDFormed,"Number of strd created before allocation");
58STATISTIC(NumLDRD2LDM, "Number of ldrd instructions turned back into ldm");
59STATISTIC(NumSTRD2STM, "Number of strd instructions turned back into stm");
60STATISTIC(NumLDRD2LDR, "Number of ldrd instructions turned back into ldr's");
61STATISTIC(NumSTRD2STR, "Number of strd instructions turned back into str's");
Evan Cheng185c9ef2009-06-13 09:12:55 +000062
David Grossd9c1bc92015-07-23 22:12:46 +000063namespace llvm {
64void initializeARMLoadStoreOptPass(PassRegistry &);
65}
66
67#define ARM_LOAD_STORE_OPT_NAME "ARM load / store optimization pass"
68
Evan Cheng10043e22007-01-19 07:51:42 +000069namespace {
Matthias Braunec50fa62015-06-01 21:26:23 +000070 /// Post- register allocation pass the combine load / store instructions to
71 /// form ldm / stm instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000072 struct ARMLoadStoreOpt : public MachineFunctionPass {
Devang Patel8c78a0b2007-05-03 01:11:54 +000073 static char ID;
David Grossd9c1bc92015-07-23 22:12:46 +000074 ARMLoadStoreOpt() : MachineFunctionPass(ID) {
75 initializeARMLoadStoreOptPass(*PassRegistry::getPassRegistry());
76 }
Devang Patel09f162c2007-05-01 21:15:47 +000077
Matthias Brauna4a3182d2015-07-10 18:08:49 +000078 const MachineFunction *MF;
Evan Cheng10043e22007-01-19 07:51:42 +000079 const TargetInstrInfo *TII;
Dan Gohman3a4be0f2008-02-10 18:45:23 +000080 const TargetRegisterInfo *TRI;
Evan Chengc3770ac2011-11-08 21:21:09 +000081 const ARMSubtarget *STI;
James Molloy556763d2014-05-16 14:14:30 +000082 const TargetLowering *TL;
Evan Chengf030f2d2007-03-07 20:30:36 +000083 ARMFunctionInfo *AFI;
Matthias Brauna4a3182d2015-07-10 18:08:49 +000084 LivePhysRegs LiveRegs;
85 RegisterClassInfo RegClassInfo;
86 MachineBasicBlock::const_iterator LiveRegPos;
87 bool LiveRegsValid;
88 bool RegClassInfoValid;
James Molloy92a15072014-05-16 14:11:38 +000089 bool isThumb1, isThumb2;
Evan Cheng10043e22007-01-19 07:51:42 +000090
Craig Topper6bc27bf2014-03-10 02:09:33 +000091 bool runOnMachineFunction(MachineFunction &Fn) override;
Evan Cheng10043e22007-01-19 07:51:42 +000092
Craig Topper6bc27bf2014-03-10 02:09:33 +000093 const char *getPassName() const override {
David Grossd9c1bc92015-07-23 22:12:46 +000094 return ARM_LOAD_STORE_OPT_NAME;
Evan Cheng10043e22007-01-19 07:51:42 +000095 }
96
97 private:
Matthias Brauna4a3182d2015-07-10 18:08:49 +000098 /// A set of load/store MachineInstrs with same base register sorted by
99 /// offset.
Evan Cheng10043e22007-01-19 07:51:42 +0000100 struct MemOpQueueEntry {
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000101 MachineInstr *MI;
102 int Offset; ///< Load/Store offset.
103 unsigned Position; ///< Position as counted from end of basic block.
104 MemOpQueueEntry(MachineInstr *MI, int Offset, unsigned Position)
105 : MI(MI), Offset(Offset), Position(Position) {}
Evan Cheng10043e22007-01-19 07:51:42 +0000106 };
107 typedef SmallVector<MemOpQueueEntry,8> MemOpQueue;
Evan Cheng10043e22007-01-19 07:51:42 +0000108
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000109 /// A set of MachineInstrs that fulfill (nearly all) conditions to get
110 /// merged into a LDM/STM.
111 struct MergeCandidate {
112 /// List of instructions ordered by load/store offset.
113 SmallVector<MachineInstr*, 4> Instrs;
114 /// Index in Instrs of the instruction being latest in the schedule.
115 unsigned LatestMIIdx;
116 /// Index in Instrs of the instruction being earliest in the schedule.
117 unsigned EarliestMIIdx;
118 /// Index into the basic block where the merged instruction will be
119 /// inserted. (See MemOpQueueEntry.Position)
120 unsigned InsertPos;
Matthias Braune40d89e2015-07-21 00:18:59 +0000121 /// Whether the instructions can be merged into a ldm/stm instruction.
122 bool CanMergeToLSMulti;
123 /// Whether the instructions can be merged into a ldrd/strd instruction.
124 bool CanMergeToLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000125 };
Matthias Braune40d89e2015-07-21 00:18:59 +0000126 SpecificBumpPtrAllocator<MergeCandidate> Allocator;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000127 SmallVector<const MergeCandidate*,4> Candidates;
Matthias Brauna50d2202015-07-21 00:19:01 +0000128 SmallVector<MachineInstr*,4> MergeBaseCandidates;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000129
130 void moveLiveRegsBefore(const MachineBasicBlock &MBB,
131 MachineBasicBlock::const_iterator Before);
132 unsigned findFreeReg(const TargetRegisterClass &RegClass);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000133 void UpdateBaseRegUses(MachineBasicBlock &MBB,
134 MachineBasicBlock::iterator MBBI,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000135 DebugLoc DL, unsigned Base, unsigned WordOffset,
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000136 ARMCC::CondCodes Pred, unsigned PredReg);
Matthias Braune40d89e2015-07-21 00:18:59 +0000137 MachineInstr *CreateLoadStoreMulti(MachineBasicBlock &MBB,
138 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
139 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
140 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs);
141 MachineInstr *CreateLoadStoreDouble(MachineBasicBlock &MBB,
142 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
143 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
144 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000145 void FormCandidates(const MemOpQueue &MemOps);
146 MachineInstr *MergeOpsUpdate(const MergeCandidate &Cand);
Evan Cheng1283c6a2009-06-15 08:28:29 +0000147 bool FixInvalidRegPairOp(MachineBasicBlock &MBB,
148 MachineBasicBlock::iterator &MBBI);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000149 bool MergeBaseUpdateLoadStore(MachineInstr *MI);
150 bool MergeBaseUpdateLSMultiple(MachineInstr *MI);
Matthias Brauna50d2202015-07-21 00:19:01 +0000151 bool MergeBaseUpdateLSDouble(MachineInstr &MI) const;
Evan Cheng10043e22007-01-19 07:51:42 +0000152 bool LoadStoreMultipleOpti(MachineBasicBlock &MBB);
153 bool MergeReturnIntoLDM(MachineBasicBlock &MBB);
154 };
Devang Patel8c78a0b2007-05-03 01:11:54 +0000155 char ARMLoadStoreOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000156}
Evan Cheng10043e22007-01-19 07:51:42 +0000157
David Grossd9c1bc92015-07-23 22:12:46 +0000158INITIALIZE_PASS(ARMLoadStoreOpt, "arm-load-store-opt", ARM_LOAD_STORE_OPT_NAME, false, false)
159
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000160static bool definesCPSR(const MachineInstr *MI) {
161 for (const auto &MO : MI->operands()) {
162 if (!MO.isReg())
163 continue;
164 if (MO.isDef() && MO.getReg() == ARM::CPSR && !MO.isDead())
165 // If the instruction has live CPSR def, then it's not safe to fold it
166 // into load / store.
167 return true;
168 }
169
170 return false;
171}
172
173static int getMemoryOpOffset(const MachineInstr *MI) {
Matthias Braunfa3872e2015-05-18 20:27:55 +0000174 unsigned Opcode = MI->getOpcode();
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000175 bool isAM3 = Opcode == ARM::LDRD || Opcode == ARM::STRD;
176 unsigned NumOperands = MI->getDesc().getNumOperands();
177 unsigned OffField = MI->getOperand(NumOperands-3).getImm();
178
179 if (Opcode == ARM::t2LDRi12 || Opcode == ARM::t2LDRi8 ||
180 Opcode == ARM::t2STRi12 || Opcode == ARM::t2STRi8 ||
181 Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8 ||
182 Opcode == ARM::LDRi12 || Opcode == ARM::STRi12)
183 return OffField;
184
185 // Thumb1 immediate offsets are scaled by 4
Renato Golinb9887ef2015-02-25 14:41:06 +0000186 if (Opcode == ARM::tLDRi || Opcode == ARM::tSTRi ||
187 Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi)
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000188 return OffField * 4;
189
190 int Offset = isAM3 ? ARM_AM::getAM3Offset(OffField)
191 : ARM_AM::getAM5Offset(OffField) * 4;
192 ARM_AM::AddrOpc Op = isAM3 ? ARM_AM::getAM3Op(OffField)
193 : ARM_AM::getAM5Op(OffField);
194
195 if (Op == ARM_AM::sub)
196 return -Offset;
197
198 return Offset;
199}
200
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000201static const MachineOperand &getLoadStoreBaseOp(const MachineInstr &MI) {
202 return MI.getOperand(1);
203}
204
205static const MachineOperand &getLoadStoreRegOp(const MachineInstr &MI) {
206 return MI.getOperand(0);
207}
208
Matthias Braunfa3872e2015-05-18 20:27:55 +0000209static int getLoadStoreMultipleOpcode(unsigned Opcode, ARM_AM::AMSubMode Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +0000210 switch (Opcode) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000211 default: llvm_unreachable("Unhandled opcode!");
Jim Grosbach1e4d9a12010-10-26 22:37:02 +0000212 case ARM::LDRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000213 ++NumLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000214 switch (Mode) {
215 default: llvm_unreachable("Unhandled submode!");
216 case ARM_AM::ia: return ARM::LDMIA;
217 case ARM_AM::da: return ARM::LDMDA;
218 case ARM_AM::db: return ARM::LDMDB;
219 case ARM_AM::ib: return ARM::LDMIB;
220 }
Jim Grosbach338de3e2010-10-27 23:12:14 +0000221 case ARM::STRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000222 ++NumSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000223 switch (Mode) {
224 default: llvm_unreachable("Unhandled submode!");
225 case ARM_AM::ia: return ARM::STMIA;
226 case ARM_AM::da: return ARM::STMDA;
227 case ARM_AM::db: return ARM::STMDB;
228 case ARM_AM::ib: return ARM::STMIB;
229 }
James Molloy556763d2014-05-16 14:14:30 +0000230 case ARM::tLDRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000231 case ARM::tLDRspi:
James Molloy556763d2014-05-16 14:14:30 +0000232 // tLDMIA is writeback-only - unless the base register is in the input
233 // reglist.
234 ++NumLDMGened;
235 switch (Mode) {
236 default: llvm_unreachable("Unhandled submode!");
237 case ARM_AM::ia: return ARM::tLDMIA;
238 }
239 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000240 case ARM::tSTRspi:
James Molloy556763d2014-05-16 14:14:30 +0000241 // There is no non-writeback tSTMIA either.
242 ++NumSTMGened;
243 switch (Mode) {
244 default: llvm_unreachable("Unhandled submode!");
245 case ARM_AM::ia: return ARM::tSTMIA_UPD;
246 }
Evan Cheng4605e8a2009-07-09 23:11:34 +0000247 case ARM::t2LDRi8:
248 case ARM::t2LDRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000249 ++NumLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000250 switch (Mode) {
251 default: llvm_unreachable("Unhandled submode!");
252 case ARM_AM::ia: return ARM::t2LDMIA;
253 case ARM_AM::db: return ARM::t2LDMDB;
254 }
Evan Cheng4605e8a2009-07-09 23:11:34 +0000255 case ARM::t2STRi8:
256 case ARM::t2STRi12:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000257 ++NumSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000258 switch (Mode) {
259 default: llvm_unreachable("Unhandled submode!");
260 case ARM_AM::ia: return ARM::t2STMIA;
261 case ARM_AM::db: return ARM::t2STMDB;
262 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000263 case ARM::VLDRS:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000264 ++NumVLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000265 switch (Mode) {
266 default: llvm_unreachable("Unhandled submode!");
267 case ARM_AM::ia: return ARM::VLDMSIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000268 case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000269 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000270 case ARM::VSTRS:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000271 ++NumVSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000272 switch (Mode) {
273 default: llvm_unreachable("Unhandled submode!");
274 case ARM_AM::ia: return ARM::VSTMSIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000275 case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000276 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000277 case ARM::VLDRD:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000278 ++NumVLDMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000279 switch (Mode) {
280 default: llvm_unreachable("Unhandled submode!");
281 case ARM_AM::ia: return ARM::VLDMDIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000282 case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000283 }
Jim Grosbachd7cf55c2009-11-09 00:11:35 +0000284 case ARM::VSTRD:
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000285 ++NumVSTMGened;
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000286 switch (Mode) {
287 default: llvm_unreachable("Unhandled submode!");
288 case ARM_AM::ia: return ARM::VSTMDIA;
Owen Andersond6c5a742011-03-29 16:45:53 +0000289 case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000290 }
Evan Cheng10043e22007-01-19 07:51:42 +0000291 }
Evan Cheng10043e22007-01-19 07:51:42 +0000292}
293
Benjamin Kramer113b2a92015-06-05 14:32:54 +0000294static ARM_AM::AMSubMode getLoadStoreMultipleSubMode(unsigned Opcode) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000295 switch (Opcode) {
296 default: llvm_unreachable("Unhandled opcode!");
Bill Wendlingb9bd5942010-11-18 19:44:29 +0000297 case ARM::LDMIA_RET:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000298 case ARM::LDMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000299 case ARM::LDMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000300 case ARM::STMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000301 case ARM::STMIA_UPD:
James Molloy556763d2014-05-16 14:14:30 +0000302 case ARM::tLDMIA:
303 case ARM::tLDMIA_UPD:
304 case ARM::tSTMIA_UPD:
Bill Wendlingb9bd5942010-11-18 19:44:29 +0000305 case ARM::t2LDMIA_RET:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000306 case ARM::t2LDMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000307 case ARM::t2LDMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000308 case ARM::t2STMIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000309 case ARM::t2STMIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000310 case ARM::VLDMSIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000311 case ARM::VLDMSIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000312 case ARM::VSTMSIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000313 case ARM::VSTMSIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000314 case ARM::VLDMDIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000315 case ARM::VLDMDIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000316 case ARM::VSTMDIA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000317 case ARM::VSTMDIA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000318 return ARM_AM::ia;
319
320 case ARM::LDMDA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000321 case ARM::LDMDA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000322 case ARM::STMDA:
Bill Wendling11cc1762010-11-17 19:16:20 +0000323 case ARM::STMDA_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000324 return ARM_AM::da;
325
326 case ARM::LDMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000327 case ARM::LDMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000328 case ARM::STMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000329 case ARM::STMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000330 case ARM::t2LDMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000331 case ARM::t2LDMDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000332 case ARM::t2STMDB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000333 case ARM::t2STMDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000334 case ARM::VLDMSDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000335 case ARM::VSTMSDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000336 case ARM::VLDMDDB_UPD:
Bill Wendling11cc1762010-11-17 19:16:20 +0000337 case ARM::VSTMDDB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000338 return ARM_AM::db;
339
340 case ARM::LDMIB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000341 case ARM::LDMIB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000342 case ARM::STMIB:
Bill Wendling11cc1762010-11-17 19:16:20 +0000343 case ARM::STMIB_UPD:
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000344 return ARM_AM::ib;
345 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000346}
347
James Molloy556763d2014-05-16 14:14:30 +0000348static bool isT1i32Load(unsigned Opc) {
Renato Golinb9887ef2015-02-25 14:41:06 +0000349 return Opc == ARM::tLDRi || Opc == ARM::tLDRspi;
James Molloy556763d2014-05-16 14:14:30 +0000350}
351
Evan Cheng71756e72009-08-04 01:43:45 +0000352static bool isT2i32Load(unsigned Opc) {
353 return Opc == ARM::t2LDRi12 || Opc == ARM::t2LDRi8;
354}
355
Evan Cheng4605e8a2009-07-09 23:11:34 +0000356static bool isi32Load(unsigned Opc) {
James Molloy556763d2014-05-16 14:14:30 +0000357 return Opc == ARM::LDRi12 || isT1i32Load(Opc) || isT2i32Load(Opc) ;
358}
359
360static bool isT1i32Store(unsigned Opc) {
Renato Golinb9887ef2015-02-25 14:41:06 +0000361 return Opc == ARM::tSTRi || Opc == ARM::tSTRspi;
Evan Cheng71756e72009-08-04 01:43:45 +0000362}
363
364static bool isT2i32Store(unsigned Opc) {
365 return Opc == ARM::t2STRi12 || Opc == ARM::t2STRi8;
Evan Cheng4605e8a2009-07-09 23:11:34 +0000366}
367
368static bool isi32Store(unsigned Opc) {
James Molloy556763d2014-05-16 14:14:30 +0000369 return Opc == ARM::STRi12 || isT1i32Store(Opc) || isT2i32Store(Opc);
370}
371
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000372static bool isLoadSingle(unsigned Opc) {
373 return isi32Load(Opc) || Opc == ARM::VLDRS || Opc == ARM::VLDRD;
374}
375
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000376static unsigned getImmScale(unsigned Opc) {
377 switch (Opc) {
378 default: llvm_unreachable("Unhandled opcode!");
379 case ARM::tLDRi:
380 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +0000381 case ARM::tLDRspi:
382 case ARM::tSTRspi:
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000383 return 1;
384 case ARM::tLDRHi:
385 case ARM::tSTRHi:
386 return 2;
387 case ARM::tLDRBi:
388 case ARM::tSTRBi:
389 return 4;
390 }
391}
392
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000393static unsigned getLSMultipleTransferSize(const MachineInstr *MI) {
394 switch (MI->getOpcode()) {
395 default: return 0;
396 case ARM::LDRi12:
397 case ARM::STRi12:
398 case ARM::tLDRi:
399 case ARM::tSTRi:
400 case ARM::tLDRspi:
401 case ARM::tSTRspi:
402 case ARM::t2LDRi8:
403 case ARM::t2LDRi12:
404 case ARM::t2STRi8:
405 case ARM::t2STRi12:
406 case ARM::VLDRS:
407 case ARM::VSTRS:
408 return 4;
409 case ARM::VLDRD:
410 case ARM::VSTRD:
411 return 8;
412 case ARM::LDMIA:
413 case ARM::LDMDA:
414 case ARM::LDMDB:
415 case ARM::LDMIB:
416 case ARM::STMIA:
417 case ARM::STMDA:
418 case ARM::STMDB:
419 case ARM::STMIB:
420 case ARM::tLDMIA:
421 case ARM::tLDMIA_UPD:
422 case ARM::tSTMIA_UPD:
423 case ARM::t2LDMIA:
424 case ARM::t2LDMDB:
425 case ARM::t2STMIA:
426 case ARM::t2STMDB:
427 case ARM::VLDMSIA:
428 case ARM::VSTMSIA:
429 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 4;
430 case ARM::VLDMDIA:
431 case ARM::VSTMDIA:
432 return (MI->getNumOperands() - MI->getDesc().getNumOperands() + 1) * 8;
433 }
434}
435
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000436/// Update future uses of the base register with the offset introduced
437/// due to writeback. This function only works on Thumb1.
438void
439ARMLoadStoreOpt::UpdateBaseRegUses(MachineBasicBlock &MBB,
440 MachineBasicBlock::iterator MBBI,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000441 DebugLoc DL, unsigned Base,
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000442 unsigned WordOffset,
443 ARMCC::CondCodes Pred, unsigned PredReg) {
444 assert(isThumb1 && "Can only update base register uses for Thumb1!");
445 // Start updating any instructions with immediate offsets. Insert a SUB before
446 // the first non-updateable instruction (if any).
447 for (; MBBI != MBB.end(); ++MBBI) {
448 bool InsertSub = false;
449 unsigned Opc = MBBI->getOpcode();
450
451 if (MBBI->readsRegister(Base)) {
452 int Offset;
453 bool IsLoad =
454 Opc == ARM::tLDRi || Opc == ARM::tLDRHi || Opc == ARM::tLDRBi;
455 bool IsStore =
456 Opc == ARM::tSTRi || Opc == ARM::tSTRHi || Opc == ARM::tSTRBi;
457
458 if (IsLoad || IsStore) {
459 // Loads and stores with immediate offsets can be updated, but only if
460 // the new offset isn't negative.
461 // The MachineOperand containing the offset immediate is the last one
462 // before predicates.
463 MachineOperand &MO =
464 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
465 // The offsets are scaled by 1, 2 or 4 depending on the Opcode.
466 Offset = MO.getImm() - WordOffset * getImmScale(Opc);
467
468 // If storing the base register, it needs to be reset first.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000469 unsigned InstrSrcReg = getLoadStoreRegOp(*MBBI).getReg();
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000470
471 if (Offset >= 0 && !(IsStore && InstrSrcReg == Base))
472 MO.setImm(Offset);
473 else
474 InsertSub = true;
475
476 } else if ((Opc == ARM::tSUBi8 || Opc == ARM::tADDi8) &&
477 !definesCPSR(MBBI)) {
478 // SUBS/ADDS using this register, with a dead def of the CPSR.
479 // Merge it with the update; if the merged offset is too large,
480 // insert a new sub instead.
481 MachineOperand &MO =
482 MBBI->getOperand(MBBI->getDesc().getNumOperands() - 3);
483 Offset = (Opc == ARM::tSUBi8) ?
484 MO.getImm() + WordOffset * 4 :
485 MO.getImm() - WordOffset * 4 ;
486 if (Offset >= 0 && TL->isLegalAddImmediate(Offset)) {
487 // FIXME: Swap ADDS<->SUBS if Offset < 0, erase instruction if
488 // Offset == 0.
489 MO.setImm(Offset);
490 // The base register has now been reset, so exit early.
491 return;
492 } else {
493 InsertSub = true;
494 }
495
496 } else {
497 // Can't update the instruction.
498 InsertSub = true;
499 }
500
501 } else if (definesCPSR(MBBI) || MBBI->isCall() || MBBI->isBranch()) {
502 // Since SUBS sets the condition flags, we can't place the base reset
503 // after an instruction that has a live CPSR def.
504 // The base register might also contain an argument for a function call.
505 InsertSub = true;
506 }
507
508 if (InsertSub) {
509 // An instruction above couldn't be updated, so insert a sub.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000510 AddDefaultT1CC(BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
Matthias Braunaa9fa352015-05-27 05:12:40 +0000511 .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000512 return;
513 }
514
John Brawnd86e0042015-06-23 16:02:11 +0000515 if (MBBI->killsRegister(Base) || MBBI->definesRegister(Base))
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000516 // Register got killed. Stop updating.
517 return;
518 }
519
520 // End of block was reached.
521 if (MBB.succ_size() > 0) {
522 // FIXME: Because of a bug, live registers are sometimes missing from
523 // the successor blocks' live-in sets. This means we can't trust that
524 // information and *always* have to reset at the end of a block.
525 // See PR21029.
526 if (MBBI != MBB.end()) --MBBI;
527 AddDefaultT1CC(
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000528 BuildMI(MBB, MBBI, DL, TII->get(ARM::tSUBi8), Base), true)
Matthias Braunaa9fa352015-05-27 05:12:40 +0000529 .addReg(Base).addImm(WordOffset * 4).addImm(Pred).addReg(PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000530 }
531}
532
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000533/// Return the first register of class \p RegClass that is not in \p Regs.
534unsigned ARMLoadStoreOpt::findFreeReg(const TargetRegisterClass &RegClass) {
535 if (!RegClassInfoValid) {
536 RegClassInfo.runOnMachineFunction(*MF);
537 RegClassInfoValid = true;
538 }
539
540 for (unsigned Reg : RegClassInfo.getOrder(&RegClass))
541 if (!LiveRegs.contains(Reg))
542 return Reg;
543 return 0;
544}
545
546/// Compute live registers just before instruction \p Before (in normal schedule
547/// direction). Computes backwards so multiple queries in the same block must
548/// come in reverse order.
549void ARMLoadStoreOpt::moveLiveRegsBefore(const MachineBasicBlock &MBB,
550 MachineBasicBlock::const_iterator Before) {
551 // Initialize if we never queried in this block.
552 if (!LiveRegsValid) {
553 LiveRegs.init(TRI);
554 LiveRegs.addLiveOuts(&MBB, true);
555 LiveRegPos = MBB.end();
556 LiveRegsValid = true;
557 }
558 // Move backward just before the "Before" position.
559 while (LiveRegPos != Before) {
560 --LiveRegPos;
561 LiveRegs.stepBackward(*LiveRegPos);
562 }
563}
564
565static bool ContainsReg(const ArrayRef<std::pair<unsigned, bool>> &Regs,
566 unsigned Reg) {
567 for (const std::pair<unsigned, bool> &R : Regs)
568 if (R.first == Reg)
569 return true;
570 return false;
571}
572
Matthias Braunec50fa62015-06-01 21:26:23 +0000573/// Create and insert a LDM or STM with Base as base register and registers in
574/// Regs as the register operands that would be loaded / stored. It returns
575/// true if the transformation is done.
Matthias Braune40d89e2015-07-21 00:18:59 +0000576MachineInstr *ARMLoadStoreOpt::CreateLoadStoreMulti(MachineBasicBlock &MBB,
577 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
578 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
579 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) {
Evan Cheng10043e22007-01-19 07:51:42 +0000580 unsigned NumRegs = Regs.size();
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000581 assert(NumRegs > 1);
Evan Cheng10043e22007-01-19 07:51:42 +0000582
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000583 // For Thumb1 targets, it might be necessary to clobber the CPSR to merge.
584 // Compute liveness information for that register to make the decision.
585 bool SafeToClobberCPSR = !isThumb1 ||
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000586 (MBB.computeRegisterLiveness(TRI, ARM::CPSR, InsertBefore, 20) ==
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000587 MachineBasicBlock::LQR_Dead);
588
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000589 bool Writeback = isThumb1; // Thumb1 LDM/STM have base reg writeback.
590
591 // Exception: If the base register is in the input reglist, Thumb1 LDM is
592 // non-writeback.
593 // It's also not possible to merge an STR of the base register in Thumb1.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000594 if (isThumb1 && isi32Load(Opcode) && ContainsReg(Regs, Base)) {
595 assert(Base != ARM::SP && "Thumb1 does not allow SP in register list");
596 if (Opcode == ARM::tLDRi) {
597 Writeback = false;
598 } else if (Opcode == ARM::tSTRi) {
599 return nullptr;
600 }
601 }
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000602
Evan Cheng10043e22007-01-19 07:51:42 +0000603 ARM_AM::AMSubMode Mode = ARM_AM::ia;
James Molloy556763d2014-05-16 14:14:30 +0000604 // VFP and Thumb2 do not support IB or DA modes. Thumb1 only supports IA.
Bob Wilson13ce07f2010-08-27 23:18:17 +0000605 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
James Molloy556763d2014-05-16 14:14:30 +0000606 bool haveIBAndDA = isNotVFP && !isThumb2 && !isThumb1;
607
James Molloybb73c232014-05-16 14:08:46 +0000608 if (Offset == 4 && haveIBAndDA) {
Evan Cheng10043e22007-01-19 07:51:42 +0000609 Mode = ARM_AM::ib;
James Molloybb73c232014-05-16 14:08:46 +0000610 } else if (Offset == -4 * (int)NumRegs + 4 && haveIBAndDA) {
Evan Cheng10043e22007-01-19 07:51:42 +0000611 Mode = ARM_AM::da;
James Molloy556763d2014-05-16 14:14:30 +0000612 } else if (Offset == -4 * (int)NumRegs && isNotVFP && !isThumb1) {
Bob Wilsonca5af122010-08-27 23:57:52 +0000613 // VLDM/VSTM do not support DB mode without also updating the base reg.
Evan Cheng10043e22007-01-19 07:51:42 +0000614 Mode = ARM_AM::db;
Renato Golinb9887ef2015-02-25 14:41:06 +0000615 } else if (Offset != 0 || Opcode == ARM::tLDRspi || Opcode == ARM::tSTRspi) {
James Molloybb73c232014-05-16 14:08:46 +0000616 // Check if this is a supported opcode before inserting instructions to
Owen Anderson7ac53ad2011-03-29 20:27:38 +0000617 // calculate a new base register.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000618 if (!getLoadStoreMultipleOpcode(Opcode, Mode)) return nullptr;
Owen Anderson7ac53ad2011-03-29 20:27:38 +0000619
Evan Cheng10043e22007-01-19 07:51:42 +0000620 // If starting offset isn't zero, insert a MI to materialize a new base.
621 // But only do so if it is cost effective, i.e. merging more than two
622 // loads / stores.
623 if (NumRegs <= 2)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000624 return nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000625
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000626 // On Thumb1, it's not worth materializing a new base register without
627 // clobbering the CPSR (i.e. not using ADDS/SUBS).
628 if (!SafeToClobberCPSR)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000629 return nullptr;
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000630
Evan Cheng10043e22007-01-19 07:51:42 +0000631 unsigned NewBase;
James Molloybb73c232014-05-16 14:08:46 +0000632 if (isi32Load(Opcode)) {
Scott Douglass290183d2015-10-01 11:56:19 +0000633 // If it is a load, then just use one of the destination registers
634 // as the new base. Will no longer be writeback in Thumb1.
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000635 NewBase = Regs[NumRegs-1].first;
Scott Douglass290183d2015-10-01 11:56:19 +0000636 Writeback = false;
James Molloybb73c232014-05-16 14:08:46 +0000637 } else {
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000638 // Find a free register that we can use as scratch register.
639 moveLiveRegsBefore(MBB, InsertBefore);
640 // The merged instruction does not exist yet but will use several Regs if
641 // it is a Store.
642 if (!isLoadSingle(Opcode))
643 for (const std::pair<unsigned, bool> &R : Regs)
644 LiveRegs.addReg(R.first);
645
646 NewBase = findFreeReg(isThumb1 ? ARM::tGPRRegClass : ARM::GPRRegClass);
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000647 if (NewBase == 0)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000648 return nullptr;
Evan Cheng10043e22007-01-19 07:51:42 +0000649 }
James Molloy556763d2014-05-16 14:14:30 +0000650
651 int BaseOpc =
652 isThumb2 ? ARM::t2ADDri :
Renato Golinb9887ef2015-02-25 14:41:06 +0000653 (isThumb1 && Base == ARM::SP) ? ARM::tADDrSPi :
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000654 (isThumb1 && Offset < 8) ? ARM::tADDi3 :
James Molloy556763d2014-05-16 14:14:30 +0000655 isThumb1 ? ARM::tADDi8 : ARM::ADDri;
656
Evan Cheng10043e22007-01-19 07:51:42 +0000657 if (Offset < 0) {
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000658 Offset = - Offset;
James Molloy556763d2014-05-16 14:14:30 +0000659 BaseOpc =
660 isThumb2 ? ARM::t2SUBri :
Renato Golinb9887ef2015-02-25 14:41:06 +0000661 (isThumb1 && Offset < 8 && Base != ARM::SP) ? ARM::tSUBi3 :
James Molloy556763d2014-05-16 14:14:30 +0000662 isThumb1 ? ARM::tSUBi8 : ARM::SUBri;
Evan Cheng10043e22007-01-19 07:51:42 +0000663 }
Evan Cheng41bc2fd2007-03-06 21:59:20 +0000664
James Molloy556763d2014-05-16 14:14:30 +0000665 if (!TL->isLegalAddImmediate(Offset))
666 // FIXME: Try add with register operand?
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000667 return nullptr; // Probably not worth it then.
668
669 // We can only append a kill flag to the add/sub input if the value is not
670 // used in the register list of the stm as well.
671 bool KillOldBase = BaseKill &&
672 (!isi32Store(Opcode) || !ContainsReg(Regs, Base));
James Molloy556763d2014-05-16 14:14:30 +0000673
674 if (isThumb1) {
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000675 // Thumb1: depending on immediate size, use either
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000676 // ADDS NewBase, Base, #imm3
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000677 // or
Moritz Rotheef9f4d2014-09-16 16:25:07 +0000678 // MOV NewBase, Base
679 // ADDS NewBase, #imm8.
Renato Golinb9887ef2015-02-25 14:41:06 +0000680 if (Base != NewBase &&
681 (BaseOpc == ARM::tADDi8 || BaseOpc == ARM::tSUBi8)) {
James Molloy556763d2014-05-16 14:14:30 +0000682 // Need to insert a MOV to the new base first.
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000683 if (isARMLowRegister(NewBase) && isARMLowRegister(Base) &&
Eric Christopher1b21f002015-01-29 00:19:33 +0000684 !STI->hasV6Ops()) {
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000685 // thumbv4t doesn't have lo->lo copies, and we can't predicate tMOVSr
686 if (Pred != ARMCC::AL)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000687 return nullptr;
688 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVSr), NewBase)
689 .addReg(Base, getKillRegState(KillOldBase));
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000690 } else
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000691 BuildMI(MBB, InsertBefore, DL, TII->get(ARM::tMOVr), NewBase)
692 .addReg(Base, getKillRegState(KillOldBase))
Jonathan Roelofs229eb4c2015-01-21 22:39:43 +0000693 .addImm(Pred).addReg(PredReg);
694
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000695 // The following ADDS/SUBS becomes an update.
Moritz Rothdfdda0d2014-08-21 17:11:03 +0000696 Base = NewBase;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000697 KillOldBase = true;
James Molloy556763d2014-05-16 14:14:30 +0000698 }
Renato Golinb9887ef2015-02-25 14:41:06 +0000699 if (BaseOpc == ARM::tADDrSPi) {
700 assert(Offset % 4 == 0 && "tADDrSPi offset is scaled by 4");
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000701 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
702 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset/4)
Renato Golinb9887ef2015-02-25 14:41:06 +0000703 .addImm(Pred).addReg(PredReg);
704 } else
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000705 AddDefaultT1CC(
706 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase), true)
707 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
Renato Golinb9887ef2015-02-25 14:41:06 +0000708 .addImm(Pred).addReg(PredReg);
James Molloy556763d2014-05-16 14:14:30 +0000709 } else {
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000710 BuildMI(MBB, InsertBefore, DL, TII->get(BaseOpc), NewBase)
711 .addReg(Base, getKillRegState(KillOldBase)).addImm(Offset)
James Molloy556763d2014-05-16 14:14:30 +0000712 .addImm(Pred).addReg(PredReg).addReg(0);
713 }
Evan Cheng10043e22007-01-19 07:51:42 +0000714 Base = NewBase;
James Molloybb73c232014-05-16 14:08:46 +0000715 BaseKill = true; // New base is always killed straight away.
Evan Cheng10043e22007-01-19 07:51:42 +0000716 }
717
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000718 bool isDef = isLoadSingle(Opcode);
James Molloy556763d2014-05-16 14:14:30 +0000719
720 // Get LS multiple opcode. Note that for Thumb1 this might be an opcode with
721 // base register writeback.
Bill Wendlinga68e3a52010-11-16 01:16:36 +0000722 Opcode = getLoadStoreMultipleOpcode(Opcode, Mode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000723 if (!Opcode)
724 return nullptr;
James Molloy556763d2014-05-16 14:14:30 +0000725
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000726 // Check if a Thumb1 LDM/STM merge is safe. This is the case if:
727 // - There is no writeback (LDM of base register),
728 // - the base register is killed by the merged instruction,
729 // - or it's safe to overwrite the condition flags, i.e. to insert a SUBS
730 // to reset the base register.
731 // Otherwise, don't merge.
732 // It's safe to return here since the code to materialize a new base register
733 // above is also conditional on SafeToClobberCPSR.
734 if (isThumb1 && !SafeToClobberCPSR && Writeback && !BaseKill)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000735 return nullptr;
Moritz Roth8f376562014-08-15 17:00:30 +0000736
James Molloy556763d2014-05-16 14:14:30 +0000737 MachineInstrBuilder MIB;
738
739 if (Writeback) {
Scott Douglass290183d2015-10-01 11:56:19 +0000740 assert(isThumb1 && "expected Writeback only inThumb1");
741 if (Opcode == ARM::tLDMIA) {
742 assert(!(ContainsReg(Regs, Base)) && "Thumb1 can't LDM ! with Base in Regs");
James Molloy556763d2014-05-16 14:14:30 +0000743 // Update tLDMIA with writeback if necessary.
744 Opcode = ARM::tLDMIA_UPD;
Scott Douglass290183d2015-10-01 11:56:19 +0000745 }
James Molloy556763d2014-05-16 14:14:30 +0000746
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000747 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
James Molloy556763d2014-05-16 14:14:30 +0000748
749 // Thumb1: we might need to set base writeback when building the MI.
750 MIB.addReg(Base, getDefRegState(true))
751 .addReg(Base, getKillRegState(BaseKill));
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000752
753 // The base isn't dead after a merged instruction with writeback.
754 // Insert a sub instruction after the newly formed instruction to reset.
755 if (!BaseKill)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000756 UpdateBaseRegUses(MBB, InsertBefore, DL, Base, NumRegs, Pred, PredReg);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000757
James Molloy556763d2014-05-16 14:14:30 +0000758 } else {
759 // No writeback, simply build the MachineInstr.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000760 MIB = BuildMI(MBB, InsertBefore, DL, TII->get(Opcode));
James Molloy556763d2014-05-16 14:14:30 +0000761 MIB.addReg(Base, getKillRegState(BaseKill));
762 }
763
764 MIB.addImm(Pred).addReg(PredReg);
765
Matthias Braunaa9fa352015-05-27 05:12:40 +0000766 for (const std::pair<unsigned, bool> &R : Regs)
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000767 MIB.addReg(R.first, getDefRegState(isDef) | getKillRegState(R.second));
Evan Cheng10043e22007-01-19 07:51:42 +0000768
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000769 return MIB.getInstr();
Tim Northover569f69d2013-10-10 09:28:20 +0000770}
771
Matthias Braune40d89e2015-07-21 00:18:59 +0000772MachineInstr *ARMLoadStoreOpt::CreateLoadStoreDouble(MachineBasicBlock &MBB,
773 MachineBasicBlock::iterator InsertBefore, int Offset, unsigned Base,
774 bool BaseKill, unsigned Opcode, ARMCC::CondCodes Pred, unsigned PredReg,
775 DebugLoc DL, ArrayRef<std::pair<unsigned, bool>> Regs) const {
776 bool IsLoad = isi32Load(Opcode);
777 assert((IsLoad || isi32Store(Opcode)) && "Must have integer load or store");
778 unsigned LoadStoreOpcode = IsLoad ? ARM::t2LDRDi8 : ARM::t2STRDi8;
779
780 assert(Regs.size() == 2);
781 MachineInstrBuilder MIB = BuildMI(MBB, InsertBefore, DL,
782 TII->get(LoadStoreOpcode));
783 if (IsLoad) {
784 MIB.addReg(Regs[0].first, RegState::Define)
785 .addReg(Regs[1].first, RegState::Define);
786 } else {
787 MIB.addReg(Regs[0].first, getKillRegState(Regs[0].second))
788 .addReg(Regs[1].first, getKillRegState(Regs[1].second));
789 }
790 MIB.addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
791 return MIB.getInstr();
792}
793
Matthias Braunec50fa62015-06-01 21:26:23 +0000794/// Call MergeOps and update MemOps and merges accordingly on success.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000795MachineInstr *ARMLoadStoreOpt::MergeOpsUpdate(const MergeCandidate &Cand) {
796 const MachineInstr *First = Cand.Instrs.front();
797 unsigned Opcode = First->getOpcode();
798 bool IsLoad = isLoadSingle(Opcode);
Evan Cheng1fb4de82010-06-21 21:21:14 +0000799 SmallVector<std::pair<unsigned, bool>, 8> Regs;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000800 SmallVector<unsigned, 4> ImpDefs;
801 DenseSet<unsigned> KilledRegs;
Pete Coopere3c81612015-07-16 00:09:18 +0000802 DenseSet<unsigned> UsedRegs;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000803 // Determine list of registers and list of implicit super-register defs.
804 for (const MachineInstr *MI : Cand.Instrs) {
805 const MachineOperand &MO = getLoadStoreRegOp(*MI);
806 unsigned Reg = MO.getReg();
807 bool IsKill = MO.isKill();
808 if (IsKill)
809 KilledRegs.insert(Reg);
810 Regs.push_back(std::make_pair(Reg, IsKill));
Pete Coopere3c81612015-07-16 00:09:18 +0000811 UsedRegs.insert(Reg);
Jakob Stoklund Olesencdee3262012-03-28 22:50:56 +0000812
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000813 if (IsLoad) {
814 // Collect any implicit defs of super-registers, after merging we can't
815 // be sure anymore that we properly preserved these live ranges and must
816 // removed these implicit operands.
817 for (const MachineOperand &MO : MI->implicit_operands()) {
818 if (!MO.isReg() || !MO.isDef() || MO.isDead())
819 continue;
820 assert(MO.isImplicit());
821 unsigned DefReg = MO.getReg();
822
823 if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) != ImpDefs.end())
824 continue;
825 // We can ignore cases where the super-reg is read and written.
826 if (MI->readsRegister(DefReg))
827 continue;
Jakob Stoklund Olesencdee3262012-03-28 22:50:56 +0000828 ImpDefs.push_back(DefReg);
Evan Cheng1fb4de82010-06-21 21:21:14 +0000829 }
830 }
Jakob Stoklund Olesen655e4e62009-12-23 21:28:23 +0000831 }
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000832
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000833 // Attempt the merge.
834 typedef MachineBasicBlock::iterator iterator;
835 MachineInstr *LatestMI = Cand.Instrs[Cand.LatestMIIdx];
836 iterator InsertBefore = std::next(iterator(LatestMI));
837 MachineBasicBlock &MBB = *LatestMI->getParent();
838 unsigned Offset = getMemoryOpOffset(First);
839 unsigned Base = getLoadStoreBaseOp(*First).getReg();
840 bool BaseKill = LatestMI->killsRegister(Base);
841 unsigned PredReg = 0;
842 ARMCC::CondCodes Pred = getInstrPredicate(First, PredReg);
843 DebugLoc DL = First->getDebugLoc();
Matthias Braune40d89e2015-07-21 00:18:59 +0000844 MachineInstr *Merged = nullptr;
845 if (Cand.CanMergeToLSDouble)
846 Merged = CreateLoadStoreDouble(MBB, InsertBefore, Offset, Base, BaseKill,
847 Opcode, Pred, PredReg, DL, Regs);
848 if (!Merged && Cand.CanMergeToLSMulti)
849 Merged = CreateLoadStoreMulti(MBB, InsertBefore, Offset, Base, BaseKill,
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000850 Opcode, Pred, PredReg, DL, Regs);
851 if (!Merged)
852 return nullptr;
853
854 // Determine earliest instruction that will get removed. We then keep an
855 // iterator just above it so the following erases don't invalidated it.
856 iterator EarliestI(Cand.Instrs[Cand.EarliestMIIdx]);
857 bool EarliestAtBegin = false;
858 if (EarliestI == MBB.begin()) {
859 EarliestAtBegin = true;
860 } else {
861 EarliestI = std::prev(EarliestI);
Moritz Rothf5d0c7c2014-09-24 16:35:50 +0000862 }
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000863
864 // Remove instructions which have been merged.
865 for (MachineInstr *MI : Cand.Instrs)
866 MBB.erase(MI);
867
868 // Determine range between the earliest removed instruction and the new one.
869 if (EarliestAtBegin)
870 EarliestI = MBB.begin();
871 else
872 EarliestI = std::next(EarliestI);
873 auto FixupRange = make_range(EarliestI, iterator(Merged));
874
875 if (isLoadSingle(Opcode)) {
876 // If the previous loads defined a super-reg, then we have to mark earlier
877 // operands undef; Replicate the super-reg def on the merged instruction.
878 for (MachineInstr &MI : FixupRange) {
879 for (unsigned &ImpDefReg : ImpDefs) {
880 for (MachineOperand &MO : MI.implicit_operands()) {
881 if (!MO.isReg() || MO.getReg() != ImpDefReg)
882 continue;
883 if (MO.readsReg())
884 MO.setIsUndef();
885 else if (MO.isDef())
886 ImpDefReg = 0;
887 }
888 }
889 }
890
891 MachineInstrBuilder MIB(*Merged->getParent()->getParent(), Merged);
892 for (unsigned ImpDef : ImpDefs)
893 MIB.addReg(ImpDef, RegState::ImplicitDefine);
894 } else {
895 // Remove kill flags: We are possibly storing the values later now.
896 assert(isi32Store(Opcode) || Opcode == ARM::VSTRS || Opcode == ARM::VSTRD);
897 for (MachineInstr &MI : FixupRange) {
898 for (MachineOperand &MO : MI.uses()) {
899 if (!MO.isReg() || !MO.isKill())
900 continue;
Pete Coopere3c81612015-07-16 00:09:18 +0000901 if (UsedRegs.count(MO.getReg()))
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000902 MO.setIsKill(false);
903 }
904 }
905 assert(ImpDefs.empty());
906 }
907
908 return Merged;
Jakob Stoklund Olesen655e4e62009-12-23 21:28:23 +0000909}
910
Matthias Braune40d89e2015-07-21 00:18:59 +0000911static bool isValidLSDoubleOffset(int Offset) {
912 unsigned Value = abs(Offset);
913 // t2LDRDi8/t2STRDi8 supports an 8 bit immediate which is internally
914 // multiplied by 4.
915 return (Value % 4) == 0 && Value < 1024;
916}
917
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000918/// Find candidates for load/store multiple merge in list of MemOpQueueEntries.
919void ARMLoadStoreOpt::FormCandidates(const MemOpQueue &MemOps) {
920 const MachineInstr *FirstMI = MemOps[0].MI;
921 unsigned Opcode = FirstMI->getOpcode();
Bob Wilson13ce07f2010-08-27 23:18:17 +0000922 bool isNotVFP = isi32Load(Opcode) || isi32Store(Opcode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000923 unsigned Size = getLSMultipleTransferSize(FirstMI);
Evan Cheng0f7cbe82007-05-15 01:29:07 +0000924
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000925 unsigned SIndex = 0;
926 unsigned EIndex = MemOps.size();
927 do {
928 // Look at the first instruction.
929 const MachineInstr *MI = MemOps[SIndex].MI;
930 int Offset = MemOps[SIndex].Offset;
931 const MachineOperand &PMO = getLoadStoreRegOp(*MI);
932 unsigned PReg = PMO.getReg();
933 unsigned PRegNum = PMO.isUndef() ? UINT_MAX : TRI->getEncodingValue(PReg);
934 unsigned Latest = SIndex;
935 unsigned Earliest = SIndex;
936 unsigned Count = 1;
Matthias Braune40d89e2015-07-21 00:18:59 +0000937 bool CanMergeToLSDouble =
938 STI->isThumb2() && isNotVFP && isValidLSDoubleOffset(Offset);
939 // ARM errata 602117: LDRD with base in list may result in incorrect base
940 // register when interrupted or faulted.
941 if (STI->isCortexM3() && isi32Load(Opcode) &&
942 PReg == getLoadStoreBaseOp(*MI).getReg())
943 CanMergeToLSDouble = false;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000944
Matthias Braune40d89e2015-07-21 00:18:59 +0000945 bool CanMergeToLSMulti = true;
946 // On swift vldm/vstm starting with an odd register number as that needs
947 // more uops than single vldrs.
948 if (STI->isSwift() && !isNotVFP && (PRegNum % 2) == 1)
949 CanMergeToLSMulti = false;
950
951 // LDRD/STRD do not allow SP/PC. LDM/STM do not support it or have it
952 // deprecated; LDM to PC is fine but cannot happen here.
953 if (PReg == ARM::SP || PReg == ARM::PC)
954 CanMergeToLSMulti = CanMergeToLSDouble = false;
955
956 // Merge following instructions where possible.
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000957 for (unsigned I = SIndex+1; I < EIndex; ++I, ++Count) {
958 int NewOffset = MemOps[I].Offset;
959 if (NewOffset != Offset + (int)Size)
960 break;
961 const MachineOperand &MO = getLoadStoreRegOp(*MemOps[I].MI);
962 unsigned Reg = MO.getReg();
Matthias Braune40d89e2015-07-21 00:18:59 +0000963 if (Reg == ARM::SP || Reg == ARM::PC)
Matthias Braun731e3592015-07-20 23:17:20 +0000964 break;
965
Matthias Braune40d89e2015-07-21 00:18:59 +0000966 // See if the current load/store may be part of a multi load/store.
967 unsigned RegNum = MO.isUndef() ? UINT_MAX : TRI->getEncodingValue(Reg);
968 bool PartOfLSMulti = CanMergeToLSMulti;
969 if (PartOfLSMulti) {
970 // Register numbers must be in ascending order.
971 if (RegNum <= PRegNum)
972 PartOfLSMulti = false;
973 // For VFP / NEON load/store multiples, the registers must be
974 // consecutive and within the limit on the number of registers per
975 // instruction.
976 else if (!isNotVFP && RegNum != PRegNum+1)
977 PartOfLSMulti = false;
978 }
979 // See if the current load/store may be part of a double load/store.
980 bool PartOfLSDouble = CanMergeToLSDouble && Count <= 1;
981
982 if (!PartOfLSMulti && !PartOfLSDouble)
983 break;
984 CanMergeToLSMulti &= PartOfLSMulti;
985 CanMergeToLSDouble &= PartOfLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000986 // Track MemOp with latest and earliest position (Positions are
987 // counted in reverse).
988 unsigned Position = MemOps[I].Position;
989 if (Position < MemOps[Latest].Position)
990 Latest = I;
991 else if (Position > MemOps[Earliest].Position)
992 Earliest = I;
993 // Prepare for next MemOp.
Evan Cheng10043e22007-01-19 07:51:42 +0000994 Offset += Size;
Evan Cheng10043e22007-01-19 07:51:42 +0000995 PRegNum = RegNum;
Evan Cheng10043e22007-01-19 07:51:42 +0000996 }
997
Matthias Brauna4a3182d2015-07-10 18:08:49 +0000998 // Form a candidate from the Ops collected so far.
Matthias Braune40d89e2015-07-21 00:18:59 +0000999 MergeCandidate *Candidate = new(Allocator.Allocate()) MergeCandidate;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001000 for (unsigned C = SIndex, CE = SIndex + Count; C < CE; ++C)
1001 Candidate->Instrs.push_back(MemOps[C].MI);
1002 Candidate->LatestMIIdx = Latest - SIndex;
1003 Candidate->EarliestMIIdx = Earliest - SIndex;
1004 Candidate->InsertPos = MemOps[Latest].Position;
Matthias Braune40d89e2015-07-21 00:18:59 +00001005 if (Count == 1)
1006 CanMergeToLSMulti = CanMergeToLSDouble = false;
1007 Candidate->CanMergeToLSMulti = CanMergeToLSMulti;
1008 Candidate->CanMergeToLSDouble = CanMergeToLSDouble;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001009 Candidates.push_back(Candidate);
1010 // Continue after the chain.
1011 SIndex += Count;
1012 } while (SIndex < EIndex);
Evan Cheng10043e22007-01-19 07:51:42 +00001013}
1014
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001015static unsigned getUpdatingLSMultipleOpcode(unsigned Opc,
1016 ARM_AM::AMSubMode Mode) {
Bob Wilson947f04b2010-03-13 01:08:20 +00001017 switch (Opc) {
Bob Wilson947f04b2010-03-13 01:08:20 +00001018 default: llvm_unreachable("Unhandled opcode!");
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001019 case ARM::LDMIA:
1020 case ARM::LDMDA:
1021 case ARM::LDMDB:
1022 case ARM::LDMIB:
1023 switch (Mode) {
1024 default: llvm_unreachable("Unhandled submode!");
1025 case ARM_AM::ia: return ARM::LDMIA_UPD;
1026 case ARM_AM::ib: return ARM::LDMIB_UPD;
1027 case ARM_AM::da: return ARM::LDMDA_UPD;
1028 case ARM_AM::db: return ARM::LDMDB_UPD;
1029 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001030 case ARM::STMIA:
1031 case ARM::STMDA:
1032 case ARM::STMDB:
1033 case ARM::STMIB:
1034 switch (Mode) {
1035 default: llvm_unreachable("Unhandled submode!");
1036 case ARM_AM::ia: return ARM::STMIA_UPD;
1037 case ARM_AM::ib: return ARM::STMIB_UPD;
1038 case ARM_AM::da: return ARM::STMDA_UPD;
1039 case ARM_AM::db: return ARM::STMDB_UPD;
1040 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001041 case ARM::t2LDMIA:
1042 case ARM::t2LDMDB:
1043 switch (Mode) {
1044 default: llvm_unreachable("Unhandled submode!");
1045 case ARM_AM::ia: return ARM::t2LDMIA_UPD;
1046 case ARM_AM::db: return ARM::t2LDMDB_UPD;
1047 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001048 case ARM::t2STMIA:
1049 case ARM::t2STMDB:
1050 switch (Mode) {
1051 default: llvm_unreachable("Unhandled submode!");
1052 case ARM_AM::ia: return ARM::t2STMIA_UPD;
1053 case ARM_AM::db: return ARM::t2STMDB_UPD;
1054 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001055 case ARM::VLDMSIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001056 switch (Mode) {
1057 default: llvm_unreachable("Unhandled submode!");
1058 case ARM_AM::ia: return ARM::VLDMSIA_UPD;
1059 case ARM_AM::db: return ARM::VLDMSDB_UPD;
1060 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001061 case ARM::VLDMDIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001062 switch (Mode) {
1063 default: llvm_unreachable("Unhandled submode!");
1064 case ARM_AM::ia: return ARM::VLDMDIA_UPD;
1065 case ARM_AM::db: return ARM::VLDMDDB_UPD;
1066 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001067 case ARM::VSTMSIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001068 switch (Mode) {
1069 default: llvm_unreachable("Unhandled submode!");
1070 case ARM_AM::ia: return ARM::VSTMSIA_UPD;
1071 case ARM_AM::db: return ARM::VSTMSDB_UPD;
1072 }
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001073 case ARM::VSTMDIA:
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001074 switch (Mode) {
1075 default: llvm_unreachable("Unhandled submode!");
1076 case ARM_AM::ia: return ARM::VSTMDIA_UPD;
1077 case ARM_AM::db: return ARM::VSTMDDB_UPD;
1078 }
Bob Wilson947f04b2010-03-13 01:08:20 +00001079 }
Bob Wilson947f04b2010-03-13 01:08:20 +00001080}
1081
Matthias Brauna50d2202015-07-21 00:19:01 +00001082/// Check if the given instruction increments or decrements a register and
1083/// return the amount it is incremented/decremented. Returns 0 if the CPSR flags
1084/// generated by the instruction are possibly read as well.
1085static int isIncrementOrDecrement(const MachineInstr &MI, unsigned Reg,
1086 ARMCC::CondCodes Pred, unsigned PredReg) {
1087 bool CheckCPSRDef;
1088 int Scale;
1089 switch (MI.getOpcode()) {
1090 case ARM::tADDi8: Scale = 4; CheckCPSRDef = true; break;
1091 case ARM::tSUBi8: Scale = -4; CheckCPSRDef = true; break;
1092 case ARM::t2SUBri:
1093 case ARM::SUBri: Scale = -1; CheckCPSRDef = true; break;
1094 case ARM::t2ADDri:
1095 case ARM::ADDri: Scale = 1; CheckCPSRDef = true; break;
1096 case ARM::tADDspi: Scale = 4; CheckCPSRDef = false; break;
1097 case ARM::tSUBspi: Scale = -4; CheckCPSRDef = false; break;
1098 default: return 0;
1099 }
1100
1101 unsigned MIPredReg;
1102 if (MI.getOperand(0).getReg() != Reg ||
1103 MI.getOperand(1).getReg() != Reg ||
1104 getInstrPredicate(&MI, MIPredReg) != Pred ||
1105 MIPredReg != PredReg)
1106 return 0;
1107
1108 if (CheckCPSRDef && definesCPSR(&MI))
1109 return 0;
1110 return MI.getOperand(2).getImm() * Scale;
1111}
1112
1113/// Searches for an increment or decrement of \p Reg before \p MBBI.
1114static MachineBasicBlock::iterator
1115findIncDecBefore(MachineBasicBlock::iterator MBBI, unsigned Reg,
1116 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1117 Offset = 0;
1118 MachineBasicBlock &MBB = *MBBI->getParent();
1119 MachineBasicBlock::iterator BeginMBBI = MBB.begin();
1120 MachineBasicBlock::iterator EndMBBI = MBB.end();
1121 if (MBBI == BeginMBBI)
1122 return EndMBBI;
1123
1124 // Skip debug values.
1125 MachineBasicBlock::iterator PrevMBBI = std::prev(MBBI);
1126 while (PrevMBBI->isDebugValue() && PrevMBBI != BeginMBBI)
1127 --PrevMBBI;
1128
1129 Offset = isIncrementOrDecrement(*PrevMBBI, Reg, Pred, PredReg);
1130 return Offset == 0 ? EndMBBI : PrevMBBI;
1131}
1132
1133/// Searches for a increment or decrement of \p Reg after \p MBBI.
1134static MachineBasicBlock::iterator
1135findIncDecAfter(MachineBasicBlock::iterator MBBI, unsigned Reg,
1136 ARMCC::CondCodes Pred, unsigned PredReg, int &Offset) {
1137 Offset = 0;
1138 MachineBasicBlock &MBB = *MBBI->getParent();
1139 MachineBasicBlock::iterator EndMBBI = MBB.end();
1140 MachineBasicBlock::iterator NextMBBI = std::next(MBBI);
1141 // Skip debug values.
1142 while (NextMBBI != EndMBBI && NextMBBI->isDebugValue())
1143 ++NextMBBI;
1144 if (NextMBBI == EndMBBI)
1145 return EndMBBI;
1146
1147 Offset = isIncrementOrDecrement(*NextMBBI, Reg, Pred, PredReg);
1148 return Offset == 0 ? EndMBBI : NextMBBI;
1149}
1150
Matthias Braunec50fa62015-06-01 21:26:23 +00001151/// Fold proceeding/trailing inc/dec of base register into the
1152/// LDM/STM/VLDM{D|S}/VSTM{D|S} op when possible:
Evan Cheng10043e22007-01-19 07:51:42 +00001153///
1154/// stmia rn, <ra, rb, rc>
1155/// rn := rn + 4 * 3;
1156/// =>
1157/// stmia rn!, <ra, rb, rc>
1158///
1159/// rn := rn - 4 * 3;
1160/// ldmia rn, <ra, rb, rc>
1161/// =>
1162/// ldmdb rn!, <ra, rb, rc>
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001163bool ARMLoadStoreOpt::MergeBaseUpdateLSMultiple(MachineInstr *MI) {
James Molloy556763d2014-05-16 14:14:30 +00001164 // Thumb1 is already using updating loads/stores.
1165 if (isThumb1) return false;
1166
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001167 const MachineOperand &BaseOP = MI->getOperand(0);
1168 unsigned Base = BaseOP.getReg();
1169 bool BaseKill = BaseOP.isKill();
Evan Cheng94f04c62007-07-05 07:18:20 +00001170 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001171 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
Matthias Braunfa3872e2015-05-18 20:27:55 +00001172 unsigned Opcode = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001173 DebugLoc DL = MI->getDebugLoc();
Evan Cheng10043e22007-01-19 07:51:42 +00001174
Bob Wilson13ce07f2010-08-27 23:18:17 +00001175 // Can't use an updating ld/st if the base register is also a dest
1176 // register. e.g. ldmdb r0!, {r0, r1, r2}. The behavior is undefined.
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001177 for (unsigned i = 2, e = MI->getNumOperands(); i != e; ++i)
Bob Wilson13ce07f2010-08-27 23:18:17 +00001178 if (MI->getOperand(i).getReg() == Base)
1179 return false;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001180
Matthias Brauna50d2202015-07-21 00:19:01 +00001181 int Bytes = getLSMultipleTransferSize(MI);
Matthias Braun84e28972015-07-20 23:17:16 +00001182 MachineBasicBlock &MBB = *MI->getParent();
Matthias Braun84e28972015-07-20 23:17:16 +00001183 MachineBasicBlock::iterator MBBI(MI);
Matthias Brauna50d2202015-07-21 00:19:01 +00001184 int Offset;
1185 MachineBasicBlock::iterator MergeInstr
1186 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1187 ARM_AM::AMSubMode Mode = getLoadStoreMultipleSubMode(Opcode);
1188 if (Mode == ARM_AM::ia && Offset == -Bytes) {
1189 Mode = ARM_AM::db;
1190 } else if (Mode == ARM_AM::ib && Offset == -Bytes) {
1191 Mode = ARM_AM::da;
1192 } else {
1193 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1194 if (((Mode != ARM_AM::ia && Mode != ARM_AM::ib) || Offset != Bytes) &&
1195 ((Mode != ARM_AM::da && Mode != ARM_AM::db) || Offset != -Bytes))
1196 return false;
Bob Wilson947f04b2010-03-13 01:08:20 +00001197 }
Matthias Brauna50d2202015-07-21 00:19:01 +00001198 MBB.erase(MergeInstr);
Bob Wilson947f04b2010-03-13 01:08:20 +00001199
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001200 unsigned NewOpc = getUpdatingLSMultipleOpcode(Opcode, Mode);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001201 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
Bob Wilson947f04b2010-03-13 01:08:20 +00001202 .addReg(Base, getDefRegState(true)) // WB base register
Bob Wilson13ce07f2010-08-27 23:18:17 +00001203 .addReg(Base, getKillRegState(BaseKill))
Bob Wilson13ce07f2010-08-27 23:18:17 +00001204 .addImm(Pred).addReg(PredReg);
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001205
Bob Wilson947f04b2010-03-13 01:08:20 +00001206 // Transfer the rest of operands.
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001207 for (unsigned OpNum = 3, e = MI->getNumOperands(); OpNum != e; ++OpNum)
Bob Wilson947f04b2010-03-13 01:08:20 +00001208 MIB.addOperand(MI->getOperand(OpNum));
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001209
Bob Wilson947f04b2010-03-13 01:08:20 +00001210 // Transfer memoperands.
Chris Lattner1d0c2572011-04-29 05:24:29 +00001211 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Bob Wilson947f04b2010-03-13 01:08:20 +00001212
1213 MBB.erase(MBBI);
1214 return true;
Evan Cheng10043e22007-01-19 07:51:42 +00001215}
1216
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001217static unsigned getPreIndexedLoadStoreOpcode(unsigned Opc,
1218 ARM_AM::AddrOpc Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +00001219 switch (Opc) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001220 case ARM::LDRi12:
Owen Anderson16d33f32011-08-26 20:43:14 +00001221 return ARM::LDR_PRE_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001222 case ARM::STRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001223 return ARM::STR_PRE_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001224 case ARM::VLDRS:
1225 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1226 case ARM::VLDRD:
1227 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1228 case ARM::VSTRS:
1229 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1230 case ARM::VSTRD:
1231 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001232 case ARM::t2LDRi8:
1233 case ARM::t2LDRi12:
1234 return ARM::t2LDR_PRE;
1235 case ARM::t2STRi8:
1236 case ARM::t2STRi12:
1237 return ARM::t2STR_PRE;
Torok Edwinfbcc6632009-07-14 16:55:14 +00001238 default: llvm_unreachable("Unhandled opcode!");
Evan Cheng10043e22007-01-19 07:51:42 +00001239 }
Evan Cheng10043e22007-01-19 07:51:42 +00001240}
1241
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001242static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
1243 ARM_AM::AddrOpc Mode) {
Evan Cheng10043e22007-01-19 07:51:42 +00001244 switch (Opc) {
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001245 case ARM::LDRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001246 return ARM::LDR_POST_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001247 case ARM::STRi12:
Owen Anderson2aedba62011-07-26 20:54:26 +00001248 return ARM::STR_POST_IMM;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001249 case ARM::VLDRS:
1250 return Mode == ARM_AM::add ? ARM::VLDMSIA_UPD : ARM::VLDMSDB_UPD;
1251 case ARM::VLDRD:
1252 return Mode == ARM_AM::add ? ARM::VLDMDIA_UPD : ARM::VLDMDDB_UPD;
1253 case ARM::VSTRS:
1254 return Mode == ARM_AM::add ? ARM::VSTMSIA_UPD : ARM::VSTMSDB_UPD;
1255 case ARM::VSTRD:
1256 return Mode == ARM_AM::add ? ARM::VSTMDIA_UPD : ARM::VSTMDDB_UPD;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001257 case ARM::t2LDRi8:
1258 case ARM::t2LDRi12:
1259 return ARM::t2LDR_POST;
1260 case ARM::t2STRi8:
1261 case ARM::t2STRi12:
1262 return ARM::t2STR_POST;
Torok Edwinfbcc6632009-07-14 16:55:14 +00001263 default: llvm_unreachable("Unhandled opcode!");
Evan Cheng10043e22007-01-19 07:51:42 +00001264 }
Evan Cheng10043e22007-01-19 07:51:42 +00001265}
1266
Matthias Braunec50fa62015-06-01 21:26:23 +00001267/// Fold proceeding/trailing inc/dec of base register into the
1268/// LDR/STR/FLD{D|S}/FST{D|S} op when possible:
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001269bool ARMLoadStoreOpt::MergeBaseUpdateLoadStore(MachineInstr *MI) {
James Molloy556763d2014-05-16 14:14:30 +00001270 // Thumb1 doesn't have updating LDR/STR.
1271 // FIXME: Use LDM/STM with single register instead.
1272 if (isThumb1) return false;
1273
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001274 unsigned Base = getLoadStoreBaseOp(*MI).getReg();
1275 bool BaseKill = getLoadStoreBaseOp(*MI).isKill();
Matthias Braunfa3872e2015-05-18 20:27:55 +00001276 unsigned Opcode = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001277 DebugLoc DL = MI->getDebugLoc();
Bob Wilsonaf10d272010-03-12 22:50:09 +00001278 bool isAM5 = (Opcode == ARM::VLDRD || Opcode == ARM::VLDRS ||
1279 Opcode == ARM::VSTRD || Opcode == ARM::VSTRS);
Jim Grosbach338de3e2010-10-27 23:12:14 +00001280 bool isAM2 = (Opcode == ARM::LDRi12 || Opcode == ARM::STRi12);
1281 if (isi32Load(Opcode) || isi32Store(Opcode))
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00001282 if (MI->getOperand(2).getImm() != 0)
1283 return false;
Bob Wilsonaf10d272010-03-12 22:50:09 +00001284 if (isAM5 && ARM_AM::getAM5Offset(MI->getOperand(2).getImm()) != 0)
Evan Cheng4605e8a2009-07-09 23:11:34 +00001285 return false;
Evan Cheng10043e22007-01-19 07:51:42 +00001286
Evan Cheng10043e22007-01-19 07:51:42 +00001287 // Can't do the merge if the destination register is the same as the would-be
1288 // writeback register.
Chad Rosierace9c5d2013-03-25 16:29:20 +00001289 if (MI->getOperand(0).getReg() == Base)
Evan Cheng10043e22007-01-19 07:51:42 +00001290 return false;
1291
Evan Cheng94f04c62007-07-05 07:18:20 +00001292 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001293 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
Matthias Brauna50d2202015-07-21 00:19:01 +00001294 int Bytes = getLSMultipleTransferSize(MI);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001295 MachineBasicBlock &MBB = *MI->getParent();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001296 MachineBasicBlock::iterator MBBI(MI);
Matthias Brauna50d2202015-07-21 00:19:01 +00001297 int Offset;
1298 MachineBasicBlock::iterator MergeInstr
1299 = findIncDecBefore(MBBI, Base, Pred, PredReg, Offset);
1300 unsigned NewOpc;
1301 if (!isAM5 && Offset == Bytes) {
1302 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1303 } else if (Offset == -Bytes) {
1304 NewOpc = getPreIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1305 } else {
1306 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1307 if (Offset == Bytes) {
1308 NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::add);
1309 } else if (!isAM5 && Offset == -Bytes) {
1310 NewOpc = getPostIndexedLoadStoreOpcode(Opcode, ARM_AM::sub);
1311 } else
1312 return false;
Evan Cheng10043e22007-01-19 07:51:42 +00001313 }
Matthias Brauna50d2202015-07-21 00:19:01 +00001314 MBB.erase(MergeInstr);
Evan Cheng10043e22007-01-19 07:51:42 +00001315
Matthias Brauna50d2202015-07-21 00:19:01 +00001316 ARM_AM::AddrOpc AddSub = Offset < 0 ? ARM_AM::sub : ARM_AM::add;
Evan Cheng10043e22007-01-19 07:51:42 +00001317
Matthias Brauna50d2202015-07-21 00:19:01 +00001318 bool isLd = isLoadSingle(Opcode);
Bob Wilson53149402010-03-13 00:43:32 +00001319 if (isAM5) {
James Molloybb73c232014-05-16 14:08:46 +00001320 // VLDM[SD]_UPD, VSTM[SD]_UPD
Bob Wilson13ce07f2010-08-27 23:18:17 +00001321 // (There are no base-updating versions of VLDR/VSTR instructions, but the
1322 // updating load/store-multiple instructions can be used with only one
1323 // register.)
Bob Wilson53149402010-03-13 00:43:32 +00001324 MachineOperand &MO = MI->getOperand(0);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001325 BuildMI(MBB, MBBI, DL, TII->get(NewOpc))
Bob Wilson947f04b2010-03-13 01:08:20 +00001326 .addReg(Base, getDefRegState(true)) // WB base register
Bob Wilson53149402010-03-13 00:43:32 +00001327 .addReg(Base, getKillRegState(isLd ? BaseKill : false))
Bob Wilson53149402010-03-13 00:43:32 +00001328 .addImm(Pred).addReg(PredReg)
Bob Wilson53149402010-03-13 00:43:32 +00001329 .addReg(MO.getReg(), (isLd ? getDefRegState(true) :
1330 getKillRegState(MO.isKill())));
1331 } else if (isLd) {
Jim Grosbach23254742011-08-12 22:20:41 +00001332 if (isAM2) {
Owen Anderson63143432011-08-29 17:59:41 +00001333 // LDR_PRE, LDR_POST
1334 if (NewOpc == ARM::LDR_PRE_IMM || NewOpc == ARM::LDRB_PRE_IMM) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001335 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Owen Anderson63143432011-08-29 17:59:41 +00001336 .addReg(Base, RegState::Define)
1337 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
1338 } else {
Matthias Brauna50d2202015-07-21 00:19:01 +00001339 int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001340 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Owen Anderson63143432011-08-29 17:59:41 +00001341 .addReg(Base, RegState::Define)
Matthias Brauna50d2202015-07-21 00:19:01 +00001342 .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
Owen Anderson63143432011-08-29 17:59:41 +00001343 }
Jim Grosbach23254742011-08-12 22:20:41 +00001344 } else {
Evan Cheng71756e72009-08-04 01:43:45 +00001345 // t2LDR_PRE, t2LDR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001346 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), MI->getOperand(0).getReg())
Evan Cheng71756e72009-08-04 01:43:45 +00001347 .addReg(Base, RegState::Define)
1348 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001349 }
Evan Cheng71756e72009-08-04 01:43:45 +00001350 } else {
1351 MachineOperand &MO = MI->getOperand(0);
Jim Grosbachf0c95ca2011-08-05 20:35:44 +00001352 // FIXME: post-indexed stores use am2offset_imm, which still encodes
1353 // the vestigal zero-reg offset register. When that's fixed, this clause
1354 // can be removed entirely.
Jim Grosbach23254742011-08-12 22:20:41 +00001355 if (isAM2 && NewOpc == ARM::STR_POST_IMM) {
Matthias Brauna50d2202015-07-21 00:19:01 +00001356 int Imm = ARM_AM::getAM2Opc(AddSub, Bytes, ARM_AM::no_shift);
Evan Cheng71756e72009-08-04 01:43:45 +00001357 // STR_PRE, STR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001358 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
Evan Cheng71756e72009-08-04 01:43:45 +00001359 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
Matthias Brauna50d2202015-07-21 00:19:01 +00001360 .addReg(Base).addReg(0).addImm(Imm).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001361 } else {
Evan Cheng71756e72009-08-04 01:43:45 +00001362 // t2STR_PRE, t2STR_POST
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001363 BuildMI(MBB, MBBI, DL, TII->get(NewOpc), Base)
Evan Cheng71756e72009-08-04 01:43:45 +00001364 .addReg(MO.getReg(), getKillRegState(MO.isKill()))
1365 .addReg(Base).addImm(Offset).addImm(Pred).addReg(PredReg);
Jim Grosbach23254742011-08-12 22:20:41 +00001366 }
Evan Cheng10043e22007-01-19 07:51:42 +00001367 }
1368 MBB.erase(MBBI);
1369
1370 return true;
1371}
1372
Matthias Brauna50d2202015-07-21 00:19:01 +00001373bool ARMLoadStoreOpt::MergeBaseUpdateLSDouble(MachineInstr &MI) const {
1374 unsigned Opcode = MI.getOpcode();
1375 assert((Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8) &&
1376 "Must have t2STRDi8 or t2LDRDi8");
1377 if (MI.getOperand(3).getImm() != 0)
1378 return false;
1379
1380 // Behaviour for writeback is undefined if base register is the same as one
1381 // of the others.
1382 const MachineOperand &BaseOp = MI.getOperand(2);
1383 unsigned Base = BaseOp.getReg();
1384 const MachineOperand &Reg0Op = MI.getOperand(0);
1385 const MachineOperand &Reg1Op = MI.getOperand(1);
1386 if (Reg0Op.getReg() == Base || Reg1Op.getReg() == Base)
1387 return false;
1388
1389 unsigned PredReg;
1390 ARMCC::CondCodes Pred = getInstrPredicate(&MI, PredReg);
1391 MachineBasicBlock::iterator MBBI(MI);
1392 MachineBasicBlock &MBB = *MI.getParent();
1393 int Offset;
1394 MachineBasicBlock::iterator MergeInstr = findIncDecBefore(MBBI, Base, Pred,
1395 PredReg, Offset);
1396 unsigned NewOpc;
1397 if (Offset == 8 || Offset == -8) {
1398 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_PRE : ARM::t2STRD_PRE;
1399 } else {
1400 MergeInstr = findIncDecAfter(MBBI, Base, Pred, PredReg, Offset);
1401 if (Offset == 8 || Offset == -8) {
1402 NewOpc = Opcode == ARM::t2LDRDi8 ? ARM::t2LDRD_POST : ARM::t2STRD_POST;
1403 } else
1404 return false;
1405 }
1406 MBB.erase(MergeInstr);
1407
1408 DebugLoc DL = MI.getDebugLoc();
1409 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc));
1410 if (NewOpc == ARM::t2LDRD_PRE || NewOpc == ARM::t2LDRD_POST) {
1411 MIB.addOperand(Reg0Op).addOperand(Reg1Op)
1412 .addReg(BaseOp.getReg(), RegState::Define);
1413 } else {
1414 assert(NewOpc == ARM::t2STRD_PRE || NewOpc == ARM::t2STRD_POST);
1415 MIB.addReg(BaseOp.getReg(), RegState::Define)
1416 .addOperand(Reg0Op).addOperand(Reg1Op);
1417 }
1418 MIB.addReg(BaseOp.getReg(), RegState::Kill)
1419 .addImm(Offset).addImm(Pred).addReg(PredReg);
1420 assert(TII->get(Opcode).getNumOperands() == 6 &&
1421 TII->get(NewOpc).getNumOperands() == 7 &&
1422 "Unexpected number of operands in Opcode specification.");
1423
1424 // Transfer implicit operands.
1425 for (const MachineOperand &MO : MI.implicit_operands())
1426 MIB.addOperand(MO);
1427 MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1428
1429 MBB.erase(MBBI);
1430 return true;
1431}
1432
Matthias Braunec50fa62015-06-01 21:26:23 +00001433/// Returns true if instruction is a memory operation that this pass is capable
1434/// of operating on.
Evan Cheng4605e8a2009-07-09 23:11:34 +00001435static bool isMemoryOp(const MachineInstr *MI) {
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001436 // When no memory operands are present, conservatively assume unaligned,
1437 // volatile, unfoldable.
1438 if (!MI->hasOneMemOperand())
1439 return false;
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001440
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001441 const MachineMemOperand *MMO = *MI->memoperands_begin();
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001442
Jakob Stoklund Olesenc1eccbc2010-06-29 01:13:07 +00001443 // Don't touch volatile memory accesses - we may be changing their order.
1444 if (MMO->isVolatile())
1445 return false;
1446
1447 // Unaligned ldr/str is emulated by some kernels, but unaligned ldm/stm is
1448 // not.
1449 if (MMO->getAlignment() < 4)
1450 return false;
Jakob Stoklund Olesenbff09062010-01-14 00:54:10 +00001451
Jakob Stoklund Olesen0b94eb12010-02-24 18:57:08 +00001452 // str <undef> could probably be eliminated entirely, but for now we just want
1453 // to avoid making a mess of it.
1454 // FIXME: Use str <undef> as a wildcard to enable better stm folding.
1455 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg() &&
1456 MI->getOperand(0).isUndef())
1457 return false;
1458
Bob Wilsoncf6e29a2010-03-04 21:04:38 +00001459 // Likewise don't mess with references to undefined addresses.
1460 if (MI->getNumOperands() > 1 && MI->getOperand(1).isReg() &&
1461 MI->getOperand(1).isUndef())
1462 return false;
1463
Matthias Braunfa3872e2015-05-18 20:27:55 +00001464 unsigned Opcode = MI->getOpcode();
Evan Chengd28de672007-03-06 18:02:41 +00001465 switch (Opcode) {
1466 default: break;
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001467 case ARM::VLDRS:
1468 case ARM::VSTRS:
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001469 return MI->getOperand(1).isReg();
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001470 case ARM::VLDRD:
1471 case ARM::VSTRD:
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001472 return MI->getOperand(1).isReg();
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00001473 case ARM::LDRi12:
Jim Grosbach338de3e2010-10-27 23:12:14 +00001474 case ARM::STRi12:
James Molloy556763d2014-05-16 14:14:30 +00001475 case ARM::tLDRi:
1476 case ARM::tSTRi:
Renato Golinb9887ef2015-02-25 14:41:06 +00001477 case ARM::tLDRspi:
1478 case ARM::tSTRspi:
Evan Cheng4605e8a2009-07-09 23:11:34 +00001479 case ARM::t2LDRi8:
1480 case ARM::t2LDRi12:
1481 case ARM::t2STRi8:
1482 case ARM::t2STRi12:
Evan Chenga6b9cab2009-09-27 09:46:04 +00001483 return MI->getOperand(1).isReg();
Evan Chengd28de672007-03-06 18:02:41 +00001484 }
1485 return false;
1486}
1487
Evan Cheng1283c6a2009-06-15 08:28:29 +00001488static void InsertLDR_STR(MachineBasicBlock &MBB,
1489 MachineBasicBlock::iterator &MBBI,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001490 int Offset, bool isDef,
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001491 DebugLoc DL, unsigned NewOpc,
Evan Chenga6b9cab2009-09-27 09:46:04 +00001492 unsigned Reg, bool RegDeadKill, bool RegUndef,
1493 unsigned BaseReg, bool BaseKill, bool BaseUndef,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001494 bool OffKill, bool OffUndef,
Evan Cheng1283c6a2009-06-15 08:28:29 +00001495 ARMCC::CondCodes Pred, unsigned PredReg,
Evan Chenga6b9cab2009-09-27 09:46:04 +00001496 const TargetInstrInfo *TII, bool isT2) {
Evan Chenga6b9cab2009-09-27 09:46:04 +00001497 if (isDef) {
1498 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1499 TII->get(NewOpc))
Evan Cheng5d8df7f2009-06-19 01:59:04 +00001500 .addReg(Reg, getDefRegState(true) | getDeadRegState(RegDeadKill))
Evan Chenga6b9cab2009-09-27 09:46:04 +00001501 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
Evan Chenga6b9cab2009-09-27 09:46:04 +00001502 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1503 } else {
1504 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, MBBI->getDebugLoc(),
1505 TII->get(NewOpc))
1506 .addReg(Reg, getKillRegState(RegDeadKill) | getUndefRegState(RegUndef))
1507 .addReg(BaseReg, getKillRegState(BaseKill)|getUndefRegState(BaseUndef));
Evan Chenga6b9cab2009-09-27 09:46:04 +00001508 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
1509 }
Evan Cheng1283c6a2009-06-15 08:28:29 +00001510}
1511
1512bool ARMLoadStoreOpt::FixInvalidRegPairOp(MachineBasicBlock &MBB,
1513 MachineBasicBlock::iterator &MBBI) {
1514 MachineInstr *MI = &*MBBI;
1515 unsigned Opcode = MI->getOpcode();
Matthias Braunba3ecc32015-06-24 20:03:27 +00001516 if (Opcode != ARM::LDRD && Opcode != ARM::STRD && Opcode != ARM::t2LDRDi8)
1517 return false;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001518
Matthias Braunba3ecc32015-06-24 20:03:27 +00001519 const MachineOperand &BaseOp = MI->getOperand(2);
1520 unsigned BaseReg = BaseOp.getReg();
1521 unsigned EvenReg = MI->getOperand(0).getReg();
1522 unsigned OddReg = MI->getOperand(1).getReg();
1523 unsigned EvenRegNum = TRI->getDwarfRegNum(EvenReg, false);
1524 unsigned OddRegNum = TRI->getDwarfRegNum(OddReg, false);
Evan Cheng1283c6a2009-06-15 08:28:29 +00001525
Matthias Braunba3ecc32015-06-24 20:03:27 +00001526 // ARM errata 602117: LDRD with base in list may result in incorrect base
1527 // register when interrupted or faulted.
1528 bool Errata602117 = EvenReg == BaseReg &&
1529 (Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8) && STI->isCortexM3();
1530 // ARM LDRD/STRD needs consecutive registers.
1531 bool NonConsecutiveRegs = (Opcode == ARM::LDRD || Opcode == ARM::STRD) &&
1532 (EvenRegNum % 2 != 0 || EvenRegNum + 1 != OddRegNum);
1533
1534 if (!Errata602117 && !NonConsecutiveRegs)
1535 return false;
1536
Matthias Braunba3ecc32015-06-24 20:03:27 +00001537 bool isT2 = Opcode == ARM::t2LDRDi8 || Opcode == ARM::t2STRDi8;
1538 bool isLd = Opcode == ARM::LDRD || Opcode == ARM::t2LDRDi8;
1539 bool EvenDeadKill = isLd ?
1540 MI->getOperand(0).isDead() : MI->getOperand(0).isKill();
1541 bool EvenUndef = MI->getOperand(0).isUndef();
1542 bool OddDeadKill = isLd ?
1543 MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
1544 bool OddUndef = MI->getOperand(1).isUndef();
1545 bool BaseKill = BaseOp.isKill();
1546 bool BaseUndef = BaseOp.isUndef();
1547 bool OffKill = isT2 ? false : MI->getOperand(3).isKill();
1548 bool OffUndef = isT2 ? false : MI->getOperand(3).isUndef();
1549 int OffImm = getMemoryOpOffset(MI);
1550 unsigned PredReg = 0;
1551 ARMCC::CondCodes Pred = getInstrPredicate(MI, PredReg);
1552
1553 if (OddRegNum > EvenRegNum && OffImm == 0) {
1554 // Ascending register numbers and no offset. It's safe to change it to a
1555 // ldm or stm.
1556 unsigned NewOpc = (isLd)
1557 ? (isT2 ? ARM::t2LDMIA : ARM::LDMIA)
1558 : (isT2 ? ARM::t2STMIA : ARM::STMIA);
1559 if (isLd) {
1560 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1561 .addReg(BaseReg, getKillRegState(BaseKill))
1562 .addImm(Pred).addReg(PredReg)
1563 .addReg(EvenReg, getDefRegState(isLd) | getDeadRegState(EvenDeadKill))
1564 .addReg(OddReg, getDefRegState(isLd) | getDeadRegState(OddDeadKill));
1565 ++NumLDRD2LDM;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001566 } else {
Matthias Braunba3ecc32015-06-24 20:03:27 +00001567 BuildMI(MBB, MBBI, MBBI->getDebugLoc(), TII->get(NewOpc))
1568 .addReg(BaseReg, getKillRegState(BaseKill))
1569 .addImm(Pred).addReg(PredReg)
1570 .addReg(EvenReg,
1571 getKillRegState(EvenDeadKill) | getUndefRegState(EvenUndef))
1572 .addReg(OddReg,
1573 getKillRegState(OddDeadKill) | getUndefRegState(OddUndef));
1574 ++NumSTRD2STM;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001575 }
Matthias Braunba3ecc32015-06-24 20:03:27 +00001576 } else {
1577 // Split into two instructions.
1578 unsigned NewOpc = (isLd)
1579 ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1580 : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1581 // Be extra careful for thumb2. t2LDRi8 can't reference a zero offset,
1582 // so adjust and use t2LDRi12 here for that.
1583 unsigned NewOpc2 = (isLd)
1584 ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi12)
1585 : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi12);
1586 DebugLoc dl = MBBI->getDebugLoc();
1587 // If this is a load and base register is killed, it may have been
1588 // re-defed by the load, make sure the first load does not clobber it.
1589 if (isLd &&
1590 (BaseKill || OffKill) &&
1591 (TRI->regsOverlap(EvenReg, BaseReg))) {
1592 assert(!TRI->regsOverlap(OddReg, BaseReg));
1593 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1594 OddReg, OddDeadKill, false,
1595 BaseReg, false, BaseUndef, false, OffUndef,
1596 Pred, PredReg, TII, isT2);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001597 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1598 EvenReg, EvenDeadKill, false,
1599 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1600 Pred, PredReg, TII, isT2);
1601 } else {
1602 if (OddReg == EvenReg && EvenDeadKill) {
1603 // If the two source operands are the same, the kill marker is
1604 // probably on the first one. e.g.
1605 // t2STRDi8 %R5<kill>, %R5, %R9<kill>, 0, 14, %reg0
1606 EvenDeadKill = false;
1607 OddDeadKill = true;
1608 }
1609 // Never kill the base register in the first instruction.
1610 if (EvenReg == BaseReg)
1611 EvenDeadKill = false;
1612 InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
1613 EvenReg, EvenDeadKill, EvenUndef,
1614 BaseReg, false, BaseUndef, false, OffUndef,
1615 Pred, PredReg, TII, isT2);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001616 InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
1617 OddReg, OddDeadKill, OddUndef,
1618 BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
1619 Pred, PredReg, TII, isT2);
1620 }
1621 if (isLd)
1622 ++NumLDRD2LDR;
1623 else
1624 ++NumSTRD2STR;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001625 }
Matthias Braunba3ecc32015-06-24 20:03:27 +00001626
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001627 MBBI = MBB.erase(MBBI);
Matthias Braunba3ecc32015-06-24 20:03:27 +00001628 return true;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001629}
1630
Matthias Braunec50fa62015-06-01 21:26:23 +00001631/// An optimization pass to turn multiple LDR / STR ops of the same base and
1632/// incrementing offset into LDM / STM ops.
Evan Cheng10043e22007-01-19 07:51:42 +00001633bool ARMLoadStoreOpt::LoadStoreMultipleOpti(MachineBasicBlock &MBB) {
Evan Cheng10043e22007-01-19 07:51:42 +00001634 MemOpQueue MemOps;
1635 unsigned CurrBase = 0;
Matthias Braunfa3872e2015-05-18 20:27:55 +00001636 unsigned CurrOpc = ~0u;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001637 ARMCC::CondCodes CurrPred = ARMCC::AL;
Evan Cheng10043e22007-01-19 07:51:42 +00001638 unsigned Position = 0;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001639 assert(Candidates.size() == 0);
Matthias Brauna50d2202015-07-21 00:19:01 +00001640 assert(MergeBaseCandidates.size() == 0);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001641 LiveRegsValid = false;
Evan Chengd28de672007-03-06 18:02:41 +00001642
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001643 for (MachineBasicBlock::iterator I = MBB.end(), MBBI; I != MBB.begin();
1644 I = MBBI) {
1645 // The instruction in front of the iterator is the one we look at.
1646 MBBI = std::prev(I);
Evan Cheng1283c6a2009-06-15 08:28:29 +00001647 if (FixInvalidRegPairOp(MBB, MBBI))
1648 continue;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001649 ++Position;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001650
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001651 if (isMemoryOp(MBBI)) {
Matthias Braunfa3872e2015-05-18 20:27:55 +00001652 unsigned Opcode = MBBI->getOpcode();
Evan Cheng1fb4de82010-06-21 21:21:14 +00001653 const MachineOperand &MO = MBBI->getOperand(0);
1654 unsigned Reg = MO.getReg();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001655 unsigned Base = getLoadStoreBaseOp(*MBBI).getReg();
Evan Cheng94f04c62007-07-05 07:18:20 +00001656 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00001657 ARMCC::CondCodes Pred = getInstrPredicate(MBBI, PredReg);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001658 int Offset = getMemoryOpOffset(MBBI);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001659 if (CurrBase == 0) {
Evan Cheng10043e22007-01-19 07:51:42 +00001660 // Start of a new chain.
1661 CurrBase = Base;
1662 CurrOpc = Opcode;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001663 CurrPred = Pred;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001664 MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
1665 continue;
1666 }
1667 // Note: No need to match PredReg in the next if.
1668 if (CurrOpc == Opcode && CurrBase == Base && CurrPred == Pred) {
1669 // Watch out for:
1670 // r4 := ldr [r0, #8]
1671 // r4 := ldr [r0, #4]
1672 // or
1673 // r0 := ldr [r0]
1674 // If a load overrides the base register or a register loaded by
1675 // another load in our chain, we cannot take this instruction.
1676 bool Overlap = false;
1677 if (isLoadSingle(Opcode)) {
1678 Overlap = (Base == Reg);
1679 if (!Overlap) {
1680 for (const MemOpQueueEntry &E : MemOps) {
1681 if (TRI->regsOverlap(Reg, E.MI->getOperand(0).getReg())) {
1682 Overlap = true;
Evan Cheng10043e22007-01-19 07:51:42 +00001683 break;
1684 }
1685 }
1686 }
1687 }
Evan Cheng10043e22007-01-19 07:51:42 +00001688
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001689 if (!Overlap) {
1690 // Check offset and sort memory operation into the current chain.
1691 if (Offset > MemOps.back().Offset) {
1692 MemOps.push_back(MemOpQueueEntry(MBBI, Offset, Position));
1693 continue;
1694 } else {
1695 MemOpQueue::iterator MI, ME;
1696 for (MI = MemOps.begin(), ME = MemOps.end(); MI != ME; ++MI) {
1697 if (Offset < MI->Offset) {
1698 // Found a place to insert.
1699 break;
1700 }
1701 if (Offset == MI->Offset) {
1702 // Collision, abort.
1703 MI = ME;
1704 break;
1705 }
1706 }
1707 if (MI != MemOps.end()) {
1708 MemOps.insert(MI, MemOpQueueEntry(MBBI, Offset, Position));
1709 continue;
1710 }
1711 }
Evan Cheng7f5976e2009-06-04 01:15:28 +00001712 }
Evan Cheng2818fdd2007-03-07 02:38:05 +00001713 }
Evan Cheng10043e22007-01-19 07:51:42 +00001714
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001715 // Don't advance the iterator; The op will start a new chain next.
1716 MBBI = I;
1717 --Position;
1718 // Fallthrough to look into existing chain.
Matthias Brauna50d2202015-07-21 00:19:01 +00001719 } else if (MBBI->isDebugValue()) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001720 continue;
Matthias Brauna50d2202015-07-21 00:19:01 +00001721 } else if (MBBI->getOpcode() == ARM::t2LDRDi8 ||
1722 MBBI->getOpcode() == ARM::t2STRDi8) {
1723 // ARMPreAllocLoadStoreOpt has already formed some LDRD/STRD instructions
1724 // remember them because we may still be able to merge add/sub into them.
1725 MergeBaseCandidates.push_back(MBBI);
1726 }
1727
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001728
1729 // If we are here then the chain is broken; Extract candidates for a merge.
1730 if (MemOps.size() > 0) {
1731 FormCandidates(MemOps);
1732 // Reset for the next chain.
Evan Cheng10043e22007-01-19 07:51:42 +00001733 CurrBase = 0;
Matthias Braunfa3872e2015-05-18 20:27:55 +00001734 CurrOpc = ~0u;
Evan Cheng0f7cbe82007-05-15 01:29:07 +00001735 CurrPred = ARMCC::AL;
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001736 MemOps.clear();
Evan Cheng10043e22007-01-19 07:51:42 +00001737 }
1738 }
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001739 if (MemOps.size() > 0)
1740 FormCandidates(MemOps);
1741
1742 // Sort candidates so they get processed from end to begin of the basic
1743 // block later; This is necessary for liveness calculation.
1744 auto LessThan = [](const MergeCandidate* M0, const MergeCandidate *M1) {
1745 return M0->InsertPos < M1->InsertPos;
1746 };
1747 std::sort(Candidates.begin(), Candidates.end(), LessThan);
1748
1749 // Go through list of candidates and merge.
1750 bool Changed = false;
1751 for (const MergeCandidate *Candidate : Candidates) {
Matthias Braune40d89e2015-07-21 00:18:59 +00001752 if (Candidate->CanMergeToLSMulti || Candidate->CanMergeToLSDouble) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001753 MachineInstr *Merged = MergeOpsUpdate(*Candidate);
1754 // Merge preceding/trailing base inc/dec into the merged op.
1755 if (Merged) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001756 Changed = true;
Matthias Braune40d89e2015-07-21 00:18:59 +00001757 unsigned Opcode = Merged->getOpcode();
Matthias Brauna50d2202015-07-21 00:19:01 +00001758 if (Opcode == ARM::t2STRDi8 || Opcode == ARM::t2LDRDi8)
1759 MergeBaseUpdateLSDouble(*Merged);
1760 else
Matthias Braune40d89e2015-07-21 00:18:59 +00001761 MergeBaseUpdateLSMultiple(Merged);
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001762 } else {
1763 for (MachineInstr *MI : Candidate->Instrs) {
1764 if (MergeBaseUpdateLoadStore(MI))
1765 Changed = true;
1766 }
1767 }
1768 } else {
1769 assert(Candidate->Instrs.size() == 1);
1770 if (MergeBaseUpdateLoadStore(Candidate->Instrs.front()))
1771 Changed = true;
1772 }
1773 }
1774 Candidates.clear();
Matthias Brauna50d2202015-07-21 00:19:01 +00001775 // Try to fold add/sub into the LDRD/STRD formed by ARMPreAllocLoadStoreOpt.
1776 for (MachineInstr *MI : MergeBaseCandidates)
1777 MergeBaseUpdateLSDouble(*MI);
1778 MergeBaseCandidates.clear();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001779
1780 return Changed;
Evan Cheng10043e22007-01-19 07:51:42 +00001781}
1782
Matthias Braunec50fa62015-06-01 21:26:23 +00001783/// If this is a exit BB, try merging the return ops ("bx lr" and "mov pc, lr")
1784/// into the preceding stack restore so it directly restore the value of LR
1785/// into pc.
Bob Wilson162242b2010-03-20 22:20:40 +00001786/// ldmfd sp!, {..., lr}
Evan Cheng10043e22007-01-19 07:51:42 +00001787/// bx lr
Bob Wilson162242b2010-03-20 22:20:40 +00001788/// or
1789/// ldmfd sp!, {..., lr}
1790/// mov pc, lr
Evan Cheng10043e22007-01-19 07:51:42 +00001791/// =>
Bob Wilson162242b2010-03-20 22:20:40 +00001792/// ldmfd sp!, {..., pc}
Evan Cheng10043e22007-01-19 07:51:42 +00001793bool ARMLoadStoreOpt::MergeReturnIntoLDM(MachineBasicBlock &MBB) {
James Molloy556763d2014-05-16 14:14:30 +00001794 // Thumb1 LDM doesn't allow high registers.
1795 if (isThumb1) return false;
Evan Cheng10043e22007-01-19 07:51:42 +00001796 if (MBB.empty()) return false;
1797
Jakob Stoklund Olesenbbb1a542011-01-13 22:47:43 +00001798 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng4605e8a2009-07-09 23:11:34 +00001799 if (MBBI != MBB.begin() &&
Bob Wilson162242b2010-03-20 22:20:40 +00001800 (MBBI->getOpcode() == ARM::BX_RET ||
1801 MBBI->getOpcode() == ARM::tBX_RET ||
1802 MBBI->getOpcode() == ARM::MOVPCLR)) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001803 MachineInstr *PrevMI = std::prev(MBBI);
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001804 unsigned Opcode = PrevMI->getOpcode();
1805 if (Opcode == ARM::LDMIA_UPD || Opcode == ARM::LDMDA_UPD ||
1806 Opcode == ARM::LDMDB_UPD || Opcode == ARM::LDMIB_UPD ||
1807 Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
Evan Cheng10043e22007-01-19 07:51:42 +00001808 MachineOperand &MO = PrevMI->getOperand(PrevMI->getNumOperands()-1);
Evan Cheng71756e72009-08-04 01:43:45 +00001809 if (MO.getReg() != ARM::LR)
1810 return false;
Bill Wendlinga68e3a52010-11-16 01:16:36 +00001811 unsigned NewOpc = (isThumb2 ? ARM::t2LDMIA_RET : ARM::LDMIA_RET);
1812 assert(((isThumb2 && Opcode == ARM::t2LDMIA_UPD) ||
1813 Opcode == ARM::LDMIA_UPD) && "Unsupported multiple load-return!");
Evan Cheng71756e72009-08-04 01:43:45 +00001814 PrevMI->setDesc(TII->get(NewOpc));
1815 MO.setReg(ARM::PC);
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001816 PrevMI->copyImplicitOps(*MBB.getParent(), &*MBBI);
Evan Cheng71756e72009-08-04 01:43:45 +00001817 MBB.erase(MBBI);
1818 return true;
Evan Cheng10043e22007-01-19 07:51:42 +00001819 }
1820 }
1821 return false;
1822}
1823
1824bool ARMLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001825 MF = &Fn;
Eric Christopher1b21f002015-01-29 00:19:33 +00001826 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
1827 TL = STI->getTargetLowering();
Evan Chengf030f2d2007-03-07 20:30:36 +00001828 AFI = Fn.getInfo<ARMFunctionInfo>();
Eric Christopher1b21f002015-01-29 00:19:33 +00001829 TII = STI->getInstrInfo();
1830 TRI = STI->getRegisterInfo();
Chad Rosier9659de32015-08-07 17:02:29 +00001831
Matthias Brauna4a3182d2015-07-10 18:08:49 +00001832 RegClassInfoValid = false;
Evan Cheng4605e8a2009-07-09 23:11:34 +00001833 isThumb2 = AFI->isThumb2Function();
James Molloy92a15072014-05-16 14:11:38 +00001834 isThumb1 = AFI->isThumbFunction() && !isThumb2;
1835
Evan Cheng10043e22007-01-19 07:51:42 +00001836 bool Modified = false;
1837 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1838 ++MFI) {
1839 MachineBasicBlock &MBB = *MFI;
1840 Modified |= LoadStoreMultipleOpti(MBB);
Eric Christopher1b21f002015-01-29 00:19:33 +00001841 if (STI->hasV5TOps())
Bob Wilson914df822011-01-06 19:24:41 +00001842 Modified |= MergeReturnIntoLDM(MBB);
Evan Cheng10043e22007-01-19 07:51:42 +00001843 }
Evan Chengd28de672007-03-06 18:02:41 +00001844
Matthias Braune40d89e2015-07-21 00:18:59 +00001845 Allocator.DestroyAll();
Evan Cheng10043e22007-01-19 07:51:42 +00001846 return Modified;
1847}
Evan Cheng185c9ef2009-06-13 09:12:55 +00001848
Chad Rosier5d485db2015-09-16 13:11:31 +00001849namespace llvm {
1850void initializeARMPreAllocLoadStoreOptPass(PassRegistry &);
1851}
1852
1853#define ARM_PREALLOC_LOAD_STORE_OPT_NAME \
1854 "ARM pre- register allocation load / store optimization pass"
1855
Evan Cheng185c9ef2009-06-13 09:12:55 +00001856namespace {
Matthias Braunec50fa62015-06-01 21:26:23 +00001857 /// Pre- register allocation pass that move load / stores from consecutive
1858 /// locations close to make it more likely they will be combined later.
Nick Lewycky02d5f772009-10-25 06:33:48 +00001859 struct ARMPreAllocLoadStoreOpt : public MachineFunctionPass{
Evan Cheng185c9ef2009-06-13 09:12:55 +00001860 static char ID;
Chad Rosier5d485db2015-09-16 13:11:31 +00001861 ARMPreAllocLoadStoreOpt() : MachineFunctionPass(ID) {
1862 initializeARMPreAllocLoadStoreOptPass(*PassRegistry::getPassRegistry());
1863 }
Evan Cheng185c9ef2009-06-13 09:12:55 +00001864
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001865 const DataLayout *TD;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001866 const TargetInstrInfo *TII;
1867 const TargetRegisterInfo *TRI;
Evan Cheng1283c6a2009-06-15 08:28:29 +00001868 const ARMSubtarget *STI;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001869 MachineRegisterInfo *MRI;
Evan Chengfd6aad72009-09-25 21:44:53 +00001870 MachineFunction *MF;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001871
Craig Topper6bc27bf2014-03-10 02:09:33 +00001872 bool runOnMachineFunction(MachineFunction &Fn) override;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001873
Craig Topper6bc27bf2014-03-10 02:09:33 +00001874 const char *getPassName() const override {
Chad Rosier5d485db2015-09-16 13:11:31 +00001875 return ARM_PREALLOC_LOAD_STORE_OPT_NAME;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001876 }
1877
1878 private:
Evan Chengeba57e42009-06-15 20:54:56 +00001879 bool CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1, DebugLoc &dl,
1880 unsigned &NewOpc, unsigned &EvenReg,
1881 unsigned &OddReg, unsigned &BaseReg,
Jim Grosbach338de3e2010-10-27 23:12:14 +00001882 int &Offset,
Evan Chengfd6aad72009-09-25 21:44:53 +00001883 unsigned &PredReg, ARMCC::CondCodes &Pred,
1884 bool &isT2);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001885 bool RescheduleOps(MachineBasicBlock *MBB,
Craig Topperaf0dea12013-07-04 01:31:24 +00001886 SmallVectorImpl<MachineInstr *> &Ops,
Evan Cheng185c9ef2009-06-13 09:12:55 +00001887 unsigned Base, bool isLd,
1888 DenseMap<MachineInstr*, unsigned> &MI2LocMap);
1889 bool RescheduleLoadStoreInstrs(MachineBasicBlock *MBB);
1890 };
1891 char ARMPreAllocLoadStoreOpt::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001892}
Evan Cheng185c9ef2009-06-13 09:12:55 +00001893
Chad Rosier5d485db2015-09-16 13:11:31 +00001894INITIALIZE_PASS(ARMPreAllocLoadStoreOpt, "arm-prera-load-store-opt",
1895 ARM_PREALLOC_LOAD_STORE_OPT_NAME, false, false)
1896
Evan Cheng185c9ef2009-06-13 09:12:55 +00001897bool ARMPreAllocLoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001898 TD = &Fn.getDataLayout();
Eric Christopher7c558cf2014-10-14 08:44:19 +00001899 STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
Eric Christopher1b21f002015-01-29 00:19:33 +00001900 TII = STI->getInstrInfo();
1901 TRI = STI->getRegisterInfo();
Evan Cheng185c9ef2009-06-13 09:12:55 +00001902 MRI = &Fn.getRegInfo();
Evan Chengfd6aad72009-09-25 21:44:53 +00001903 MF = &Fn;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001904
1905 bool Modified = false;
1906 for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
1907 ++MFI)
1908 Modified |= RescheduleLoadStoreInstrs(MFI);
1909
1910 return Modified;
1911}
1912
Evan Chengb4b20bb2009-06-19 23:17:27 +00001913static bool IsSafeAndProfitableToMove(bool isLd, unsigned Base,
1914 MachineBasicBlock::iterator I,
1915 MachineBasicBlock::iterator E,
Craig Topper71b7b682014-08-21 05:55:13 +00001916 SmallPtrSetImpl<MachineInstr*> &MemOps,
Evan Chengb4b20bb2009-06-19 23:17:27 +00001917 SmallSet<unsigned, 4> &MemRegs,
1918 const TargetRegisterInfo *TRI) {
Evan Cheng185c9ef2009-06-13 09:12:55 +00001919 // Are there stores / loads / calls between them?
1920 // FIXME: This is overly conservative. We should make use of alias information
1921 // some day.
Evan Chengb4b20bb2009-06-19 23:17:27 +00001922 SmallSet<unsigned, 4> AddedRegPressure;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001923 while (++I != E) {
Jim Grosbach4e5e6a82010-06-04 01:23:30 +00001924 if (I->isDebugValue() || MemOps.count(&*I))
Evan Chengb4b20bb2009-06-19 23:17:27 +00001925 continue;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001926 if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001927 return false;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001928 if (isLd && I->mayStore())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001929 return false;
1930 if (!isLd) {
Evan Cheng7f8e5632011-12-07 07:15:52 +00001931 if (I->mayLoad())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001932 return false;
1933 // It's not safe to move the first 'str' down.
1934 // str r1, [r0]
1935 // strh r5, [r0]
1936 // str r4, [r0, #+4]
Evan Cheng7f8e5632011-12-07 07:15:52 +00001937 if (I->mayStore())
Evan Cheng185c9ef2009-06-13 09:12:55 +00001938 return false;
1939 }
1940 for (unsigned j = 0, NumOps = I->getNumOperands(); j != NumOps; ++j) {
1941 MachineOperand &MO = I->getOperand(j);
Evan Chengb4b20bb2009-06-19 23:17:27 +00001942 if (!MO.isReg())
1943 continue;
1944 unsigned Reg = MO.getReg();
1945 if (MO.isDef() && TRI->regsOverlap(Reg, Base))
Evan Cheng185c9ef2009-06-13 09:12:55 +00001946 return false;
Evan Chengb4b20bb2009-06-19 23:17:27 +00001947 if (Reg != Base && !MemRegs.count(Reg))
1948 AddedRegPressure.insert(Reg);
Evan Cheng185c9ef2009-06-13 09:12:55 +00001949 }
1950 }
Evan Chengb4b20bb2009-06-19 23:17:27 +00001951
1952 // Estimate register pressure increase due to the transformation.
1953 if (MemRegs.size() <= 4)
1954 // Ok if we are moving small number of instructions.
1955 return true;
1956 return AddedRegPressure.size() <= MemRegs.size() * 2;
Evan Cheng185c9ef2009-06-13 09:12:55 +00001957}
1958
Andrew Trick28c1d182011-11-11 22:18:09 +00001959
Matthias Braunec50fa62015-06-01 21:26:23 +00001960/// Copy \p Op0 and \p Op1 operands into a new array assigned to MI.
Andrew Trick28c1d182011-11-11 22:18:09 +00001961static void concatenateMemOperands(MachineInstr *MI, MachineInstr *Op0,
1962 MachineInstr *Op1) {
1963 assert(MI->memoperands_empty() && "expected a new machineinstr");
1964 size_t numMemRefs = (Op0->memoperands_end() - Op0->memoperands_begin())
1965 + (Op1->memoperands_end() - Op1->memoperands_begin());
1966
1967 MachineFunction *MF = MI->getParent()->getParent();
1968 MachineSDNode::mmo_iterator MemBegin = MF->allocateMemRefsArray(numMemRefs);
1969 MachineSDNode::mmo_iterator MemEnd =
1970 std::copy(Op0->memoperands_begin(), Op0->memoperands_end(), MemBegin);
1971 MemEnd =
1972 std::copy(Op1->memoperands_begin(), Op1->memoperands_end(), MemEnd);
1973 MI->setMemRefs(MemBegin, MemEnd);
1974}
1975
Evan Chengeba57e42009-06-15 20:54:56 +00001976bool
1977ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr *Op1,
Matthias Braun125c9f52015-06-03 16:30:24 +00001978 DebugLoc &dl, unsigned &NewOpc,
1979 unsigned &FirstReg,
1980 unsigned &SecondReg,
1981 unsigned &BaseReg, int &Offset,
1982 unsigned &PredReg,
Evan Chengfd6aad72009-09-25 21:44:53 +00001983 ARMCC::CondCodes &Pred,
1984 bool &isT2) {
Evan Cheng139c3db2009-09-29 07:07:30 +00001985 // Make sure we're allowed to generate LDRD/STRD.
1986 if (!STI->hasV5TEOps())
1987 return false;
1988
Jim Grosbachd7cf55c2009-11-09 00:11:35 +00001989 // FIXME: VLDRS / VSTRS -> VLDRD / VSTRD
Evan Chengfd6aad72009-09-25 21:44:53 +00001990 unsigned Scale = 1;
Evan Chengeba57e42009-06-15 20:54:56 +00001991 unsigned Opcode = Op0->getOpcode();
James Molloybb73c232014-05-16 14:08:46 +00001992 if (Opcode == ARM::LDRi12) {
Evan Chengeba57e42009-06-15 20:54:56 +00001993 NewOpc = ARM::LDRD;
James Molloybb73c232014-05-16 14:08:46 +00001994 } else if (Opcode == ARM::STRi12) {
Evan Chengeba57e42009-06-15 20:54:56 +00001995 NewOpc = ARM::STRD;
James Molloybb73c232014-05-16 14:08:46 +00001996 } else if (Opcode == ARM::t2LDRi8 || Opcode == ARM::t2LDRi12) {
Evan Chengfd6aad72009-09-25 21:44:53 +00001997 NewOpc = ARM::t2LDRDi8;
1998 Scale = 4;
1999 isT2 = true;
2000 } else if (Opcode == ARM::t2STRi8 || Opcode == ARM::t2STRi12) {
2001 NewOpc = ARM::t2STRDi8;
2002 Scale = 4;
2003 isT2 = true;
James Molloybb73c232014-05-16 14:08:46 +00002004 } else {
Evan Chengfd6aad72009-09-25 21:44:53 +00002005 return false;
James Molloybb73c232014-05-16 14:08:46 +00002006 }
Evan Chengfd6aad72009-09-25 21:44:53 +00002007
Jim Grosbach9302bfd2010-10-26 19:34:41 +00002008 // Make sure the base address satisfies i64 ld / st alignment requirement.
Quentin Colombet663150f2013-06-20 22:51:44 +00002009 // At the moment, we ignore the memoryoperand's value.
2010 // If we want to use AliasAnalysis, we should check it accordingly.
Evan Chengeba57e42009-06-15 20:54:56 +00002011 if (!Op0->hasOneMemOperand() ||
Dan Gohman48b185d2009-09-25 20:36:54 +00002012 (*Op0->memoperands_begin())->isVolatile())
Evan Cheng1283c6a2009-06-15 08:28:29 +00002013 return false;
2014
Dan Gohman48b185d2009-09-25 20:36:54 +00002015 unsigned Align = (*Op0->memoperands_begin())->getAlignment();
Dan Gohman913c9982010-04-15 04:33:49 +00002016 const Function *Func = MF->getFunction();
Evan Cheng1283c6a2009-06-15 08:28:29 +00002017 unsigned ReqAlign = STI->hasV6Ops()
Jim Grosbach338de3e2010-10-27 23:12:14 +00002018 ? TD->getABITypeAlignment(Type::getInt64Ty(Func->getContext()))
Evan Chengfd6aad72009-09-25 21:44:53 +00002019 : 8; // Pre-v6 need 8-byte align
Evan Chengeba57e42009-06-15 20:54:56 +00002020 if (Align < ReqAlign)
2021 return false;
2022
2023 // Then make sure the immediate offset fits.
2024 int OffImm = getMemoryOpOffset(Op0);
Evan Chenga6b9cab2009-09-27 09:46:04 +00002025 if (isT2) {
Evan Cheng42401d62011-03-15 18:41:52 +00002026 int Limit = (1 << 8) * Scale;
2027 if (OffImm >= Limit || (OffImm <= -Limit) || (OffImm & (Scale-1)))
2028 return false;
Evan Chengfd6aad72009-09-25 21:44:53 +00002029 Offset = OffImm;
Evan Chenga6b9cab2009-09-27 09:46:04 +00002030 } else {
2031 ARM_AM::AddrOpc AddSub = ARM_AM::add;
2032 if (OffImm < 0) {
2033 AddSub = ARM_AM::sub;
2034 OffImm = - OffImm;
2035 }
2036 int Limit = (1 << 8) * Scale;
2037 if (OffImm >= Limit || (OffImm & (Scale-1)))
2038 return false;
Evan Chengfd6aad72009-09-25 21:44:53 +00002039 Offset = ARM_AM::getAM3Opc(AddSub, OffImm);
Evan Chenga6b9cab2009-09-27 09:46:04 +00002040 }
Matthias Braun125c9f52015-06-03 16:30:24 +00002041 FirstReg = Op0->getOperand(0).getReg();
2042 SecondReg = Op1->getOperand(0).getReg();
2043 if (FirstReg == SecondReg)
Evan Chengeba57e42009-06-15 20:54:56 +00002044 return false;
2045 BaseReg = Op0->getOperand(1).getReg();
Craig Topperf6e7e122012-03-27 07:21:54 +00002046 Pred = getInstrPredicate(Op0, PredReg);
Evan Chengeba57e42009-06-15 20:54:56 +00002047 dl = Op0->getDebugLoc();
2048 return true;
Evan Cheng1283c6a2009-06-15 08:28:29 +00002049}
2050
Evan Cheng185c9ef2009-06-13 09:12:55 +00002051bool ARMPreAllocLoadStoreOpt::RescheduleOps(MachineBasicBlock *MBB,
Craig Topperaf0dea12013-07-04 01:31:24 +00002052 SmallVectorImpl<MachineInstr *> &Ops,
Evan Cheng185c9ef2009-06-13 09:12:55 +00002053 unsigned Base, bool isLd,
2054 DenseMap<MachineInstr*, unsigned> &MI2LocMap) {
2055 bool RetVal = false;
2056
2057 // Sort by offset (in reverse order).
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00002058 std::sort(Ops.begin(), Ops.end(),
2059 [](const MachineInstr *LHS, const MachineInstr *RHS) {
2060 int LOffset = getMemoryOpOffset(LHS);
2061 int ROffset = getMemoryOpOffset(RHS);
2062 assert(LHS == RHS || LOffset != ROffset);
2063 return LOffset > ROffset;
2064 });
Evan Cheng185c9ef2009-06-13 09:12:55 +00002065
2066 // The loads / stores of the same base are in order. Scan them from first to
Jim Grosbach1bcdf322010-06-04 00:15:00 +00002067 // last and check for the following:
Evan Cheng185c9ef2009-06-13 09:12:55 +00002068 // 1. Any def of base.
2069 // 2. Any gaps.
2070 while (Ops.size() > 1) {
2071 unsigned FirstLoc = ~0U;
2072 unsigned LastLoc = 0;
Craig Topper062a2ba2014-04-25 05:30:21 +00002073 MachineInstr *FirstOp = nullptr;
2074 MachineInstr *LastOp = nullptr;
Evan Cheng185c9ef2009-06-13 09:12:55 +00002075 int LastOffset = 0;
Evan Cheng0e796032009-06-18 02:04:01 +00002076 unsigned LastOpcode = 0;
Evan Cheng185c9ef2009-06-13 09:12:55 +00002077 unsigned LastBytes = 0;
2078 unsigned NumMove = 0;
2079 for (int i = Ops.size() - 1; i >= 0; --i) {
2080 MachineInstr *Op = Ops[i];
2081 unsigned Loc = MI2LocMap[Op];
2082 if (Loc <= FirstLoc) {
2083 FirstLoc = Loc;
2084 FirstOp = Op;
2085 }
2086 if (Loc >= LastLoc) {
2087 LastLoc = Loc;
2088 LastOp = Op;
2089 }
2090
Andrew Trick642f0f62012-01-11 03:56:08 +00002091 unsigned LSMOpcode
2092 = getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
2093 if (LastOpcode && LSMOpcode != LastOpcode)
Evan Cheng0e796032009-06-18 02:04:01 +00002094 break;
2095
Evan Cheng185c9ef2009-06-13 09:12:55 +00002096 int Offset = getMemoryOpOffset(Op);
2097 unsigned Bytes = getLSMultipleTransferSize(Op);
2098 if (LastBytes) {
2099 if (Bytes != LastBytes || Offset != (LastOffset + (int)Bytes))
2100 break;
2101 }
2102 LastOffset = Offset;
2103 LastBytes = Bytes;
Andrew Trick642f0f62012-01-11 03:56:08 +00002104 LastOpcode = LSMOpcode;
Evan Chengfd6aad72009-09-25 21:44:53 +00002105 if (++NumMove == 8) // FIXME: Tune this limit.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002106 break;
2107 }
2108
2109 if (NumMove <= 1)
2110 Ops.pop_back();
2111 else {
Evan Chengb4b20bb2009-06-19 23:17:27 +00002112 SmallPtrSet<MachineInstr*, 4> MemOps;
2113 SmallSet<unsigned, 4> MemRegs;
2114 for (int i = NumMove-1; i >= 0; --i) {
2115 MemOps.insert(Ops[i]);
2116 MemRegs.insert(Ops[i]->getOperand(0).getReg());
2117 }
Evan Cheng185c9ef2009-06-13 09:12:55 +00002118
2119 // Be conservative, if the instructions are too far apart, don't
2120 // move them. We want to limit the increase of register pressure.
Evan Chengb4b20bb2009-06-19 23:17:27 +00002121 bool DoMove = (LastLoc - FirstLoc) <= NumMove*4; // FIXME: Tune this.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002122 if (DoMove)
Evan Chengb4b20bb2009-06-19 23:17:27 +00002123 DoMove = IsSafeAndProfitableToMove(isLd, Base, FirstOp, LastOp,
2124 MemOps, MemRegs, TRI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002125 if (!DoMove) {
2126 for (unsigned i = 0; i != NumMove; ++i)
2127 Ops.pop_back();
2128 } else {
2129 // This is the new location for the loads / stores.
2130 MachineBasicBlock::iterator InsertPos = isLd ? FirstOp : LastOp;
Jim Grosbachf14e08b2010-06-15 00:41:09 +00002131 while (InsertPos != MBB->end()
2132 && (MemOps.count(InsertPos) || InsertPos->isDebugValue()))
Evan Cheng185c9ef2009-06-13 09:12:55 +00002133 ++InsertPos;
Evan Cheng1283c6a2009-06-15 08:28:29 +00002134
2135 // If we are moving a pair of loads / stores, see if it makes sense
2136 // to try to allocate a pair of registers that can form register pairs.
Evan Chengeba57e42009-06-15 20:54:56 +00002137 MachineInstr *Op0 = Ops.back();
2138 MachineInstr *Op1 = Ops[Ops.size()-2];
Matthias Braun125c9f52015-06-03 16:30:24 +00002139 unsigned FirstReg = 0, SecondReg = 0;
Jim Grosbach338de3e2010-10-27 23:12:14 +00002140 unsigned BaseReg = 0, PredReg = 0;
Evan Chengeba57e42009-06-15 20:54:56 +00002141 ARMCC::CondCodes Pred = ARMCC::AL;
Evan Chengfd6aad72009-09-25 21:44:53 +00002142 bool isT2 = false;
Evan Chengeba57e42009-06-15 20:54:56 +00002143 unsigned NewOpc = 0;
Evan Chenga6b9cab2009-09-27 09:46:04 +00002144 int Offset = 0;
Evan Chengeba57e42009-06-15 20:54:56 +00002145 DebugLoc dl;
2146 if (NumMove == 2 && CanFormLdStDWord(Op0, Op1, dl, NewOpc,
Matthias Braun125c9f52015-06-03 16:30:24 +00002147 FirstReg, SecondReg, BaseReg,
Evan Chengfd6aad72009-09-25 21:44:53 +00002148 Offset, PredReg, Pred, isT2)) {
Evan Chengeba57e42009-06-15 20:54:56 +00002149 Ops.pop_back();
2150 Ops.pop_back();
Evan Cheng1283c6a2009-06-15 08:28:29 +00002151
Evan Cheng6cc775f2011-06-28 19:10:37 +00002152 const MCInstrDesc &MCID = TII->get(NewOpc);
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00002153 const TargetRegisterClass *TRC = TII->getRegClass(MCID, 0, TRI, *MF);
Matthias Braun125c9f52015-06-03 16:30:24 +00002154 MRI->constrainRegClass(FirstReg, TRC);
2155 MRI->constrainRegClass(SecondReg, TRC);
Cameron Zwarichec645bf2011-05-18 21:25:14 +00002156
Evan Chengeba57e42009-06-15 20:54:56 +00002157 // Form the pair instruction.
Evan Cheng0e796032009-06-18 02:04:01 +00002158 if (isLd) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002159 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
Matthias Braun125c9f52015-06-03 16:30:24 +00002160 .addReg(FirstReg, RegState::Define)
2161 .addReg(SecondReg, RegState::Define)
Evan Chengfd6aad72009-09-25 21:44:53 +00002162 .addReg(BaseReg);
Jim Grosbach338de3e2010-10-27 23:12:14 +00002163 // FIXME: We're converting from LDRi12 to an insn that still
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00002164 // uses addrmode2, so we need an explicit offset reg. It should
Jim Grosbach338de3e2010-10-27 23:12:14 +00002165 // always by reg0 since we're transforming LDRi12s.
Evan Chengfd6aad72009-09-25 21:44:53 +00002166 if (!isT2)
Jim Grosbach1e4d9a12010-10-26 22:37:02 +00002167 MIB.addReg(0);
Evan Chengfd6aad72009-09-25 21:44:53 +00002168 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
Andrew Trick28c1d182011-11-11 22:18:09 +00002169 concatenateMemOperands(MIB, Op0, Op1);
2170 DEBUG(dbgs() << "Formed " << *MIB << "\n");
Evan Cheng0e796032009-06-18 02:04:01 +00002171 ++NumLDRDFormed;
2172 } else {
Evan Cheng6cc775f2011-06-28 19:10:37 +00002173 MachineInstrBuilder MIB = BuildMI(*MBB, InsertPos, dl, MCID)
Matthias Braun125c9f52015-06-03 16:30:24 +00002174 .addReg(FirstReg)
2175 .addReg(SecondReg)
Evan Chengfd6aad72009-09-25 21:44:53 +00002176 .addReg(BaseReg);
Jim Grosbach338de3e2010-10-27 23:12:14 +00002177 // FIXME: We're converting from LDRi12 to an insn that still
2178 // uses addrmode2, so we need an explicit offset reg. It should
2179 // always by reg0 since we're transforming STRi12s.
Evan Chengfd6aad72009-09-25 21:44:53 +00002180 if (!isT2)
Jim Grosbach338de3e2010-10-27 23:12:14 +00002181 MIB.addReg(0);
Evan Chengfd6aad72009-09-25 21:44:53 +00002182 MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
Andrew Trick28c1d182011-11-11 22:18:09 +00002183 concatenateMemOperands(MIB, Op0, Op1);
2184 DEBUG(dbgs() << "Formed " << *MIB << "\n");
Evan Cheng0e796032009-06-18 02:04:01 +00002185 ++NumSTRDFormed;
2186 }
2187 MBB->erase(Op0);
2188 MBB->erase(Op1);
Evan Cheng1283c6a2009-06-15 08:28:29 +00002189
Matthias Braun125c9f52015-06-03 16:30:24 +00002190 if (!isT2) {
2191 // Add register allocation hints to form register pairs.
2192 MRI->setRegAllocationHint(FirstReg, ARMRI::RegPairEven, SecondReg);
2193 MRI->setRegAllocationHint(SecondReg, ARMRI::RegPairOdd, FirstReg);
2194 }
Evan Chengeba57e42009-06-15 20:54:56 +00002195 } else {
2196 for (unsigned i = 0; i != NumMove; ++i) {
2197 MachineInstr *Op = Ops.back();
2198 Ops.pop_back();
2199 MBB->splice(InsertPos, MBB, Op);
2200 }
Evan Cheng185c9ef2009-06-13 09:12:55 +00002201 }
2202
2203 NumLdStMoved += NumMove;
2204 RetVal = true;
2205 }
2206 }
2207 }
2208
2209 return RetVal;
2210}
2211
2212bool
2213ARMPreAllocLoadStoreOpt::RescheduleLoadStoreInstrs(MachineBasicBlock *MBB) {
2214 bool RetVal = false;
2215
2216 DenseMap<MachineInstr*, unsigned> MI2LocMap;
2217 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2LdsMap;
2218 DenseMap<unsigned, SmallVector<MachineInstr*, 4> > Base2StsMap;
2219 SmallVector<unsigned, 4> LdBases;
2220 SmallVector<unsigned, 4> StBases;
2221
2222 unsigned Loc = 0;
2223 MachineBasicBlock::iterator MBBI = MBB->begin();
2224 MachineBasicBlock::iterator E = MBB->end();
2225 while (MBBI != E) {
2226 for (; MBBI != E; ++MBBI) {
2227 MachineInstr *MI = MBBI;
Evan Cheng7f8e5632011-12-07 07:15:52 +00002228 if (MI->isCall() || MI->isTerminator()) {
Evan Cheng185c9ef2009-06-13 09:12:55 +00002229 // Stop at barriers.
2230 ++MBBI;
2231 break;
2232 }
2233
Jim Grosbach4e5e6a82010-06-04 01:23:30 +00002234 if (!MI->isDebugValue())
2235 MI2LocMap[MI] = ++Loc;
2236
Evan Cheng185c9ef2009-06-13 09:12:55 +00002237 if (!isMemoryOp(MI))
2238 continue;
2239 unsigned PredReg = 0;
Craig Topperf6e7e122012-03-27 07:21:54 +00002240 if (getInstrPredicate(MI, PredReg) != ARMCC::AL)
Evan Cheng185c9ef2009-06-13 09:12:55 +00002241 continue;
2242
Evan Chengfd6aad72009-09-25 21:44:53 +00002243 int Opc = MI->getOpcode();
Matthias Brauna4a3182d2015-07-10 18:08:49 +00002244 bool isLd = isLoadSingle(Opc);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002245 unsigned Base = MI->getOperand(1).getReg();
2246 int Offset = getMemoryOpOffset(MI);
2247
2248 bool StopHere = false;
2249 if (isLd) {
2250 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2251 Base2LdsMap.find(Base);
2252 if (BI != Base2LdsMap.end()) {
2253 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2254 if (Offset == getMemoryOpOffset(BI->second[i])) {
2255 StopHere = true;
2256 break;
2257 }
2258 }
2259 if (!StopHere)
2260 BI->second.push_back(MI);
2261 } else {
Craig Topper9ae47072013-07-10 16:38:35 +00002262 Base2LdsMap[Base].push_back(MI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002263 LdBases.push_back(Base);
2264 }
2265 } else {
2266 DenseMap<unsigned, SmallVector<MachineInstr*, 4> >::iterator BI =
2267 Base2StsMap.find(Base);
2268 if (BI != Base2StsMap.end()) {
2269 for (unsigned i = 0, e = BI->second.size(); i != e; ++i) {
2270 if (Offset == getMemoryOpOffset(BI->second[i])) {
2271 StopHere = true;
2272 break;
2273 }
2274 }
2275 if (!StopHere)
2276 BI->second.push_back(MI);
2277 } else {
Craig Topper9ae47072013-07-10 16:38:35 +00002278 Base2StsMap[Base].push_back(MI);
Evan Cheng185c9ef2009-06-13 09:12:55 +00002279 StBases.push_back(Base);
2280 }
2281 }
2282
2283 if (StopHere) {
Evan Chengb4b20bb2009-06-19 23:17:27 +00002284 // Found a duplicate (a base+offset combination that's seen earlier).
2285 // Backtrack.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002286 --Loc;
2287 break;
2288 }
2289 }
2290
2291 // Re-schedule loads.
2292 for (unsigned i = 0, e = LdBases.size(); i != e; ++i) {
2293 unsigned Base = LdBases[i];
Craig Topperaf0dea12013-07-04 01:31:24 +00002294 SmallVectorImpl<MachineInstr *> &Lds = Base2LdsMap[Base];
Evan Cheng185c9ef2009-06-13 09:12:55 +00002295 if (Lds.size() > 1)
2296 RetVal |= RescheduleOps(MBB, Lds, Base, true, MI2LocMap);
2297 }
2298
2299 // Re-schedule stores.
2300 for (unsigned i = 0, e = StBases.size(); i != e; ++i) {
2301 unsigned Base = StBases[i];
Craig Topperaf0dea12013-07-04 01:31:24 +00002302 SmallVectorImpl<MachineInstr *> &Sts = Base2StsMap[Base];
Evan Cheng185c9ef2009-06-13 09:12:55 +00002303 if (Sts.size() > 1)
2304 RetVal |= RescheduleOps(MBB, Sts, Base, false, MI2LocMap);
2305 }
2306
2307 if (MBBI != E) {
2308 Base2LdsMap.clear();
2309 Base2StsMap.clear();
2310 LdBases.clear();
2311 StBases.clear();
2312 }
2313 }
2314
2315 return RetVal;
2316}
2317
2318
Matthias Braunec50fa62015-06-01 21:26:23 +00002319/// Returns an instance of the load / store optimization pass.
Evan Cheng185c9ef2009-06-13 09:12:55 +00002320FunctionPass *llvm::createARMLoadStoreOptimizationPass(bool PreAlloc) {
2321 if (PreAlloc)
2322 return new ARMPreAllocLoadStoreOpt();
2323 return new ARMLoadStoreOpt();
2324}
David Gross2ad5d172015-07-23 21:46:09 +00002325