blob: d767c9ec805a50bb4ce35dbf1644842bb808e26d [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//=- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a pass that performs load / store related peephole
11// optimizations. This pass should be run after register allocation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000016#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "MCTargetDesc/AArch64AddressingModes.h"
18#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000019#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000020#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000021#include "llvm/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetRegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000032using namespace llvm;
33
34#define DEBUG_TYPE "aarch64-ldst-opt"
35
36/// AArch64AllocLoadStoreOpt - Post-register allocation pass to combine
37/// load / store instructions to form ldp / stp instructions.
38
39STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
40STATISTIC(NumPostFolded, "Number of post-index updates folded");
41STATISTIC(NumPreFolded, "Number of pre-index updates folded");
42STATISTIC(NumUnscaledPairCreated,
43 "Number of load/store from unscaled generated");
44
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000045static cl::opt<unsigned> ScanLimit("aarch64-load-store-scan-limit",
46 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000047
48// Place holder while testing unscaled load/store combining
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000049static cl::opt<bool> EnableAArch64UnscaledMemOp(
50 "aarch64-unscaled-mem-op", cl::Hidden,
51 cl::desc("Allow AArch64 unscaled load/store combining"), cl::init(true));
Tim Northover3b0846e2014-05-24 12:50:23 +000052
Chad Rosier96530b32015-08-05 13:44:51 +000053namespace llvm {
54void initializeAArch64LoadStoreOptPass(PassRegistry &);
55}
56
57#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
58
Tim Northover3b0846e2014-05-24 12:50:23 +000059namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000060
61typedef struct LdStPairFlags {
62 // If a matching instruction is found, MergeForward is set to true if the
63 // merge is to remove the first instruction and replace the second with
64 // a pair-wise insn, and false if the reverse is true.
65 bool MergeForward;
66
67 // SExtIdx gives the index of the result of the load pair that must be
68 // extended. The value of SExtIdx assumes that the paired load produces the
69 // value in this order: (I, returned iterator), i.e., -1 means no value has
70 // to be extended, 0 means I, and 1 means the returned iterator.
71 int SExtIdx;
72
73 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
74
75 void setMergeForward(bool V = true) { MergeForward = V; }
76 bool getMergeForward() const { return MergeForward; }
77
78 void setSExtIdx(int V) { SExtIdx = V; }
79 int getSExtIdx() const { return SExtIdx; }
80
81} LdStPairFlags;
82
Tim Northover3b0846e2014-05-24 12:50:23 +000083struct AArch64LoadStoreOpt : public MachineFunctionPass {
84 static char ID;
Chad Rosier96530b32015-08-05 13:44:51 +000085 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
86 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
87 }
Tim Northover3b0846e2014-05-24 12:50:23 +000088
89 const AArch64InstrInfo *TII;
90 const TargetRegisterInfo *TRI;
91
92 // Scan the instructions looking for a load/store that can be combined
93 // with the current instruction into a load/store pair.
94 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +000095 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +000096 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +000097 unsigned Limit);
98 // Merge the two instructions indicated into a single pair-wise instruction.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +000099 // If MergeForward is true, erase the first instruction and fold its
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 // operation into the second. If false, the reverse. Return the instruction
101 // following the first instruction (which may change during processing).
102 MachineBasicBlock::iterator
103 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000104 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000105 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106
107 // Scan the instruction list to find a base register update that can
108 // be combined with the current instruction (a load or store) using
109 // pre or post indexed addressing with writeback. Scan forwards.
110 MachineBasicBlock::iterator
111 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I, unsigned Limit,
112 int Value);
113
114 // Scan the instruction list to find a base register update that can
115 // be combined with the current instruction (a load or store) using
116 // pre or post indexed addressing with writeback. Scan backwards.
117 MachineBasicBlock::iterator
118 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
119
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000120 // Find an instruction that updates the base register of the ld/st
121 // instruction.
122 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
123 unsigned BaseReg, int Offset);
124
Chad Rosier2dfd3542015-09-23 13:51:44 +0000125 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000127 mergeUpdateInsn(MachineBasicBlock::iterator I,
128 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000129
130 bool optimizeBlock(MachineBasicBlock &MBB);
131
132 bool runOnMachineFunction(MachineFunction &Fn) override;
133
134 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000135 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000136 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000137};
138char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000139} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000140
Chad Rosier96530b32015-08-05 13:44:51 +0000141INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
142 AARCH64_LOAD_STORE_OPT_NAME, false, false)
143
Chad Rosier22eb7102015-08-06 17:37:18 +0000144static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 switch (Opc) {
146 default:
147 return false;
148 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000149 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000150 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000151 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000152 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000153 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000154 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000155 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000156 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000157 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000158 case AArch64::LDURSWi:
159 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000160 }
161}
162
Chad Rosier22eb7102015-08-06 17:37:18 +0000163static bool isUnscaledLdSt(MachineInstr *MI) {
164 return isUnscaledLdSt(MI->getOpcode());
165}
166
Chad Rosier32d4d372015-09-29 16:07:32 +0000167// Scaling factor for unscaled load or store.
168static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000169 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000170 default:
Tilmann Schellera17a4322014-06-03 16:33:13 +0000171 llvm_unreachable("Opcode has unknown size!");
Chad Rosiera4d32172015-09-29 14:57:10 +0000172 case AArch64::LDRSui:
173 case AArch64::LDURSi:
174 case AArch64::LDRSWui:
175 case AArch64::LDURSWi:
176 case AArch64::LDRWui:
177 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 case AArch64::STRSui:
179 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000180 case AArch64::STRWui:
181 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000182 case AArch64::LDPSi:
183 case AArch64::LDPWi:
184 case AArch64::STPSi:
185 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000187 case AArch64::LDRDui:
188 case AArch64::LDURDi:
189 case AArch64::LDRXui:
190 case AArch64::LDURXi:
191 case AArch64::STRDui:
192 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 case AArch64::STRXui:
194 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000195 case AArch64::LDPDi:
196 case AArch64::LDPXi:
197 case AArch64::STPDi:
198 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000199 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000200 case AArch64::LDRQui:
201 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000202 case AArch64::STRQui:
203 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000204 case AArch64::LDPQi:
205 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000206 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000207 }
208}
209
Quentin Colombet66b61632015-03-06 22:42:10 +0000210static unsigned getMatchingNonSExtOpcode(unsigned Opc,
211 bool *IsValidLdStrOpc = nullptr) {
212 if (IsValidLdStrOpc)
213 *IsValidLdStrOpc = true;
214 switch (Opc) {
215 default:
216 if (IsValidLdStrOpc)
217 *IsValidLdStrOpc = false;
218 return UINT_MAX;
219 case AArch64::STRDui:
220 case AArch64::STURDi:
221 case AArch64::STRQui:
222 case AArch64::STURQi:
223 case AArch64::STRWui:
224 case AArch64::STURWi:
225 case AArch64::STRXui:
226 case AArch64::STURXi:
227 case AArch64::LDRDui:
228 case AArch64::LDURDi:
229 case AArch64::LDRQui:
230 case AArch64::LDURQi:
231 case AArch64::LDRWui:
232 case AArch64::LDURWi:
233 case AArch64::LDRXui:
234 case AArch64::LDURXi:
235 case AArch64::STRSui:
236 case AArch64::STURSi:
237 case AArch64::LDRSui:
238 case AArch64::LDURSi:
239 return Opc;
240 case AArch64::LDRSWui:
241 return AArch64::LDRWui;
242 case AArch64::LDURSWi:
243 return AArch64::LDURWi;
244 }
245}
246
Tim Northover3b0846e2014-05-24 12:50:23 +0000247static unsigned getMatchingPairOpcode(unsigned Opc) {
248 switch (Opc) {
249 default:
250 llvm_unreachable("Opcode has no pairwise equivalent!");
251 case AArch64::STRSui:
252 case AArch64::STURSi:
253 return AArch64::STPSi;
254 case AArch64::STRDui:
255 case AArch64::STURDi:
256 return AArch64::STPDi;
257 case AArch64::STRQui:
258 case AArch64::STURQi:
259 return AArch64::STPQi;
260 case AArch64::STRWui:
261 case AArch64::STURWi:
262 return AArch64::STPWi;
263 case AArch64::STRXui:
264 case AArch64::STURXi:
265 return AArch64::STPXi;
266 case AArch64::LDRSui:
267 case AArch64::LDURSi:
268 return AArch64::LDPSi;
269 case AArch64::LDRDui:
270 case AArch64::LDURDi:
271 return AArch64::LDPDi;
272 case AArch64::LDRQui:
273 case AArch64::LDURQi:
274 return AArch64::LDPQi;
275 case AArch64::LDRWui:
276 case AArch64::LDURWi:
277 return AArch64::LDPWi;
278 case AArch64::LDRXui:
279 case AArch64::LDURXi:
280 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000281 case AArch64::LDRSWui:
282 case AArch64::LDURSWi:
283 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000284 }
285}
286
287static unsigned getPreIndexedOpcode(unsigned Opc) {
288 switch (Opc) {
289 default:
290 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000291 case AArch64::STRSui:
292 return AArch64::STRSpre;
293 case AArch64::STRDui:
294 return AArch64::STRDpre;
295 case AArch64::STRQui:
296 return AArch64::STRQpre;
297 case AArch64::STRWui:
298 return AArch64::STRWpre;
299 case AArch64::STRXui:
300 return AArch64::STRXpre;
301 case AArch64::LDRSui:
302 return AArch64::LDRSpre;
303 case AArch64::LDRDui:
304 return AArch64::LDRDpre;
305 case AArch64::LDRQui:
306 return AArch64::LDRQpre;
307 case AArch64::LDRWui:
308 return AArch64::LDRWpre;
309 case AArch64::LDRXui:
310 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000311 case AArch64::LDRSWui:
312 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000313 case AArch64::LDPSi:
314 return AArch64::LDPSpre;
315 case AArch64::LDPDi:
316 return AArch64::LDPDpre;
317 case AArch64::LDPQi:
318 return AArch64::LDPQpre;
319 case AArch64::LDPWi:
320 return AArch64::LDPWpre;
321 case AArch64::LDPXi:
322 return AArch64::LDPXpre;
323 case AArch64::STPSi:
324 return AArch64::STPSpre;
325 case AArch64::STPDi:
326 return AArch64::STPDpre;
327 case AArch64::STPQi:
328 return AArch64::STPQpre;
329 case AArch64::STPWi:
330 return AArch64::STPWpre;
331 case AArch64::STPXi:
332 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000333 }
334}
335
336static unsigned getPostIndexedOpcode(unsigned Opc) {
337 switch (Opc) {
338 default:
339 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
340 case AArch64::STRSui:
341 return AArch64::STRSpost;
342 case AArch64::STRDui:
343 return AArch64::STRDpost;
344 case AArch64::STRQui:
345 return AArch64::STRQpost;
346 case AArch64::STRWui:
347 return AArch64::STRWpost;
348 case AArch64::STRXui:
349 return AArch64::STRXpost;
350 case AArch64::LDRSui:
351 return AArch64::LDRSpost;
352 case AArch64::LDRDui:
353 return AArch64::LDRDpost;
354 case AArch64::LDRQui:
355 return AArch64::LDRQpost;
356 case AArch64::LDRWui:
357 return AArch64::LDRWpost;
358 case AArch64::LDRXui:
359 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000360 case AArch64::LDRSWui:
361 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000362 case AArch64::LDPSi:
363 return AArch64::LDPSpost;
364 case AArch64::LDPDi:
365 return AArch64::LDPDpost;
366 case AArch64::LDPQi:
367 return AArch64::LDPQpost;
368 case AArch64::LDPWi:
369 return AArch64::LDPWpost;
370 case AArch64::LDPXi:
371 return AArch64::LDPXpost;
372 case AArch64::STPSi:
373 return AArch64::STPSpost;
374 case AArch64::STPDi:
375 return AArch64::STPDpost;
376 case AArch64::STPQi:
377 return AArch64::STPQpost;
378 case AArch64::STPWi:
379 return AArch64::STPWpost;
380 case AArch64::STPXi:
381 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000382 }
383}
384
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000385static bool isPairedLdSt(const MachineInstr *MI) {
386 switch (MI->getOpcode()) {
387 default:
388 return false;
389 case AArch64::LDPSi:
390 case AArch64::LDPDi:
391 case AArch64::LDPQi:
392 case AArch64::LDPWi:
393 case AArch64::LDPXi:
394 case AArch64::STPSi:
395 case AArch64::STPDi:
396 case AArch64::STPQi:
397 case AArch64::STPWi:
398 case AArch64::STPXi:
399 return true;
400 }
401}
402
403static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
404 unsigned PairedRegOp = 0) {
405 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
406 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
407 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000408}
409
410static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000411 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
412 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000413}
414
415static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000416 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
417 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000418}
419
Tim Northover3b0846e2014-05-24 12:50:23 +0000420MachineBasicBlock::iterator
421AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
422 MachineBasicBlock::iterator Paired,
Chad Rosier96a18a92015-07-21 17:42:04 +0000423 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000424 MachineBasicBlock::iterator NextI = I;
425 ++NextI;
426 // If NextI is the second of the two instructions to be merged, we need
427 // to skip one further. Either way we merge will invalidate the iterator,
428 // and we don't need to scan the new instruction, as it's a pairwise
429 // instruction, which we're not considering for further action anyway.
430 if (NextI == Paired)
431 ++NextI;
432
Chad Rosier96a18a92015-07-21 17:42:04 +0000433 int SExtIdx = Flags.getSExtIdx();
Quentin Colombet66b61632015-03-06 22:42:10 +0000434 unsigned Opc =
435 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosier22eb7102015-08-06 17:37:18 +0000436 bool IsUnscaled = isUnscaledLdSt(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000437 int OffsetStride =
Chad Rosier32d4d372015-09-29 16:07:32 +0000438 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemScale(I) : 1;
Tim Northover3b0846e2014-05-24 12:50:23 +0000439
Chad Rosier96a18a92015-07-21 17:42:04 +0000440 bool MergeForward = Flags.getMergeForward();
Quentin Colombet66b61632015-03-06 22:42:10 +0000441 unsigned NewOpc = getMatchingPairOpcode(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000442 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000443 // instructions MergeForward indicates.
444 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
445 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000446 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000447 const MachineOperand &BaseRegOp =
448 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000449
450 // Which register is Rt and which is Rt2 depends on the offset order.
451 MachineInstr *RtMI, *Rt2MI;
Chad Rosier08ef4622015-09-03 16:41:28 +0000452 if (getLdStOffsetOp(I).getImm() ==
453 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000454 RtMI = Paired;
455 Rt2MI = I;
Quentin Colombet66b61632015-03-06 22:42:10 +0000456 // Here we swapped the assumption made for SExtIdx.
457 // I.e., we turn ldp I, Paired into ldp Paired, I.
458 // Update the index accordingly.
459 if (SExtIdx != -1)
460 SExtIdx = (SExtIdx + 1) % 2;
Tim Northover3b0846e2014-05-24 12:50:23 +0000461 } else {
462 RtMI = I;
463 Rt2MI = Paired;
464 }
Chad Rosier08ef4622015-09-03 16:41:28 +0000465 // Handle Unscaled
Chad Rosierf77e9092015-08-06 15:50:12 +0000466 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier08ef4622015-09-03 16:41:28 +0000467 if (IsUnscaled && EnableAArch64UnscaledMemOp)
468 OffsetImm /= OffsetStride;
Tim Northover3b0846e2014-05-24 12:50:23 +0000469
470 // Construct the new instruction.
471 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
472 I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000473 .addOperand(getLdStRegOp(RtMI))
474 .addOperand(getLdStRegOp(Rt2MI))
Tim Northover3b0846e2014-05-24 12:50:23 +0000475 .addOperand(BaseRegOp)
476 .addImm(OffsetImm);
477 (void)MIB;
478
479 // FIXME: Do we need/want to copy the mem operands from the source
480 // instructions? Probably. What uses them after this?
481
482 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
483 DEBUG(I->print(dbgs()));
484 DEBUG(dbgs() << " ");
485 DEBUG(Paired->print(dbgs()));
486 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000487
488 if (SExtIdx != -1) {
489 // Generate the sign extension for the proper result of the ldp.
490 // I.e., with X1, that would be:
491 // %W1<def> = KILL %W1, %X1<imp-def>
492 // %X1<def> = SBFMXri %X1<kill>, 0, 31
493 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
494 // Right now, DstMO has the extended register, since it comes from an
495 // extended opcode.
496 unsigned DstRegX = DstMO.getReg();
497 // Get the W variant of that register.
498 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
499 // Update the result of LDP to use the W instead of the X variant.
500 DstMO.setReg(DstRegW);
501 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
502 DEBUG(dbgs() << "\n");
503 // Make the machine verifier happy by providing a definition for
504 // the X register.
505 // Insert this definition right after the generated LDP, i.e., before
506 // InsertionPoint.
507 MachineInstrBuilder MIBKill =
508 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
509 TII->get(TargetOpcode::KILL), DstRegW)
510 .addReg(DstRegW)
511 .addReg(DstRegX, RegState::Define);
512 MIBKill->getOperand(2).setImplicit();
513 // Create the sign extension.
514 MachineInstrBuilder MIBSXTW =
515 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
516 TII->get(AArch64::SBFMXri), DstRegX)
517 .addReg(DstRegX)
518 .addImm(0)
519 .addImm(31);
520 (void)MIBSXTW;
521 DEBUG(dbgs() << " Extend operand:\n ");
522 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
523 DEBUG(dbgs() << "\n");
524 } else {
525 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
526 DEBUG(dbgs() << "\n");
527 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000528
529 // Erase the old instructions.
530 I->eraseFromParent();
531 Paired->eraseFromParent();
532
533 return NextI;
534}
535
536/// trackRegDefsUses - Remember what registers the specified instruction uses
537/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000538static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000539 BitVector &UsedRegs,
540 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000541 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000542 if (MO.isRegMask())
543 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
544
545 if (!MO.isReg())
546 continue;
547 unsigned Reg = MO.getReg();
548 if (MO.isDef()) {
549 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
550 ModifiedRegs.set(*AI);
551 } else {
552 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
553 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
554 UsedRegs.set(*AI);
555 }
556 }
557}
558
559static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +0000560 // Convert the byte-offset used by unscaled into an "element" offset used
561 // by the scaled pair load/store instructions.
Chad Rosier08ef4622015-09-03 16:41:28 +0000562 if (IsUnscaled)
Chad Rosier3dd0e942015-08-18 16:20:03 +0000563 Offset /= OffsetStride;
564
565 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +0000566}
567
568// Do alignment, specialized to power of 2 and for signed ints,
569// avoiding having to do a C-style cast from uint_64t to int when
570// using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
571// FIXME: Move this function to include/MathExtras.h?
572static int alignTo(int Num, int PowOf2) {
573 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
574}
575
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000576static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
577 const AArch64InstrInfo *TII) {
578 // One of the instructions must modify memory.
579 if (!MIa->mayStore() && !MIb->mayStore())
580 return false;
581
582 // Both instructions must be memory operations.
583 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
584 return false;
585
586 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
587}
588
589static bool mayAlias(MachineInstr *MIa,
590 SmallVectorImpl<MachineInstr *> &MemInsns,
591 const AArch64InstrInfo *TII) {
592 for (auto &MIb : MemInsns)
593 if (mayAlias(MIa, MIb, TII))
594 return true;
595
596 return false;
597}
598
Tim Northover3b0846e2014-05-24 12:50:23 +0000599/// findMatchingInsn - Scan the instructions looking for a load/store that can
600/// be combined with the current instruction into a load/store pair.
601MachineBasicBlock::iterator
602AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000603 LdStPairFlags &Flags,
Quentin Colombet66b61632015-03-06 22:42:10 +0000604 unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000605 MachineBasicBlock::iterator E = I->getParent()->end();
606 MachineBasicBlock::iterator MBBI = I;
607 MachineInstr *FirstMI = I;
608 ++MBBI;
609
Matthias Braunfa3872e2015-05-18 20:27:55 +0000610 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000611 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +0000612 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +0000613 unsigned Reg = getLdStRegOp(FirstMI).getReg();
614 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
615 int Offset = getLdStOffsetOp(FirstMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000616
617 // Early exit if the first instruction modifies the base register.
618 // e.g., ldr x0, [x0]
Tim Northover3b0846e2014-05-24 12:50:23 +0000619 if (FirstMI->modifiesRegister(BaseReg, TRI))
620 return E;
Chad Rosiercaed6db2015-08-10 17:17:19 +0000621
622 // Early exit if the offset if not possible to match. (6 bits of positive
623 // range, plus allow an extra one in case we find a later insn that matches
624 // with Offset-1)
Tim Northover3b0846e2014-05-24 12:50:23 +0000625 int OffsetStride =
Chad Rosier32d4d372015-09-29 16:07:32 +0000626 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemScale(FirstMI) : 1;
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
628 return E;
629
630 // Track which registers have been modified and used between the first insn
631 // (inclusive) and the second insn.
632 BitVector ModifiedRegs, UsedRegs;
633 ModifiedRegs.resize(TRI->getNumRegs());
634 UsedRegs.resize(TRI->getNumRegs());
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000635
636 // Remember any instructions that read/write memory between FirstMI and MI.
637 SmallVector<MachineInstr *, 4> MemInsns;
638
Tim Northover3b0846e2014-05-24 12:50:23 +0000639 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
640 MachineInstr *MI = MBBI;
641 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
642 // optimization by changing how far we scan.
643 if (MI->isDebugValue())
644 continue;
645
646 // Now that we know this is a real instruction, count it.
647 ++Count;
648
Chad Rosier08ef4622015-09-03 16:41:28 +0000649 bool CanMergeOpc = Opc == MI->getOpcode();
650 Flags.setSExtIdx(-1);
651 if (!CanMergeOpc) {
652 bool IsValidLdStrOpc;
653 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
654 assert(IsValidLdStrOpc &&
655 "Given Opc should be a Load or Store with an immediate");
656 // Opc will be the first instruction in the pair.
657 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
658 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
659 }
660
661 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +0000662 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +0000663 // If we've found another instruction with the same opcode, check to see
664 // if the base and offset are compatible with our starting instruction.
665 // These instructions all have scaled immediate operands, so we just
666 // check for +1/-1. Make sure to check the new instruction offset is
667 // actually an immediate and not a symbolic reference destined for
668 // a relocation.
669 //
670 // Pairwise instructions have a 7-bit signed offset field. Single insns
671 // have a 12-bit unsigned offset field. To be a valid combine, the
672 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +0000673 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
674 int MIOffset = getLdStOffsetOp(MI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
676 (Offset + OffsetStride == MIOffset))) {
677 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
678 // If this is a volatile load/store that otherwise matched, stop looking
679 // as something is going on that we don't have enough information to
680 // safely transform. Similarly, stop if we see a hint to avoid pairs.
681 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
682 return E;
683 // If the resultant immediate offset of merging these instructions
684 // is out of range for a pairwise instruction, bail and keep looking.
Chad Rosier08ef4622015-09-03 16:41:28 +0000685 bool MIIsUnscaled = isUnscaledLdSt(MI);
686 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000687 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000688 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 continue;
690 }
691 // If the alignment requirements of the paired (scaled) instruction
692 // can't express the offset of the unscaled input, bail and keep
693 // looking.
694 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
695 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
696 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000697 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000698 continue;
699 }
700 // If the destination register of the loads is the same register, bail
701 // and keep looking. A load-pair instruction with both destination
702 // registers the same is UNPREDICTABLE and will result in an exception.
Chad Rosierf77e9092015-08-06 15:50:12 +0000703 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000704 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000705 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000706 continue;
707 }
708
709 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000710 // the two instructions and none of the instructions between the second
711 // and first alias with the second, we can combine the second into the
712 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +0000713 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
714 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000715 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000716 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +0000717 return MBBI;
718 }
719
720 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000721 // between the two instructions and none of the instructions between the
722 // first and the second alias with the first, we can combine the first
723 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +0000724 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +0000725 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000726 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000727 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000728 return MBBI;
729 }
730 // Unable to combine these instructions due to interference in between.
731 // Keep looking.
732 }
733 }
734
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000735 // If the instruction wasn't a matching load or store. Stop searching if we
736 // encounter a call instruction that might modify memory.
737 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +0000738 return E;
739
740 // Update modified / uses register lists.
741 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
742
743 // Otherwise, if the base register is modified, we have no match, so
744 // return early.
745 if (ModifiedRegs[BaseReg])
746 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000747
748 // Update list of instructions that read/write memory.
749 if (MI->mayLoadOrStore())
750 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 }
752 return E;
753}
754
755MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000756AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
757 MachineBasicBlock::iterator Update,
758 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 assert((Update->getOpcode() == AArch64::ADDXri ||
760 Update->getOpcode() == AArch64::SUBXri) &&
761 "Unexpected base register update instruction to merge!");
762 MachineBasicBlock::iterator NextI = I;
763 // Return the instruction following the merged instruction, which is
764 // the instruction following our unmerged load. Unless that's the add/sub
765 // instruction we're merging, in which case it's the one after that.
766 if (++NextI == Update)
767 ++NextI;
768
769 int Value = Update->getOperand(2).getImm();
770 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +0000771 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +0000772 if (Update->getOpcode() == AArch64::SUBXri)
773 Value = -Value;
774
Chad Rosier2dfd3542015-09-23 13:51:44 +0000775 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
776 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000777 MachineInstrBuilder MIB;
778 if (!isPairedLdSt(I)) {
779 // Non-paired instruction.
780 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
781 .addOperand(getLdStRegOp(Update))
782 .addOperand(getLdStRegOp(I))
783 .addOperand(getLdStBaseOp(I))
784 .addImm(Value);
785 } else {
786 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +0000787 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000788 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
789 .addOperand(getLdStRegOp(Update))
790 .addOperand(getLdStRegOp(I, 0))
791 .addOperand(getLdStRegOp(I, 1))
792 .addOperand(getLdStBaseOp(I))
793 .addImm(Value / Scale);
794 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000795 (void)MIB;
796
Chad Rosier2dfd3542015-09-23 13:51:44 +0000797 if (IsPreIdx)
798 DEBUG(dbgs() << "Creating pre-indexed load/store.");
799 else
800 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +0000801 DEBUG(dbgs() << " Replacing instructions:\n ");
802 DEBUG(I->print(dbgs()));
803 DEBUG(dbgs() << " ");
804 DEBUG(Update->print(dbgs()));
805 DEBUG(dbgs() << " with instruction:\n ");
806 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
807 DEBUG(dbgs() << "\n");
808
809 // Erase the old instructions for the block.
810 I->eraseFromParent();
811 Update->eraseFromParent();
812
813 return NextI;
814}
815
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000816bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
817 MachineInstr *MI,
818 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000819 switch (MI->getOpcode()) {
820 default:
821 break;
822 case AArch64::SUBXri:
823 // Negate the offset for a SUB instruction.
824 Offset *= -1;
825 // FALLTHROUGH
826 case AArch64::ADDXri:
827 // Make sure it's a vanilla immediate operand, not a relocation or
828 // anything else we can't handle.
829 if (!MI->getOperand(2).isImm())
830 break;
831 // Watch out for 1 << 12 shifted value.
832 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
833 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000834
835 // The update instruction source and destination register must be the
836 // same as the load/store base register.
837 if (MI->getOperand(0).getReg() != BaseReg ||
838 MI->getOperand(1).getReg() != BaseReg)
839 break;
840
841 bool IsPairedInsn = isPairedLdSt(MemMI);
842 int UpdateOffset = MI->getOperand(2).getImm();
843 // For non-paired load/store instructions, the immediate must fit in a
844 // signed 9-bit integer.
845 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
846 break;
847
848 // For paired load/store instructions, the immediate must be a multiple of
849 // the scaling factor. The scaled offset must also fit into a signed 7-bit
850 // integer.
851 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +0000852 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000853 if (UpdateOffset % Scale != 0)
854 break;
855
856 int ScaledOffset = UpdateOffset / Scale;
857 if (ScaledOffset > 64 || ScaledOffset < -64)
858 break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000860
861 // If we have a non-zero Offset, we check that it matches the amount
862 // we're adding to the register.
863 if (!Offset || Offset == MI->getOperand(2).getImm())
864 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000865 break;
866 }
867 return false;
868}
869
870MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
871 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
872 MachineBasicBlock::iterator E = I->getParent()->end();
873 MachineInstr *MemMI = I;
874 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +0000875
Chad Rosierf77e9092015-08-06 15:50:12 +0000876 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier32d4d372015-09-29 16:07:32 +0000877 int Offset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000878
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000879 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +0000880 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000881 bool IsPairedInsn = isPairedLdSt(MemMI);
882 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
883 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
884 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
885 return E;
886 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000887
888 // Scan forward looking for post-index opportunities.
889 // Updating instructions can't be formed if the memory insn already
890 // has an offset other than the value we're looking for.
891 if (Offset != Value)
892 return E;
893
894 // Track which registers have been modified and used between the first insn
895 // (inclusive) and the second insn.
896 BitVector ModifiedRegs, UsedRegs;
897 ModifiedRegs.resize(TRI->getNumRegs());
898 UsedRegs.resize(TRI->getNumRegs());
899 ++MBBI;
900 for (unsigned Count = 0; MBBI != E; ++MBBI) {
901 MachineInstr *MI = MBBI;
902 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
903 // optimization by changing how far we scan.
904 if (MI->isDebugValue())
905 continue;
906
907 // Now that we know this is a real instruction, count it.
908 ++Count;
909
910 // If we found a match, return it.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000911 if (isMatchingUpdateInsn(I, MI, BaseReg, Value))
Tim Northover3b0846e2014-05-24 12:50:23 +0000912 return MBBI;
913
914 // Update the status of what the instruction clobbered and used.
915 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
916
917 // Otherwise, if the base register is used or modified, we have no match, so
918 // return early.
919 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
920 return E;
921 }
922 return E;
923}
924
925MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
926 MachineBasicBlock::iterator I, unsigned Limit) {
927 MachineBasicBlock::iterator B = I->getParent()->begin();
928 MachineBasicBlock::iterator E = I->getParent()->end();
929 MachineInstr *MemMI = I;
930 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +0000931
Chad Rosierf77e9092015-08-06 15:50:12 +0000932 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
933 int Offset = getLdStOffsetOp(MemMI).getImm();
Chad Rosier32d4d372015-09-29 16:07:32 +0000934 unsigned MemSize = getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000935
936 // If the load/store is the first instruction in the block, there's obviously
937 // not any matching update. Ditto if the memory offset isn't zero.
938 if (MBBI == B || Offset != 0)
939 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000940 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +0000941 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000942 bool IsPairedInsn = isPairedLdSt(MemMI);
943 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
944 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
945 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
946 return E;
947 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000948
949 // Track which registers have been modified and used between the first insn
950 // (inclusive) and the second insn.
951 BitVector ModifiedRegs, UsedRegs;
952 ModifiedRegs.resize(TRI->getNumRegs());
953 UsedRegs.resize(TRI->getNumRegs());
954 --MBBI;
955 for (unsigned Count = 0; MBBI != B; --MBBI) {
956 MachineInstr *MI = MBBI;
957 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
958 // optimization by changing how far we scan.
959 if (MI->isDebugValue())
960 continue;
961
962 // Now that we know this is a real instruction, count it.
963 ++Count;
964
965 // If we found a match, return it.
Chad Rosier32d4d372015-09-29 16:07:32 +0000966 if (isMatchingUpdateInsn(I, MI, BaseReg, MemSize))
Tim Northover3b0846e2014-05-24 12:50:23 +0000967 return MBBI;
968
969 // Update the status of what the instruction clobbered and used.
970 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
971
972 // Otherwise, if the base register is used or modified, we have no match, so
973 // return early.
974 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
975 return E;
976 }
977 return E;
978}
979
980bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
981 bool Modified = false;
982 // Two tranformations to do here:
983 // 1) Find loads and stores that can be merged into a single load or store
984 // pair instruction.
985 // e.g.,
986 // ldr x0, [x2]
987 // ldr x1, [x2, #8]
988 // ; becomes
989 // ldp x0, x1, [x2]
990 // 2) Find base register updates that can be merged into the load or store
991 // as a base-reg writeback.
992 // e.g.,
993 // ldr x0, [x2]
994 // add x2, x2, #4
995 // ; becomes
996 // ldr x0, [x2], #4
997
998 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
999 MBBI != E;) {
1000 MachineInstr *MI = MBBI;
1001 switch (MI->getOpcode()) {
1002 default:
1003 // Just move on to the next instruction.
1004 ++MBBI;
1005 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001006 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001007 case AArch64::STRSui:
1008 case AArch64::STRDui:
1009 case AArch64::STRQui:
1010 case AArch64::STRXui:
1011 case AArch64::STRWui:
1012 case AArch64::LDRSui:
1013 case AArch64::LDRDui:
1014 case AArch64::LDRQui:
1015 case AArch64::LDRXui:
1016 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001017 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001018 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001019 case AArch64::STURSi:
1020 case AArch64::STURDi:
1021 case AArch64::STURQi:
1022 case AArch64::STURWi:
1023 case AArch64::STURXi:
1024 case AArch64::LDURSi:
1025 case AArch64::LDURDi:
1026 case AArch64::LDURQi:
1027 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001028 case AArch64::LDURXi:
1029 case AArch64::LDURSWi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001030 // If this is a volatile load/store, don't mess with it.
1031 if (MI->hasOrderedMemoryRef()) {
1032 ++MBBI;
1033 break;
1034 }
1035 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001036 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001037 ++MBBI;
1038 break;
1039 }
1040 // Check if this load/store has a hint to avoid pair formation.
1041 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1042 if (TII->isLdStPairSuppressed(MI)) {
1043 ++MBBI;
1044 break;
1045 }
1046 // Look ahead up to ScanLimit instructions for a pairable instruction.
Chad Rosier96a18a92015-07-21 17:42:04 +00001047 LdStPairFlags Flags;
Tim Northover3b0846e2014-05-24 12:50:23 +00001048 MachineBasicBlock::iterator Paired =
Chad Rosier96a18a92015-07-21 17:42:04 +00001049 findMatchingInsn(MBBI, Flags, ScanLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001050 if (Paired != E) {
Chad Rosier9f4709b2015-08-26 13:39:48 +00001051 ++NumPairCreated;
1052 if (isUnscaledLdSt(MI))
1053 ++NumUnscaledPairCreated;
1054
Tim Northover3b0846e2014-05-24 12:50:23 +00001055 // Merge the loads into a pair. Keeping the iterator straight is a
1056 // pain, so we let the merge routine tell us what the next instruction
1057 // is after it's done mucking about.
Chad Rosier96a18a92015-07-21 17:42:04 +00001058 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +00001059 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001060 break;
1061 }
1062 ++MBBI;
1063 break;
1064 }
1065 // FIXME: Do the other instructions.
1066 }
1067 }
1068
1069 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1070 MBBI != E;) {
1071 MachineInstr *MI = MBBI;
1072 // Do update merging. It's simpler to keep this separate from the above
1073 // switch, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001074 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001075 switch (Opc) {
1076 default:
1077 // Just move on to the next instruction.
1078 ++MBBI;
1079 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001080 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001081 case AArch64::STRSui:
1082 case AArch64::STRDui:
1083 case AArch64::STRQui:
1084 case AArch64::STRXui:
1085 case AArch64::STRWui:
1086 case AArch64::LDRSui:
1087 case AArch64::LDRDui:
1088 case AArch64::LDRQui:
1089 case AArch64::LDRXui:
1090 case AArch64::LDRWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001091 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001092 case AArch64::STURSi:
1093 case AArch64::STURDi:
1094 case AArch64::STURQi:
1095 case AArch64::STURWi:
1096 case AArch64::STURXi:
1097 case AArch64::LDURSi:
1098 case AArch64::LDURDi:
1099 case AArch64::LDURQi:
1100 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001101 case AArch64::LDURXi:
1102 // Paired instructions.
1103 case AArch64::LDPSi:
1104 case AArch64::LDPDi:
1105 case AArch64::LDPQi:
1106 case AArch64::LDPWi:
1107 case AArch64::LDPXi:
1108 case AArch64::STPSi:
1109 case AArch64::STPDi:
1110 case AArch64::STPQi:
1111 case AArch64::STPWi:
1112 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001113 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001114 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001115 ++MBBI;
1116 break;
1117 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001118 // Look forward to try to form a post-index instruction. For example,
1119 // ldr x0, [x20]
1120 // add x20, x20, #32
1121 // merged into:
1122 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001123 MachineBasicBlock::iterator Update =
1124 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1125 if (Update != E) {
1126 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001127 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001128 Modified = true;
1129 ++NumPostFolded;
1130 break;
1131 }
1132 // Don't know how to handle pre/post-index versions, so move to the next
1133 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001134 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001135 ++MBBI;
1136 break;
1137 }
1138
1139 // Look back to try to find a pre-index instruction. For example,
1140 // add x0, x0, #8
1141 // ldr x1, [x0]
1142 // merged into:
1143 // ldr x1, [x0, #8]!
1144 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1145 if (Update != E) {
1146 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001147 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001148 Modified = true;
1149 ++NumPreFolded;
1150 break;
1151 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001152 // The immediate in the load/store is scaled by the size of the register
1153 // being loaded. The immediate in the add we're looking for,
1154 // however, is not, so adjust here.
Chad Rosier32d4d372015-09-29 16:07:32 +00001155 int Value =
1156 MI->getOperand(isPairedLdSt(MI) ? 3 : 2).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001157
1158 // FIXME: The immediate in the load/store should be scaled by the size of
1159 // the memory operation, not the size of the register being loaded/stored.
1160 // This works in general, but does not work for the LDPSW instruction,
1161 // which defines two 64-bit registers, but loads 32-bit values.
Tim Northover3b0846e2014-05-24 12:50:23 +00001162
1163 // Look forward to try to find a post-index instruction. For example,
1164 // ldr x1, [x0, #64]
1165 // add x0, x0, #64
1166 // merged into:
1167 // ldr x1, [x0, #64]!
Tim Northover3b0846e2014-05-24 12:50:23 +00001168 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1169 if (Update != E) {
1170 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001171 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001172 Modified = true;
1173 ++NumPreFolded;
1174 break;
1175 }
1176
1177 // Nothing found. Just move to the next instruction.
1178 ++MBBI;
1179 break;
1180 }
1181 // FIXME: Do the other instructions.
1182 }
1183 }
1184
1185 return Modified;
1186}
1187
1188bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Eric Christopher6c901622015-01-28 03:51:33 +00001189 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1190 TRI = Fn.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001191
1192 bool Modified = false;
1193 for (auto &MBB : Fn)
1194 Modified |= optimizeBlock(MBB);
1195
1196 return Modified;
1197}
1198
1199// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1200// loads and stores near one another?
1201
Chad Rosier43f5c842015-08-05 12:40:13 +00001202/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1203/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001204FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1205 return new AArch64LoadStoreOpt();
1206}