blob: b744dc2f5e07f9041b65d57abc201230f1b0070c [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
Chad Rosier96530b32015-08-05 13:44:51 +000054namespace llvm {
55void initializeAArch64LoadStoreOptPass(PassRegistry &);
56}
57
58#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
59
Tim Northover3b0846e2014-05-24 12:50:23 +000060namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000061
62typedef struct LdStPairFlags {
63 // If a matching instruction is found, MergeForward is set to true if the
64 // merge is to remove the first instruction and replace the second with
65 // a pair-wise insn, and false if the reverse is true.
66 bool MergeForward;
67
68 // SExtIdx gives the index of the result of the load pair that must be
69 // extended. The value of SExtIdx assumes that the paired load produces the
70 // value in this order: (I, returned iterator), i.e., -1 means no value has
71 // to be extended, 0 means I, and 1 means the returned iterator.
72 int SExtIdx;
73
74 LdStPairFlags() : MergeForward(false), SExtIdx(-1) {}
75
76 void setMergeForward(bool V = true) { MergeForward = V; }
77 bool getMergeForward() const { return MergeForward; }
78
79 void setSExtIdx(int V) { SExtIdx = V; }
80 int getSExtIdx() const { return SExtIdx; }
81
82} LdStPairFlags;
83
Tim Northover3b0846e2014-05-24 12:50:23 +000084struct AArch64LoadStoreOpt : public MachineFunctionPass {
85 static char ID;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +000086 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +000087 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
88 }
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 const AArch64InstrInfo *TII;
91 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +000092 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +000093
Chad Rosierbba881e2016-02-02 15:02:30 +000094 // Track which registers have been modified and used.
95 BitVector ModifiedRegs, UsedRegs;
96
Tim Northover3b0846e2014-05-24 12:50:23 +000097 // Scan the instructions looking for a load/store that can be combined
98 // with the current instruction into a load/store pair.
99 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000101 LdStPairFlags &Flags,
Tim Northover3b0846e2014-05-24 12:50:23 +0000102 unsigned Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000103
104 // Scan the instructions looking for a store that writes to the address from
105 // which the current load instruction reads. Return true if one is found.
106 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
107 MachineBasicBlock::iterator &StoreI);
108
Chad Rosierb5933d72016-02-09 19:02:12 +0000109 // Merge the two instructions indicated into a wider instruction.
110 MachineBasicBlock::iterator
111 mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000112 MachineBasicBlock::iterator MergeMI,
Chad Rosierb5933d72016-02-09 19:02:12 +0000113 const LdStPairFlags &Flags);
114
Tim Northover3b0846e2014-05-24 12:50:23 +0000115 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000116 MachineBasicBlock::iterator
117 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000118 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000119 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000120
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000121 // Promote the load that reads directly from the address stored to.
122 MachineBasicBlock::iterator
123 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
124 MachineBasicBlock::iterator StoreI);
125
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 // Scan the instruction list to find a base register update that can
127 // be combined with the current instruction (a load or store) using
128 // pre or post indexed addressing with writeback. Scan forwards.
129 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000130 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000131 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000132
133 // Scan the instruction list to find a base register update that can
134 // be combined with the current instruction (a load or store) using
135 // pre or post indexed addressing with writeback. Scan backwards.
136 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000137 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000138
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000139 // Find an instruction that updates the base register of the ld/st
140 // instruction.
141 bool isMatchingUpdateInsn(MachineInstr *MemMI, MachineInstr *MI,
142 unsigned BaseReg, int Offset);
143
Chad Rosier2dfd3542015-09-23 13:51:44 +0000144 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000146 mergeUpdateInsn(MachineBasicBlock::iterator I,
147 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000148
Chad Rosier24c46ad2016-02-09 18:10:20 +0000149 // Is this a candidate for ld/st merging or pairing? For example, we don't
150 // touch volatiles or load/stores that have a hint to avoid pair formation.
151 bool isCandidateToMergeOrPair(MachineInstr *MI);
152
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000153 // Find and merge foldable ldr/str instructions.
154 bool tryToMergeLdStInst(MachineBasicBlock::iterator &MBBI);
155
Chad Rosier24c46ad2016-02-09 18:10:20 +0000156 // Find and pair ldr/str instructions.
157 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
158
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000159 // Find and promote load instructions which read directly from store.
160 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
161
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000162 // Check if converting two narrow loads into a single wider load with
163 // bitfield extracts could be enabled.
164 bool enableNarrowLdMerge(MachineFunction &Fn);
165
166 bool optimizeBlock(MachineBasicBlock &MBB, bool enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000167
168 bool runOnMachineFunction(MachineFunction &Fn) override;
169
170 const char *getPassName() const override {
Chad Rosier96530b32015-08-05 13:44:51 +0000171 return AARCH64_LOAD_STORE_OPT_NAME;
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000173};
174char AArch64LoadStoreOpt::ID = 0;
Jim Grosbach1eee3df2014-08-11 22:42:31 +0000175} // namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000176
Chad Rosier96530b32015-08-05 13:44:51 +0000177INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
178 AARCH64_LOAD_STORE_OPT_NAME, false, false)
179
Chad Rosier22eb7102015-08-06 17:37:18 +0000180static bool isUnscaledLdSt(unsigned Opc) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000181 switch (Opc) {
182 default:
183 return false;
184 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000186 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000187 case AArch64::STURBBi:
188 case AArch64::STURHHi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000191 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000195 case AArch64::LDURXi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000196 case AArch64::LDURSWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000197 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000198 case AArch64::LDURBBi:
199 case AArch64::LDURSBWi:
200 case AArch64::LDURSHWi:
Quentin Colombet29f55332015-01-24 01:25:54 +0000201 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000202 }
203}
204
Chad Rosier22eb7102015-08-06 17:37:18 +0000205static bool isUnscaledLdSt(MachineInstr *MI) {
206 return isUnscaledLdSt(MI->getOpcode());
207}
208
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000209static unsigned getBitExtrOpcode(MachineInstr *MI) {
210 switch (MI->getOpcode()) {
211 default:
212 llvm_unreachable("Unexpected opcode.");
213 case AArch64::LDRBBui:
214 case AArch64::LDURBBi:
215 case AArch64::LDRHHui:
216 case AArch64::LDURHHi:
217 return AArch64::UBFMWri;
218 case AArch64::LDRSBWui:
219 case AArch64::LDURSBWi:
220 case AArch64::LDRSHWui:
221 case AArch64::LDURSHWi:
222 return AArch64::SBFMWri;
223 }
224}
225
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000226static bool isNarrowStore(unsigned Opc) {
227 switch (Opc) {
228 default:
229 return false;
230 case AArch64::STRBBui:
231 case AArch64::STURBBi:
232 case AArch64::STRHHui:
233 case AArch64::STURHHi:
234 return true;
235 }
236}
237
Jun Bum Limc12c2792015-11-19 18:41:27 +0000238static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000239 switch (Opc) {
240 default:
241 return false;
242 case AArch64::LDRHHui:
243 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000244 case AArch64::LDRBBui:
245 case AArch64::LDURBBi:
246 case AArch64::LDRSHWui:
247 case AArch64::LDURSHWi:
248 case AArch64::LDRSBWui:
249 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000250 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000251 }
252}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000253
Jun Bum Limc12c2792015-11-19 18:41:27 +0000254static bool isNarrowLoad(MachineInstr *MI) {
255 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000256}
257
Chad Rosier00f9d232016-02-11 14:25:08 +0000258static bool isNarrowLoadOrStore(unsigned Opc) {
259 return isNarrowLoad(Opc) || isNarrowStore(Opc);
260}
261
Chad Rosier32d4d372015-09-29 16:07:32 +0000262// Scaling factor for unscaled load or store.
263static int getMemScale(MachineInstr *MI) {
Chad Rosier22eb7102015-08-06 17:37:18 +0000264 switch (MI->getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000265 default:
Chad Rosierdabe2532015-09-29 18:26:15 +0000266 llvm_unreachable("Opcode has unknown scale!");
267 case AArch64::LDRBBui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000268 case AArch64::LDURBBi:
269 case AArch64::LDRSBWui:
270 case AArch64::LDURSBWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000271 case AArch64::STRBBui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000272 case AArch64::STURBBi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000273 return 1;
274 case AArch64::LDRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000275 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000276 case AArch64::LDRSHWui:
277 case AArch64::LDURSHWi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000278 case AArch64::STRHHui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000279 case AArch64::STURHHi:
Chad Rosierdabe2532015-09-29 18:26:15 +0000280 return 2;
Chad Rosiera4d32172015-09-29 14:57:10 +0000281 case AArch64::LDRSui:
282 case AArch64::LDURSi:
283 case AArch64::LDRSWui:
284 case AArch64::LDURSWi:
285 case AArch64::LDRWui:
286 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000287 case AArch64::STRSui:
288 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000289 case AArch64::STRWui:
290 case AArch64::STURWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000291 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000292 case AArch64::LDPSWi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000293 case AArch64::LDPWi:
294 case AArch64::STPSi:
295 case AArch64::STPWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000296 return 4;
Chad Rosiera4d32172015-09-29 14:57:10 +0000297 case AArch64::LDRDui:
298 case AArch64::LDURDi:
299 case AArch64::LDRXui:
300 case AArch64::LDURXi:
301 case AArch64::STRDui:
302 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000303 case AArch64::STRXui:
304 case AArch64::STURXi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000305 case AArch64::LDPDi:
306 case AArch64::LDPXi:
307 case AArch64::STPDi:
308 case AArch64::STPXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000309 return 8;
Tim Northover3b0846e2014-05-24 12:50:23 +0000310 case AArch64::LDRQui:
311 case AArch64::LDURQi:
Chad Rosiera4d32172015-09-29 14:57:10 +0000312 case AArch64::STRQui:
313 case AArch64::STURQi:
Chad Rosier32d4d372015-09-29 16:07:32 +0000314 case AArch64::LDPQi:
315 case AArch64::STPQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000316 return 16;
Tim Northover3b0846e2014-05-24 12:50:23 +0000317 }
318}
319
Quentin Colombet66b61632015-03-06 22:42:10 +0000320static unsigned getMatchingNonSExtOpcode(unsigned Opc,
321 bool *IsValidLdStrOpc = nullptr) {
322 if (IsValidLdStrOpc)
323 *IsValidLdStrOpc = true;
324 switch (Opc) {
325 default:
326 if (IsValidLdStrOpc)
327 *IsValidLdStrOpc = false;
328 return UINT_MAX;
329 case AArch64::STRDui:
330 case AArch64::STURDi:
331 case AArch64::STRQui:
332 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000333 case AArch64::STRBBui:
334 case AArch64::STURBBi:
335 case AArch64::STRHHui:
336 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000337 case AArch64::STRWui:
338 case AArch64::STURWi:
339 case AArch64::STRXui:
340 case AArch64::STURXi:
341 case AArch64::LDRDui:
342 case AArch64::LDURDi:
343 case AArch64::LDRQui:
344 case AArch64::LDURQi:
345 case AArch64::LDRWui:
346 case AArch64::LDURWi:
347 case AArch64::LDRXui:
348 case AArch64::LDURXi:
349 case AArch64::STRSui:
350 case AArch64::STURSi:
351 case AArch64::LDRSui:
352 case AArch64::LDURSi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000353 case AArch64::LDRHHui:
354 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000355 case AArch64::LDRBBui:
356 case AArch64::LDURBBi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000357 return Opc;
358 case AArch64::LDRSWui:
359 return AArch64::LDRWui;
360 case AArch64::LDURSWi:
361 return AArch64::LDURWi;
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000362 case AArch64::LDRSBWui:
363 return AArch64::LDRBBui;
364 case AArch64::LDRSHWui:
365 return AArch64::LDRHHui;
366 case AArch64::LDURSBWi:
367 return AArch64::LDURBBi;
368 case AArch64::LDURSHWi:
369 return AArch64::LDURHHi;
Quentin Colombet66b61632015-03-06 22:42:10 +0000370 }
371}
372
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000373static unsigned getMatchingWideOpcode(unsigned Opc) {
374 switch (Opc) {
375 default:
376 llvm_unreachable("Opcode has no wide equivalent!");
377 case AArch64::STRBBui:
378 return AArch64::STRHHui;
379 case AArch64::STRHHui:
380 return AArch64::STRWui;
381 case AArch64::STURBBi:
382 return AArch64::STURHHi;
383 case AArch64::STURHHi:
384 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000385 case AArch64::STURWi:
386 return AArch64::STURXi;
387 case AArch64::STRWui:
388 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000389 case AArch64::LDRHHui:
390 case AArch64::LDRSHWui:
391 return AArch64::LDRWui;
392 case AArch64::LDURHHi:
393 case AArch64::LDURSHWi:
394 return AArch64::LDURWi;
395 case AArch64::LDRBBui:
396 case AArch64::LDRSBWui:
397 return AArch64::LDRHHui;
398 case AArch64::LDURBBi:
399 case AArch64::LDURSBWi:
400 return AArch64::LDURHHi;
401 }
402}
403
Tim Northover3b0846e2014-05-24 12:50:23 +0000404static unsigned getMatchingPairOpcode(unsigned Opc) {
405 switch (Opc) {
406 default:
407 llvm_unreachable("Opcode has no pairwise equivalent!");
408 case AArch64::STRSui:
409 case AArch64::STURSi:
410 return AArch64::STPSi;
411 case AArch64::STRDui:
412 case AArch64::STURDi:
413 return AArch64::STPDi;
414 case AArch64::STRQui:
415 case AArch64::STURQi:
416 return AArch64::STPQi;
417 case AArch64::STRWui:
418 case AArch64::STURWi:
419 return AArch64::STPWi;
420 case AArch64::STRXui:
421 case AArch64::STURXi:
422 return AArch64::STPXi;
423 case AArch64::LDRSui:
424 case AArch64::LDURSi:
425 return AArch64::LDPSi;
426 case AArch64::LDRDui:
427 case AArch64::LDURDi:
428 return AArch64::LDPDi;
429 case AArch64::LDRQui:
430 case AArch64::LDURQi:
431 return AArch64::LDPQi;
432 case AArch64::LDRWui:
433 case AArch64::LDURWi:
434 return AArch64::LDPWi;
435 case AArch64::LDRXui:
436 case AArch64::LDURXi:
437 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000438 case AArch64::LDRSWui:
439 case AArch64::LDURSWi:
440 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000441 }
442}
443
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000444static unsigned isMatchingStore(MachineInstr *LoadInst,
445 MachineInstr *StoreInst) {
446 unsigned LdOpc = LoadInst->getOpcode();
447 unsigned StOpc = StoreInst->getOpcode();
448 switch (LdOpc) {
449 default:
450 llvm_unreachable("Unsupported load instruction!");
451 case AArch64::LDRBBui:
452 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
453 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
454 case AArch64::LDURBBi:
455 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
456 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
457 case AArch64::LDRHHui:
458 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
459 StOpc == AArch64::STRXui;
460 case AArch64::LDURHHi:
461 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
462 StOpc == AArch64::STURXi;
463 case AArch64::LDRWui:
464 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
465 case AArch64::LDURWi:
466 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
467 case AArch64::LDRXui:
468 return StOpc == AArch64::STRXui;
469 case AArch64::LDURXi:
470 return StOpc == AArch64::STURXi;
471 }
472}
473
Tim Northover3b0846e2014-05-24 12:50:23 +0000474static unsigned getPreIndexedOpcode(unsigned Opc) {
475 switch (Opc) {
476 default:
477 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000478 case AArch64::STRSui:
479 return AArch64::STRSpre;
480 case AArch64::STRDui:
481 return AArch64::STRDpre;
482 case AArch64::STRQui:
483 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000484 case AArch64::STRBBui:
485 return AArch64::STRBBpre;
486 case AArch64::STRHHui:
487 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000488 case AArch64::STRWui:
489 return AArch64::STRWpre;
490 case AArch64::STRXui:
491 return AArch64::STRXpre;
492 case AArch64::LDRSui:
493 return AArch64::LDRSpre;
494 case AArch64::LDRDui:
495 return AArch64::LDRDpre;
496 case AArch64::LDRQui:
497 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000498 case AArch64::LDRBBui:
499 return AArch64::LDRBBpre;
500 case AArch64::LDRHHui:
501 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000502 case AArch64::LDRWui:
503 return AArch64::LDRWpre;
504 case AArch64::LDRXui:
505 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000506 case AArch64::LDRSWui:
507 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000508 case AArch64::LDPSi:
509 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000510 case AArch64::LDPSWi:
511 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000512 case AArch64::LDPDi:
513 return AArch64::LDPDpre;
514 case AArch64::LDPQi:
515 return AArch64::LDPQpre;
516 case AArch64::LDPWi:
517 return AArch64::LDPWpre;
518 case AArch64::LDPXi:
519 return AArch64::LDPXpre;
520 case AArch64::STPSi:
521 return AArch64::STPSpre;
522 case AArch64::STPDi:
523 return AArch64::STPDpre;
524 case AArch64::STPQi:
525 return AArch64::STPQpre;
526 case AArch64::STPWi:
527 return AArch64::STPWpre;
528 case AArch64::STPXi:
529 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 }
531}
532
533static unsigned getPostIndexedOpcode(unsigned Opc) {
534 switch (Opc) {
535 default:
536 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
537 case AArch64::STRSui:
538 return AArch64::STRSpost;
539 case AArch64::STRDui:
540 return AArch64::STRDpost;
541 case AArch64::STRQui:
542 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000543 case AArch64::STRBBui:
544 return AArch64::STRBBpost;
545 case AArch64::STRHHui:
546 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000547 case AArch64::STRWui:
548 return AArch64::STRWpost;
549 case AArch64::STRXui:
550 return AArch64::STRXpost;
551 case AArch64::LDRSui:
552 return AArch64::LDRSpost;
553 case AArch64::LDRDui:
554 return AArch64::LDRDpost;
555 case AArch64::LDRQui:
556 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000557 case AArch64::LDRBBui:
558 return AArch64::LDRBBpost;
559 case AArch64::LDRHHui:
560 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000561 case AArch64::LDRWui:
562 return AArch64::LDRWpost;
563 case AArch64::LDRXui:
564 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000565 case AArch64::LDRSWui:
566 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 case AArch64::LDPSi:
568 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000569 case AArch64::LDPSWi:
570 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000571 case AArch64::LDPDi:
572 return AArch64::LDPDpost;
573 case AArch64::LDPQi:
574 return AArch64::LDPQpost;
575 case AArch64::LDPWi:
576 return AArch64::LDPWpost;
577 case AArch64::LDPXi:
578 return AArch64::LDPXpost;
579 case AArch64::STPSi:
580 return AArch64::STPSpost;
581 case AArch64::STPDi:
582 return AArch64::STPDpost;
583 case AArch64::STPQi:
584 return AArch64::STPQpost;
585 case AArch64::STPWi:
586 return AArch64::STPWpost;
587 case AArch64::STPXi:
588 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000589 }
590}
591
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000592static bool isPairedLdSt(const MachineInstr *MI) {
593 switch (MI->getOpcode()) {
594 default:
595 return false;
596 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000597 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000598 case AArch64::LDPDi:
599 case AArch64::LDPQi:
600 case AArch64::LDPWi:
601 case AArch64::LDPXi:
602 case AArch64::STPSi:
603 case AArch64::STPDi:
604 case AArch64::STPQi:
605 case AArch64::STPWi:
606 case AArch64::STPXi:
607 return true;
608 }
609}
610
611static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
612 unsigned PairedRegOp = 0) {
613 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
614 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
615 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000616}
617
618static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000619 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
620 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000621}
622
623static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000624 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
625 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000626}
627
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000628static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
629 MachineInstr *StoreInst) {
630 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
631 int LoadSize = getMemScale(LoadInst);
632 int StoreSize = getMemScale(StoreInst);
633 int UnscaledStOffset = isUnscaledLdSt(StoreInst)
634 ? getLdStOffsetOp(StoreInst).getImm()
635 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
636 int UnscaledLdOffset = isUnscaledLdSt(LoadInst)
637 ? getLdStOffsetOp(LoadInst).getImm()
638 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
639 return (UnscaledStOffset <= UnscaledLdOffset) &&
640 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
641}
642
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000643static bool isPromotableZeroStoreOpcode(MachineInstr *MI) {
644 unsigned Opc = MI->getOpcode();
645 return isNarrowStore(Opc) || Opc == AArch64::STRWui || Opc == AArch64::STURWi;
646}
647
648static bool isPromotableZeroStoreInst(MachineInstr *MI) {
649 return (isPromotableZeroStoreOpcode(MI)) &&
650 getLdStRegOp(MI).getReg() == AArch64::WZR;
651}
652
Tim Northover3b0846e2014-05-24 12:50:23 +0000653MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000654AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000655 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000656 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 MachineBasicBlock::iterator NextI = I;
658 ++NextI;
659 // If NextI is the second of the two instructions to be merged, we need
660 // to skip one further. Either way we merge will invalidate the iterator,
661 // and we don't need to scan the new instruction, as it's a pairwise
662 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000663 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000664 ++NextI;
665
Chad Rosierb5933d72016-02-09 19:02:12 +0000666 unsigned Opc = I->getOpcode();
Chad Rosier11eedc92016-02-09 19:17:18 +0000667 bool IsScaled = !isUnscaledLdSt(Opc);
668 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000669
Chad Rosier96a18a92015-07-21 17:42:04 +0000670 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000671 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000672 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000673 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000674 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000676 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000677 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000678
679 // Which register is Rt and which is Rt2 depends on the offset order.
680 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000681 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000682 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
683 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000684 Rt2MI = I;
685 } else {
686 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000687 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000688 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000689
James Molloy5b18b4c2015-10-23 10:41:38 +0000690 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000691 // Change the scaled offset from small to large type.
692 if (IsScaled) {
693 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
694 OffsetImm /= 2;
695 }
696
Chad Rosierc46ef882016-02-09 19:33:42 +0000697 DebugLoc DL = I->getDebugLoc();
698 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000699 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000700 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000701 // When merging small (< 32 bit) loads for big-endian targets, the order of
702 // the component parts gets swapped.
703 if (!Subtarget->isLittleEndian())
704 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000705 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000706 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000707 NewMemMI =
708 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
709 .addOperand(getLdStRegOp(RtNewDest))
710 .addOperand(BaseRegOp)
711 .addImm(OffsetImm)
712 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000713
714 DEBUG(
715 dbgs()
716 << "Creating the new load and extract. Replacing instructions:\n ");
717 DEBUG(I->print(dbgs()));
718 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000719 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000720 DEBUG(dbgs() << " with instructions:\n ");
721 DEBUG((NewMemMI)->print(dbgs()));
722
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000723 int Width = getMemScale(I) == 1 ? 8 : 16;
724 int LSBLow = 0;
725 int LSBHigh = Width;
726 int ImmsLow = LSBLow + Width - 1;
727 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000728 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000729 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000730 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000731 BitExtMI1 =
732 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
733 .addOperand(getLdStRegOp(Rt2MI))
734 .addReg(getLdStRegOp(RtNewDest).getReg())
735 .addImm(LSBHigh)
736 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000737 // Create the bitfield extract for low bits.
738 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
739 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000740 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000741 .addOperand(getLdStRegOp(RtMI))
742 .addReg(getLdStRegOp(RtNewDest).getReg())
743 .addImm(ImmsLow);
744 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000745 BitExtMI2 =
746 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
747 .addOperand(getLdStRegOp(RtMI))
748 .addReg(getLdStRegOp(RtNewDest).getReg())
749 .addImm(LSBLow)
750 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000751 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000752 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000753 // Create the bitfield extract for low bits.
754 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
755 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000756 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000757 .addOperand(getLdStRegOp(RtMI))
758 .addReg(getLdStRegOp(RtNewDest).getReg())
759 .addImm(ImmsLow);
760 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000761 BitExtMI1 =
762 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
763 .addOperand(getLdStRegOp(RtMI))
764 .addReg(getLdStRegOp(RtNewDest).getReg())
765 .addImm(LSBLow)
766 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000767 }
768
769 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000770 BitExtMI2 =
771 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
772 .addOperand(getLdStRegOp(Rt2MI))
773 .addReg(getLdStRegOp(RtNewDest).getReg())
774 .addImm(LSBHigh)
775 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000776 }
777 DEBUG(dbgs() << " ");
778 DEBUG((BitExtMI1)->print(dbgs()));
779 DEBUG(dbgs() << " ");
780 DEBUG((BitExtMI2)->print(dbgs()));
781 DEBUG(dbgs() << "\n");
782
783 // Erase the old instructions.
784 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000785 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000786 return NextI;
787 }
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000788 assert(isPromotableZeroStoreInst(I) && "Expected promotable zero store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000789
Tim Northover3b0846e2014-05-24 12:50:23 +0000790 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000791 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000792 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000793 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Chad Rosierb5933d72016-02-09 19:02:12 +0000794 .addOperand(BaseRegOp)
795 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000796 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000797
Tim Northover3b0846e2014-05-24 12:50:23 +0000798 (void)MIB;
799
Chad Rosierb5933d72016-02-09 19:02:12 +0000800 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
801 DEBUG(I->print(dbgs()));
802 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000803 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000804 DEBUG(dbgs() << " with instruction:\n ");
805 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
806 DEBUG(dbgs() << "\n");
807
808 // Erase the old instructions.
809 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000810 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000811 return NextI;
812}
813
814MachineBasicBlock::iterator
815AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
816 MachineBasicBlock::iterator Paired,
817 const LdStPairFlags &Flags) {
818 MachineBasicBlock::iterator NextI = I;
819 ++NextI;
820 // If NextI is the second of the two instructions to be merged, we need
821 // to skip one further. Either way we merge will invalidate the iterator,
822 // and we don't need to scan the new instruction, as it's a pairwise
823 // instruction, which we're not considering for further action anyway.
824 if (NextI == Paired)
825 ++NextI;
826
827 int SExtIdx = Flags.getSExtIdx();
828 unsigned Opc =
829 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
830 bool IsUnscaled = isUnscaledLdSt(Opc);
831 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
832
833 bool MergeForward = Flags.getMergeForward();
834 // Insert our new paired instruction after whichever of the paired
835 // instructions MergeForward indicates.
836 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
837 // Also based on MergeForward is from where we copy the base register operand
838 // so we get the flags compatible with the input code.
839 const MachineOperand &BaseRegOp =
840 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
841
Chad Rosier00f9d232016-02-11 14:25:08 +0000842 int Offset = getLdStOffsetOp(I).getImm();
843 int PairedOffset = getLdStOffsetOp(Paired).getImm();
844 bool PairedIsUnscaled = isUnscaledLdSt(Paired->getOpcode());
845 if (IsUnscaled != PairedIsUnscaled) {
846 // We're trying to pair instructions that differ in how they are scaled. If
847 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
848 // the opposite (i.e., make Paired's offset unscaled).
849 int MemSize = getMemScale(Paired);
850 if (PairedIsUnscaled) {
851 // If the unscaled offset isn't a multiple of the MemSize, we can't
852 // pair the operations together.
853 assert(!(PairedOffset % getMemScale(Paired)) &&
854 "Offset should be a multiple of the stride!");
855 PairedOffset /= MemSize;
856 } else {
857 PairedOffset *= MemSize;
858 }
859 }
860
Chad Rosierb5933d72016-02-09 19:02:12 +0000861 // Which register is Rt and which is Rt2 depends on the offset order.
862 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000863 if (Offset == PairedOffset + OffsetStride) {
Chad Rosierb5933d72016-02-09 19:02:12 +0000864 RtMI = Paired;
865 Rt2MI = I;
866 // Here we swapped the assumption made for SExtIdx.
867 // I.e., we turn ldp I, Paired into ldp Paired, I.
868 // Update the index accordingly.
869 if (SExtIdx != -1)
870 SExtIdx = (SExtIdx + 1) % 2;
871 } else {
872 RtMI = I;
873 Rt2MI = Paired;
874 }
875 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000876 // Scale the immediate offset, if necessary.
877 if (isUnscaledLdSt(RtMI->getOpcode())) {
878 assert(!(OffsetImm % getMemScale(RtMI)) &&
879 "Unscaled offset cannot be scaled.");
880 OffsetImm /= getMemScale(RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000881 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000882
883 // Construct the new instruction.
884 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000885 DebugLoc DL = I->getDebugLoc();
886 MachineBasicBlock *MBB = I->getParent();
887 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000888 .addOperand(getLdStRegOp(RtMI))
889 .addOperand(getLdStRegOp(Rt2MI))
890 .addOperand(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000891 .addImm(OffsetImm)
892 .setMemRefs(I->mergeMemRefsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000893
894 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000895
896 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
897 DEBUG(I->print(dbgs()));
898 DEBUG(dbgs() << " ");
899 DEBUG(Paired->print(dbgs()));
900 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000901 if (SExtIdx != -1) {
902 // Generate the sign extension for the proper result of the ldp.
903 // I.e., with X1, that would be:
904 // %W1<def> = KILL %W1, %X1<imp-def>
905 // %X1<def> = SBFMXri %X1<kill>, 0, 31
906 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
907 // Right now, DstMO has the extended register, since it comes from an
908 // extended opcode.
909 unsigned DstRegX = DstMO.getReg();
910 // Get the W variant of that register.
911 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
912 // Update the result of LDP to use the W instead of the X variant.
913 DstMO.setReg(DstRegW);
914 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
915 DEBUG(dbgs() << "\n");
916 // Make the machine verifier happy by providing a definition for
917 // the X register.
918 // Insert this definition right after the generated LDP, i.e., before
919 // InsertionPoint.
920 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000921 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000922 .addReg(DstRegW)
923 .addReg(DstRegX, RegState::Define);
924 MIBKill->getOperand(2).setImplicit();
925 // Create the sign extension.
926 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000927 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000928 .addReg(DstRegX)
929 .addImm(0)
930 .addImm(31);
931 (void)MIBSXTW;
932 DEBUG(dbgs() << " Extend operand:\n ");
933 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000934 } else {
935 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000936 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000937 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000938
939 // Erase the old instructions.
940 I->eraseFromParent();
941 Paired->eraseFromParent();
942
943 return NextI;
944}
945
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000946MachineBasicBlock::iterator
947AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
948 MachineBasicBlock::iterator StoreI) {
949 MachineBasicBlock::iterator NextI = LoadI;
950 ++NextI;
951
952 int LoadSize = getMemScale(LoadI);
953 int StoreSize = getMemScale(StoreI);
954 unsigned LdRt = getLdStRegOp(LoadI).getReg();
955 unsigned StRt = getLdStRegOp(StoreI).getReg();
956 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
957
958 assert((IsStoreXReg ||
959 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
960 "Unexpected RegClass");
961
962 MachineInstr *BitExtMI;
963 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
964 // Remove the load, if the destination register of the loads is the same
965 // register for stored value.
966 if (StRt == LdRt && LoadSize == 8) {
967 DEBUG(dbgs() << "Remove load instruction:\n ");
968 DEBUG(LoadI->print(dbgs()));
969 DEBUG(dbgs() << "\n");
970 LoadI->eraseFromParent();
971 return NextI;
972 }
973 // Replace the load with a mov if the load and store are in the same size.
974 BitExtMI =
975 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
976 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
977 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
978 .addReg(StRt)
979 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
980 } else {
981 // FIXME: Currently we disable this transformation in big-endian targets as
982 // performance and correctness are verified only in little-endian.
983 if (!Subtarget->isLittleEndian())
984 return NextI;
985 bool IsUnscaled = isUnscaledLdSt(LoadI);
986 assert(IsUnscaled == isUnscaledLdSt(StoreI) && "Unsupported ld/st match");
987 assert(LoadSize <= StoreSize && "Invalid load size");
988 int UnscaledLdOffset = IsUnscaled
989 ? getLdStOffsetOp(LoadI).getImm()
990 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
991 int UnscaledStOffset = IsUnscaled
992 ? getLdStOffsetOp(StoreI).getImm()
993 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
994 int Width = LoadSize * 8;
995 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
996 int Imms = Immr + Width - 1;
997 unsigned DestReg = IsStoreXReg
998 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
999 &AArch64::GPR64RegClass)
1000 : LdRt;
1001
1002 assert((UnscaledLdOffset >= UnscaledStOffset &&
1003 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1004 "Invalid offset");
1005
1006 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1007 Imms = Immr + Width - 1;
1008 if (UnscaledLdOffset == UnscaledStOffset) {
1009 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1010 | ((Immr) << 6) // immr
1011 | ((Imms) << 0) // imms
1012 ;
1013
1014 BitExtMI =
1015 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1016 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1017 DestReg)
1018 .addReg(StRt)
1019 .addImm(AndMaskEncoded);
1020 } else {
1021 BitExtMI =
1022 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1023 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1024 DestReg)
1025 .addReg(StRt)
1026 .addImm(Immr)
1027 .addImm(Imms);
1028 }
1029 }
1030
1031 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1032 DEBUG(StoreI->print(dbgs()));
1033 DEBUG(dbgs() << " ");
1034 DEBUG(LoadI->print(dbgs()));
1035 DEBUG(dbgs() << " with instructions:\n ");
1036 DEBUG(StoreI->print(dbgs()));
1037 DEBUG(dbgs() << " ");
1038 DEBUG((BitExtMI)->print(dbgs()));
1039 DEBUG(dbgs() << "\n");
1040
1041 // Erase the old instructions.
1042 LoadI->eraseFromParent();
1043 return NextI;
1044}
1045
Tim Northover3b0846e2014-05-24 12:50:23 +00001046/// trackRegDefsUses - Remember what registers the specified instruction uses
1047/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001048static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001049 BitVector &UsedRegs,
1050 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001051 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001052 if (MO.isRegMask())
1053 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1054
1055 if (!MO.isReg())
1056 continue;
1057 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001058 if (!Reg)
1059 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001060 if (MO.isDef()) {
1061 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1062 ModifiedRegs.set(*AI);
1063 } else {
1064 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1065 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1066 UsedRegs.set(*AI);
1067 }
1068 }
1069}
1070
1071static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001072 // Convert the byte-offset used by unscaled into an "element" offset used
1073 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001074 if (IsUnscaled) {
1075 // If the byte-offset isn't a multiple of the stride, there's no point
1076 // trying to match it.
1077 if (Offset % OffsetStride)
1078 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001079 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001080 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001081 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001082}
1083
1084// Do alignment, specialized to power of 2 and for signed ints,
1085// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001086// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001087// FIXME: Move this function to include/MathExtras.h?
1088static int alignTo(int Num, int PowOf2) {
1089 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1090}
1091
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001092static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1093 const AArch64InstrInfo *TII) {
1094 // One of the instructions must modify memory.
1095 if (!MIa->mayStore() && !MIb->mayStore())
1096 return false;
1097
1098 // Both instructions must be memory operations.
1099 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1100 return false;
1101
1102 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1103}
1104
1105static bool mayAlias(MachineInstr *MIa,
1106 SmallVectorImpl<MachineInstr *> &MemInsns,
1107 const AArch64InstrInfo *TII) {
1108 for (auto &MIb : MemInsns)
1109 if (mayAlias(MIa, MIb, TII))
1110 return true;
1111
1112 return false;
1113}
1114
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001115bool AArch64LoadStoreOpt::findMatchingStore(
1116 MachineBasicBlock::iterator I, unsigned Limit,
1117 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001118 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001119 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001120 MachineInstr *LoadMI = I;
1121 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001122
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001123 // If the load is the first instruction in the block, there's obviously
1124 // not any matching store.
1125 if (MBBI == B)
1126 return false;
1127
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001128 // Track which registers have been modified and used between the first insn
1129 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001130 ModifiedRegs.reset();
1131 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001132
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001133 unsigned Count = 0;
1134 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001135 --MBBI;
1136 MachineInstr *MI = MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001137
1138 // Don't count DBG_VALUE instructions towards the search limit.
1139 if (!MI->isDebugValue())
1140 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001141
1142 // If the load instruction reads directly from the address to which the
1143 // store instruction writes and the stored value is not modified, we can
1144 // promote the load. Since we do not handle stores with pre-/post-index,
1145 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001146 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001147 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001148 isLdOffsetInRangeOfSt(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001149 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1150 StoreI = MBBI;
1151 return true;
1152 }
1153
1154 if (MI->isCall())
1155 return false;
1156
1157 // Update modified / uses register lists.
1158 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1159
1160 // Otherwise, if the base register is modified, we have no match, so
1161 // return early.
1162 if (ModifiedRegs[BaseReg])
1163 return false;
1164
1165 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001166 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001167 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001168 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001169 return false;
1170}
1171
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001172// Returns true if these two opcodes can be merged or paired. Otherwise,
1173// returns false.
1174static bool canMergeOpc(unsigned OpcA, unsigned OpcB, LdStPairFlags &Flags) {
1175 // Opcodes match: nothing more to check.
1176 if (OpcA == OpcB)
1177 return true;
1178
1179 // Try to match a sign-extended load/store with a zero-extended load/store.
1180 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1181 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1182 assert(IsValidLdStrOpc &&
1183 "Given Opc should be a Load or Store with an immediate");
1184 // OpcA will be the first instruction in the pair.
1185 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1186 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1187 return true;
1188 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001189
1190 // If the second instruction isn't even a load/store, bail out.
1191 if (!PairIsValidLdStrOpc)
1192 return false;
1193
1194 // FIXME: We don't support merging narrow loads/stores with mixed
1195 // scaled/unscaled offsets.
1196 if (isNarrowLoadOrStore(OpcA) || isNarrowLoadOrStore(OpcB))
1197 return false;
1198
1199 // Try to match an unscaled load/store with a scaled load/store.
1200 return isUnscaledLdSt(OpcA) != isUnscaledLdSt(OpcB) &&
1201 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1202
1203 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001204}
1205
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001206/// Scan the instructions looking for a load/store that can be combined with the
1207/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001208MachineBasicBlock::iterator
1209AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001210 LdStPairFlags &Flags, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001211 MachineBasicBlock::iterator E = I->getParent()->end();
1212 MachineBasicBlock::iterator MBBI = I;
1213 MachineInstr *FirstMI = I;
1214 ++MBBI;
1215
Matthias Braunfa3872e2015-05-18 20:27:55 +00001216 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001217 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +00001218 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001219 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1220 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1221 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001222 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001223 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001224
1225 // Track which registers have been modified and used between the first insn
1226 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001227 ModifiedRegs.reset();
1228 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001229
1230 // Remember any instructions that read/write memory between FirstMI and MI.
1231 SmallVector<MachineInstr *, 4> MemInsns;
1232
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1234 MachineInstr *MI = MBBI;
1235 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1236 // optimization by changing how far we scan.
1237 if (MI->isDebugValue())
1238 continue;
1239
1240 // Now that we know this is a real instruction, count it.
1241 ++Count;
1242
Chad Rosier18896c02016-02-04 16:01:40 +00001243 Flags.setSExtIdx(-1);
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001244 if (canMergeOpc(Opc, MI->getOpcode(), Flags) &&
1245 getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001246 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001247 // If we've found another instruction with the same opcode, check to see
1248 // if the base and offset are compatible with our starting instruction.
1249 // These instructions all have scaled immediate operands, so we just
1250 // check for +1/-1. Make sure to check the new instruction offset is
1251 // actually an immediate and not a symbolic reference destined for
1252 // a relocation.
1253 //
1254 // Pairwise instructions have a 7-bit signed offset field. Single insns
1255 // have a 12-bit unsigned offset field. To be a valid combine, the
1256 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001257 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1258 int MIOffset = getLdStOffsetOp(MI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +00001259 bool MIIsUnscaled = isUnscaledLdSt(MI);
1260 if (IsUnscaled != MIIsUnscaled) {
1261 // We're trying to pair instructions that differ in how they are scaled.
1262 // If FirstMI is scaled then scale the offset of MI accordingly.
1263 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1264 int MemSize = getMemScale(MI);
1265 if (MIIsUnscaled) {
1266 // If the unscaled offset isn't a multiple of the MemSize, we can't
1267 // pair the operations together: bail and keep looking.
1268 if (MIOffset % MemSize)
1269 continue;
1270 MIOffset /= MemSize;
1271 } else {
1272 MIOffset *= MemSize;
1273 }
1274 }
1275
Tim Northover3b0846e2014-05-24 12:50:23 +00001276 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1277 (Offset + OffsetStride == MIOffset))) {
1278 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1279 // If this is a volatile load/store that otherwise matched, stop looking
1280 // as something is going on that we don't have enough information to
1281 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1282 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1283 return E;
1284 // If the resultant immediate offset of merging these instructions
1285 // is out of range for a pairwise instruction, bail and keep looking.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001286 bool IsNarrowLoad = isNarrowLoad(MI->getOpcode());
1287 if (!IsNarrowLoad &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001288 !inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001289 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001290 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001291 continue;
1292 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001293
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001294 if (IsNarrowLoad || IsPromotableZeroStore) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001295 // If the alignment requirements of the scaled wide load/store
1296 // instruction can't express the offset of the scaled narrow
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001297 // input, bail and keep looking.
1298 if (!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) {
1299 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1300 MemInsns.push_back(MI);
1301 continue;
1302 }
1303 } else {
1304 // If the alignment requirements of the paired (scaled) instruction
1305 // can't express the offset of the unscaled input, bail and keep
1306 // looking.
1307 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1308 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1309 MemInsns.push_back(MI);
1310 continue;
1311 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001312 }
1313 // If the destination register of the loads is the same register, bail
1314 // and keep looking. A load-pair instruction with both destination
1315 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001316 // For narrow stores, allow only when the stored value is the same
1317 // (i.e., WZR).
1318 if ((MayLoad && Reg == getLdStRegOp(MI).getReg()) ||
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001319 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001320 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001321 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001322 continue;
1323 }
1324
1325 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001326 // the two instructions and none of the instructions between the second
1327 // and first alias with the second, we can combine the second into the
1328 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001329 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1330 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001331 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001332 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001333 return MBBI;
1334 }
1335
1336 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001337 // between the two instructions and none of the instructions between the
1338 // first and the second alias with the first, we can combine the first
1339 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001340 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001341 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001342 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001343 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001344 return MBBI;
1345 }
1346 // Unable to combine these instructions due to interference in between.
1347 // Keep looking.
1348 }
1349 }
1350
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001351 // If the instruction wasn't a matching load or store. Stop searching if we
1352 // encounter a call instruction that might modify memory.
1353 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001354 return E;
1355
1356 // Update modified / uses register lists.
1357 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1358
1359 // Otherwise, if the base register is modified, we have no match, so
1360 // return early.
1361 if (ModifiedRegs[BaseReg])
1362 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001363
1364 // Update list of instructions that read/write memory.
1365 if (MI->mayLoadOrStore())
1366 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001367 }
1368 return E;
1369}
1370
1371MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001372AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1373 MachineBasicBlock::iterator Update,
1374 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001375 assert((Update->getOpcode() == AArch64::ADDXri ||
1376 Update->getOpcode() == AArch64::SUBXri) &&
1377 "Unexpected base register update instruction to merge!");
1378 MachineBasicBlock::iterator NextI = I;
1379 // Return the instruction following the merged instruction, which is
1380 // the instruction following our unmerged load. Unless that's the add/sub
1381 // instruction we're merging, in which case it's the one after that.
1382 if (++NextI == Update)
1383 ++NextI;
1384
1385 int Value = Update->getOperand(2).getImm();
1386 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001387 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001388 if (Update->getOpcode() == AArch64::SUBXri)
1389 Value = -Value;
1390
Chad Rosier2dfd3542015-09-23 13:51:44 +00001391 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1392 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393 MachineInstrBuilder MIB;
1394 if (!isPairedLdSt(I)) {
1395 // Non-paired instruction.
1396 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1397 .addOperand(getLdStRegOp(Update))
1398 .addOperand(getLdStRegOp(I))
1399 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001400 .addImm(Value)
1401 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001402 } else {
1403 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001404 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001405 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1406 .addOperand(getLdStRegOp(Update))
1407 .addOperand(getLdStRegOp(I, 0))
1408 .addOperand(getLdStRegOp(I, 1))
1409 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001410 .addImm(Value / Scale)
1411 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001412 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001413 (void)MIB;
1414
Chad Rosier2dfd3542015-09-23 13:51:44 +00001415 if (IsPreIdx)
1416 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1417 else
1418 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001419 DEBUG(dbgs() << " Replacing instructions:\n ");
1420 DEBUG(I->print(dbgs()));
1421 DEBUG(dbgs() << " ");
1422 DEBUG(Update->print(dbgs()));
1423 DEBUG(dbgs() << " with instruction:\n ");
1424 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1425 DEBUG(dbgs() << "\n");
1426
1427 // Erase the old instructions for the block.
1428 I->eraseFromParent();
1429 Update->eraseFromParent();
1430
1431 return NextI;
1432}
1433
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001434bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1435 MachineInstr *MI,
1436 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001437 switch (MI->getOpcode()) {
1438 default:
1439 break;
1440 case AArch64::SUBXri:
1441 // Negate the offset for a SUB instruction.
1442 Offset *= -1;
1443 // FALLTHROUGH
1444 case AArch64::ADDXri:
1445 // Make sure it's a vanilla immediate operand, not a relocation or
1446 // anything else we can't handle.
1447 if (!MI->getOperand(2).isImm())
1448 break;
1449 // Watch out for 1 << 12 shifted value.
1450 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1451 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001452
1453 // The update instruction source and destination register must be the
1454 // same as the load/store base register.
1455 if (MI->getOperand(0).getReg() != BaseReg ||
1456 MI->getOperand(1).getReg() != BaseReg)
1457 break;
1458
1459 bool IsPairedInsn = isPairedLdSt(MemMI);
1460 int UpdateOffset = MI->getOperand(2).getImm();
1461 // For non-paired load/store instructions, the immediate must fit in a
1462 // signed 9-bit integer.
1463 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1464 break;
1465
1466 // For paired load/store instructions, the immediate must be a multiple of
1467 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1468 // integer.
1469 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001470 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001471 if (UpdateOffset % Scale != 0)
1472 break;
1473
1474 int ScaledOffset = UpdateOffset / Scale;
1475 if (ScaledOffset > 64 || ScaledOffset < -64)
1476 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001477 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001478
1479 // If we have a non-zero Offset, we check that it matches the amount
1480 // we're adding to the register.
1481 if (!Offset || Offset == MI->getOperand(2).getImm())
1482 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001483 break;
1484 }
1485 return false;
1486}
1487
1488MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001489 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 MachineBasicBlock::iterator E = I->getParent()->end();
1491 MachineInstr *MemMI = I;
1492 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001493
Chad Rosierf77e9092015-08-06 15:50:12 +00001494 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001495 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001496
Chad Rosierb7c5b912015-10-01 13:43:05 +00001497 // Scan forward looking for post-index opportunities. Updating instructions
1498 // can't be formed if the memory instruction doesn't have the offset we're
1499 // looking for.
1500 if (MIUnscaledOffset != UnscaledOffset)
1501 return E;
1502
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001503 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001504 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001505 bool IsPairedInsn = isPairedLdSt(MemMI);
1506 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1507 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1508 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1509 return E;
1510 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001511
Tim Northover3b0846e2014-05-24 12:50:23 +00001512 // Track which registers have been modified and used between the first insn
1513 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001514 ModifiedRegs.reset();
1515 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001516 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001517 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001518 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001519 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001520 if (MI->isDebugValue())
1521 continue;
1522
Chad Rosier35706ad2016-02-04 21:26:02 +00001523 // Now that we know this is a real instruction, count it.
1524 ++Count;
1525
Tim Northover3b0846e2014-05-24 12:50:23 +00001526 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001527 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001528 return MBBI;
1529
1530 // Update the status of what the instruction clobbered and used.
1531 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1532
1533 // Otherwise, if the base register is used or modified, we have no match, so
1534 // return early.
1535 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1536 return E;
1537 }
1538 return E;
1539}
1540
1541MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001542 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001543 MachineBasicBlock::iterator B = I->getParent()->begin();
1544 MachineBasicBlock::iterator E = I->getParent()->end();
1545 MachineInstr *MemMI = I;
1546 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001547
Chad Rosierf77e9092015-08-06 15:50:12 +00001548 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1549 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001550
1551 // If the load/store is the first instruction in the block, there's obviously
1552 // not any matching update. Ditto if the memory offset isn't zero.
1553 if (MBBI == B || Offset != 0)
1554 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001555 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001556 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001557 bool IsPairedInsn = isPairedLdSt(MemMI);
1558 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1559 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1560 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1561 return E;
1562 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001563
1564 // Track which registers have been modified and used between the first insn
1565 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001566 ModifiedRegs.reset();
1567 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001568 unsigned Count = 0;
1569 do {
1570 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001571 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001572
Geoff Berry173b14d2016-02-09 20:47:21 +00001573 // Don't count DBG_VALUE instructions towards the search limit.
1574 if (!MI->isDebugValue())
1575 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001576
Tim Northover3b0846e2014-05-24 12:50:23 +00001577 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001578 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001579 return MBBI;
1580
1581 // Update the status of what the instruction clobbered and used.
1582 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1583
1584 // Otherwise, if the base register is used or modified, we have no match, so
1585 // return early.
1586 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1587 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001588 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001589 return E;
1590}
1591
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001592bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1593 MachineBasicBlock::iterator &MBBI) {
1594 MachineInstr *MI = MBBI;
1595 // If this is a volatile load, don't mess with it.
1596 if (MI->hasOrderedMemoryRef())
1597 return false;
1598
1599 // Make sure this is a reg+imm.
1600 // FIXME: It is possible to extend it to handle reg+reg cases.
1601 if (!getLdStOffsetOp(MI).isImm())
1602 return false;
1603
Chad Rosier35706ad2016-02-04 21:26:02 +00001604 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001605 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001606 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001607 ++NumLoadsFromStoresPromoted;
1608 // Promote the load. Keeping the iterator straight is a
1609 // pain, so we let the merge routine tell us what the next instruction
1610 // is after it's done mucking about.
1611 MBBI = promoteLoadFromStore(MBBI, StoreI);
1612 return true;
1613 }
1614 return false;
1615}
1616
Chad Rosier24c46ad2016-02-09 18:10:20 +00001617bool AArch64LoadStoreOpt::isCandidateToMergeOrPair(MachineInstr *MI) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001618 // If this is a volatile load/store, don't mess with it.
1619 if (MI->hasOrderedMemoryRef())
1620 return false;
1621
1622 // Make sure this is a reg+imm (as opposed to an address reloc).
1623 if (!getLdStOffsetOp(MI).isImm())
1624 return false;
1625
Chad Rosiercc5d61f2016-02-09 20:44:41 +00001626 // Can't merge/pair if the instruction modifies the base register.
1627 // e.g., ldr x0, [x0]
1628 unsigned BaseReg = getLdStBaseOp(MI).getReg();
1629 if (MI->modifiesRegister(BaseReg, TRI))
1630 return false;
1631
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001632 // Check if this load/store has a hint to avoid pair formation.
1633 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1634 if (TII->isLdStPairSuppressed(MI))
1635 return false;
1636
Chad Rosier24c46ad2016-02-09 18:10:20 +00001637 return true;
1638}
1639
1640// Find narrow loads that can be converted into a single wider load with
1641// bitfield extract instructions. Also merge adjacent zero stores into a wider
1642// store.
1643bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1644 MachineBasicBlock::iterator &MBBI) {
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001645 assert((isNarrowLoad(MBBI) || isPromotableZeroStoreOpcode(MBBI)) &&
1646 "Expected narrow op.");
Chad Rosier24c46ad2016-02-09 18:10:20 +00001647 MachineInstr *MI = MBBI;
1648 MachineBasicBlock::iterator E = MI->getParent()->end();
1649
1650 if (!isCandidateToMergeOrPair(MI))
1651 return false;
1652
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001653 // For promotable zero stores, the stored value should be WZR.
1654 if (isPromotableZeroStoreOpcode(MI) &&
1655 getLdStRegOp(MI).getReg() != AArch64::WZR)
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001656 return false;
1657
Chad Rosier24c46ad2016-02-09 18:10:20 +00001658 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001659 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001660 MachineBasicBlock::iterator MergeMI =
1661 findMatchingInsn(MBBI, Flags, LdStLimit);
Chad Rosierd7363db2016-02-09 19:09:22 +00001662 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001663 if (isNarrowLoad(MI)) {
1664 ++NumNarrowLoadsPromoted;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001665 } else if (isPromotableZeroStoreInst(MI)) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001666 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001667 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001668 // Keeping the iterator straight is a pain, so we let the merge routine tell
1669 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001670 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001671 return true;
1672 }
1673 return false;
1674}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001675
Chad Rosier24c46ad2016-02-09 18:10:20 +00001676// Find loads and stores that can be merged into a single load or store pair
1677// instruction.
1678bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1679 MachineInstr *MI = MBBI;
1680 MachineBasicBlock::iterator E = MI->getParent()->end();
1681
1682 if (!isCandidateToMergeOrPair(MI))
1683 return false;
1684
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001685 // Early exit if the offset is not possible to match. (6 bits of positive
1686 // range, plus allow an extra one in case we find a later insn that matches
1687 // with Offset-1)
1688 bool IsUnscaled = isUnscaledLdSt(MI);
1689 int Offset = getLdStOffsetOp(MI).getImm();
1690 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1691 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1692 return false;
1693
Chad Rosier24c46ad2016-02-09 18:10:20 +00001694 // Look ahead up to LdStLimit instructions for a pairable instruction.
1695 LdStPairFlags Flags;
1696 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, Flags, LdStLimit);
1697 if (Paired != E) {
1698 ++NumPairCreated;
1699 if (isUnscaledLdSt(MI))
1700 ++NumUnscaledPairCreated;
1701 // Keeping the iterator straight is a pain, so we let the merge routine tell
1702 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001703 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1704 return true;
1705 }
1706 return false;
1707}
1708
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001709bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1710 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001711 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001712 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001713 // 1) Find loads that directly read from stores and promote them by
1714 // replacing with mov instructions. If the store is wider than the load,
1715 // the load will be replaced with a bitfield extract.
1716 // e.g.,
1717 // str w1, [x0, #4]
1718 // ldrh w2, [x0, #6]
1719 // ; becomes
1720 // str w1, [x0, #4]
1721 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001722 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001723 MBBI != E;) {
1724 MachineInstr *MI = MBBI;
1725 switch (MI->getOpcode()) {
1726 default:
1727 // Just move on to the next instruction.
1728 ++MBBI;
1729 break;
1730 // Scaled instructions.
1731 case AArch64::LDRBBui:
1732 case AArch64::LDRHHui:
1733 case AArch64::LDRWui:
1734 case AArch64::LDRXui:
1735 // Unscaled instructions.
1736 case AArch64::LDURBBi:
1737 case AArch64::LDURHHi:
1738 case AArch64::LDURWi:
1739 case AArch64::LDURXi: {
1740 if (tryToPromoteLoadFromStore(MBBI)) {
1741 Modified = true;
1742 break;
1743 }
1744 ++MBBI;
1745 break;
1746 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001747 }
1748 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001749 // 2) Find narrow loads that can be converted into a single wider load
1750 // with bitfield extract instructions.
1751 // e.g.,
1752 // ldrh w0, [x2]
1753 // ldrh w1, [x2, #2]
1754 // ; becomes
1755 // ldr w0, [x2]
1756 // ubfx w1, w0, #16, #16
1757 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001758 //
1759 // Also merge adjacent zero stores into a wider store.
1760 // e.g.,
1761 // strh wzr, [x0]
1762 // strh wzr, [x0, #2]
1763 // ; becomes
1764 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001765 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001766 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001767 MachineInstr *MI = MBBI;
1768 switch (MI->getOpcode()) {
1769 default:
1770 // Just move on to the next instruction.
1771 ++MBBI;
1772 break;
1773 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001774 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001775 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001776 case AArch64::LDRSBWui:
1777 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001778 case AArch64::STRBBui:
1779 case AArch64::STRHHui:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001780 case AArch64::STRWui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001781 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001782 case AArch64::LDURBBi:
1783 case AArch64::LDURHHi:
1784 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001785 case AArch64::LDURSHWi:
1786 case AArch64::STURBBi:
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001787 case AArch64::STURHHi:
1788 case AArch64::STURWi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001789 if (tryToMergeLdStInst(MBBI)) {
1790 Modified = true;
1791 break;
1792 }
1793 ++MBBI;
1794 break;
1795 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001796 }
1797 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001798 // 3) Find loads and stores that can be merged into a single load or store
1799 // pair instruction.
1800 // e.g.,
1801 // ldr x0, [x2]
1802 // ldr x1, [x2, #8]
1803 // ; becomes
1804 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001805 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00001806 MBBI != E;) {
1807 MachineInstr *MI = MBBI;
1808 switch (MI->getOpcode()) {
1809 default:
1810 // Just move on to the next instruction.
1811 ++MBBI;
1812 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001813 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001814 case AArch64::STRSui:
1815 case AArch64::STRDui:
1816 case AArch64::STRQui:
1817 case AArch64::STRXui:
1818 case AArch64::STRWui:
1819 case AArch64::LDRSui:
1820 case AArch64::LDRDui:
1821 case AArch64::LDRQui:
1822 case AArch64::LDRXui:
1823 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001824 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001825 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001826 case AArch64::STURSi:
1827 case AArch64::STURDi:
1828 case AArch64::STURQi:
1829 case AArch64::STURWi:
1830 case AArch64::STURXi:
1831 case AArch64::LDURSi:
1832 case AArch64::LDURDi:
1833 case AArch64::LDURQi:
1834 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001835 case AArch64::LDURXi:
1836 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001837 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001838 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001839 break;
1840 }
1841 ++MBBI;
1842 break;
1843 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001844 }
1845 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001846 // 4) Find base register updates that can be merged into the load or store
1847 // as a base-reg writeback.
1848 // e.g.,
1849 // ldr x0, [x2]
1850 // add x2, x2, #4
1851 // ; becomes
1852 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001853 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1854 MBBI != E;) {
1855 MachineInstr *MI = MBBI;
1856 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001857 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001858 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001859 switch (Opc) {
1860 default:
1861 // Just move on to the next instruction.
1862 ++MBBI;
1863 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001864 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001865 case AArch64::STRSui:
1866 case AArch64::STRDui:
1867 case AArch64::STRQui:
1868 case AArch64::STRXui:
1869 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001870 case AArch64::STRHHui:
1871 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001872 case AArch64::LDRSui:
1873 case AArch64::LDRDui:
1874 case AArch64::LDRQui:
1875 case AArch64::LDRXui:
1876 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001877 case AArch64::LDRHHui:
1878 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001879 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001880 case AArch64::STURSi:
1881 case AArch64::STURDi:
1882 case AArch64::STURQi:
1883 case AArch64::STURWi:
1884 case AArch64::STURXi:
1885 case AArch64::LDURSi:
1886 case AArch64::LDURDi:
1887 case AArch64::LDURQi:
1888 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001889 case AArch64::LDURXi:
1890 // Paired instructions.
1891 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001892 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001893 case AArch64::LDPDi:
1894 case AArch64::LDPQi:
1895 case AArch64::LDPWi:
1896 case AArch64::LDPXi:
1897 case AArch64::STPSi:
1898 case AArch64::STPDi:
1899 case AArch64::STPQi:
1900 case AArch64::STPWi:
1901 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001903 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001904 ++MBBI;
1905 break;
1906 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001907 // Look forward to try to form a post-index instruction. For example,
1908 // ldr x0, [x20]
1909 // add x20, x20, #32
1910 // merged into:
1911 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001912 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001913 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001914 if (Update != E) {
1915 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001916 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001917 Modified = true;
1918 ++NumPostFolded;
1919 break;
1920 }
1921 // Don't know how to handle pre/post-index versions, so move to the next
1922 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001923 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001924 ++MBBI;
1925 break;
1926 }
1927
1928 // Look back to try to find a pre-index instruction. For example,
1929 // add x0, x0, #8
1930 // ldr x1, [x0]
1931 // merged into:
1932 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001933 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001934 if (Update != E) {
1935 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001936 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001937 Modified = true;
1938 ++NumPreFolded;
1939 break;
1940 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001941 // The immediate in the load/store is scaled by the size of the memory
1942 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001943 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001944 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001945
Tim Northover3b0846e2014-05-24 12:50:23 +00001946 // Look forward to try to find a post-index instruction. For example,
1947 // ldr x1, [x0, #64]
1948 // add x0, x0, #64
1949 // merged into:
1950 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001951 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001952 if (Update != E) {
1953 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001954 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001955 Modified = true;
1956 ++NumPreFolded;
1957 break;
1958 }
1959
1960 // Nothing found. Just move to the next instruction.
1961 ++MBBI;
1962 break;
1963 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001964 }
1965 }
1966
1967 return Modified;
1968}
1969
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001970bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Chad Rosiercd2be7f2016-02-12 15:51:51 +00001971 bool ProfitableArch = Subtarget->isCortexA57() || Subtarget->isKryo();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001972 // FIXME: The benefit from converting narrow loads into a wider load could be
1973 // microarchitectural as it assumes that a single load with two bitfield
1974 // extracts is cheaper than two narrow loads. Currently, this conversion is
1975 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001976 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001977}
1978
Tim Northover3b0846e2014-05-24 12:50:23 +00001979bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001980 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1981 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1982 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001983
Chad Rosierbba881e2016-02-02 15:02:30 +00001984 // Resize the modified and used register bitfield trackers. We do this once
1985 // per function and then clear the bitfield each time we optimize a load or
1986 // store.
1987 ModifiedRegs.resize(TRI->getNumRegs());
1988 UsedRegs.resize(TRI->getNumRegs());
1989
Tim Northover3b0846e2014-05-24 12:50:23 +00001990 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001991 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001992 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001993 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001994
1995 return Modified;
1996}
1997
1998// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1999// loads and stores near one another?
2000
Chad Rosier3f8b09d2016-02-09 19:42:19 +00002001// FIXME: When pairing store instructions it's very possible for this pass to
2002// hoist a store with a KILL marker above another use (without a KILL marker).
2003// The resulting IR is invalid, but nothing uses the KILL markers after this
2004// pass, so it's never caused a problem in practice.
2005
Chad Rosier43f5c842015-08-05 12:40:13 +00002006/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2007/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00002008FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2009 return new AArch64LoadStoreOpt();
2010}