blob: 179b540844a9c1810e1bc793491139d60e7180a3 [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
Tim Northover3b0846e2014-05-24 12:50:23 +000036STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
37STATISTIC(NumPostFolded, "Number of post-index updates folded");
38STATISTIC(NumPreFolded, "Number of pre-index updates folded");
39STATISTIC(NumUnscaledPairCreated,
40 "Number of load/store from unscaled generated");
Jun Bum Limc12c2792015-11-19 18:41:27 +000041STATISTIC(NumNarrowLoadsPromoted, "Number of narrow loads promoted");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000042STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000043STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000044
Chad Rosier35706ad2016-02-04 21:26:02 +000045// The LdStLimit limits how far we search for load/store pairs.
46static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000047 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000048
Chad Rosier35706ad2016-02-04 21:26:02 +000049// The UpdateLimit limits how far we search for update instructions when we form
50// pre-/post-index instructions.
51static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
52 cl::Hidden);
53
Jun Bum Lim33be4992016-05-06 15:08:57 +000054static cl::opt<bool> EnableNarrowLdMerge("enable-narrow-ld-merge", cl::Hidden,
Jun Bum Limb21d4e12016-05-20 18:45:49 +000055 cl::init(false),
Jun Bum Lim33be4992016-05-06 15:08:57 +000056 cl::desc("Enable narrow load merge"));
57
Chad Rosier96530b32015-08-05 13:44:51 +000058namespace llvm {
59void initializeAArch64LoadStoreOptPass(PassRegistry &);
60}
61
62#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
63
Tim Northover3b0846e2014-05-24 12:50:23 +000064namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000065
66typedef struct LdStPairFlags {
67 // If a matching instruction is found, MergeForward is set to true if the
68 // merge is to remove the first instruction and replace the second with
69 // a pair-wise insn, and false if the reverse is true.
70 bool MergeForward;
71
72 // SExtIdx gives the index of the result of the load pair that must be
73 // extended. The value of SExtIdx assumes that the paired load produces the
74 // value in this order: (I, returned iterator), i.e., -1 means no value has
75 // to be extended, 0 means I, and 1 means the returned iterator.
76 int SExtIdx;
77
78 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
79
80 void setMergeForward(bool V = true) { MergeForward = V; }
81 bool getMergeForward() const { return MergeForward; }
82
83 void setSExtIdx(int V) { SExtIdx = V; }
84 int getSExtIdx() const { return SExtIdx; }
85
86} LdStPairFlags;
87
Tim Northover3b0846e2014-05-24 12:50:23 +000088struct AArch64LoadStoreOpt : public MachineFunctionPass {
89 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000090 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000091 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
92 }
Tim Northover3b0846e2014-05-24 12:50:23 +000093
94 const AArch64InstrInfo *TII;
95 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000096 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000097
Chad Rosierbba881e2016-02-02 15:02:30 +000098 // Track which registers have been modified and used.
99 BitVector ModifiedRegs, UsedRegs;
100
Tim Northover3b0846e2014-05-24 12:50:23 +0000101 // Scan the instructions looking for a load/store that can be combined
102 // with the current instruction into a load/store pair.
103 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000104 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000105 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +0000106 unsigned Limit,
107 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000108
109 // Scan the instructions looking for a store that writes to the address from
110 // which the current load instruction reads. Return true if one is found.
111 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
112 MachineBasicBlock::iterator &StoreI);
113
Chad Rosierb5933d72016-02-09 19:02:12 +0000114 // Merge the two instructions indicated into a wider instruction.
115 MachineBasicBlock::iterator
116 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000117 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000118 const LdStPairFlags &Flags);
119
Tim Northover3b0846e2014-05-24 12:50:23 +0000120 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000121 MachineBasicBlock::iterator
122 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000123 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000124 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000125
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000126 // Promote the load that reads directly from the address stored to.
127 MachineBasicBlock::iterator
128 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
129 MachineBasicBlock::iterator StoreI);
130
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 // Scan the instruction list to find a base register update that can
132 // be combined with the current instruction (a load or store) using
133 // pre or post indexed addressing with writeback. Scan forwards.
134 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000135 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000136 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000137
138 // Scan the instruction list to find a base register update that can
139 // be combined with the current instruction (a load or store) using
140 // pre or post indexed addressing with writeback. Scan backwards.
141 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000142 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000143
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000144 // Find an instruction that updates the base register of the ld/st
145 // instruction.
146 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
147 unsigned BaseReg, int Offset);
148
Chad Rosier2dfd3542015-09-23 13:51:44 +0000149 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000150 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000151 mergeUpdateInsn(MachineBasicBlock::iterator I,
152 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000153
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000154 // Find and merge foldable ldr/str instructions.
155 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
156
Chad Rosier24c46ad2016-02-09 18:10:20 +0000157 // Find and pair ldr/str instructions.
158 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
159
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000160 // Find and promote load instructions which read directly from store.
161 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
162
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000163 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000164
165 bool runOnMachineFunction(MachineFunction &Fn) override;
166
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000167 MachineFunctionProperties getRequiredProperties() const override {
168 return MachineFunctionProperties().set(
169 MachineFunctionProperties::Property::AllVRegsAllocated);
170 }
171
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000173 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000174 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000175};
176char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000177} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000178
Chad Rosier96530b32015-08-05 13:44:51 +0000179INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
180 AARCH64_LOAD_STORE_OPT_NAME, false, false)
181
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000182static unsigned getBitExtrOpcode(MachineInstr *MI) {
183 switch (MI->getOpcode()) {
184 default:
185 llvm_unreachable("Unexpected opcode.");
186 case AArch64::LDRBBui:
187 case AArch64::LDURBBi:
188 case AArch64::LDRHHui:
189 case AArch64::LDURHHi:
190 return AArch64::UBFMWri;
191 case AArch64::LDRSBWui:
192 case AArch64::LDURSBWi:
193 case AArch64::LDRSHWui:
194 case AArch64::LDURSHWi:
195 return AArch64::SBFMWri;
196 }
197}
198
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000199static bool isNarrowStore(unsigned Opc) {
200 switch (Opc) {
201 default:
202 return false;
203 case AArch64::STRBBui:
204 case AArch64::STURBBi:
205 case AArch64::STRHHui:
206 case AArch64::STURHHi:
207 return true;
208 }
209}
210
Jun Bum Limc12c2792015-11-19 18:41:27 +0000211static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000212 switch (Opc) {
213 default:
214 return false;
215 case AArch64::LDRHHui:
216 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000217 case AArch64::LDRBBui:
218 case AArch64::LDURBBi:
219 case AArch64::LDRSHWui:
220 case AArch64::LDURSHWi:
221 case AArch64::LDRSBWui:
222 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000223 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000224 }
225}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000226
Jun Bum Limc12c2792015-11-19 18:41:27 +0000227static bool isNarrowLoad(MachineInstr *MI) {
228 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000229}
230
Chad Rosier00f9d232016-02-11 14:25:08 +0000231static bool isNarrowLoadOrStore(unsigned Opc) {
232 return isNarrowLoad(Opc) || isNarrowStore(Opc);
233}
234
Chad Rosier32d4d372015-09-29 16:07:32 +0000235// Scaling factor for unscaled load or store.
236static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000237 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000238 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000239 llvm_unreachable("Opcode has unknown scale!");
240 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000241 case AArch64::LDURBBi:
242 case AArch64::LDRSBWui:
243 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000244 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000245 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000246 return 1;
247 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000248 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000249 case AArch64::LDRSHWui:
250 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000251 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000252 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000253 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000254 case AArch64::LDRSui:
255 case AArch64::LDURSi:
256 case AArch64::LDRSWui:
257 case AArch64::LDURSWi:
258 case AArch64::LDRWui:
259 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000260 case AArch64::STRSui:
261 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000262 case AArch64::STRWui:
263 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000264 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000265 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000266 case AArch64::LDPWi:
267 case AArch64::STPSi:
268 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000269 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000270 case AArch64::LDRDui:
271 case AArch64::LDURDi:
272 case AArch64::LDRXui:
273 case AArch64::LDURXi:
274 case AArch64::STRDui:
275 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000276 case AArch64::STRXui:
277 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000278 case AArch64::LDPDi:
279 case AArch64::LDPXi:
280 case AArch64::STPDi:
281 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000282 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000283 case AArch64::LDRQui:
284 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000285 case AArch64::STRQui:
286 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000287 case AArch64::LDPQi:
288 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000289 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000290 }
291}
292
Quentin Colombet66b61632015-03-06 22:42:10 +0000293static unsigned getMatchingNonSExtOpcode(unsigned Opc,
294 bool *IsValidLdStrOpc = nullptr) {
295 if (IsValidLdStrOpc)
296 *IsValidLdStrOpc = true;
297 switch (Opc) {
298 default:
299 if (IsValidLdStrOpc)
300 *IsValidLdStrOpc = false;
301 return UINT_MAX;
302 case AArch64::STRDui:
303 case AArch64::STURDi:
304 case AArch64::STRQui:
305 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000306 case AArch64::STRBBui:
307 case AArch64::STURBBi:
308 case AArch64::STRHHui:
309 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000310 case AArch64::STRWui:
311 case AArch64::STURWi:
312 case AArch64::STRXui:
313 case AArch64::STURXi:
314 case AArch64::LDRDui:
315 case AArch64::LDURDi:
316 case AArch64::LDRQui:
317 case AArch64::LDURQi:
318 case AArch64::LDRWui:
319 case AArch64::LDURWi:
320 case AArch64::LDRXui:
321 case AArch64::LDURXi:
322 case AArch64::STRSui:
323 case AArch64::STURSi:
324 case AArch64::LDRSui:
325 case AArch64::LDURSi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000326 case AArch64::LDRHHui:
327 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000328 case AArch64::LDRBBui:
329 case AArch64::LDURBBi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000330 return Opc;
331 case AArch64::LDRSWui:
332 return AArch64::LDRWui;
333 case AArch64::LDURSWi:
334 return AArch64::LDURWi;
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000335 case AArch64::LDRSBWui:
336 return AArch64::LDRBBui;
337 case AArch64::LDRSHWui:
338 return AArch64::LDRHHui;
339 case AArch64::LDURSBWi:
340 return AArch64::LDURBBi;
341 case AArch64::LDURSHWi:
342 return AArch64::LDURHHi;
Quentin Colombet66b61632015-03-06 22:42:10 +0000343 }
344}
345
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000346static unsigned getMatchingWideOpcode(unsigned Opc) {
347 switch (Opc) {
348 default:
349 llvm_unreachable("Opcode has no wide equivalent!");
350 case AArch64::STRBBui:
351 return AArch64::STRHHui;
352 case AArch64::STRHHui:
353 return AArch64::STRWui;
354 case AArch64::STURBBi:
355 return AArch64::STURHHi;
356 case AArch64::STURHHi:
357 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000358 case AArch64::STURWi:
359 return AArch64::STURXi;
360 case AArch64::STRWui:
361 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000362 case AArch64::LDRHHui:
363 case AArch64::LDRSHWui:
364 return AArch64::LDRWui;
365 case AArch64::LDURHHi:
366 case AArch64::LDURSHWi:
367 return AArch64::LDURWi;
368 case AArch64::LDRBBui:
369 case AArch64::LDRSBWui:
370 return AArch64::LDRHHui;
371 case AArch64::LDURBBi:
372 case AArch64::LDURSBWi:
373 return AArch64::LDURHHi;
374 }
375}
376
Tim Northover3b0846e2014-05-24 12:50:23 +0000377static unsigned getMatchingPairOpcode(unsigned Opc) {
378 switch (Opc) {
379 default:
380 llvm_unreachable("Opcode has no pairwise equivalent!");
381 case AArch64::STRSui:
382 case AArch64::STURSi:
383 return AArch64::STPSi;
384 case AArch64::STRDui:
385 case AArch64::STURDi:
386 return AArch64::STPDi;
387 case AArch64::STRQui:
388 case AArch64::STURQi:
389 return AArch64::STPQi;
390 case AArch64::STRWui:
391 case AArch64::STURWi:
392 return AArch64::STPWi;
393 case AArch64::STRXui:
394 case AArch64::STURXi:
395 return AArch64::STPXi;
396 case AArch64::LDRSui:
397 case AArch64::LDURSi:
398 return AArch64::LDPSi;
399 case AArch64::LDRDui:
400 case AArch64::LDURDi:
401 return AArch64::LDPDi;
402 case AArch64::LDRQui:
403 case AArch64::LDURQi:
404 return AArch64::LDPQi;
405 case AArch64::LDRWui:
406 case AArch64::LDURWi:
407 return AArch64::LDPWi;
408 case AArch64::LDRXui:
409 case AArch64::LDURXi:
410 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000411 case AArch64::LDRSWui:
412 case AArch64::LDURSWi:
413 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000414 }
415}
416
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000417static unsigned isMatchingStore(MachineInstr *LoadInst,
418 MachineInstr *StoreInst) {
419 unsigned LdOpc = LoadInst->getOpcode();
420 unsigned StOpc = StoreInst->getOpcode();
421 switch (LdOpc) {
422 default:
423 llvm_unreachable("Unsupported load instruction!");
424 case AArch64::LDRBBui:
425 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
426 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
427 case AArch64::LDURBBi:
428 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
429 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
430 case AArch64::LDRHHui:
431 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
432 StOpc == AArch64::STRXui;
433 case AArch64::LDURHHi:
434 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
435 StOpc == AArch64::STURXi;
436 case AArch64::LDRWui:
437 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
438 case AArch64::LDURWi:
439 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
440 case AArch64::LDRXui:
441 return StOpc == AArch64::STRXui;
442 case AArch64::LDURXi:
443 return StOpc == AArch64::STURXi;
444 }
445}
446
Tim Northover3b0846e2014-05-24 12:50:23 +0000447static unsigned getPreIndexedOpcode(unsigned Opc) {
448 switch (Opc) {
449 default:
450 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000451 case AArch64::STRSui:
452 return AArch64::STRSpre;
453 case AArch64::STRDui:
454 return AArch64::STRDpre;
455 case AArch64::STRQui:
456 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000457 case AArch64::STRBBui:
458 return AArch64::STRBBpre;
459 case AArch64::STRHHui:
460 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000461 case AArch64::STRWui:
462 return AArch64::STRWpre;
463 case AArch64::STRXui:
464 return AArch64::STRXpre;
465 case AArch64::LDRSui:
466 return AArch64::LDRSpre;
467 case AArch64::LDRDui:
468 return AArch64::LDRDpre;
469 case AArch64::LDRQui:
470 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000471 case AArch64::LDRBBui:
472 return AArch64::LDRBBpre;
473 case AArch64::LDRHHui:
474 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000475 case AArch64::LDRWui:
476 return AArch64::LDRWpre;
477 case AArch64::LDRXui:
478 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000479 case AArch64::LDRSWui:
480 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000481 case AArch64::LDPSi:
482 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000483 case AArch64::LDPSWi:
484 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000485 case AArch64::LDPDi:
486 return AArch64::LDPDpre;
487 case AArch64::LDPQi:
488 return AArch64::LDPQpre;
489 case AArch64::LDPWi:
490 return AArch64::LDPWpre;
491 case AArch64::LDPXi:
492 return AArch64::LDPXpre;
493 case AArch64::STPSi:
494 return AArch64::STPSpre;
495 case AArch64::STPDi:
496 return AArch64::STPDpre;
497 case AArch64::STPQi:
498 return AArch64::STPQpre;
499 case AArch64::STPWi:
500 return AArch64::STPWpre;
501 case AArch64::STPXi:
502 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000503 }
504}
505
506static unsigned getPostIndexedOpcode(unsigned Opc) {
507 switch (Opc) {
508 default:
509 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
510 case AArch64::STRSui:
511 return AArch64::STRSpost;
512 case AArch64::STRDui:
513 return AArch64::STRDpost;
514 case AArch64::STRQui:
515 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000516 case AArch64::STRBBui:
517 return AArch64::STRBBpost;
518 case AArch64::STRHHui:
519 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 case AArch64::STRWui:
521 return AArch64::STRWpost;
522 case AArch64::STRXui:
523 return AArch64::STRXpost;
524 case AArch64::LDRSui:
525 return AArch64::LDRSpost;
526 case AArch64::LDRDui:
527 return AArch64::LDRDpost;
528 case AArch64::LDRQui:
529 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000530 case AArch64::LDRBBui:
531 return AArch64::LDRBBpost;
532 case AArch64::LDRHHui:
533 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000534 case AArch64::LDRWui:
535 return AArch64::LDRWpost;
536 case AArch64::LDRXui:
537 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000538 case AArch64::LDRSWui:
539 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000540 case AArch64::LDPSi:
541 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000542 case AArch64::LDPSWi:
543 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000544 case AArch64::LDPDi:
545 return AArch64::LDPDpost;
546 case AArch64::LDPQi:
547 return AArch64::LDPQpost;
548 case AArch64::LDPWi:
549 return AArch64::LDPWpost;
550 case AArch64::LDPXi:
551 return AArch64::LDPXpost;
552 case AArch64::STPSi:
553 return AArch64::STPSpost;
554 case AArch64::STPDi:
555 return AArch64::STPDpost;
556 case AArch64::STPQi:
557 return AArch64::STPQpost;
558 case AArch64::STPWi:
559 return AArch64::STPWpost;
560 case AArch64::STPXi:
561 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000562 }
563}
564
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000565static bool isPairedLdSt(const MachineInstr *MI) {
566 switch (MI->getOpcode()) {
567 default:
568 return false;
569 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000570 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000571 case AArch64::LDPDi:
572 case AArch64::LDPQi:
573 case AArch64::LDPWi:
574 case AArch64::LDPXi:
575 case AArch64::STPSi:
576 case AArch64::STPDi:
577 case AArch64::STPQi:
578 case AArch64::STPWi:
579 case AArch64::STPXi:
580 return true;
581 }
582}
583
584static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
585 unsigned PairedRegOp = 0) {
586 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
587 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
588 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000589}
590
591static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000592 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
593 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000594}
595
596static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000597 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
598 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000599}
600
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000601static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000602 MachineInstr *StoreInst,
603 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000604 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
605 int LoadSize = getMemScale(LoadInst);
606 int StoreSize = getMemScale(StoreInst);
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000607 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000608 ? getLdStOffsetOp(StoreInst).getImm()
609 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000610 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000611 ? getLdStOffsetOp(LoadInst).getImm()
612 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
613 return (UnscaledStOffset <= UnscaledLdOffset) &&
614 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
615}
616
Jun Bum Lim33be4992016-05-06 15:08:57 +0000617static bool isPromotableZeroStoreOpcode(unsigned Opc) {
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000618 return isNarrowStore(Opc) || Opc == AArch64::STRWui || Opc == AArch64::STURWi;
619}
620
Jun Bum Lim33be4992016-05-06 15:08:57 +0000621static bool isPromotableZeroStoreOpcode(MachineInstr *MI) {
622 return isPromotableZeroStoreOpcode(MI->getOpcode());
623}
624
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000625static bool isPromotableZeroStoreInst(MachineInstr *MI) {
626 return (isPromotableZeroStoreOpcode(MI)) &&
627 getLdStRegOp(MI).getReg() == AArch64::WZR;
628}
629
Tim Northover3b0846e2014-05-24 12:50:23 +0000630MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000631AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000632 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000633 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 MachineBasicBlock::iterator NextI = I;
635 ++NextI;
636 // If NextI is the second of the two instructions to be merged, we need
637 // to skip one further. Either way we merge will invalidate the iterator,
638 // and we don't need to scan the new instruction, as it's a pairwise
639 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000640 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000641 ++NextI;
642
Chad Rosierb5933d72016-02-09 19:02:12 +0000643 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000644 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Chad Rosier11eedc92016-02-09 19:17:18 +0000645 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000646
Chad Rosier96a18a92015-07-21 17:42:04 +0000647 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000648 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000649 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000650 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000651 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000652 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000653 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000654 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000655
656 // Which register is Rt and which is Rt2 depends on the offset order.
657 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000658 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000659 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
660 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000661 Rt2MI = I;
662 } else {
663 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000664 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000665 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000666
James Molloy5b18b4c2015-10-23 10:41:38 +0000667 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000668 // Change the scaled offset from small to large type.
669 if (IsScaled) {
670 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
671 OffsetImm /= 2;
672 }
673
Chad Rosierc46ef882016-02-09 19:33:42 +0000674 DebugLoc DL = I->getDebugLoc();
675 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000676 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000677 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000678 // When merging small (< 32 bit) loads for big-endian targets, the order of
679 // the component parts gets swapped.
680 if (!Subtarget->isLittleEndian())
681 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000682 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000683 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000684 NewMemMI =
685 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
686 .addOperand(getLdStRegOp(RtNewDest))
687 .addOperand(BaseRegOp)
688 .addImm(OffsetImm)
689 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Chad Rosierf7ac5f22016-03-30 18:08:51 +0000690 (void)NewMemMI;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000691
692 DEBUG(
693 dbgs()
694 << "Creating the new load and extract. Replacing instructions:\n ");
695 DEBUG(I->print(dbgs()));
696 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000697 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000698 DEBUG(dbgs() << " with instructions:\n ");
699 DEBUG((NewMemMI)->print(dbgs()));
700
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000701 int Width = getMemScale(I) == 1 ? 8 : 16;
702 int LSBLow = 0;
703 int LSBHigh = Width;
704 int ImmsLow = LSBLow + Width - 1;
705 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000706 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000707 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000708 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000709 BitExtMI1 =
710 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
711 .addOperand(getLdStRegOp(Rt2MI))
712 .addReg(getLdStRegOp(RtNewDest).getReg())
713 .addImm(LSBHigh)
714 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000715 // Create the bitfield extract for low bits.
716 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
717 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000718 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000719 .addOperand(getLdStRegOp(RtMI))
720 .addReg(getLdStRegOp(RtNewDest).getReg())
721 .addImm(ImmsLow);
722 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000723 BitExtMI2 =
724 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
725 .addOperand(getLdStRegOp(RtMI))
726 .addReg(getLdStRegOp(RtNewDest).getReg())
727 .addImm(LSBLow)
728 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000729 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000730 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000731 // Create the bitfield extract for low bits.
732 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
733 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000734 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000735 .addOperand(getLdStRegOp(RtMI))
736 .addReg(getLdStRegOp(RtNewDest).getReg())
737 .addImm(ImmsLow);
738 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000739 BitExtMI1 =
740 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
741 .addOperand(getLdStRegOp(RtMI))
742 .addReg(getLdStRegOp(RtNewDest).getReg())
743 .addImm(LSBLow)
744 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000745 }
746
747 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000748 BitExtMI2 =
749 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
750 .addOperand(getLdStRegOp(Rt2MI))
751 .addReg(getLdStRegOp(RtNewDest).getReg())
752 .addImm(LSBHigh)
753 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000754 }
Chad Rosierf7ac5f22016-03-30 18:08:51 +0000755 (void)BitExtMI1;
756 (void)BitExtMI2;
757
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000758 DEBUG(dbgs() << " ");
759 DEBUG((BitExtMI1)->print(dbgs()));
760 DEBUG(dbgs() << " ");
761 DEBUG((BitExtMI2)->print(dbgs()));
762 DEBUG(dbgs() << "\n");
763
764 // Erase the old instructions.
765 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000766 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000767 return NextI;
768 }
Jun Bum Limcf974432016-03-31 14:47:24 +0000769 assert(isPromotableZeroStoreInst(I) && isPromotableZeroStoreInst(MergeMI) &&
770 "Expected promotable zero store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000771
Tim Northover3b0846e2014-05-24 12:50:23 +0000772 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000773 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000774 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000775 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Chad Rosierb5933d72016-02-09 19:02:12 +0000776 .addOperand(BaseRegOp)
777 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000778 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000779 (void)MIB;
780
Chad Rosierb5933d72016-02-09 19:02:12 +0000781 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
782 DEBUG(I->print(dbgs()));
783 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000784 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000785 DEBUG(dbgs() << " with instruction:\n ");
786 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
787 DEBUG(dbgs() << "\n");
788
789 // Erase the old instructions.
790 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000791 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000792 return NextI;
793}
794
795MachineBasicBlock::iterator
796AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
797 MachineBasicBlock::iterator Paired,
798 const LdStPairFlags &Flags) {
799 MachineBasicBlock::iterator NextI = I;
800 ++NextI;
801 // If NextI is the second of the two instructions to be merged, we need
802 // to skip one further. Either way we merge will invalidate the iterator,
803 // and we don't need to scan the new instruction, as it's a pairwise
804 // instruction, which we're not considering for further action anyway.
805 if (NextI == Paired)
806 ++NextI;
807
808 int SExtIdx = Flags.getSExtIdx();
809 unsigned Opc =
810 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000811 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Chad Rosierb5933d72016-02-09 19:02:12 +0000812 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
813
814 bool MergeForward = Flags.getMergeForward();
815 // Insert our new paired instruction after whichever of the paired
816 // instructions MergeForward indicates.
817 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
818 // Also based on MergeForward is from where we copy the base register operand
819 // so we get the flags compatible with the input code.
820 const MachineOperand &BaseRegOp =
821 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
822
Chad Rosier00f9d232016-02-11 14:25:08 +0000823 int Offset = getLdStOffsetOp(I).getImm();
824 int PairedOffset = getLdStOffsetOp(Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000825 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000826 if (IsUnscaled != PairedIsUnscaled) {
827 // We're trying to pair instructions that differ in how they are scaled. If
828 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
829 // the opposite (i.e., make Paired's offset unscaled).
830 int MemSize = getMemScale(Paired);
831 if (PairedIsUnscaled) {
832 // If the unscaled offset isn't a multiple of the MemSize, we can't
833 // pair the operations together.
834 assert(!(PairedOffset % getMemScale(Paired)) &&
835 "Offset should be a multiple of the stride!");
836 PairedOffset /= MemSize;
837 } else {
838 PairedOffset *= MemSize;
839 }
840 }
841
Chad Rosierb5933d72016-02-09 19:02:12 +0000842 // Which register is Rt and which is Rt2 depends on the offset order.
843 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000844 if (Offset == PairedOffset + OffsetStride) {
Chad Rosierb5933d72016-02-09 19:02:12 +0000845 RtMI = Paired;
846 Rt2MI = I;
847 // Here we swapped the assumption made for SExtIdx.
848 // I.e., we turn ldp I, Paired into ldp Paired, I.
849 // Update the index accordingly.
850 if (SExtIdx != -1)
851 SExtIdx = (SExtIdx + 1) % 2;
852 } else {
853 RtMI = I;
854 Rt2MI = Paired;
855 }
856 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000857 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000858 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Chad Rosier00f9d232016-02-11 14:25:08 +0000859 assert(!(OffsetImm % getMemScale(RtMI)) &&
860 "Unscaled offset cannot be scaled.");
861 OffsetImm /= getMemScale(RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000862 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000863
864 // Construct the new instruction.
865 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000866 DebugLoc DL = I->getDebugLoc();
867 MachineBasicBlock *MBB = I->getParent();
868 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000869 .addOperand(getLdStRegOp(RtMI))
870 .addOperand(getLdStRegOp(Rt2MI))
871 .addOperand(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000872 .addImm(OffsetImm)
873 .setMemRefs(I->mergeMemRefsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000874
875 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000876
877 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
878 DEBUG(I->print(dbgs()));
879 DEBUG(dbgs() << " ");
880 DEBUG(Paired->print(dbgs()));
881 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000882 if (SExtIdx != -1) {
883 // Generate the sign extension for the proper result of the ldp.
884 // I.e., with X1, that would be:
885 // %W1<def> = KILL %W1, %X1<imp-def>
886 // %X1<def> = SBFMXri %X1<kill>, 0, 31
887 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
888 // Right now, DstMO has the extended register, since it comes from an
889 // extended opcode.
890 unsigned DstRegX = DstMO.getReg();
891 // Get the W variant of that register.
892 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
893 // Update the result of LDP to use the W instead of the X variant.
894 DstMO.setReg(DstRegW);
895 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
896 DEBUG(dbgs() << "\n");
897 // Make the machine verifier happy by providing a definition for
898 // the X register.
899 // Insert this definition right after the generated LDP, i.e., before
900 // InsertionPoint.
901 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000902 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000903 .addReg(DstRegW)
904 .addReg(DstRegX, RegState::Define);
905 MIBKill->getOperand(2).setImplicit();
906 // Create the sign extension.
907 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000908 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000909 .addReg(DstRegX)
910 .addImm(0)
911 .addImm(31);
912 (void)MIBSXTW;
913 DEBUG(dbgs() << " Extend operand:\n ");
914 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000915 } else {
916 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000917 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000918 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000919
920 // Erase the old instructions.
921 I->eraseFromParent();
922 Paired->eraseFromParent();
923
924 return NextI;
925}
926
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000927MachineBasicBlock::iterator
928AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
929 MachineBasicBlock::iterator StoreI) {
930 MachineBasicBlock::iterator NextI = LoadI;
931 ++NextI;
932
933 int LoadSize = getMemScale(LoadI);
934 int StoreSize = getMemScale(StoreI);
935 unsigned LdRt = getLdStRegOp(LoadI).getReg();
936 unsigned StRt = getLdStRegOp(StoreI).getReg();
937 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
938
939 assert((IsStoreXReg ||
940 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
941 "Unexpected RegClass");
942
943 MachineInstr *BitExtMI;
944 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
945 // Remove the load, if the destination register of the loads is the same
946 // register for stored value.
947 if (StRt == LdRt && LoadSize == 8) {
948 DEBUG(dbgs() << "Remove load instruction:\n ");
949 DEBUG(LoadI->print(dbgs()));
950 DEBUG(dbgs() << "\n");
951 LoadI->eraseFromParent();
952 return NextI;
953 }
954 // Replace the load with a mov if the load and store are in the same size.
955 BitExtMI =
956 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
957 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
958 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
959 .addReg(StRt)
960 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
961 } else {
962 // FIXME: Currently we disable this transformation in big-endian targets as
963 // performance and correctness are verified only in little-endian.
964 if (!Subtarget->isLittleEndian())
965 return NextI;
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000966 bool IsUnscaled = TII->isUnscaledLdSt(LoadI);
967 assert(IsUnscaled == TII->isUnscaledLdSt(StoreI) &&
968 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000969 assert(LoadSize <= StoreSize && "Invalid load size");
970 int UnscaledLdOffset = IsUnscaled
971 ? getLdStOffsetOp(LoadI).getImm()
972 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
973 int UnscaledStOffset = IsUnscaled
974 ? getLdStOffsetOp(StoreI).getImm()
975 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
976 int Width = LoadSize * 8;
977 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
978 int Imms = Immr + Width - 1;
979 unsigned DestReg = IsStoreXReg
980 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
981 &AArch64::GPR64RegClass)
982 : LdRt;
983
984 assert((UnscaledLdOffset >= UnscaledStOffset &&
985 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
986 "Invalid offset");
987
988 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
989 Imms = Immr + Width - 1;
990 if (UnscaledLdOffset == UnscaledStOffset) {
991 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
992 | ((Immr) << 6) // immr
993 | ((Imms) << 0) // imms
994 ;
995
996 BitExtMI =
997 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
998 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
999 DestReg)
1000 .addReg(StRt)
1001 .addImm(AndMaskEncoded);
1002 } else {
1003 BitExtMI =
1004 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1005 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1006 DestReg)
1007 .addReg(StRt)
1008 .addImm(Immr)
1009 .addImm(Imms);
1010 }
1011 }
Chad Rosierf7ac5f22016-03-30 18:08:51 +00001012 (void)BitExtMI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001013
1014 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1015 DEBUG(StoreI->print(dbgs()));
1016 DEBUG(dbgs() << " ");
1017 DEBUG(LoadI->print(dbgs()));
1018 DEBUG(dbgs() << " with instructions:\n ");
1019 DEBUG(StoreI->print(dbgs()));
1020 DEBUG(dbgs() << " ");
1021 DEBUG((BitExtMI)->print(dbgs()));
1022 DEBUG(dbgs() << "\n");
1023
1024 // Erase the old instructions.
1025 LoadI->eraseFromParent();
1026 return NextI;
1027}
1028
Tim Northover3b0846e2014-05-24 12:50:23 +00001029/// trackRegDefsUses - Remember what registers the specified instruction uses
1030/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001031static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001032 BitVector &UsedRegs,
1033 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001034 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001035 if (MO.isRegMask())
1036 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1037
1038 if (!MO.isReg())
1039 continue;
1040 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001041 if (!Reg)
1042 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001043 if (MO.isDef()) {
1044 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1045 ModifiedRegs.set(*AI);
1046 } else {
1047 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1048 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1049 UsedRegs.set(*AI);
1050 }
1051 }
1052}
1053
1054static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001055 // Convert the byte-offset used by unscaled into an "element" offset used
1056 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001057 if (IsUnscaled) {
1058 // If the byte-offset isn't a multiple of the stride, there's no point
1059 // trying to match it.
1060 if (Offset % OffsetStride)
1061 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001062 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001063 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001064 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001065}
1066
1067// Do alignment, specialized to power of 2 and for signed ints,
1068// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001069// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001070// FIXME: Move this function to include/MathExtras.h?
1071static int alignTo(int Num, int PowOf2) {
1072 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1073}
1074
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001075static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1076 const AArch64InstrInfo *TII) {
1077 // One of the instructions must modify memory.
1078 if (!MIa->mayStore() && !MIb->mayStore())
1079 return false;
1080
1081 // Both instructions must be memory operations.
1082 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1083 return false;
1084
1085 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1086}
1087
1088static bool mayAlias(MachineInstr *MIa,
1089 SmallVectorImpl<MachineInstr *> &MemInsns,
1090 const AArch64InstrInfo *TII) {
1091 for (auto &MIb : MemInsns)
1092 if (mayAlias(MIa, MIb, TII))
1093 return true;
1094
1095 return false;
1096}
1097
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001098bool AArch64LoadStoreOpt::findMatchingStore(
1099 MachineBasicBlock::iterator I, unsigned Limit,
1100 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001101 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001102 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001103 MachineInstr *LoadMI = I;
1104 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001105
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001106 // If the load is the first instruction in the block, there's obviously
1107 // not any matching store.
1108 if (MBBI == B)
1109 return false;
1110
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001111 // Track which registers have been modified and used between the first insn
1112 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001113 ModifiedRegs.reset();
1114 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001115
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001116 unsigned Count = 0;
1117 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001118 --MBBI;
1119 MachineInstr *MI = MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001120
1121 // Don't count DBG_VALUE instructions towards the search limit.
1122 if (!MI->isDebugValue())
1123 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001124
1125 // If the load instruction reads directly from the address to which the
1126 // store instruction writes and the stored value is not modified, we can
1127 // promote the load. Since we do not handle stores with pre-/post-index,
1128 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001129 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001130 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001131 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001132 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1133 StoreI = MBBI;
1134 return true;
1135 }
1136
1137 if (MI->isCall())
1138 return false;
1139
1140 // Update modified / uses register lists.
1141 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1142
1143 // Otherwise, if the base register is modified, we have no match, so
1144 // return early.
1145 if (ModifiedRegs[BaseReg])
1146 return false;
1147
1148 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001149 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001150 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001151 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001152 return false;
1153}
1154
Chad Rosierc5083c22016-06-10 20:47:14 +00001155// Returns true if FirstMI and MI are candidates for merging or pairing.
1156// Otherwise, returns false.
1157static bool areCandidatesToMergeOrPair(MachineInstr *FirstMI, MachineInstr *MI,
1158 LdStPairFlags &Flags,
1159 const AArch64InstrInfo *TII) {
1160 // If this is volatile or if pairing is suppressed, not a candidate.
1161 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1162 return false;
1163
1164 // We should have already checked FirstMI for pair suppression and volatility.
1165 assert(!FirstMI->hasOrderedMemoryRef() &&
1166 !TII->isLdStPairSuppressed(FirstMI) &&
1167 "FirstMI shouldn't get here if either of these checks are true.");
1168
1169 unsigned OpcA = FirstMI->getOpcode();
1170 unsigned OpcB = MI->getOpcode();
1171
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001172 // Opcodes match: nothing more to check.
1173 if (OpcA == OpcB)
1174 return true;
1175
1176 // Try to match a sign-extended load/store with a zero-extended load/store.
1177 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1178 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1179 assert(IsValidLdStrOpc &&
1180 "Given Opc should be a Load or Store with an immediate");
1181 // OpcA will be the first instruction in the pair.
1182 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1183 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1184 return true;
1185 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001186
1187 // If the second instruction isn't even a load/store, bail out.
1188 if (!PairIsValidLdStrOpc)
1189 return false;
1190
1191 // FIXME: We don't support merging narrow loads/stores with mixed
1192 // scaled/unscaled offsets.
1193 if (isNarrowLoadOrStore(OpcA) || isNarrowLoadOrStore(OpcB))
1194 return false;
1195
1196 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001197 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001198 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1199
1200 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001201}
1202
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001203/// Scan the instructions looking for a load/store that can be combined with the
1204/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001205MachineBasicBlock::iterator
1206AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001207 LdStPairFlags &Flags, unsigned Limit,
1208 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001209 MachineBasicBlock::iterator E = I->getParent()->end();
1210 MachineBasicBlock::iterator MBBI = I;
1211 MachineInstr *FirstMI = I;
1212 ++MBBI;
1213
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001214 bool MayLoad = FirstMI->mayLoad();
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001215 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001216 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1217 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1218 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001219 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001220 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001221
1222 // Track which registers have been modified and used between the first insn
1223 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001224 ModifiedRegs.reset();
1225 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001226
1227 // Remember any instructions that read/write memory between FirstMI and MI.
1228 SmallVector<MachineInstr *, 4> MemInsns;
1229
Tim Northover3b0846e2014-05-24 12:50:23 +00001230 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1231 MachineInstr *MI = MBBI;
1232 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1233 // optimization by changing how far we scan.
1234 if (MI->isDebugValue())
1235 continue;
1236
1237 // Now that we know this is a real instruction, count it.
1238 ++Count;
1239
Chad Rosier18896c02016-02-04 16:01:40 +00001240 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001241 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001242 getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001243 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001244 // If we've found another instruction with the same opcode, check to see
1245 // if the base and offset are compatible with our starting instruction.
1246 // These instructions all have scaled immediate operands, so we just
1247 // check for +1/-1. Make sure to check the new instruction offset is
1248 // actually an immediate and not a symbolic reference destined for
1249 // a relocation.
1250 //
1251 // Pairwise instructions have a 7-bit signed offset field. Single insns
1252 // have a 12-bit unsigned offset field. To be a valid combine, the
1253 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001254 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1255 int MIOffset = getLdStOffsetOp(MI).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001256 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001257 if (IsUnscaled != MIIsUnscaled) {
1258 // We're trying to pair instructions that differ in how they are scaled.
1259 // If FirstMI is scaled then scale the offset of MI accordingly.
1260 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1261 int MemSize = getMemScale(MI);
1262 if (MIIsUnscaled) {
1263 // If the unscaled offset isn't a multiple of the MemSize, we can't
1264 // pair the operations together: bail and keep looking.
1265 if (MIOffset % MemSize)
1266 continue;
1267 MIOffset /= MemSize;
1268 } else {
1269 MIOffset *= MemSize;
1270 }
1271 }
1272
Tim Northover3b0846e2014-05-24 12:50:23 +00001273 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1274 (Offset + OffsetStride == MIOffset))) {
1275 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001276 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001277 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001278 // instruction can't express the offset of the scaled narrow input,
1279 // bail and keep looking. For promotable zero stores, allow only when
1280 // the stored value is the same (i.e., WZR).
1281 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1282 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001283 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1284 MemInsns.push_back(MI);
1285 continue;
1286 }
1287 } else {
Jun Bum Limcf974432016-03-31 14:47:24 +00001288 // If the resultant immediate offset of merging these instructions
1289 // is out of range for a pairwise instruction, bail and keep looking.
1290 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1291 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1292 MemInsns.push_back(MI);
1293 continue;
1294 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001295 // If the alignment requirements of the paired (scaled) instruction
1296 // can't express the offset of the unscaled input, bail and keep
1297 // looking.
1298 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1299 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1300 MemInsns.push_back(MI);
1301 continue;
1302 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001303 }
1304 // If the destination register of the loads is the same register, bail
1305 // and keep looking. A load-pair instruction with both destination
1306 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001307 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001308 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001309 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 continue;
1311 }
1312
1313 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001314 // the two instructions and none of the instructions between the second
1315 // and first alias with the second, we can combine the second into the
1316 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001317 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1318 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001319 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001320 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001321 return MBBI;
1322 }
1323
1324 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001325 // between the two instructions and none of the instructions between the
1326 // first and the second alias with the first, we can combine the first
1327 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001328 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001329 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001330 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001331 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001332 return MBBI;
1333 }
1334 // Unable to combine these instructions due to interference in between.
1335 // Keep looking.
1336 }
1337 }
1338
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001339 // If the instruction wasn't a matching load or store. Stop searching if we
1340 // encounter a call instruction that might modify memory.
1341 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001342 return E;
1343
1344 // Update modified / uses register lists.
1345 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1346
1347 // Otherwise, if the base register is modified, we have no match, so
1348 // return early.
1349 if (ModifiedRegs[BaseReg])
1350 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001351
1352 // Update list of instructions that read/write memory.
1353 if (MI->mayLoadOrStore())
1354 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001355 }
1356 return E;
1357}
1358
1359MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001360AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1361 MachineBasicBlock::iterator Update,
1362 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001363 assert((Update->getOpcode() == AArch64::ADDXri ||
1364 Update->getOpcode() == AArch64::SUBXri) &&
1365 "Unexpected base register update instruction to merge!");
1366 MachineBasicBlock::iterator NextI = I;
1367 // Return the instruction following the merged instruction, which is
1368 // the instruction following our unmerged load. Unless that's the add/sub
1369 // instruction we're merging, in which case it's the one after that.
1370 if (++NextI == Update)
1371 ++NextI;
1372
1373 int Value = Update->getOperand(2).getImm();
1374 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001375 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001376 if (Update->getOpcode() == AArch64::SUBXri)
1377 Value = -Value;
1378
Chad Rosier2dfd3542015-09-23 13:51:44 +00001379 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1380 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001381 MachineInstrBuilder MIB;
1382 if (!isPairedLdSt(I)) {
1383 // Non-paired instruction.
1384 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1385 .addOperand(getLdStRegOp(Update))
1386 .addOperand(getLdStRegOp(I))
1387 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001388 .addImm(Value)
1389 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001390 } else {
1391 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001392 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1394 .addOperand(getLdStRegOp(Update))
1395 .addOperand(getLdStRegOp(I, 0))
1396 .addOperand(getLdStRegOp(I, 1))
1397 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001398 .addImm(Value / Scale)
1399 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001400 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001401 (void)MIB;
1402
Chad Rosier2dfd3542015-09-23 13:51:44 +00001403 if (IsPreIdx)
1404 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1405 else
1406 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001407 DEBUG(dbgs() << " Replacing instructions:\n ");
1408 DEBUG(I->print(dbgs()));
1409 DEBUG(dbgs() << " ");
1410 DEBUG(Update->print(dbgs()));
1411 DEBUG(dbgs() << " with instruction:\n ");
1412 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1413 DEBUG(dbgs() << "\n");
1414
1415 // Erase the old instructions for the block.
1416 I->eraseFromParent();
1417 Update->eraseFromParent();
1418
1419 return NextI;
1420}
1421
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001422bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1423 MachineInstr *MI,
1424 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001425 switch (MI->getOpcode()) {
1426 default:
1427 break;
1428 case AArch64::SUBXri:
1429 // Negate the offset for a SUB instruction.
1430 Offset *= -1;
1431 // FALLTHROUGH
1432 case AArch64::ADDXri:
1433 // Make sure it's a vanilla immediate operand, not a relocation or
1434 // anything else we can't handle.
1435 if (!MI->getOperand(2).isImm())
1436 break;
1437 // Watch out for 1 << 12 shifted value.
1438 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1439 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001440
1441 // The update instruction source and destination register must be the
1442 // same as the load/store base register.
1443 if (MI->getOperand(0).getReg() != BaseReg ||
1444 MI->getOperand(1).getReg() != BaseReg)
1445 break;
1446
1447 bool IsPairedInsn = isPairedLdSt(MemMI);
1448 int UpdateOffset = MI->getOperand(2).getImm();
1449 // For non-paired load/store instructions, the immediate must fit in a
1450 // signed 9-bit integer.
1451 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1452 break;
1453
1454 // For paired load/store instructions, the immediate must be a multiple of
1455 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1456 // integer.
1457 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001458 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001459 if (UpdateOffset % Scale != 0)
1460 break;
1461
1462 int ScaledOffset = UpdateOffset / Scale;
1463 if (ScaledOffset > 64 || ScaledOffset < -64)
1464 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001465 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001466
1467 // If we have a non-zero Offset, we check that it matches the amount
1468 // we're adding to the register.
1469 if (!Offset || Offset == MI->getOperand(2).getImm())
1470 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001471 break;
1472 }
1473 return false;
1474}
1475
1476MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001477 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 MachineBasicBlock::iterator E = I->getParent()->end();
1479 MachineInstr *MemMI = I;
1480 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001481
Chad Rosierf77e9092015-08-06 15:50:12 +00001482 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001483 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001484
Chad Rosierb7c5b912015-10-01 13:43:05 +00001485 // Scan forward looking for post-index opportunities. Updating instructions
1486 // can't be formed if the memory instruction doesn't have the offset we're
1487 // looking for.
1488 if (MIUnscaledOffset != UnscaledOffset)
1489 return E;
1490
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001491 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001492 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001493 bool IsPairedInsn = isPairedLdSt(MemMI);
1494 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1495 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1496 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1497 return E;
1498 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001499
Tim Northover3b0846e2014-05-24 12:50:23 +00001500 // Track which registers have been modified and used between the first insn
1501 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001502 ModifiedRegs.reset();
1503 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001504 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001505 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001506 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001507 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001508 if (MI->isDebugValue())
1509 continue;
1510
Chad Rosier35706ad2016-02-04 21:26:02 +00001511 // Now that we know this is a real instruction, count it.
1512 ++Count;
1513
Tim Northover3b0846e2014-05-24 12:50:23 +00001514 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001515 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001516 return MBBI;
1517
1518 // Update the status of what the instruction clobbered and used.
1519 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1520
1521 // Otherwise, if the base register is used or modified, we have no match, so
1522 // return early.
1523 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1524 return E;
1525 }
1526 return E;
1527}
1528
1529MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001530 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001531 MachineBasicBlock::iterator B = I->getParent()->begin();
1532 MachineBasicBlock::iterator E = I->getParent()->end();
1533 MachineInstr *MemMI = I;
1534 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001535
Chad Rosierf77e9092015-08-06 15:50:12 +00001536 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1537 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001538
1539 // If the load/store is the first instruction in the block, there's obviously
1540 // not any matching update. Ditto if the memory offset isn't zero.
1541 if (MBBI == B || Offset != 0)
1542 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001543 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001544 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001545 bool IsPairedInsn = isPairedLdSt(MemMI);
1546 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1547 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1548 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1549 return E;
1550 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001551
1552 // Track which registers have been modified and used between the first insn
1553 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001554 ModifiedRegs.reset();
1555 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001556 unsigned Count = 0;
1557 do {
1558 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001559 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001560
Geoff Berry173b14d2016-02-09 20:47:21 +00001561 // Don't count DBG_VALUE instructions towards the search limit.
1562 if (!MI->isDebugValue())
1563 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001564
Tim Northover3b0846e2014-05-24 12:50:23 +00001565 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001566 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001567 return MBBI;
1568
1569 // Update the status of what the instruction clobbered and used.
1570 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1571
1572 // Otherwise, if the base register is used or modified, we have no match, so
1573 // return early.
1574 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1575 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001576 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001577 return E;
1578}
1579
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001580bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1581 MachineBasicBlock::iterator &MBBI) {
1582 MachineInstr *MI = MBBI;
1583 // If this is a volatile load, don't mess with it.
1584 if (MI->hasOrderedMemoryRef())
1585 return false;
1586
1587 // Make sure this is a reg+imm.
1588 // FIXME: It is possible to extend it to handle reg+reg cases.
1589 if (!getLdStOffsetOp(MI).isImm())
1590 return false;
1591
Chad Rosier35706ad2016-02-04 21:26:02 +00001592 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001593 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001594 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001595 ++NumLoadsFromStoresPromoted;
1596 // Promote the load. Keeping the iterator straight is a
1597 // pain, so we let the merge routine tell us what the next instruction
1598 // is after it's done mucking about.
1599 MBBI = promoteLoadFromStore(MBBI, StoreI);
1600 return true;
1601 }
1602 return false;
1603}
1604
Chad Rosier24c46ad2016-02-09 18:10:20 +00001605// Find narrow loads that can be converted into a single wider load with
1606// bitfield extract instructions. Also merge adjacent zero stores into a wider
1607// store.
1608bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1609 MachineBasicBlock::iterator &MBBI) {
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001610 assert((isNarrowLoad(MBBI) || isPromotableZeroStoreOpcode(MBBI)) &&
1611 "Expected narrow op.");
Chad Rosier24c46ad2016-02-09 18:10:20 +00001612 MachineInstr *MI = MBBI;
1613 MachineBasicBlock::iterator E = MI->getParent()->end();
1614
Chad Rosiercdfd7e72016-03-18 19:21:02 +00001615 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001616 return false;
1617
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001618 // For promotable zero stores, the stored value should be WZR.
1619 if (isPromotableZeroStoreOpcode(MI) &&
1620 getLdStRegOp(MI).getReg() != AArch64::WZR)
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001621 return false;
1622
Chad Rosier24c46ad2016-02-09 18:10:20 +00001623 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001624 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001625 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001626 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001627 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001628 if (isNarrowLoad(MI)) {
1629 ++NumNarrowLoadsPromoted;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001630 } else if (isPromotableZeroStoreInst(MI)) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001631 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001632 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001633 // Keeping the iterator straight is a pain, so we let the merge routine tell
1634 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001635 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001636 return true;
1637 }
1638 return false;
1639}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001640
Chad Rosier24c46ad2016-02-09 18:10:20 +00001641// Find loads and stores that can be merged into a single load or store pair
1642// instruction.
1643bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1644 MachineInstr *MI = MBBI;
1645 MachineBasicBlock::iterator E = MI->getParent()->end();
1646
Chad Rosiercdfd7e72016-03-18 19:21:02 +00001647 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001648 return false;
1649
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001650 // Early exit if the offset is not possible to match. (6 bits of positive
1651 // range, plus allow an extra one in case we find a later insn that matches
1652 // with Offset-1)
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001653 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001654 int Offset = getLdStOffsetOp(MI).getImm();
1655 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1656 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1657 return false;
1658
Chad Rosier24c46ad2016-02-09 18:10:20 +00001659 // Look ahead up to LdStLimit instructions for a pairable instruction.
1660 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001661 MachineBasicBlock::iterator Paired =
1662 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001663 if (Paired != E) {
1664 ++NumPairCreated;
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001665 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001666 ++NumUnscaledPairCreated;
1667 // Keeping the iterator straight is a pain, so we let the merge routine tell
1668 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001669 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1670 return true;
1671 }
1672 return false;
1673}
1674
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001675bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1676 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001677 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001678 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001679 // 1) Find loads that directly read from stores and promote them by
1680 // replacing with mov instructions. If the store is wider than the load,
1681 // the load will be replaced with a bitfield extract.
1682 // e.g.,
1683 // str w1, [x0, #4]
1684 // ldrh w2, [x0, #6]
1685 // ; becomes
1686 // str w1, [x0, #4]
1687 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001688 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001689 MBBI != E;) {
1690 MachineInstr *MI = MBBI;
1691 switch (MI->getOpcode()) {
1692 default:
1693 // Just move on to the next instruction.
1694 ++MBBI;
1695 break;
1696 // Scaled instructions.
1697 case AArch64::LDRBBui:
1698 case AArch64::LDRHHui:
1699 case AArch64::LDRWui:
1700 case AArch64::LDRXui:
1701 // Unscaled instructions.
1702 case AArch64::LDURBBi:
1703 case AArch64::LDURHHi:
1704 case AArch64::LDURWi:
1705 case AArch64::LDURXi: {
1706 if (tryToPromoteLoadFromStore(MBBI)) {
1707 Modified = true;
1708 break;
1709 }
1710 ++MBBI;
1711 break;
1712 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001713 }
1714 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001715 // 2) Find narrow loads that can be converted into a single wider load
1716 // with bitfield extract instructions.
1717 // e.g.,
1718 // ldrh w0, [x2]
1719 // ldrh w1, [x2, #2]
1720 // ; becomes
1721 // ldr w0, [x2]
1722 // ubfx w1, w0, #16, #16
1723 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001724 //
1725 // Also merge adjacent zero stores into a wider store.
1726 // e.g.,
1727 // strh wzr, [x0]
1728 // strh wzr, [x0, #2]
1729 // ; becomes
1730 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001731 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001732 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001733 MachineInstr *MI = MBBI;
Jun Bum Lim33be4992016-05-06 15:08:57 +00001734 unsigned Opc = MI->getOpcode();
1735 if (isPromotableZeroStoreOpcode(Opc) ||
1736 (EnableNarrowLdMerge && isNarrowLoad(Opc))) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001737 if (tryToMergeLdStInst(MBBI)) {
1738 Modified = true;
Jun Bum Lim33be4992016-05-06 15:08:57 +00001739 } else
1740 ++MBBI;
1741 } else
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001742 ++MBBI;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001743 }
Jun Bum Lim33be4992016-05-06 15:08:57 +00001744
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001745 // 3) Find loads and stores that can be merged into a single load or store
1746 // pair instruction.
1747 // e.g.,
1748 // ldr x0, [x2]
1749 // ldr x1, [x2, #8]
1750 // ; becomes
1751 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001752 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001753 MBBI != E;) {
1754 MachineInstr *MI = MBBI;
1755 switch (MI->getOpcode()) {
1756 default:
1757 // Just move on to the next instruction.
1758 ++MBBI;
1759 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001760 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001761 case AArch64::STRSui:
1762 case AArch64::STRDui:
1763 case AArch64::STRQui:
1764 case AArch64::STRXui:
1765 case AArch64::STRWui:
1766 case AArch64::LDRSui:
1767 case AArch64::LDRDui:
1768 case AArch64::LDRQui:
1769 case AArch64::LDRXui:
1770 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001771 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001772 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001773 case AArch64::STURSi:
1774 case AArch64::STURDi:
1775 case AArch64::STURQi:
1776 case AArch64::STURWi:
1777 case AArch64::STURXi:
1778 case AArch64::LDURSi:
1779 case AArch64::LDURDi:
1780 case AArch64::LDURQi:
1781 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001782 case AArch64::LDURXi:
1783 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001784 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001785 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001786 break;
1787 }
1788 ++MBBI;
1789 break;
1790 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001791 }
1792 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001793 // 4) Find base register updates that can be merged into the load or store
1794 // as a base-reg writeback.
1795 // e.g.,
1796 // ldr x0, [x2]
1797 // add x2, x2, #4
1798 // ; becomes
1799 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001800 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1801 MBBI != E;) {
1802 MachineInstr *MI = MBBI;
1803 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001804 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001805 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001806 switch (Opc) {
1807 default:
1808 // Just move on to the next instruction.
1809 ++MBBI;
1810 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001811 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001812 case AArch64::STRSui:
1813 case AArch64::STRDui:
1814 case AArch64::STRQui:
1815 case AArch64::STRXui:
1816 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001817 case AArch64::STRHHui:
1818 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001819 case AArch64::LDRSui:
1820 case AArch64::LDRDui:
1821 case AArch64::LDRQui:
1822 case AArch64::LDRXui:
1823 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001824 case AArch64::LDRHHui:
1825 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001826 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001827 case AArch64::STURSi:
1828 case AArch64::STURDi:
1829 case AArch64::STURQi:
1830 case AArch64::STURWi:
1831 case AArch64::STURXi:
1832 case AArch64::LDURSi:
1833 case AArch64::LDURDi:
1834 case AArch64::LDURQi:
1835 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001836 case AArch64::LDURXi:
1837 // Paired instructions.
1838 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001839 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001840 case AArch64::LDPDi:
1841 case AArch64::LDPQi:
1842 case AArch64::LDPWi:
1843 case AArch64::LDPXi:
1844 case AArch64::STPSi:
1845 case AArch64::STPDi:
1846 case AArch64::STPQi:
1847 case AArch64::STPWi:
1848 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001849 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001850 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001851 ++MBBI;
1852 break;
1853 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001854 // Look forward to try to form a post-index instruction. For example,
1855 // ldr x0, [x20]
1856 // add x20, x20, #32
1857 // merged into:
1858 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001859 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001860 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001861 if (Update != E) {
1862 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001863 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001864 Modified = true;
1865 ++NumPostFolded;
1866 break;
1867 }
1868 // Don't know how to handle pre/post-index versions, so move to the next
1869 // instruction.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001870 if (TII->isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001871 ++MBBI;
1872 break;
1873 }
1874
1875 // Look back to try to find a pre-index instruction. For example,
1876 // add x0, x0, #8
1877 // ldr x1, [x0]
1878 // merged into:
1879 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001880 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001881 if (Update != E) {
1882 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001883 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001884 Modified = true;
1885 ++NumPreFolded;
1886 break;
1887 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001888 // The immediate in the load/store is scaled by the size of the memory
1889 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001890 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001891 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001892
Tim Northover3b0846e2014-05-24 12:50:23 +00001893 // Look forward to try to find a post-index instruction. For example,
1894 // ldr x1, [x0, #64]
1895 // add x0, x0, #64
1896 // merged into:
1897 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001898 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001899 if (Update != E) {
1900 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001901 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 Modified = true;
1903 ++NumPreFolded;
1904 break;
1905 }
1906
1907 // Nothing found. Just move to the next instruction.
1908 ++MBBI;
1909 break;
1910 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001911 }
1912 }
1913
1914 return Modified;
1915}
1916
1917bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00001918 if (skipFunction(*Fn.getFunction()))
1919 return false;
1920
Oliver Stannardd414c992015-11-10 11:04:18 +00001921 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1922 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1923 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001924
Chad Rosierbba881e2016-02-02 15:02:30 +00001925 // Resize the modified and used register bitfield trackers. We do this once
1926 // per function and then clear the bitfield each time we optimize a load or
1927 // store.
1928 ModifiedRegs.resize(TRI->getNumRegs());
1929 UsedRegs.resize(TRI->getNumRegs());
1930
Tim Northover3b0846e2014-05-24 12:50:23 +00001931 bool Modified = false;
Matthias Braun651cff42016-06-02 18:03:53 +00001932 bool enableNarrowLdOpt =
1933 Subtarget->mergeNarrowLoads() && !Subtarget->requiresStrictAlign();
Tim Northover3b0846e2014-05-24 12:50:23 +00001934 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001935 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001936
1937 return Modified;
1938}
1939
1940// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1941// loads and stores near one another?
1942
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001943// FIXME: When pairing store instructions it's very possible for this pass to
1944// hoist a store with a KILL marker above another use (without a KILL marker).
1945// The resulting IR is invalid, but nothing uses the KILL markers after this
1946// pass, so it's never caused a problem in practice.
1947
Chad Rosier43f5c842015-08-05 12:40:13 +00001948/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1949/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001950FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1951 return new AArch64LoadStoreOpt();
1952}