blob: e23e24cf90f1e3737f13cb553598254f53da8b5b [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 }
137
138private:
139 int getMemSize(MachineInstr *MemMI);
140};
141char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000142} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000143
Chad Rosier96530b32015-08-05 13:44:51 +0000144INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
145 AARCH64_LOAD_STORE_OPT_NAME, false, false)
146
Tim Northover3b0846e2014-05-24 12:50:23 +0000147static bool isUnscaledLdst(unsigned Opc) {
148 switch (Opc) {
149 default:
150 return false;
151 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000152 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000153 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000154 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000155 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000156 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000157 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000159 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000160 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000161 case AArch64::LDURSWi:
162 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000163 }
164}
165
166// Size in bytes of the data moved by an unscaled load or store
167int AArch64LoadStoreOpt::getMemSize(MachineInstr *MemMI) {
168 switch (MemMI->getOpcode()) {
169 default:
Tilmann Schellera17a4322014-06-03 16:33:13 +0000170 llvm_unreachable("Opcode has unknown size!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000171 case AArch64::STRSui:
172 case AArch64::STURSi:
173 return 4;
174 case AArch64::STRDui:
175 case AArch64::STURDi:
176 return 8;
177 case AArch64::STRQui:
178 case AArch64::STURQi:
179 return 16;
180 case AArch64::STRWui:
181 case AArch64::STURWi:
182 return 4;
183 case AArch64::STRXui:
184 case AArch64::STURXi:
185 return 8;
186 case AArch64::LDRSui:
187 case AArch64::LDURSi:
188 return 4;
189 case AArch64::LDRDui:
190 case AArch64::LDURDi:
191 return 8;
192 case AArch64::LDRQui:
193 case AArch64::LDURQi:
194 return 16;
195 case AArch64::LDRWui:
196 case AArch64::LDURWi:
197 return 4;
198 case AArch64::LDRXui:
199 case AArch64::LDURXi:
200 return 8;
Quentin Colombet29f55332015-01-24 01:25:54 +0000201 case AArch64::LDRSWui:
202 case AArch64::LDURSWi:
203 return 4;
Tim Northover3b0846e2014-05-24 12:50:23 +0000204 }
205}
206
Quentin Colombet66b61632015-03-06 22:42:10 +0000207static unsigned getMatchingNonSExtOpcode(unsigned Opc,
208 bool *IsValidLdStrOpc = nullptr) {
209 if (IsValidLdStrOpc)
210 *IsValidLdStrOpc = true;
211 switch (Opc) {
212 default:
213 if (IsValidLdStrOpc)
214 *IsValidLdStrOpc = false;
215 return UINT_MAX;
216 case AArch64::STRDui:
217 case AArch64::STURDi:
218 case AArch64::STRQui:
219 case AArch64::STURQi:
220 case AArch64::STRWui:
221 case AArch64::STURWi:
222 case AArch64::STRXui:
223 case AArch64::STURXi:
224 case AArch64::LDRDui:
225 case AArch64::LDURDi:
226 case AArch64::LDRQui:
227 case AArch64::LDURQi:
228 case AArch64::LDRWui:
229 case AArch64::LDURWi:
230 case AArch64::LDRXui:
231 case AArch64::LDURXi:
232 case AArch64::STRSui:
233 case AArch64::STURSi:
234 case AArch64::LDRSui:
235 case AArch64::LDURSi:
236 return Opc;
237 case AArch64::LDRSWui:
238 return AArch64::LDRWui;
239 case AArch64::LDURSWi:
240 return AArch64::LDURWi;
241 }
242}
243
Tim Northover3b0846e2014-05-24 12:50:23 +0000244static unsigned getMatchingPairOpcode(unsigned Opc) {
245 switch (Opc) {
246 default:
247 llvm_unreachable("Opcode has no pairwise equivalent!");
248 case AArch64::STRSui:
249 case AArch64::STURSi:
250 return AArch64::STPSi;
251 case AArch64::STRDui:
252 case AArch64::STURDi:
253 return AArch64::STPDi;
254 case AArch64::STRQui:
255 case AArch64::STURQi:
256 return AArch64::STPQi;
257 case AArch64::STRWui:
258 case AArch64::STURWi:
259 return AArch64::STPWi;
260 case AArch64::STRXui:
261 case AArch64::STURXi:
262 return AArch64::STPXi;
263 case AArch64::LDRSui:
264 case AArch64::LDURSi:
265 return AArch64::LDPSi;
266 case AArch64::LDRDui:
267 case AArch64::LDURDi:
268 return AArch64::LDPDi;
269 case AArch64::LDRQui:
270 case AArch64::LDURQi:
271 return AArch64::LDPQi;
272 case AArch64::LDRWui:
273 case AArch64::LDURWi:
274 return AArch64::LDPWi;
275 case AArch64::LDRXui:
276 case AArch64::LDURXi:
277 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000278 case AArch64::LDRSWui:
279 case AArch64::LDURSWi:
280 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000281 }
282}
283
284static unsigned getPreIndexedOpcode(unsigned Opc) {
285 switch (Opc) {
286 default:
287 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000288 case AArch64::STRSui:
289 return AArch64::STRSpre;
290 case AArch64::STRDui:
291 return AArch64::STRDpre;
292 case AArch64::STRQui:
293 return AArch64::STRQpre;
294 case AArch64::STRWui:
295 return AArch64::STRWpre;
296 case AArch64::STRXui:
297 return AArch64::STRXpre;
298 case AArch64::LDRSui:
299 return AArch64::LDRSpre;
300 case AArch64::LDRDui:
301 return AArch64::LDRDpre;
302 case AArch64::LDRQui:
303 return AArch64::LDRQpre;
304 case AArch64::LDRWui:
305 return AArch64::LDRWpre;
306 case AArch64::LDRXui:
307 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000308 case AArch64::LDRSWui:
309 return AArch64::LDRSWpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000310 }
311}
312
313static unsigned getPostIndexedOpcode(unsigned Opc) {
314 switch (Opc) {
315 default:
316 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
317 case AArch64::STRSui:
318 return AArch64::STRSpost;
319 case AArch64::STRDui:
320 return AArch64::STRDpost;
321 case AArch64::STRQui:
322 return AArch64::STRQpost;
323 case AArch64::STRWui:
324 return AArch64::STRWpost;
325 case AArch64::STRXui:
326 return AArch64::STRXpost;
327 case AArch64::LDRSui:
328 return AArch64::LDRSpost;
329 case AArch64::LDRDui:
330 return AArch64::LDRDpost;
331 case AArch64::LDRQui:
332 return AArch64::LDRQpost;
333 case AArch64::LDRWui:
334 return AArch64::LDRWpost;
335 case AArch64::LDRXui:
336 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000337 case AArch64::LDRSWui:
338 return AArch64::LDRSWpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000339 }
340}
341
342MachineBasicBlock::iterator
343AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
344 MachineBasicBlock::iterator Paired,
Chad Rosier96a18a92015-07-21 17:42:04 +0000345 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000346 MachineBasicBlock::iterator NextI = I;
347 ++NextI;
348 // If NextI is the second of the two instructions to be merged, we need
349 // to skip one further. Either way we merge will invalidate the iterator,
350 // and we don't need to scan the new instruction, as it's a pairwise
351 // instruction, which we're not considering for further action anyway.
352 if (NextI == Paired)
353 ++NextI;
354
Chad Rosier96a18a92015-07-21 17:42:04 +0000355 int SExtIdx = Flags.getSExtIdx();
Quentin Colombet66b61632015-03-06 22:42:10 +0000356 unsigned Opc =
357 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
358 bool IsUnscaled = isUnscaledLdst(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000359 int OffsetStride =
360 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(I) : 1;
361
Chad Rosier96a18a92015-07-21 17:42:04 +0000362 bool MergeForward = Flags.getMergeForward();
Quentin Colombet66b61632015-03-06 22:42:10 +0000363 unsigned NewOpc = getMatchingPairOpcode(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +0000364 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000365 // instructions MergeForward indicates.
366 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
367 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000368 // so we get the flags compatible with the input code.
369 MachineOperand &BaseRegOp =
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000370 MergeForward ? Paired->getOperand(1) : I->getOperand(1);
Tim Northover3b0846e2014-05-24 12:50:23 +0000371
372 // Which register is Rt and which is Rt2 depends on the offset order.
373 MachineInstr *RtMI, *Rt2MI;
374 if (I->getOperand(2).getImm() ==
375 Paired->getOperand(2).getImm() + OffsetStride) {
376 RtMI = Paired;
377 Rt2MI = I;
Quentin Colombet66b61632015-03-06 22:42:10 +0000378 // Here we swapped the assumption made for SExtIdx.
379 // I.e., we turn ldp I, Paired into ldp Paired, I.
380 // Update the index accordingly.
381 if (SExtIdx != -1)
382 SExtIdx = (SExtIdx + 1) % 2;
Tim Northover3b0846e2014-05-24 12:50:23 +0000383 } else {
384 RtMI = I;
385 Rt2MI = Paired;
386 }
387 // Handle Unscaled
388 int OffsetImm = RtMI->getOperand(2).getImm();
389 if (IsUnscaled && EnableAArch64UnscaledMemOp)
390 OffsetImm /= OffsetStride;
391
392 // Construct the new instruction.
393 MachineInstrBuilder MIB = BuildMI(*I->getParent(), InsertionPoint,
394 I->getDebugLoc(), TII->get(NewOpc))
395 .addOperand(RtMI->getOperand(0))
396 .addOperand(Rt2MI->getOperand(0))
397 .addOperand(BaseRegOp)
398 .addImm(OffsetImm);
399 (void)MIB;
400
401 // FIXME: Do we need/want to copy the mem operands from the source
402 // instructions? Probably. What uses them after this?
403
404 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
405 DEBUG(I->print(dbgs()));
406 DEBUG(dbgs() << " ");
407 DEBUG(Paired->print(dbgs()));
408 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000409
410 if (SExtIdx != -1) {
411 // Generate the sign extension for the proper result of the ldp.
412 // I.e., with X1, that would be:
413 // %W1<def> = KILL %W1, %X1<imp-def>
414 // %X1<def> = SBFMXri %X1<kill>, 0, 31
415 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
416 // Right now, DstMO has the extended register, since it comes from an
417 // extended opcode.
418 unsigned DstRegX = DstMO.getReg();
419 // Get the W variant of that register.
420 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
421 // Update the result of LDP to use the W instead of the X variant.
422 DstMO.setReg(DstRegW);
423 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
424 DEBUG(dbgs() << "\n");
425 // Make the machine verifier happy by providing a definition for
426 // the X register.
427 // Insert this definition right after the generated LDP, i.e., before
428 // InsertionPoint.
429 MachineInstrBuilder MIBKill =
430 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
431 TII->get(TargetOpcode::KILL), DstRegW)
432 .addReg(DstRegW)
433 .addReg(DstRegX, RegState::Define);
434 MIBKill->getOperand(2).setImplicit();
435 // Create the sign extension.
436 MachineInstrBuilder MIBSXTW =
437 BuildMI(*I->getParent(), InsertionPoint, I->getDebugLoc(),
438 TII->get(AArch64::SBFMXri), DstRegX)
439 .addReg(DstRegX)
440 .addImm(0)
441 .addImm(31);
442 (void)MIBSXTW;
443 DEBUG(dbgs() << " Extend operand:\n ");
444 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
445 DEBUG(dbgs() << "\n");
446 } else {
447 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
448 DEBUG(dbgs() << "\n");
449 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000450
451 // Erase the old instructions.
452 I->eraseFromParent();
453 Paired->eraseFromParent();
454
455 return NextI;
456}
457
458/// trackRegDefsUses - Remember what registers the specified instruction uses
459/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000460static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +0000461 BitVector &UsedRegs,
462 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +0000463 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000464 if (MO.isRegMask())
465 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
466
467 if (!MO.isReg())
468 continue;
469 unsigned Reg = MO.getReg();
470 if (MO.isDef()) {
471 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
472 ModifiedRegs.set(*AI);
473 } else {
474 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
475 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
476 UsedRegs.set(*AI);
477 }
478 }
479}
480
481static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
482 if (!IsUnscaled && (Offset > 63 || Offset < -64))
483 return false;
484 if (IsUnscaled) {
485 // Convert the byte-offset used by unscaled into an "element" offset used
486 // by the scaled pair load/store instructions.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000487 int ElemOffset = Offset / OffsetStride;
488 if (ElemOffset > 63 || ElemOffset < -64)
Tim Northover3b0846e2014-05-24 12:50:23 +0000489 return false;
490 }
491 return true;
492}
493
494// Do alignment, specialized to power of 2 and for signed ints,
495// avoiding having to do a C-style cast from uint_64t to int when
496// using RoundUpToAlignment from include/llvm/Support/MathExtras.h.
497// FIXME: Move this function to include/MathExtras.h?
498static int alignTo(int Num, int PowOf2) {
499 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
500}
501
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000502static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
503 const AArch64InstrInfo *TII) {
504 // One of the instructions must modify memory.
505 if (!MIa->mayStore() && !MIb->mayStore())
506 return false;
507
508 // Both instructions must be memory operations.
509 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
510 return false;
511
512 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
513}
514
515static bool mayAlias(MachineInstr *MIa,
516 SmallVectorImpl<MachineInstr *> &MemInsns,
517 const AArch64InstrInfo *TII) {
518 for (auto &MIb : MemInsns)
519 if (mayAlias(MIa, MIb, TII))
520 return true;
521
522 return false;
523}
524
Tim Northover3b0846e2014-05-24 12:50:23 +0000525/// findMatchingInsn - Scan the instructions looking for a load/store that can
526/// be combined with the current instruction into a load/store pair.
527MachineBasicBlock::iterator
528AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000529 LdStPairFlags &Flags,
Quentin Colombet66b61632015-03-06 22:42:10 +0000530 unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000531 MachineBasicBlock::iterator E = I->getParent()->end();
532 MachineBasicBlock::iterator MBBI = I;
533 MachineInstr *FirstMI = I;
534 ++MBBI;
535
Matthias Braunfa3872e2015-05-18 20:27:55 +0000536 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000537 bool MayLoad = FirstMI->mayLoad();
Tim Northover3b0846e2014-05-24 12:50:23 +0000538 bool IsUnscaled = isUnscaledLdst(Opc);
539 unsigned Reg = FirstMI->getOperand(0).getReg();
540 unsigned BaseReg = FirstMI->getOperand(1).getReg();
541 int Offset = FirstMI->getOperand(2).getImm();
542
543 // Early exit if the first instruction modifies the base register.
544 // e.g., ldr x0, [x0]
545 // Early exit if the offset if not possible to match. (6 bits of positive
546 // range, plus allow an extra one in case we find a later insn that matches
547 // with Offset-1
548 if (FirstMI->modifiesRegister(BaseReg, TRI))
549 return E;
550 int OffsetStride =
551 IsUnscaled && EnableAArch64UnscaledMemOp ? getMemSize(FirstMI) : 1;
552 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
553 return E;
554
555 // Track which registers have been modified and used between the first insn
556 // (inclusive) and the second insn.
557 BitVector ModifiedRegs, UsedRegs;
558 ModifiedRegs.resize(TRI->getNumRegs());
559 UsedRegs.resize(TRI->getNumRegs());
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000560
561 // Remember any instructions that read/write memory between FirstMI and MI.
562 SmallVector<MachineInstr *, 4> MemInsns;
563
Tim Northover3b0846e2014-05-24 12:50:23 +0000564 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
565 MachineInstr *MI = MBBI;
566 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
567 // optimization by changing how far we scan.
568 if (MI->isDebugValue())
569 continue;
570
571 // Now that we know this is a real instruction, count it.
572 ++Count;
573
Quentin Colombet66b61632015-03-06 22:42:10 +0000574 bool CanMergeOpc = Opc == MI->getOpcode();
Chad Rosier96a18a92015-07-21 17:42:04 +0000575 Flags.setSExtIdx(-1);
Quentin Colombet66b61632015-03-06 22:42:10 +0000576 if (!CanMergeOpc) {
577 bool IsValidLdStrOpc;
578 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
579 if (!IsValidLdStrOpc)
580 continue;
581 // Opc will be the first instruction in the pair.
Chad Rosier96a18a92015-07-21 17:42:04 +0000582 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
Quentin Colombet66b61632015-03-06 22:42:10 +0000583 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
584 }
585
586 if (CanMergeOpc && MI->getOperand(2).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000587 // If we've found another instruction with the same opcode, check to see
588 // if the base and offset are compatible with our starting instruction.
589 // These instructions all have scaled immediate operands, so we just
590 // check for +1/-1. Make sure to check the new instruction offset is
591 // actually an immediate and not a symbolic reference destined for
592 // a relocation.
593 //
594 // Pairwise instructions have a 7-bit signed offset field. Single insns
595 // have a 12-bit unsigned offset field. To be a valid combine, the
596 // final offset must be in range.
597 unsigned MIBaseReg = MI->getOperand(1).getReg();
598 int MIOffset = MI->getOperand(2).getImm();
599 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
600 (Offset + OffsetStride == MIOffset))) {
601 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
602 // If this is a volatile load/store that otherwise matched, stop looking
603 // as something is going on that we don't have enough information to
604 // safely transform. Similarly, stop if we see a hint to avoid pairs.
605 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
606 return E;
607 // If the resultant immediate offset of merging these instructions
608 // is out of range for a pairwise instruction, bail and keep looking.
609 bool MIIsUnscaled = isUnscaledLdst(MI->getOpcode());
610 if (!inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
611 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000612 if (MI->mayLoadOrStore())
613 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000614 continue;
615 }
616 // If the alignment requirements of the paired (scaled) instruction
617 // can't express the offset of the unscaled input, bail and keep
618 // looking.
619 if (IsUnscaled && EnableAArch64UnscaledMemOp &&
620 (alignTo(MinOffset, OffsetStride) != MinOffset)) {
621 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000622 if (MI->mayLoadOrStore())
623 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000624 continue;
625 }
626 // If the destination register of the loads is the same register, bail
627 // and keep looking. A load-pair instruction with both destination
628 // registers the same is UNPREDICTABLE and will result in an exception.
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000629 if (MayLoad && Reg == MI->getOperand(0).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000630 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000631 if (MI->mayLoadOrStore())
632 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 continue;
634 }
635
636 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000637 // the two instructions and none of the instructions between the second
638 // and first alias with the second, we can combine the second into the
639 // first.
Tim Northover3b0846e2014-05-24 12:50:23 +0000640 if (!ModifiedRegs[MI->getOperand(0).getReg()] &&
Chad Rosiercf90acc2015-06-09 20:59:41 +0000641 !(MI->mayLoad() && UsedRegs[MI->getOperand(0).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000642 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000643 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +0000644 return MBBI;
645 }
646
647 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000648 // between the two instructions and none of the instructions between the
649 // first and the second alias with the first, we can combine the first
650 // into the second.
Tim Northover3b0846e2014-05-24 12:50:23 +0000651 if (!ModifiedRegs[FirstMI->getOperand(0).getReg()] &&
Chad Rosiercf90acc2015-06-09 20:59:41 +0000652 !(FirstMI->mayLoad() &&
653 UsedRegs[FirstMI->getOperand(0).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000654 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +0000655 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +0000656 return MBBI;
657 }
658 // Unable to combine these instructions due to interference in between.
659 // Keep looking.
660 }
661 }
662
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000663 // If the instruction wasn't a matching load or store. Stop searching if we
664 // encounter a call instruction that might modify memory.
665 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +0000666 return E;
667
668 // Update modified / uses register lists.
669 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
670
671 // Otherwise, if the base register is modified, we have no match, so
672 // return early.
673 if (ModifiedRegs[BaseReg])
674 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +0000675
676 // Update list of instructions that read/write memory.
677 if (MI->mayLoadOrStore())
678 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000679 }
680 return E;
681}
682
683MachineBasicBlock::iterator
684AArch64LoadStoreOpt::mergePreIdxUpdateInsn(MachineBasicBlock::iterator I,
685 MachineBasicBlock::iterator Update) {
686 assert((Update->getOpcode() == AArch64::ADDXri ||
687 Update->getOpcode() == AArch64::SUBXri) &&
688 "Unexpected base register update instruction to merge!");
689 MachineBasicBlock::iterator NextI = I;
690 // Return the instruction following the merged instruction, which is
691 // the instruction following our unmerged load. Unless that's the add/sub
692 // instruction we're merging, in which case it's the one after that.
693 if (++NextI == Update)
694 ++NextI;
695
696 int Value = Update->getOperand(2).getImm();
697 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
698 "Can't merge 1 << 12 offset into pre-indexed load / store");
699 if (Update->getOpcode() == AArch64::SUBXri)
700 Value = -Value;
701
702 unsigned NewOpc = getPreIndexedOpcode(I->getOpcode());
703 MachineInstrBuilder MIB =
704 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
705 .addOperand(Update->getOperand(0))
706 .addOperand(I->getOperand(0))
707 .addOperand(I->getOperand(1))
708 .addImm(Value);
709 (void)MIB;
710
711 DEBUG(dbgs() << "Creating pre-indexed load/store.");
712 DEBUG(dbgs() << " Replacing instructions:\n ");
713 DEBUG(I->print(dbgs()));
714 DEBUG(dbgs() << " ");
715 DEBUG(Update->print(dbgs()));
716 DEBUG(dbgs() << " with instruction:\n ");
717 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
718 DEBUG(dbgs() << "\n");
719
720 // Erase the old instructions for the block.
721 I->eraseFromParent();
722 Update->eraseFromParent();
723
724 return NextI;
725}
726
727MachineBasicBlock::iterator AArch64LoadStoreOpt::mergePostIdxUpdateInsn(
728 MachineBasicBlock::iterator I, MachineBasicBlock::iterator Update) {
729 assert((Update->getOpcode() == AArch64::ADDXri ||
730 Update->getOpcode() == AArch64::SUBXri) &&
731 "Unexpected base register update instruction to merge!");
732 MachineBasicBlock::iterator NextI = I;
733 // Return the instruction following the merged instruction, which is
734 // the instruction following our unmerged load. Unless that's the add/sub
735 // instruction we're merging, in which case it's the one after that.
736 if (++NextI == Update)
737 ++NextI;
738
739 int Value = Update->getOperand(2).getImm();
740 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
741 "Can't merge 1 << 12 offset into post-indexed load / store");
742 if (Update->getOpcode() == AArch64::SUBXri)
743 Value = -Value;
744
745 unsigned NewOpc = getPostIndexedOpcode(I->getOpcode());
746 MachineInstrBuilder MIB =
747 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
748 .addOperand(Update->getOperand(0))
749 .addOperand(I->getOperand(0))
750 .addOperand(I->getOperand(1))
751 .addImm(Value);
752 (void)MIB;
753
754 DEBUG(dbgs() << "Creating post-indexed load/store.");
755 DEBUG(dbgs() << " Replacing instructions:\n ");
756 DEBUG(I->print(dbgs()));
757 DEBUG(dbgs() << " ");
758 DEBUG(Update->print(dbgs()));
759 DEBUG(dbgs() << " with instruction:\n ");
760 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
761 DEBUG(dbgs() << "\n");
762
763 // Erase the old instructions for the block.
764 I->eraseFromParent();
765 Update->eraseFromParent();
766
767 return NextI;
768}
769
770static bool isMatchingUpdateInsn(MachineInstr *MI, unsigned BaseReg,
771 int Offset) {
772 switch (MI->getOpcode()) {
773 default:
774 break;
775 case AArch64::SUBXri:
776 // Negate the offset for a SUB instruction.
777 Offset *= -1;
778 // FALLTHROUGH
779 case AArch64::ADDXri:
780 // Make sure it's a vanilla immediate operand, not a relocation or
781 // anything else we can't handle.
782 if (!MI->getOperand(2).isImm())
783 break;
784 // Watch out for 1 << 12 shifted value.
785 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
786 break;
787 // If the instruction has the base register as source and dest and the
788 // immediate will fit in a signed 9-bit integer, then we have a match.
789 if (MI->getOperand(0).getReg() == BaseReg &&
790 MI->getOperand(1).getReg() == BaseReg &&
791 MI->getOperand(2).getImm() <= 255 &&
792 MI->getOperand(2).getImm() >= -256) {
793 // If we have a non-zero Offset, we check that it matches the amount
794 // we're adding to the register.
795 if (!Offset || Offset == MI->getOperand(2).getImm())
796 return true;
797 }
798 break;
799 }
800 return false;
801}
802
803MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
804 MachineBasicBlock::iterator I, unsigned Limit, int Value) {
805 MachineBasicBlock::iterator E = I->getParent()->end();
806 MachineInstr *MemMI = I;
807 MachineBasicBlock::iterator MBBI = I;
808 const MachineFunction &MF = *MemMI->getParent()->getParent();
809
810 unsigned DestReg = MemMI->getOperand(0).getReg();
811 unsigned BaseReg = MemMI->getOperand(1).getReg();
812 int Offset = MemMI->getOperand(2).getImm() *
813 TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
814
815 // If the base register overlaps the destination register, we can't
816 // merge the update.
817 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
818 return E;
819
820 // Scan forward looking for post-index opportunities.
821 // Updating instructions can't be formed if the memory insn already
822 // has an offset other than the value we're looking for.
823 if (Offset != Value)
824 return E;
825
826 // Track which registers have been modified and used between the first insn
827 // (inclusive) and the second insn.
828 BitVector ModifiedRegs, UsedRegs;
829 ModifiedRegs.resize(TRI->getNumRegs());
830 UsedRegs.resize(TRI->getNumRegs());
831 ++MBBI;
832 for (unsigned Count = 0; MBBI != E; ++MBBI) {
833 MachineInstr *MI = MBBI;
834 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
835 // optimization by changing how far we scan.
836 if (MI->isDebugValue())
837 continue;
838
839 // Now that we know this is a real instruction, count it.
840 ++Count;
841
842 // If we found a match, return it.
843 if (isMatchingUpdateInsn(MI, BaseReg, Value))
844 return MBBI;
845
846 // Update the status of what the instruction clobbered and used.
847 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
848
849 // Otherwise, if the base register is used or modified, we have no match, so
850 // return early.
851 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
852 return E;
853 }
854 return E;
855}
856
857MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
858 MachineBasicBlock::iterator I, unsigned Limit) {
859 MachineBasicBlock::iterator B = I->getParent()->begin();
860 MachineBasicBlock::iterator E = I->getParent()->end();
861 MachineInstr *MemMI = I;
862 MachineBasicBlock::iterator MBBI = I;
863 const MachineFunction &MF = *MemMI->getParent()->getParent();
864
865 unsigned DestReg = MemMI->getOperand(0).getReg();
866 unsigned BaseReg = MemMI->getOperand(1).getReg();
867 int Offset = MemMI->getOperand(2).getImm();
868 unsigned RegSize = TII->getRegClass(MemMI->getDesc(), 0, TRI, MF)->getSize();
869
870 // If the load/store is the first instruction in the block, there's obviously
871 // not any matching update. Ditto if the memory offset isn't zero.
872 if (MBBI == B || Offset != 0)
873 return E;
874 // If the base register overlaps the destination register, we can't
875 // merge the update.
876 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
877 return E;
878
879 // Track which registers have been modified and used between the first insn
880 // (inclusive) and the second insn.
881 BitVector ModifiedRegs, UsedRegs;
882 ModifiedRegs.resize(TRI->getNumRegs());
883 UsedRegs.resize(TRI->getNumRegs());
884 --MBBI;
885 for (unsigned Count = 0; MBBI != B; --MBBI) {
886 MachineInstr *MI = MBBI;
887 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
888 // optimization by changing how far we scan.
889 if (MI->isDebugValue())
890 continue;
891
892 // Now that we know this is a real instruction, count it.
893 ++Count;
894
895 // If we found a match, return it.
896 if (isMatchingUpdateInsn(MI, BaseReg, RegSize))
897 return MBBI;
898
899 // Update the status of what the instruction clobbered and used.
900 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
901
902 // Otherwise, if the base register is used or modified, we have no match, so
903 // return early.
904 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
905 return E;
906 }
907 return E;
908}
909
910bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB) {
911 bool Modified = false;
912 // Two tranformations to do here:
913 // 1) Find loads and stores that can be merged into a single load or store
914 // pair instruction.
915 // e.g.,
916 // ldr x0, [x2]
917 // ldr x1, [x2, #8]
918 // ; becomes
919 // ldp x0, x1, [x2]
920 // 2) Find base register updates that can be merged into the load or store
921 // as a base-reg writeback.
922 // e.g.,
923 // ldr x0, [x2]
924 // add x2, x2, #4
925 // ; becomes
926 // ldr x0, [x2], #4
927
928 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
929 MBBI != E;) {
930 MachineInstr *MI = MBBI;
931 switch (MI->getOpcode()) {
932 default:
933 // Just move on to the next instruction.
934 ++MBBI;
935 break;
936 case AArch64::STRSui:
937 case AArch64::STRDui:
938 case AArch64::STRQui:
939 case AArch64::STRXui:
940 case AArch64::STRWui:
941 case AArch64::LDRSui:
942 case AArch64::LDRDui:
943 case AArch64::LDRQui:
944 case AArch64::LDRXui:
945 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +0000946 case AArch64::LDRSWui:
Tim Northover3b0846e2014-05-24 12:50:23 +0000947 // do the unscaled versions as well
948 case AArch64::STURSi:
949 case AArch64::STURDi:
950 case AArch64::STURQi:
951 case AArch64::STURWi:
952 case AArch64::STURXi:
953 case AArch64::LDURSi:
954 case AArch64::LDURDi:
955 case AArch64::LDURQi:
956 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000957 case AArch64::LDURXi:
958 case AArch64::LDURSWi: {
Tim Northover3b0846e2014-05-24 12:50:23 +0000959 // If this is a volatile load/store, don't mess with it.
960 if (MI->hasOrderedMemoryRef()) {
961 ++MBBI;
962 break;
963 }
964 // Make sure this is a reg+imm (as opposed to an address reloc).
965 if (!MI->getOperand(2).isImm()) {
966 ++MBBI;
967 break;
968 }
969 // Check if this load/store has a hint to avoid pair formation.
970 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
971 if (TII->isLdStPairSuppressed(MI)) {
972 ++MBBI;
973 break;
974 }
975 // Look ahead up to ScanLimit instructions for a pairable instruction.
Chad Rosier96a18a92015-07-21 17:42:04 +0000976 LdStPairFlags Flags;
Tim Northover3b0846e2014-05-24 12:50:23 +0000977 MachineBasicBlock::iterator Paired =
Chad Rosier96a18a92015-07-21 17:42:04 +0000978 findMatchingInsn(MBBI, Flags, ScanLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000979 if (Paired != E) {
980 // Merge the loads into a pair. Keeping the iterator straight is a
981 // pain, so we let the merge routine tell us what the next instruction
982 // is after it's done mucking about.
Chad Rosier96a18a92015-07-21 17:42:04 +0000983 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000984
985 Modified = true;
986 ++NumPairCreated;
987 if (isUnscaledLdst(MI->getOpcode()))
988 ++NumUnscaledPairCreated;
989 break;
990 }
991 ++MBBI;
992 break;
993 }
994 // FIXME: Do the other instructions.
995 }
996 }
997
998 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
999 MBBI != E;) {
1000 MachineInstr *MI = MBBI;
1001 // Do update merging. It's simpler to keep this separate from the above
1002 // switch, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001003 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001004 switch (Opc) {
1005 default:
1006 // Just move on to the next instruction.
1007 ++MBBI;
1008 break;
1009 case AArch64::STRSui:
1010 case AArch64::STRDui:
1011 case AArch64::STRQui:
1012 case AArch64::STRXui:
1013 case AArch64::STRWui:
1014 case AArch64::LDRSui:
1015 case AArch64::LDRDui:
1016 case AArch64::LDRQui:
1017 case AArch64::LDRXui:
1018 case AArch64::LDRWui:
1019 // do the unscaled versions as well
1020 case AArch64::STURSi:
1021 case AArch64::STURDi:
1022 case AArch64::STURQi:
1023 case AArch64::STURWi:
1024 case AArch64::STURXi:
1025 case AArch64::LDURSi:
1026 case AArch64::LDURDi:
1027 case AArch64::LDURQi:
1028 case AArch64::LDURWi:
1029 case AArch64::LDURXi: {
1030 // Make sure this is a reg+imm (as opposed to an address reloc).
1031 if (!MI->getOperand(2).isImm()) {
1032 ++MBBI;
1033 break;
1034 }
1035 // Look ahead up to ScanLimit instructions for a mergable instruction.
1036 MachineBasicBlock::iterator Update =
1037 findMatchingUpdateInsnForward(MBBI, ScanLimit, 0);
1038 if (Update != E) {
1039 // Merge the update into the ld/st.
1040 MBBI = mergePostIdxUpdateInsn(MBBI, Update);
1041 Modified = true;
1042 ++NumPostFolded;
1043 break;
1044 }
1045 // Don't know how to handle pre/post-index versions, so move to the next
1046 // instruction.
1047 if (isUnscaledLdst(Opc)) {
1048 ++MBBI;
1049 break;
1050 }
1051
1052 // Look back to try to find a pre-index instruction. For example,
1053 // add x0, x0, #8
1054 // ldr x1, [x0]
1055 // merged into:
1056 // ldr x1, [x0, #8]!
1057 Update = findMatchingUpdateInsnBackward(MBBI, ScanLimit);
1058 if (Update != E) {
1059 // Merge the update into the ld/st.
1060 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1061 Modified = true;
1062 ++NumPreFolded;
1063 break;
1064 }
1065
1066 // Look forward to try to find a post-index instruction. For example,
1067 // ldr x1, [x0, #64]
1068 // add x0, x0, #64
1069 // merged into:
1070 // ldr x1, [x0, #64]!
1071
1072 // The immediate in the load/store is scaled by the size of the register
1073 // being loaded. The immediate in the add we're looking for,
1074 // however, is not, so adjust here.
1075 int Value = MI->getOperand(2).getImm() *
1076 TII->getRegClass(MI->getDesc(), 0, TRI, *(MBB.getParent()))
1077 ->getSize();
1078 Update = findMatchingUpdateInsnForward(MBBI, ScanLimit, Value);
1079 if (Update != E) {
1080 // Merge the update into the ld/st.
1081 MBBI = mergePreIdxUpdateInsn(MBBI, Update);
1082 Modified = true;
1083 ++NumPreFolded;
1084 break;
1085 }
1086
1087 // Nothing found. Just move to the next instruction.
1088 ++MBBI;
1089 break;
1090 }
1091 // FIXME: Do the other instructions.
1092 }
1093 }
1094
1095 return Modified;
1096}
1097
1098bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Eric Christopher6c901622015-01-28 03:51:33 +00001099 TII = static_cast<const AArch64InstrInfo *>(Fn.getSubtarget().getInstrInfo());
1100 TRI = Fn.getSubtarget().getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001101
1102 bool Modified = false;
1103 for (auto &MBB : Fn)
1104 Modified |= optimizeBlock(MBB);
1105
1106 return Modified;
1107}
1108
1109// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1110// loads and stores near one another?
1111
Chad Rosier43f5c842015-08-05 12:40:13 +00001112/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1113/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001114FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1115 return new AArch64LoadStoreOpt();
1116}