blob: d37751449cc61f2b5261d00cbbb3a9c12a35d471 [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 Rosier2dfd3542015-09-23 13:51:44 +0000120 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000121 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000122 mergeUpdateInsn(MachineBasicBlock::iterator I,
123 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000124
125 bool optimizeBlock(MachineBasicBlock &MBB);
126
127 bool runOnMachineFunction(MachineFunction &Fn) override;
128
129 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000130 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000132};
133char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000134} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000135
Chad Rosier96530b32015-08-05 13:44:51 +0000136INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
137 AARCH64_LOAD_STORE_OPT_NAME, false, false)
138
Chad Rosier22eb7102015-08-06 17:37:18 +0000139static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000140 switch (Opc) {
141 default:
142 return false;
143 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000144 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000146 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000147 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000148 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000149 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000150 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000151 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000152 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000153 case AArch64::LDURSWi:
154 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000155 }
156}
157
Chad Rosier22eb7102015-08-06 17:37:18 +0000158static bool isUnscaledLdSt(MachineInstr *MI) {
159 return isUnscaledLdSt(MI->getOpcode());
160}
161
Tim Northover3b0846e2014-05-24 12:50:23 +0000162// Size in bytes of the data moved by an unscaled load or store
Chad Rosier22eb7102015-08-06 17:37:18 +0000163static int getMemSize(MachineInstr *MI) {
164 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000165 default:
Tilmann Schellera17a4322014-06-03 16:33:13 +0000166 llvm_unreachable("Opcode has unknown size!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000167 case AArch64::STRSui:
168 case AArch64::STURSi:
169 return 4;
170 case AArch64::STRDui:
171 case AArch64::STURDi:
172 return 8;
173 case AArch64::STRQui:
174 case AArch64::STURQi:
175 return 16;
176 case AArch64::STRWui:
177 case AArch64::STURWi:
178 return 4;
179 case AArch64::STRXui:
180 case AArch64::STURXi:
181 return 8;
182 case AArch64::LDRSui:
183 case AArch64::LDURSi:
184 return 4;
185 case AArch64::LDRDui:
186 case AArch64::LDURDi:
187 return 8;
188 case AArch64::LDRQui:
189 case AArch64::LDURQi:
190 return 16;
191 case AArch64::LDRWui:
192 case AArch64::LDURWi:
193 return 4;
194 case AArch64::LDRXui:
195 case AArch64::LDURXi:
196 return 8;
Quentin Colombet29f55332015-01-24 01:25:54 +0000197 case AArch64::LDRSWui:
198 case AArch64::LDURSWi:
199 return 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000200 }
201}
202
Quentin Colombet66b61632015-03-06 22:42:10 +0000203static unsigned getMatchingNonSExtOpcode(unsigned Opc,
204 bool *IsValidLdStrOpc = nullptr) {
205 if (IsValidLdStrOpc)
206 *IsValidLdStrOpc = true;
207 switch (Opc) {
208 default:
209 if (IsValidLdStrOpc)
210 *IsValidLdStrOpc = false;
211 return UINT_MAX;
212 case AArch64::STRDui:
213 case AArch64::STURDi:
214 case AArch64::STRQui:
215 case AArch64::STURQi:
216 case AArch64::STRWui:
217 case AArch64::STURWi:
218 case AArch64::STRXui:
219 case AArch64::STURXi:
220 case AArch64::LDRDui:
221 case AArch64::LDURDi:
222 case AArch64::LDRQui:
223 case AArch64::LDURQi:
224 case AArch64::LDRWui:
225 case AArch64::LDURWi:
226 case AArch64::LDRXui:
227 case AArch64::LDURXi:
228 case AArch64::STRSui:
229 case AArch64::STURSi:
230 case AArch64::LDRSui:
231 case AArch64::LDURSi:
232 return Opc;
233 case AArch64::LDRSWui:
234 return AArch64::LDRWui;
235 case AArch64::LDURSWi:
236 return AArch64::LDURWi;
237 }
238}
239
Tim Northover3b0846e2014-05-24 12:50:23 +0000240static unsigned getMatchingPairOpcode(unsigned Opc) {
241 switch (Opc) {
242 default:
243 llvm_unreachable("Opcode has no pairwise equivalent!");
244 case AArch64::STRSui:
245 case AArch64::STURSi:
246 return AArch64::STPSi;
247 case AArch64::STRDui:
248 case AArch64::STURDi:
249 return AArch64::STPDi;
250 case AArch64::STRQui:
251 case AArch64::STURQi:
252 return AArch64::STPQi;
253 case AArch64::STRWui:
254 case AArch64::STURWi:
255 return AArch64::STPWi;
256 case AArch64::STRXui:
257 case AArch64::STURXi:
258 return AArch64::STPXi;
259 case AArch64::LDRSui:
260 case AArch64::LDURSi:
261 return AArch64::LDPSi;
262 case AArch64::LDRDui:
263 case AArch64::LDURDi:
264 return AArch64::LDPDi;
265 case AArch64::LDRQui:
266 case AArch64::LDURQi:
267 return AArch64::LDPQi;
268 case AArch64::LDRWui:
269 case AArch64::LDURWi:
270 return AArch64::LDPWi;
271 case AArch64::LDRXui:
272 case AArch64::LDURXi:
273 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000274 case AArch64::LDRSWui:
275 case AArch64::LDURSWi:
276 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000277 }
278}
279
280static unsigned getPreIndexedOpcode(unsigned Opc) {
281 switch (Opc) {
282 default:
283 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000284 case AArch64::STRSui:
285 return AArch64::STRSpre;
286 case AArch64::STRDui:
287 return AArch64::STRDpre;
288 case AArch64::STRQui:
289 return AArch64::STRQpre;
290 case AArch64::STRWui:
291 return AArch64::STRWpre;
292 case AArch64::STRXui:
293 return AArch64::STRXpre;
294 case AArch64::LDRSui:
295 return AArch64::LDRSpre;
296 case AArch64::LDRDui:
297 return AArch64::LDRDpre;
298 case AArch64::LDRQui:
299 return AArch64::LDRQpre;
300 case AArch64::LDRWui:
301 return AArch64::LDRWpre;
302 case AArch64::LDRXui:
303 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000304 case AArch64::LDRSWui:
305 return AArch64::LDRSWpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000306 }
307}
308
309static unsigned getPostIndexedOpcode(unsigned Opc) {
310 switch (Opc) {
311 default:
312 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
313 case AArch64::STRSui:
314 return AArch64::STRSpost;
315 case AArch64::STRDui:
316 return AArch64::STRDpost;
317 case AArch64::STRQui:
318 return AArch64::STRQpost;
319 case AArch64::STRWui:
320 return AArch64::STRWpost;
321 case AArch64::STRXui:
322 return AArch64::STRXpost;
323 case AArch64::LDRSui:
324 return AArch64::LDRSpost;
325 case AArch64::LDRDui:
326 return AArch64::LDRDpost;
327 case AArch64::LDRQui:
328 return AArch64::LDRQpost;
329 case AArch64::LDRWui:
330 return AArch64::LDRWpost;
331 case AArch64::LDRXui:
332 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000333 case AArch64::LDRSWui:
334 return AArch64::LDRSWpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000335 }
336}
337
Chad Rosierf77e9092015-08-06 15:50:12 +0000338static const MachineOperand &getLdStRegOp(const MachineInstr *MI) {
339 return MI->getOperand(0);
340}
341
342static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
343 return MI->getOperand(1);
344}
345
346static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
347 return MI->getOperand(2);
348}
349
Tim Northover3b0846e2014-05-24 12:50:23 +0000350MachineBasicBlock::iterator
351AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
352 MachineBasicBlock::iterator Paired,
Chad Rosier96a18a92015-07-21 17:42:04 +0000353 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000354 MachineBasicBlock::iterator NextI = I;
355 ++NextI;
356 // If NextI is the second of the two instructions to be merged, we need
357 // to skip one further. Either way we merge will invalidate the iterator,
358 // and we don't need to scan the new instruction, as it's a pairwise
359 // instruction, which we're not considering for further action anyway.
360 if (NextI == Paired)
361 ++NextI;
362
Chad Rosier96a18a92015-07-21 17:42:04 +0000363 int SExtIdx = Flags.getSExtIdx();
Quentin Colombet66b61632015-03-06 22:42:10 +0000364 unsigned Opc =
365 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosier22eb7102015-08-06 17:37:18 +0000366 bool IsUnscaled = isUnscaledLdSt(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000367 int OffsetStride =
368 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
369
Chad Rosier96a18a92015-07-21 17:42:04 +0000370 bool MergeForward = Flags.getMergeForward();
Quentin Colombet66b61632015-03-06 22:42:10 +0000371 unsigned NewOpc = getMatchingPairOpcode(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000372 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000373 // instructions MergeForward indicates.
374 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
375 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000376 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000377 const MachineOperand &BaseRegOp =
378 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000379
380 // Which register is Rt and which is Rt2 depends on the offset order.
381 MachineInstr *RtMI, *Rt2MI;
Chad Rosier08ef4622015-09-03 16:41:28 +0000382 if (getLdStOffsetOp(I).getImm() ==
383 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000384 RtMI = Paired;
385 Rt2MI = I;
Quentin Colombet66b61632015-03-06 22:42:10 +0000386 // Here we swapped the assumption made for SExtIdx.
387 // I.e., we turn ldp I, Paired into ldp Paired, I.
388 // Update the index accordingly.
389 if (SExtIdx != -1)
390 SExtIdx = (SExtIdx + 1) % 2;
Tim Northover3b0846e2014-05-24 12:50:23 +0000391 } else {
392 RtMI = I;
393 Rt2MI = Paired;
394 }
Chad Rosier08ef4622015-09-03 16:41:28 +0000395 // Handle Unscaled
Chad Rosierf77e9092015-08-06 15:50:12 +0000396 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier08ef4622015-09-03 16:41:28 +0000397 if (IsUnscaled && EnableAArch64UnscaledMemOp)
398 OffsetImm /= OffsetStride;
Tim Northover3b0846e2014-05-24 12:50:23 +0000399
400 // Construct the new instruction.
401 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
402 I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000403 .addOperand(getLdStRegOp(RtMI))
404 .addOperand(getLdStRegOp(Rt2MI))
Tim Northover3b0846e2014-05-24 12:50:23 +0000405 .addOperand(BaseRegOp)
406 .addImm(OffsetImm);
407 (void)MIB;
408
409 // FIXME: Do we need/want to copy the mem operands from the source
410 // instructions? Probably. What uses them after this?
411
412 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
413 DEBUG(I->print(dbgs()));
414 DEBUG(dbgs() << " ");
415 DEBUG(Paired->print(dbgs()));
416 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000417
418 if (SExtIdx != -1) {
419 // Generate the sign extension for the proper result of the ldp.
420 // I.e., with X1, that would be:
421 // %W1<def> = KILL %W1, %X1<imp-def>
422 // %X1<def> = SBFMXri %X1<kill>, 0, 31
423 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
424 // Right now, DstMO has the extended register, since it comes from an
425 // extended opcode.
426 unsigned DstRegX = DstMO.getReg();
427 // Get the W variant of that register.
428 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
429 // Update the result of LDP to use the W instead of the X variant.
430 DstMO.setReg(DstRegW);
431 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
432 DEBUG(dbgs() << "\n");
433 // Make the machine verifier happy by providing a definition for
434 // the X register.
435 // Insert this definition right after the generated LDP, i.e., before
436 // InsertionPoint.
437 MachineInstrBuilder MIBKill =
438 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
439 TII->get(TargetOpcode::KILL), DstRegW)
440 .addReg(DstRegW)
441 .addReg(DstRegX, RegState::Define);
442 MIBKill->getOperand(2).setImplicit();
443 // Create the sign extension.
444 MachineInstrBuilder MIBSXTW =
445 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
446 TII->get(AArch64::SBFMXri), DstRegX)
447 .addReg(DstRegX)
448 .addImm(0)
449 .addImm(31);
450 (void)MIBSXTW;
451 DEBUG(dbgs() << " Extend operand:\n ");
452 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
453 DEBUG(dbgs() << "\n");
454 } else {
455 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
456 DEBUG(dbgs() << "\n");
457 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000458
459 // Erase the old instructions.
460 I->eraseFromParent();
461 Paired->eraseFromParent();
462
463 return NextI;
464}
465
466/// trackRegDefsUses - Remember what registers the specified instruction uses
467/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000468static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 BitVector &UsedRegs,
470 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000471 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000472 if (MO.isRegMask())
473 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
474
475 if (!MO.isReg())
476 continue;
477 unsigned Reg = MO.getReg();
478 if (MO.isDef()) {
479 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
480 ModifiedRegs.set(*AI);
481 } else {
482 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
483 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
484 UsedRegs.set(*AI);
485 }
486 }
487}
488
489static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +0000490 // Convert the byte-offset used by unscaled into an "element" offset used
491 // by the scaled pair load/store instructions.
Chad Rosier08ef4622015-09-03 16:41:28 +0000492 if (IsUnscaled)
Chad Rosier3dd0e942015-08-18 16:20:03 +0000493 Offset /= OffsetStride;
494
495 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +0000496}
497
498// Do alignment, specialized to power of 2 and for signed ints,
499// avoiding having to do a C-style cast from uint_64t to int when
500// using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
501// FIXME: Move this function to include/MathExtras.h?
502static int alignTo(int Num, int PowOf2) {
503 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
504}
505
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000506static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
507 const AArch64InstrInfo *TII) {
508 // One of the instructions must modify memory.
509 if (!MIa->mayStore() && !MIb->mayStore())
510 return false;
511
512 // Both instructions must be memory operations.
513 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
514 return false;
515
516 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
517}
518
519static bool mayAlias(MachineInstr *MIa,
520 SmallVectorImpl<MachineInstr *> &MemInsns,
521 const AArch64InstrInfo *TII) {
522 for (auto &MIb : MemInsns)
523 if (mayAlias(MIa, MIb, TII))
524 return true;
525
526 return false;
527}
528
Tim Northover3b0846e2014-05-24 12:50:23 +0000529/// findMatchingInsn - Scan the instructions looking for a load/store that can
530/// be combined with the current instruction into a load/store pair.
531MachineBasicBlock::iterator
532AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000533 LdStPairFlags &Flags,
Quentin Colombet66b61632015-03-06 22:42:10 +0000534 unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000535 MachineBasicBlock::iterator E = I->getParent()->end();
536 MachineBasicBlock::iterator MBBI = I;
537 MachineInstr *FirstMI = I;
538 ++MBBI;
539
Matthias Braunfa3872e2015-05-18 20:27:55 +0000540 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000541 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +0000542 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +0000543 unsigned Reg = getLdStRegOp(FirstMI).getReg();
544 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
545 int Offset = getLdStOffsetOp(FirstMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000546
547 // Early exit if the first instruction modifies the base register.
548 // e.g., ldr x0, [x0]
Tim Northover3b0846e2014-05-24 12:50:23 +0000549 if (FirstMI->modifiesRegister(BaseReg, TRI))
550 return E;
Chad Rosiercaed6db2015-08-10 17:17:19 +0000551
552 // Early exit if the offset if not possible to match. (6 bits of positive
553 // range, plus allow an extra one in case we find a later insn that matches
554 // with Offset-1)
Tim Northover3b0846e2014-05-24 12:50:23 +0000555 int OffsetStride =
556 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
557 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
558 return E;
559
560 // Track which registers have been modified and used between the first insn
561 // (inclusive) and the second insn.
562 BitVector ModifiedRegs, UsedRegs;
563 ModifiedRegs.resize(TRI->getNumRegs());
564 UsedRegs.resize(TRI->getNumRegs());
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000565
566 // Remember any instructions that read/write memory between FirstMI and MI.
567 SmallVector<MachineInstr *, 4> MemInsns;
568
Tim Northover3b0846e2014-05-24 12:50:23 +0000569 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
570 MachineInstr *MI = MBBI;
571 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
572 // optimization by changing how far we scan.
573 if (MI->isDebugValue())
574 continue;
575
576 // Now that we know this is a real instruction, count it.
577 ++Count;
578
Chad Rosier08ef4622015-09-03 16:41:28 +0000579 bool CanMergeOpc = Opc == MI->getOpcode();
580 Flags.setSExtIdx(-1);
581 if (!CanMergeOpc) {
582 bool IsValidLdStrOpc;
583 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
584 assert(IsValidLdStrOpc &&
585 "Given Opc should be a Load or Store with an immediate");
586 // Opc will be the first instruction in the pair.
587 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
588 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
589 }
590
591 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +0000592 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +0000593 // If we've found another instruction with the same opcode, check to see
594 // if the base and offset are compatible with our starting instruction.
595 // These instructions all have scaled immediate operands, so we just
596 // check for +1/-1. Make sure to check the new instruction offset is
597 // actually an immediate and not a symbolic reference destined for
598 // a relocation.
599 //
600 // Pairwise instructions have a 7-bit signed offset field. Single insns
601 // have a 12-bit unsigned offset field. To be a valid combine, the
602 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +0000603 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
604 int MIOffset = getLdStOffsetOp(MI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000605 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
606 (Offset + OffsetStride == MIOffset))) {
607 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
608 // If this is a volatile load/store that otherwise matched, stop looking
609 // as something is going on that we don't have enough information to
610 // safely transform. Similarly, stop if we see a hint to avoid pairs.
611 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
612 return E;
613 // If the resultant immediate offset of merging these instructions
614 // is out of range for a pairwise instruction, bail and keep looking.
Chad Rosier08ef4622015-09-03 16:41:28 +0000615 bool MIIsUnscaled = isUnscaledLdSt(MI);
616 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000617 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000618 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000619 continue;
620 }
621 // If the alignment requirements of the paired (scaled) instruction
622 // can't express the offset of the unscaled input, bail and keep
623 // looking.
624 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
625 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
626 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000627 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000628 continue;
629 }
630 // If the destination register of the loads is the same register, bail
631 // and keep looking. A load-pair instruction with both destination
632 // registers the same is UNPREDICTABLE and will result in an exception.
Chad Rosierf77e9092015-08-06 15:50:12 +0000633 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +0000635 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000636 continue;
637 }
638
639 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000640 // the two instructions and none of the instructions between the second
641 // and first alias with the second, we can combine the second into the
642 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +0000643 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
644 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000645 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000646 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 return MBBI;
648 }
649
650 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000651 // between the two instructions and none of the instructions between the
652 // first and the second alias with the first, we can combine the first
653 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +0000654 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +0000655 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000656 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000657 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000658 return MBBI;
659 }
660 // Unable to combine these instructions due to interference in between.
661 // Keep looking.
662 }
663 }
664
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000665 // If the instruction wasn't a matching load or store. Stop searching if we
666 // encounter a call instruction that might modify memory.
667 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +0000668 return E;
669
670 // Update modified / uses register lists.
671 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
672
673 // Otherwise, if the base register is modified, we have no match, so
674 // return early.
675 if (ModifiedRegs[BaseReg])
676 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000677
678 // Update list of instructions that read/write memory.
679 if (MI->mayLoadOrStore())
680 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000681 }
682 return E;
683}
684
685MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000686AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
687 MachineBasicBlock::iterator Update,
688 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 assert((Update->getOpcode() == AArch64::ADDXri ||
690 Update->getOpcode() == AArch64::SUBXri) &&
691 "Unexpected base register update instruction to merge!");
692 MachineBasicBlock::iterator NextI = I;
693 // Return the instruction following the merged instruction, which is
694 // the instruction following our unmerged load. Unless that's the add/sub
695 // instruction we're merging, in which case it's the one after that.
696 if (++NextI == Update)
697 ++NextI;
698
699 int Value = Update->getOperand(2).getImm();
700 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +0000701 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +0000702 if (Update->getOpcode() == AArch64::SUBXri)
703 Value = -Value;
704
Chad Rosier2dfd3542015-09-23 13:51:44 +0000705 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
706 : getPostIndexedOpcode(I->getOpcode());
Tim Northover3b0846e2014-05-24 12:50:23 +0000707 MachineInstrBuilder MIB =
708 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Chad Rosierf77e9092015-08-06 15:50:12 +0000709 .addOperand(getLdStRegOp(Update))
710 .addOperand(getLdStRegOp(I))
711 .addOperand(getLdStBaseOp(I))
Tim Northover3b0846e2014-05-24 12:50:23 +0000712 .addImm(Value);
713 (void)MIB;
714
Chad Rosier2dfd3542015-09-23 13:51:44 +0000715 if (IsPreIdx)
716 DEBUG(dbgs() << "Creating pre-indexed load/store.");
717 else
718 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 DEBUG(dbgs() << " Replacing instructions:\n ");
720 DEBUG(I->print(dbgs()));
721 DEBUG(dbgs() << " ");
722 DEBUG(Update->print(dbgs()));
723 DEBUG(dbgs() << " with instruction:\n ");
724 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
725 DEBUG(dbgs() << "\n");
726
727 // Erase the old instructions for the block.
728 I->eraseFromParent();
729 Update->eraseFromParent();
730
731 return NextI;
732}
733
734static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
735 int Offset) {
736 switch (MI->getOpcode()) {
737 default:
738 break;
739 case AArch64::SUBXri:
740 // Negate the offset for a SUB instruction.
741 Offset *= -1;
742 // FALLTHROUGH
743 case AArch64::ADDXri:
744 // Make sure it's a vanilla immediate operand, not a relocation or
745 // anything else we can't handle.
746 if (!MI->getOperand(2).isImm())
747 break;
748 // Watch out for 1 << 12 shifted value.
749 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
750 break;
751 // If the instruction has the base register as source and dest and the
752 // immediate will fit in a signed 9-bit integer, then we have a match.
Chad Rosierf77e9092015-08-06 15:50:12 +0000753 if (getLdStRegOp(MI).getReg() == BaseReg &&
754 getLdStBaseOp(MI).getReg() == BaseReg &&
755 getLdStOffsetOp(MI).getImm() <= 255 &&
756 getLdStOffsetOp(MI).getImm() >= -256) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000757 // If we have a non-zero Offset, we check that it matches the amount
758 // we're adding to the register.
759 if (!Offset || Offset == MI->getOperand(2).getImm())
760 return true;
761 }
762 break;
763 }
764 return false;
765}
766
767MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
768 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
769 MachineBasicBlock::iterator E = I->getParent()->end();
770 MachineInstr *MemMI = I;
771 MachineBasicBlock::iterator MBBI = I;
772 const MachineFunction &MF = *MemMI->getParent()->getParent();
773
Chad Rosierf77e9092015-08-06 15:50:12 +0000774 unsigned DestReg = getLdStRegOp(MemMI).getReg();
775 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
776 int Offset = getLdStOffsetOp(MemMI).getImm() *
Tim Northover3b0846e2014-05-24 12:50:23 +0000777 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
778
779 // If the base register overlaps the destination register, we can't
780 // merge the update.
781 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
782 return E;
783
784 // Scan forward looking for post-index opportunities.
785 // Updating instructions can't be formed if the memory insn already
786 // has an offset other than the value we're looking for.
787 if (Offset != Value)
788 return E;
789
790 // Track which registers have been modified and used between the first insn
791 // (inclusive) and the second insn.
792 BitVector ModifiedRegs, UsedRegs;
793 ModifiedRegs.resize(TRI->getNumRegs());
794 UsedRegs.resize(TRI->getNumRegs());
795 ++MBBI;
796 for (unsigned Count = 0; MBBI != E; ++MBBI) {
797 MachineInstr *MI = MBBI;
798 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
799 // optimization by changing how far we scan.
800 if (MI->isDebugValue())
801 continue;
802
803 // Now that we know this is a real instruction, count it.
804 ++Count;
805
806 // If we found a match, return it.
807 if (isMatchingUpdateInsn(MI, BaseReg, Value))
808 return MBBI;
809
810 // Update the status of what the instruction clobbered and used.
811 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
812
813 // Otherwise, if the base register is used or modified, we have no match, so
814 // return early.
815 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
816 return E;
817 }
818 return E;
819}
820
821MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
822 MachineBasicBlock::iterator I, unsigned Limit) {
823 MachineBasicBlock::iterator B = I->getParent()->begin();
824 MachineBasicBlock::iterator E = I->getParent()->end();
825 MachineInstr *MemMI = I;
826 MachineBasicBlock::iterator MBBI = I;
827 const MachineFunction &MF = *MemMI->getParent()->getParent();
828
Chad Rosierf77e9092015-08-06 15:50:12 +0000829 unsigned DestReg = getLdStRegOp(MemMI).getReg();
830 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
831 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +0000832 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
833
834 // If the load/store is the first instruction in the block, there's obviously
835 // not any matching update. Ditto if the memory offset isn't zero.
836 if (MBBI == B || Offset != 0)
837 return E;
838 // If the base register overlaps the destination register, we can't
839 // merge the update.
840 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
841 return E;
842
843 // Track which registers have been modified and used between the first insn
844 // (inclusive) and the second insn.
845 BitVector ModifiedRegs, UsedRegs;
846 ModifiedRegs.resize(TRI->getNumRegs());
847 UsedRegs.resize(TRI->getNumRegs());
848 --MBBI;
849 for (unsigned Count = 0; MBBI != B; --MBBI) {
850 MachineInstr *MI = MBBI;
851 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
852 // optimization by changing how far we scan.
853 if (MI->isDebugValue())
854 continue;
855
856 // Now that we know this is a real instruction, count it.
857 ++Count;
858
859 // If we found a match, return it.
860 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
861 return MBBI;
862
863 // Update the status of what the instruction clobbered and used.
864 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
865
866 // Otherwise, if the base register is used or modified, we have no match, so
867 // return early.
868 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
869 return E;
870 }
871 return E;
872}
873
874bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
875 bool Modified = false;
876 // Two tranformations to do here:
877 // 1) Find loads and stores that can be merged into a single load or store
878 // pair instruction.
879 // e.g.,
880 // ldr x0, [x2]
881 // ldr x1, [x2, #8]
882 // ; becomes
883 // ldp x0, x1, [x2]
884 // 2) Find base register updates that can be merged into the load or store
885 // as a base-reg writeback.
886 // e.g.,
887 // ldr x0, [x2]
888 // add x2, x2, #4
889 // ; becomes
890 // ldr x0, [x2], #4
891
892 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
893 MBBI != E;) {
894 MachineInstr *MI = MBBI;
895 switch (MI->getOpcode()) {
896 default:
897 // Just move on to the next instruction.
898 ++MBBI;
899 break;
900 case AArch64::STRSui:
901 case AArch64::STRDui:
902 case AArch64::STRQui:
903 case AArch64::STRXui:
904 case AArch64::STRWui:
905 case AArch64::LDRSui:
906 case AArch64::LDRDui:
907 case AArch64::LDRQui:
908 case AArch64::LDRXui:
909 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +0000910 case AArch64::LDRSWui:
Tim Northover3b0846e2014-05-24 12:50:23 +0000911 // do the unscaled versions as well
912 case AArch64::STURSi:
913 case AArch64::STURDi:
914 case AArch64::STURQi:
915 case AArch64::STURWi:
916 case AArch64::STURXi:
917 case AArch64::LDURSi:
918 case AArch64::LDURDi:
919 case AArch64::LDURQi:
920 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000921 case AArch64::LDURXi:
922 case AArch64::LDURSWi: {
Tim Northover3b0846e2014-05-24 12:50:23 +0000923 // If this is a volatile load/store, don't mess with it.
924 if (MI->hasOrderedMemoryRef()) {
925 ++MBBI;
926 break;
927 }
928 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +0000929 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000930 ++MBBI;
931 break;
932 }
933 // Check if this load/store has a hint to avoid pair formation.
934 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
935 if (TII->isLdStPairSuppressed(MI)) {
936 ++MBBI;
937 break;
938 }
939 // Look ahead up to ScanLimit instructions for a pairable instruction.
Chad Rosier96a18a92015-07-21 17:42:04 +0000940 LdStPairFlags Flags;
Tim Northover3b0846e2014-05-24 12:50:23 +0000941 MachineBasicBlock::iterator Paired =
Chad Rosier96a18a92015-07-21 17:42:04 +0000942 findMatchingInsn(MBBI, Flags, ScanLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000943 if (Paired != E) {
Chad Rosier9f4709b2015-08-26 13:39:48 +0000944 ++NumPairCreated;
945 if (isUnscaledLdSt(MI))
946 ++NumUnscaledPairCreated;
947
Tim Northover3b0846e2014-05-24 12:50:23 +0000948 // Merge the loads into a pair. Keeping the iterator straight is a
949 // pain, so we let the merge routine tell us what the next instruction
950 // is after it's done mucking about.
Chad Rosier96a18a92015-07-21 17:42:04 +0000951 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000952 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000953 break;
954 }
955 ++MBBI;
956 break;
957 }
958 // FIXME: Do the other instructions.
959 }
960 }
961
962 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
963 MBBI != E;) {
964 MachineInstr *MI = MBBI;
965 // Do update merging. It's simpler to keep this separate from the above
966 // switch, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +0000967 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +0000968 switch (Opc) {
969 default:
970 // Just move on to the next instruction.
971 ++MBBI;
972 break;
973 case AArch64::STRSui:
974 case AArch64::STRDui:
975 case AArch64::STRQui:
976 case AArch64::STRXui:
977 case AArch64::STRWui:
978 case AArch64::LDRSui:
979 case AArch64::LDRDui:
980 case AArch64::LDRQui:
981 case AArch64::LDRXui:
982 case AArch64::LDRWui:
983 // do the unscaled versions as well
984 case AArch64::STURSi:
985 case AArch64::STURDi:
986 case AArch64::STURQi:
987 case AArch64::STURWi:
988 case AArch64::STURXi:
989 case AArch64::LDURSi:
990 case AArch64::LDURDi:
991 case AArch64::LDURQi:
992 case AArch64::LDURWi:
993 case AArch64::LDURXi: {
994 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +0000995 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000996 ++MBBI;
997 break;
998 }
999 // Look ahead up to ScanLimit instructions for a mergable instruction.
1000 MachineBasicBlock::iterator Update =
1001 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1002 if (Update != E) {
1003 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001004 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001005 Modified = true;
1006 ++NumPostFolded;
1007 break;
1008 }
1009 // Don't know how to handle pre/post-index versions, so move to the next
1010 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001011 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001012 ++MBBI;
1013 break;
1014 }
1015
1016 // Look back to try to find a pre-index instruction. For example,
1017 // add x0, x0, #8
1018 // ldr x1, [x0]
1019 // merged into:
1020 // ldr x1, [x0, #8]!
1021 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1022 if (Update != E) {
1023 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001024 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001025 Modified = true;
1026 ++NumPreFolded;
1027 break;
1028 }
1029
1030 // Look forward to try to find a post-index instruction. For example,
1031 // ldr x1, [x0, #64]
1032 // add x0, x0, #64
1033 // merged into:
1034 // ldr x1, [x0, #64]!
1035
1036 // The immediate in the load/store is scaled by the size of the register
1037 // being loaded. The immediate in the add we're looking for,
1038 // however, is not, so adjust here.
1039 int Value = MI->getOperand(2).getImm() *
1040 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1041 ->getSize();
1042 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1043 if (Update != E) {
1044 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001045 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001046 Modified = true;
1047 ++NumPreFolded;
1048 break;
1049 }
1050
1051 // Nothing found. Just move to the next instruction.
1052 ++MBBI;
1053 break;
1054 }
1055 // FIXME: Do the other instructions.
1056 }
1057 }
1058
1059 return Modified;
1060}
1061
1062bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Eric Christopher6c901622015-01-28 03:51:33 +00001063 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1064 TRI = Fn.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001065
1066 bool Modified = false;
1067 for (auto &MBB : Fn)
1068 Modified |= optimizeBlock(MBB);
1069
1070 return Modified;
1071}
1072
1073// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1074// loads and stores near one another?
1075
Chad Rosier43f5c842015-08-05 12:40:13 +00001076/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1077/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001078FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1079 return new AArch64LoadStoreOpt();
1080}