blob: 442abf81e87c5b23a0b899a9a5b51129d0c71259 [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
120 // Merge a pre-index base register update into a ld/st instruction.
121 MachineBasicBlock::iterator
122 mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
123 MachineBasicBlock::iterator Update);
124
125 // Merge a post-index base register update into a ld/st instruction.
126 MachineBasicBlock::iterator
127 mergePostIdxUpdateInsn(MachineBasicBlock::iterator I,
128 MachineBasicBlock::iterator Update);
129
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
Tim Northover3b0846e2014-05-24 12:50:23 +0000167// Size in bytes of the data moved by an unscaled load or store
Chad Rosier22eb7102015-08-06 17:37:18 +0000168static int getMemSize(MachineInstr *MI) {
169 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!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 case AArch64::STRSui:
173 case AArch64::STURSi:
174 return 4;
175 case AArch64::STRDui:
176 case AArch64::STURDi:
177 return 8;
178 case AArch64::STRQui:
179 case AArch64::STURQi:
180 return 16;
181 case AArch64::STRWui:
182 case AArch64::STURWi:
183 return 4;
184 case AArch64::STRXui:
185 case AArch64::STURXi:
186 return 8;
187 case AArch64::LDRSui:
188 case AArch64::LDURSi:
189 return 4;
190 case AArch64::LDRDui:
191 case AArch64::LDURDi:
192 return 8;
193 case AArch64::LDRQui:
194 case AArch64::LDURQi:
195 return 16;
196 case AArch64::LDRWui:
197 case AArch64::LDURWi:
198 return 4;
199 case AArch64::LDRXui:
200 case AArch64::LDURXi:
201 return 8;
Quentin Colombet29f55332015-01-24 01:25:54 +0000202 case AArch64::LDRSWui:
203 case AArch64::LDURSWi:
204 return 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000205 }
206}
207
Quentin Colombet66b61632015-03-06 22:42:10 +0000208static unsigned getMatchingNonSExtOpcode(unsigned Opc,
209 bool *IsValidLdStrOpc = nullptr) {
210 if (IsValidLdStrOpc)
211 *IsValidLdStrOpc = true;
212 switch (Opc) {
213 default:
214 if (IsValidLdStrOpc)
215 *IsValidLdStrOpc = false;
216 return UINT_MAX;
217 case AArch64::STRDui:
218 case AArch64::STURDi:
219 case AArch64::STRQui:
220 case AArch64::STURQi:
221 case AArch64::STRWui:
222 case AArch64::STURWi:
223 case AArch64::STRXui:
224 case AArch64::STURXi:
225 case AArch64::LDRDui:
226 case AArch64::LDURDi:
227 case AArch64::LDRQui:
228 case AArch64::LDURQi:
229 case AArch64::LDRWui:
230 case AArch64::LDURWi:
231 case AArch64::LDRXui:
232 case AArch64::LDURXi:
233 case AArch64::STRSui:
234 case AArch64::STURSi:
235 case AArch64::LDRSui:
236 case AArch64::LDURSi:
237 return Opc;
238 case AArch64::LDRSWui:
239 return AArch64::LDRWui;
240 case AArch64::LDURSWi:
241 return AArch64::LDURWi;
242 }
243}
244
Tim Northover3b0846e2014-05-24 12:50:23 +0000245static unsigned getMatchingPairOpcode(unsigned Opc) {
246 switch (Opc) {
247 default:
248 llvm_unreachable("Opcode has no pairwise equivalent!");
249 case AArch64::STRSui:
250 case AArch64::STURSi:
251 return AArch64::STPSi;
252 case AArch64::STRDui:
253 case AArch64::STURDi:
254 return AArch64::STPDi;
255 case AArch64::STRQui:
256 case AArch64::STURQi:
257 return AArch64::STPQi;
258 case AArch64::STRWui:
259 case AArch64::STURWi:
260 return AArch64::STPWi;
261 case AArch64::STRXui:
262 case AArch64::STURXi:
263 return AArch64::STPXi;
264 case AArch64::LDRSui:
265 case AArch64::LDURSi:
266 return AArch64::LDPSi;
267 case AArch64::LDRDui:
268 case AArch64::LDURDi:
269 return AArch64::LDPDi;
270 case AArch64::LDRQui:
271 case AArch64::LDURQi:
272 return AArch64::LDPQi;
273 case AArch64::LDRWui:
274 case AArch64::LDURWi:
275 return AArch64::LDPWi;
276 case AArch64::LDRXui:
277 case AArch64::LDURXi:
278 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000279 case AArch64::LDRSWui:
280 case AArch64::LDURSWi:
281 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000282 }
283}
284
285static unsigned getPreIndexedOpcode(unsigned Opc) {
286 switch (Opc) {
287 default:
288 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000289 case AArch64::STRSui:
290 return AArch64::STRSpre;
291 case AArch64::STRDui:
292 return AArch64::STRDpre;
293 case AArch64::STRQui:
294 return AArch64::STRQpre;
295 case AArch64::STRWui:
296 return AArch64::STRWpre;
297 case AArch64::STRXui:
298 return AArch64::STRXpre;
299 case AArch64::LDRSui:
300 return AArch64::LDRSpre;
301 case AArch64::LDRDui:
302 return AArch64::LDRDpre;
303 case AArch64::LDRQui:
304 return AArch64::LDRQpre;
305 case AArch64::LDRWui:
306 return AArch64::LDRWpre;
307 case AArch64::LDRXui:
308 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000309 case AArch64::LDRSWui:
310 return AArch64::LDRSWpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000311 }
312}
313
314static unsigned getPostIndexedOpcode(unsigned Opc) {
315 switch (Opc) {
316 default:
317 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
318 case AArch64::STRSui:
319 return AArch64::STRSpost;
320 case AArch64::STRDui:
321 return AArch64::STRDpost;
322 case AArch64::STRQui:
323 return AArch64::STRQpost;
324 case AArch64::STRWui:
325 return AArch64::STRWpost;
326 case AArch64::STRXui:
327 return AArch64::STRXpost;
328 case AArch64::LDRSui:
329 return AArch64::LDRSpost;
330 case AArch64::LDRDui:
331 return AArch64::LDRDpost;
332 case AArch64::LDRQui:
333 return AArch64::LDRQpost;
334 case AArch64::LDRWui:
335 return AArch64::LDRWpost;
336 case AArch64::LDRXui:
337 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000338 case AArch64::LDRSWui:
339 return AArch64::LDRSWpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000340 }
341}
342
Chad Rosierf77e9092015-08-06 15:50:12 +0000343static const MachineOperand &getLdStRegOp(const MachineInstr *MI) {
344 return MI->getOperand(0);
345}
346
347static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
348 return MI->getOperand(1);
349}
350
351static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
352 return MI->getOperand(2);
353}
354
Tim Northover3b0846e2014-05-24 12:50:23 +0000355MachineBasicBlock::iterator
356AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
357 MachineBasicBlock::iterator Paired,
Chad Rosier96a18a92015-07-21 17:42:04 +0000358 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000359 MachineBasicBlock::iterator NextI = I;
360 ++NextI;
361 // If NextI is the second of the two instructions to be merged, we need
362 // to skip one further. Either way we merge will invalidate the iterator,
363 // and we don't need to scan the new instruction, as it's a pairwise
364 // instruction, which we're not considering for further action anyway.
365 if (NextI == Paired)
366 ++NextI;
367
Chad Rosier96a18a92015-07-21 17:42:04 +0000368 int SExtIdx = Flags.getSExtIdx();
Quentin Colombet66b61632015-03-06 22:42:10 +0000369 unsigned Opc =
370 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosier22eb7102015-08-06 17:37:18 +0000371 bool IsUnscaled = isUnscaledLdSt(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000372 int OffsetStride =
373 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
374
Chad Rosier96a18a92015-07-21 17:42:04 +0000375 bool MergeForward = Flags.getMergeForward();
Quentin Colombet66b61632015-03-06 22:42:10 +0000376 unsigned NewOpc = getMatchingPairOpcode(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000377 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000378 // instructions MergeForward indicates.
379 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
380 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000381 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000382 const MachineOperand &BaseRegOp =
383 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000384
385 // Which register is Rt and which is Rt2 depends on the offset order.
386 MachineInstr *RtMI, *Rt2MI;
Chad Rosierf77e9092015-08-06 15:50:12 +0000387 if (getLdStOffsetOp(I).getImm() ==
388 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000389 RtMI = Paired;
390 Rt2MI = I;
Quentin Colombet66b61632015-03-06 22:42:10 +0000391 // Here we swapped the assumption made for SExtIdx.
392 // I.e., we turn ldp I, Paired into ldp Paired, I.
393 // Update the index accordingly.
394 if (SExtIdx != -1)
395 SExtIdx = (SExtIdx + 1) % 2;
Tim Northover3b0846e2014-05-24 12:50:23 +0000396 } else {
397 RtMI = I;
398 Rt2MI = Paired;
399 }
400 // Handle Unscaled
Chad Rosierf77e9092015-08-06 15:50:12 +0000401 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000402 if (IsUnscaled && EnableAArch64UnscaledMemOp)
403 OffsetImm /= OffsetStride;
404
405 // Construct the new instruction.
406 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
407 I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000408 .addOperand(getLdStRegOp(RtMI))
409 .addOperand(getLdStRegOp(Rt2MI))
Tim Northover3b0846e2014-05-24 12:50:23 +0000410 .addOperand(BaseRegOp)
411 .addImm(OffsetImm);
412 (void)MIB;
413
414 // FIXME: Do we need/want to copy the mem operands from the source
415 // instructions? Probably. What uses them after this?
416
417 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
418 DEBUG(I->print(dbgs()));
419 DEBUG(dbgs() << " ");
420 DEBUG(Paired->print(dbgs()));
421 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000422
423 if (SExtIdx != -1) {
424 // Generate the sign extension for the proper result of the ldp.
425 // I.e., with X1, that would be:
426 // %W1<def> = KILL %W1, %X1<imp-def>
427 // %X1<def> = SBFMXri %X1<kill>, 0, 31
428 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
429 // Right now, DstMO has the extended register, since it comes from an
430 // extended opcode.
431 unsigned DstRegX = DstMO.getReg();
432 // Get the W variant of that register.
433 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
434 // Update the result of LDP to use the W instead of the X variant.
435 DstMO.setReg(DstRegW);
436 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
437 DEBUG(dbgs() << "\n");
438 // Make the machine verifier happy by providing a definition for
439 // the X register.
440 // Insert this definition right after the generated LDP, i.e., before
441 // InsertionPoint.
442 MachineInstrBuilder MIBKill =
443 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
444 TII->get(TargetOpcode::KILL), DstRegW)
445 .addReg(DstRegW)
446 .addReg(DstRegX, RegState::Define);
447 MIBKill->getOperand(2).setImplicit();
448 // Create the sign extension.
449 MachineInstrBuilder MIBSXTW =
450 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
451 TII->get(AArch64::SBFMXri), DstRegX)
452 .addReg(DstRegX)
453 .addImm(0)
454 .addImm(31);
455 (void)MIBSXTW;
456 DEBUG(dbgs() << " Extend operand:\n ");
457 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
458 DEBUG(dbgs() << "\n");
459 } else {
460 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
461 DEBUG(dbgs() << "\n");
462 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000463
464 // Erase the old instructions.
465 I->eraseFromParent();
466 Paired->eraseFromParent();
467
468 return NextI;
469}
470
471/// trackRegDefsUses - Remember what registers the specified instruction uses
472/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000473static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000474 BitVector &UsedRegs,
475 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000476 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 if (MO.isRegMask())
478 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
479
480 if (!MO.isReg())
481 continue;
482 unsigned Reg = MO.getReg();
483 if (MO.isDef()) {
484 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
485 ModifiedRegs.set(*AI);
486 } else {
487 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
488 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
489 UsedRegs.set(*AI);
490 }
491 }
492}
493
494static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
495 if (!IsUnscaled && (Offset > 63 || Offset < -64))
496 return false;
497 if (IsUnscaled) {
498 // Convert the byte-offset used by unscaled into an "element" offset used
499 // by the scaled pair load/store instructions.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000500 int ElemOffset = Offset / OffsetStride;
501 if (ElemOffset > 63 || ElemOffset < -64)
Tim Northover3b0846e2014-05-24 12:50:23 +0000502 return false;
503 }
504 return true;
505}
506
507// Do alignment, specialized to power of 2 and for signed ints,
508// avoiding having to do a C-style cast from uint_64t to int when
509// using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
510// FIXME: Move this function to include/MathExtras.h?
511static int alignTo(int Num, int PowOf2) {
512 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
513}
514
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000515static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
516 const AArch64InstrInfo *TII) {
517 // One of the instructions must modify memory.
518 if (!MIa->mayStore() && !MIb->mayStore())
519 return false;
520
521 // Both instructions must be memory operations.
522 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
523 return false;
524
525 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
526}
527
528static bool mayAlias(MachineInstr *MIa,
529 SmallVectorImpl<MachineInstr *> &MemInsns,
530 const AArch64InstrInfo *TII) {
531 for (auto &MIb : MemInsns)
532 if (mayAlias(MIa, MIb, TII))
533 return true;
534
535 return false;
536}
537
Tim Northover3b0846e2014-05-24 12:50:23 +0000538/// findMatchingInsn - Scan the instructions looking for a load/store that can
539/// be combined with the current instruction into a load/store pair.
540MachineBasicBlock::iterator
541AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000542 LdStPairFlags &Flags,
Quentin Colombet66b61632015-03-06 22:42:10 +0000543 unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000544 MachineBasicBlock::iterator E = I->getParent()->end();
545 MachineBasicBlock::iterator MBBI = I;
546 MachineInstr *FirstMI = I;
547 ++MBBI;
548
Matthias Braunfa3872e2015-05-18 20:27:55 +0000549 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000550 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +0000551 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +0000552 unsigned Reg = getLdStRegOp(FirstMI).getReg();
553 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
554 int Offset = getLdStOffsetOp(FirstMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000555
556 // Early exit if the first instruction modifies the base register.
557 // e.g., ldr x0, [x0]
558 // Early exit if the offset if not possible to match. (6 bits of positive
559 // range, plus allow an extra one in case we find a later insn that matches
560 // with Offset-1
561 if (FirstMI->modifiesRegister(BaseReg, TRI))
562 return E;
563 int OffsetStride =
564 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
565 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
566 return E;
567
568 // Track which registers have been modified and used between the first insn
569 // (inclusive) and the second insn.
570 BitVector ModifiedRegs, UsedRegs;
571 ModifiedRegs.resize(TRI->getNumRegs());
572 UsedRegs.resize(TRI->getNumRegs());
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000573
574 // Remember any instructions that read/write memory between FirstMI and MI.
575 SmallVector<MachineInstr *, 4> MemInsns;
576
Tim Northover3b0846e2014-05-24 12:50:23 +0000577 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
578 MachineInstr *MI = MBBI;
579 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
580 // optimization by changing how far we scan.
581 if (MI->isDebugValue())
582 continue;
583
584 // Now that we know this is a real instruction, count it.
585 ++Count;
586
Quentin Colombet66b61632015-03-06 22:42:10 +0000587 bool CanMergeOpc = Opc == MI->getOpcode();
Chad Rosier96a18a92015-07-21 17:42:04 +0000588 Flags.setSExtIdx(-1);
Quentin Colombet66b61632015-03-06 22:42:10 +0000589 if (!CanMergeOpc) {
590 bool IsValidLdStrOpc;
591 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
Quentin Colombet7d8c74f2015-08-07 22:40:51 +0000592 assert(IsValidLdStrOpc &&
593 "Given Opc should be a Load or Store with an immediate");
Quentin Colombet66b61632015-03-06 22:42:10 +0000594 // Opc will be the first instruction in the pair.
Chad Rosier96a18a92015-07-21 17:42:04 +0000595 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
Quentin Colombet66b61632015-03-06 22:42:10 +0000596 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
597 }
598
Chad Rosierf77e9092015-08-06 15:50:12 +0000599 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000600 // If we've found another instruction with the same opcode, check to see
601 // if the base and offset are compatible with our starting instruction.
602 // These instructions all have scaled immediate operands, so we just
603 // check for +1/-1. Make sure to check the new instruction offset is
604 // actually an immediate and not a symbolic reference destined for
605 // a relocation.
606 //
607 // Pairwise instructions have a 7-bit signed offset field. Single insns
608 // have a 12-bit unsigned offset field. To be a valid combine, the
609 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +0000610 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
611 int MIOffset = getLdStOffsetOp(MI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000612 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
613 (Offset + OffsetStride == MIOffset))) {
614 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
615 // If this is a volatile load/store that otherwise matched, stop looking
616 // as something is going on that we don't have enough information to
617 // safely transform. Similarly, stop if we see a hint to avoid pairs.
618 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
619 return E;
620 // If the resultant immediate offset of merging these instructions
621 // is out of range for a pairwise instruction, bail and keep looking.
Chad Rosier22eb7102015-08-06 17:37:18 +0000622 bool MIIsUnscaled = isUnscaledLdSt(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000623 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
624 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000625 if (MI->mayLoadOrStore())
626 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 continue;
628 }
629 // If the alignment requirements of the paired (scaled) instruction
630 // can't express the offset of the unscaled input, bail and keep
631 // looking.
632 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
633 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
634 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000635 if (MI->mayLoadOrStore())
636 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000637 continue;
638 }
639 // If the destination register of the loads is the same register, bail
640 // and keep looking. A load-pair instruction with both destination
641 // registers the same is UNPREDICTABLE and will result in an exception.
Chad Rosierf77e9092015-08-06 15:50:12 +0000642 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000644 if (MI->mayLoadOrStore())
645 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000646 continue;
647 }
648
649 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000650 // the two instructions and none of the instructions between the second
651 // and first alias with the second, we can combine the second into the
652 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +0000653 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
654 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000655 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000656 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 return MBBI;
658 }
659
660 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000661 // between the two instructions and none of the instructions between the
662 // first and the second alias with the first, we can combine the first
663 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +0000664 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
665 !(FirstMI->mayLoad() && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000666 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000667 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000668 return MBBI;
669 }
670 // Unable to combine these instructions due to interference in between.
671 // Keep looking.
672 }
673 }
674
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000675 // If the instruction wasn't a matching load or store. Stop searching if we
676 // encounter a call instruction that might modify memory.
677 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +0000678 return E;
679
680 // Update modified / uses register lists.
681 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
682
683 // Otherwise, if the base register is modified, we have no match, so
684 // return early.
685 if (ModifiedRegs[BaseReg])
686 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000687
688 // Update list of instructions that read/write memory.
689 if (MI->mayLoadOrStore())
690 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000691 }
692 return E;
693}
694
695MachineBasicBlock::iterator
696AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
697 MachineBasicBlock::iterator Update) {
698 assert((Update->getOpcode() == AArch64::ADDXri ||
699 Update->getOpcode() == AArch64::SUBXri) &&
700 "Unexpected base register update instruction to merge!");
701 MachineBasicBlock::iterator NextI = I;
702 // Return the instruction following the merged instruction, which is
703 // the instruction following our unmerged load. Unless that's the add/sub
704 // instruction we're merging, in which case it's the one after that.
705 if (++NextI == Update)
706 ++NextI;
707
708 int Value = Update->getOperand(2).getImm();
709 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
710 "Can't merge 1 << 12 offset into pre-indexed load / store");
711 if (Update->getOpcode() == AArch64::SUBXri)
712 Value = -Value;
713
714 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
715 MachineInstrBuilder MIB =
716 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000717 .addOperand(getLdStRegOp(Update))
718 .addOperand(getLdStRegOp(I))
719 .addOperand(getLdStBaseOp(I))
Tim Northover3b0846e2014-05-24 12:50:23 +0000720 .addImm(Value);
721 (void)MIB;
722
723 DEBUG(dbgs() << "Creating pre-indexed load/store.");
724 DEBUG(dbgs() << " Replacing instructions:\n ");
725 DEBUG(I->print(dbgs()));
726 DEBUG(dbgs() << " ");
727 DEBUG(Update->print(dbgs()));
728 DEBUG(dbgs() << " with instruction:\n ");
729 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
730 DEBUG(dbgs() << "\n");
731
732 // Erase the old instructions for the block.
733 I->eraseFromParent();
734 Update->eraseFromParent();
735
736 return NextI;
737}
738
739MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
740 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
741 assert((Update->getOpcode() == AArch64::ADDXri ||
742 Update->getOpcode() == AArch64::SUBXri) &&
743 "Unexpected base register update instruction to merge!");
744 MachineBasicBlock::iterator NextI = I;
745 // Return the instruction following the merged instruction, which is
746 // the instruction following our unmerged load. Unless that's the add/sub
747 // instruction we're merging, in which case it's the one after that.
748 if (++NextI == Update)
749 ++NextI;
750
751 int Value = Update->getOperand(2).getImm();
752 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
753 "Can't merge 1 << 12 offset into post-indexed load / store");
754 if (Update->getOpcode() == AArch64::SUBXri)
755 Value = -Value;
756
757 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
758 MachineInstrBuilder MIB =
759 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000760 .addOperand(getLdStRegOp(Update))
761 .addOperand(getLdStRegOp(I))
762 .addOperand(getLdStBaseOp(I))
Tim Northover3b0846e2014-05-24 12:50:23 +0000763 .addImm(Value);
764 (void)MIB;
765
766 DEBUG(dbgs() << "Creating post-indexed load/store.");
767 DEBUG(dbgs() << " Replacing instructions:\n ");
768 DEBUG(I->print(dbgs()));
769 DEBUG(dbgs() << " ");
770 DEBUG(Update->print(dbgs()));
771 DEBUG(dbgs() << " with instruction:\n ");
772 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
773 DEBUG(dbgs() << "\n");
774
775 // Erase the old instructions for the block.
776 I->eraseFromParent();
777 Update->eraseFromParent();
778
779 return NextI;
780}
781
782static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
783 int Offset) {
784 switch (MI->getOpcode()) {
785 default:
786 break;
787 case AArch64::SUBXri:
788 // Negate the offset for a SUB instruction.
789 Offset *= -1;
790 // FALLTHROUGH
791 case AArch64::ADDXri:
792 // Make sure it's a vanilla immediate operand, not a relocation or
793 // anything else we can't handle.
794 if (!MI->getOperand(2).isImm())
795 break;
796 // Watch out for 1 << 12 shifted value.
797 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
798 break;
799 // If the instruction has the base register as source and dest and the
800 // immediate will fit in a signed 9-bit integer, then we have a match.
Chad Rosierf77e9092015-08-06 15:50:12 +0000801 if (getLdStRegOp(MI).getReg() == BaseReg &&
802 getLdStBaseOp(MI).getReg() == BaseReg &&
803 getLdStOffsetOp(MI).getImm() <= 255 &&
804 getLdStOffsetOp(MI).getImm() >= -256) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000805 // If we have a non-zero Offset, we check that it matches the amount
806 // we're adding to the register.
807 if (!Offset || Offset == MI->getOperand(2).getImm())
808 return true;
809 }
810 break;
811 }
812 return false;
813}
814
815MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
816 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
817 MachineBasicBlock::iterator E = I->getParent()->end();
818 MachineInstr *MemMI = I;
819 MachineBasicBlock::iterator MBBI = I;
820 const MachineFunction &MF = *MemMI->getParent()->getParent();
821
Chad Rosierf77e9092015-08-06 15:50:12 +0000822 unsigned DestReg = getLdStRegOp(MemMI).getReg();
823 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
824 int Offset = getLdStOffsetOp(MemMI).getImm() *
Tim Northover3b0846e2014-05-24 12:50:23 +0000825 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
826
827 // If the base register overlaps the destination register, we can't
828 // merge the update.
829 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
830 return E;
831
832 // Scan forward looking for post-index opportunities.
833 // Updating instructions can't be formed if the memory insn already
834 // has an offset other than the value we're looking for.
835 if (Offset != Value)
836 return E;
837
838 // Track which registers have been modified and used between the first insn
839 // (inclusive) and the second insn.
840 BitVector ModifiedRegs, UsedRegs;
841 ModifiedRegs.resize(TRI->getNumRegs());
842 UsedRegs.resize(TRI->getNumRegs());
843 ++MBBI;
844 for (unsigned Count = 0; MBBI != E; ++MBBI) {
845 MachineInstr *MI = MBBI;
846 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
847 // optimization by changing how far we scan.
848 if (MI->isDebugValue())
849 continue;
850
851 // Now that we know this is a real instruction, count it.
852 ++Count;
853
854 // If we found a match, return it.
855 if (isMatchingUpdateInsn(MI, BaseReg, Value))
856 return MBBI;
857
858 // Update the status of what the instruction clobbered and used.
859 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
860
861 // Otherwise, if the base register is used or modified, we have no match, so
862 // return early.
863 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
864 return E;
865 }
866 return E;
867}
868
869MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
870 MachineBasicBlock::iterator I, unsigned Limit) {
871 MachineBasicBlock::iterator B = I->getParent()->begin();
872 MachineBasicBlock::iterator E = I->getParent()->end();
873 MachineInstr *MemMI = I;
874 MachineBasicBlock::iterator MBBI = I;
875 const MachineFunction &MF = *MemMI->getParent()->getParent();
876
Chad Rosierf77e9092015-08-06 15:50:12 +0000877 unsigned DestReg = getLdStRegOp(MemMI).getReg();
878 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
879 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000880 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
881
882 // If the load/store is the first instruction in the block, there's obviously
883 // not any matching update. Ditto if the memory offset isn't zero.
884 if (MBBI == B || Offset != 0)
885 return E;
886 // If the base register overlaps the destination register, we can't
887 // merge the update.
888 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
889 return E;
890
891 // Track which registers have been modified and used between the first insn
892 // (inclusive) and the second insn.
893 BitVector ModifiedRegs, UsedRegs;
894 ModifiedRegs.resize(TRI->getNumRegs());
895 UsedRegs.resize(TRI->getNumRegs());
896 --MBBI;
897 for (unsigned Count = 0; MBBI != B; --MBBI) {
898 MachineInstr *MI = MBBI;
899 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
900 // optimization by changing how far we scan.
901 if (MI->isDebugValue())
902 continue;
903
904 // Now that we know this is a real instruction, count it.
905 ++Count;
906
907 // If we found a match, return it.
908 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
909 return MBBI;
910
911 // Update the status of what the instruction clobbered and used.
912 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
913
914 // Otherwise, if the base register is used or modified, we have no match, so
915 // return early.
916 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
917 return E;
918 }
919 return E;
920}
921
922bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
923 bool Modified = false;
924 // Two tranformations to do here:
925 // 1) Find loads and stores that can be merged into a single load or store
926 // pair instruction.
927 // e.g.,
928 // ldr x0, [x2]
929 // ldr x1, [x2, #8]
930 // ; becomes
931 // ldp x0, x1, [x2]
932 // 2) Find base register updates that can be merged into the load or store
933 // as a base-reg writeback.
934 // e.g.,
935 // ldr x0, [x2]
936 // add x2, x2, #4
937 // ; becomes
938 // ldr x0, [x2], #4
939
940 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
941 MBBI != E;) {
942 MachineInstr *MI = MBBI;
943 switch (MI->getOpcode()) {
944 default:
945 // Just move on to the next instruction.
946 ++MBBI;
947 break;
948 case AArch64::STRSui:
949 case AArch64::STRDui:
950 case AArch64::STRQui:
951 case AArch64::STRXui:
952 case AArch64::STRWui:
953 case AArch64::LDRSui:
954 case AArch64::LDRDui:
955 case AArch64::LDRQui:
956 case AArch64::LDRXui:
957 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +0000958 case AArch64::LDRSWui:
Tim Northover3b0846e2014-05-24 12:50:23 +0000959 // do the unscaled versions as well
960 case AArch64::STURSi:
961 case AArch64::STURDi:
962 case AArch64::STURQi:
963 case AArch64::STURWi:
964 case AArch64::STURXi:
965 case AArch64::LDURSi:
966 case AArch64::LDURDi:
967 case AArch64::LDURQi:
968 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000969 case AArch64::LDURXi:
970 case AArch64::LDURSWi: {
Tim Northover3b0846e2014-05-24 12:50:23 +0000971 // If this is a volatile load/store, don't mess with it.
972 if (MI->hasOrderedMemoryRef()) {
973 ++MBBI;
974 break;
975 }
976 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +0000977 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000978 ++MBBI;
979 break;
980 }
981 // Check if this load/store has a hint to avoid pair formation.
982 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
983 if (TII->isLdStPairSuppressed(MI)) {
984 ++MBBI;
985 break;
986 }
987 // Look ahead up to ScanLimit instructions for a pairable instruction.
Chad Rosier96a18a92015-07-21 17:42:04 +0000988 LdStPairFlags Flags;
Tim Northover3b0846e2014-05-24 12:50:23 +0000989 MachineBasicBlock::iterator Paired =
Chad Rosier96a18a92015-07-21 17:42:04 +0000990 findMatchingInsn(MBBI, Flags, ScanLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000991 if (Paired != E) {
992 // Merge the loads into a pair. Keeping the iterator straight is a
993 // pain, so we let the merge routine tell us what the next instruction
994 // is after it's done mucking about.
Chad Rosier96a18a92015-07-21 17:42:04 +0000995 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000996
997 Modified = true;
998 ++NumPairCreated;
Chad Rosier22eb7102015-08-06 17:37:18 +0000999 if (isUnscaledLdSt(MI))
Tim Northover3b0846e2014-05-24 12:50:23 +00001000 ++NumUnscaledPairCreated;
1001 break;
1002 }
1003 ++MBBI;
1004 break;
1005 }
1006 // FIXME: Do the other instructions.
1007 }
1008 }
1009
1010 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1011 MBBI != E;) {
1012 MachineInstr *MI = MBBI;
1013 // Do update merging. It's simpler to keep this separate from the above
1014 // switch, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001015 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001016 switch (Opc) {
1017 default:
1018 // Just move on to the next instruction.
1019 ++MBBI;
1020 break;
1021 case AArch64::STRSui:
1022 case AArch64::STRDui:
1023 case AArch64::STRQui:
1024 case AArch64::STRXui:
1025 case AArch64::STRWui:
1026 case AArch64::LDRSui:
1027 case AArch64::LDRDui:
1028 case AArch64::LDRQui:
1029 case AArch64::LDRXui:
1030 case AArch64::LDRWui:
1031 // do the unscaled versions as well
1032 case AArch64::STURSi:
1033 case AArch64::STURDi:
1034 case AArch64::STURQi:
1035 case AArch64::STURWi:
1036 case AArch64::STURXi:
1037 case AArch64::LDURSi:
1038 case AArch64::LDURDi:
1039 case AArch64::LDURQi:
1040 case AArch64::LDURWi:
1041 case AArch64::LDURXi: {
1042 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001043 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001044 ++MBBI;
1045 break;
1046 }
1047 // Look ahead up to ScanLimit instructions for a mergable instruction.
1048 MachineBasicBlock::iterator Update =
1049 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1050 if (Update != E) {
1051 // Merge the update into the ld/st.
1052 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1053 Modified = true;
1054 ++NumPostFolded;
1055 break;
1056 }
1057 // Don't know how to handle pre/post-index versions, so move to the next
1058 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001059 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001060 ++MBBI;
1061 break;
1062 }
1063
1064 // Look back to try to find a pre-index instruction. For example,
1065 // add x0, x0, #8
1066 // ldr x1, [x0]
1067 // merged into:
1068 // ldr x1, [x0, #8]!
1069 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1070 if (Update != E) {
1071 // Merge the update into the ld/st.
1072 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1073 Modified = true;
1074 ++NumPreFolded;
1075 break;
1076 }
1077
1078 // Look forward to try to find a post-index instruction. For example,
1079 // ldr x1, [x0, #64]
1080 // add x0, x0, #64
1081 // merged into:
1082 // ldr x1, [x0, #64]!
1083
1084 // The immediate in the load/store is scaled by the size of the register
1085 // being loaded. The immediate in the add we're looking for,
1086 // however, is not, so adjust here.
1087 int Value = MI->getOperand(2).getImm() *
1088 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1089 ->getSize();
1090 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1091 if (Update != E) {
1092 // Merge the update into the ld/st.
1093 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1094 Modified = true;
1095 ++NumPreFolded;
1096 break;
1097 }
1098
1099 // Nothing found. Just move to the next instruction.
1100 ++MBBI;
1101 break;
1102 }
1103 // FIXME: Do the other instructions.
1104 }
1105 }
1106
1107 return Modified;
1108}
1109
1110bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Eric Christopher6c901622015-01-28 03:51:33 +00001111 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1112 TRI = Fn.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001113
1114 bool Modified = false;
1115 for (auto &MBB : Fn)
1116 Modified |= optimizeBlock(MBB);
1117
1118 return Modified;
1119}
1120
1121// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1122// loads and stores near one another?
1123
Chad Rosier43f5c842015-08-05 12:40:13 +00001124/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1125/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001126FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1127 return new AArch64LoadStoreOpt();
1128}