blob: d0de6d24fc945fd3d2731815f06bc3f3154c7398 [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
238static bool isNarrowStore(MachineInstr *MI) {
239 return isNarrowStore(MI->getOpcode());
240}
241
Jun Bum Limc12c2792015-11-19 18:41:27 +0000242static bool isNarrowLoad(unsigned Opc) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000243 switch (Opc) {
244 default:
245 return false;
246 case AArch64::LDRHHui:
247 case AArch64::LDURHHi:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000248 case AArch64::LDRBBui:
249 case AArch64::LDURBBi:
250 case AArch64::LDRSHWui:
251 case AArch64::LDURSHWi:
252 case AArch64::LDRSBWui:
253 case AArch64::LDURSBWi:
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000254 return true;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000255 }
256}
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000257
Jun Bum Limc12c2792015-11-19 18:41:27 +0000258static bool isNarrowLoad(MachineInstr *MI) {
259 return isNarrowLoad(MI->getOpcode());
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000260}
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;
385 case AArch64::LDRHHui:
386 case AArch64::LDRSHWui:
387 return AArch64::LDRWui;
388 case AArch64::LDURHHi:
389 case AArch64::LDURSHWi:
390 return AArch64::LDURWi;
391 case AArch64::LDRBBui:
392 case AArch64::LDRSBWui:
393 return AArch64::LDRHHui;
394 case AArch64::LDURBBi:
395 case AArch64::LDURSBWi:
396 return AArch64::LDURHHi;
397 }
398}
399
Tim Northover3b0846e2014-05-24 12:50:23 +0000400static unsigned getMatchingPairOpcode(unsigned Opc) {
401 switch (Opc) {
402 default:
403 llvm_unreachable("Opcode has no pairwise equivalent!");
404 case AArch64::STRSui:
405 case AArch64::STURSi:
406 return AArch64::STPSi;
407 case AArch64::STRDui:
408 case AArch64::STURDi:
409 return AArch64::STPDi;
410 case AArch64::STRQui:
411 case AArch64::STURQi:
412 return AArch64::STPQi;
413 case AArch64::STRWui:
414 case AArch64::STURWi:
415 return AArch64::STPWi;
416 case AArch64::STRXui:
417 case AArch64::STURXi:
418 return AArch64::STPXi;
419 case AArch64::LDRSui:
420 case AArch64::LDURSi:
421 return AArch64::LDPSi;
422 case AArch64::LDRDui:
423 case AArch64::LDURDi:
424 return AArch64::LDPDi;
425 case AArch64::LDRQui:
426 case AArch64::LDURQi:
427 return AArch64::LDPQi;
428 case AArch64::LDRWui:
429 case AArch64::LDURWi:
430 return AArch64::LDPWi;
431 case AArch64::LDRXui:
432 case AArch64::LDURXi:
433 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000434 case AArch64::LDRSWui:
435 case AArch64::LDURSWi:
436 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000437 }
438}
439
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000440static unsigned isMatchingStore(MachineInstr *LoadInst,
441 MachineInstr *StoreInst) {
442 unsigned LdOpc = LoadInst->getOpcode();
443 unsigned StOpc = StoreInst->getOpcode();
444 switch (LdOpc) {
445 default:
446 llvm_unreachable("Unsupported load instruction!");
447 case AArch64::LDRBBui:
448 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
449 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
450 case AArch64::LDURBBi:
451 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
452 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
453 case AArch64::LDRHHui:
454 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
455 StOpc == AArch64::STRXui;
456 case AArch64::LDURHHi:
457 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
458 StOpc == AArch64::STURXi;
459 case AArch64::LDRWui:
460 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
461 case AArch64::LDURWi:
462 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
463 case AArch64::LDRXui:
464 return StOpc == AArch64::STRXui;
465 case AArch64::LDURXi:
466 return StOpc == AArch64::STURXi;
467 }
468}
469
Tim Northover3b0846e2014-05-24 12:50:23 +0000470static unsigned getPreIndexedOpcode(unsigned Opc) {
471 switch (Opc) {
472 default:
473 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000474 case AArch64::STRSui:
475 return AArch64::STRSpre;
476 case AArch64::STRDui:
477 return AArch64::STRDpre;
478 case AArch64::STRQui:
479 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000480 case AArch64::STRBBui:
481 return AArch64::STRBBpre;
482 case AArch64::STRHHui:
483 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000484 case AArch64::STRWui:
485 return AArch64::STRWpre;
486 case AArch64::STRXui:
487 return AArch64::STRXpre;
488 case AArch64::LDRSui:
489 return AArch64::LDRSpre;
490 case AArch64::LDRDui:
491 return AArch64::LDRDpre;
492 case AArch64::LDRQui:
493 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000494 case AArch64::LDRBBui:
495 return AArch64::LDRBBpre;
496 case AArch64::LDRHHui:
497 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000498 case AArch64::LDRWui:
499 return AArch64::LDRWpre;
500 case AArch64::LDRXui:
501 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000502 case AArch64::LDRSWui:
503 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000504 case AArch64::LDPSi:
505 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000506 case AArch64::LDPSWi:
507 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000508 case AArch64::LDPDi:
509 return AArch64::LDPDpre;
510 case AArch64::LDPQi:
511 return AArch64::LDPQpre;
512 case AArch64::LDPWi:
513 return AArch64::LDPWpre;
514 case AArch64::LDPXi:
515 return AArch64::LDPXpre;
516 case AArch64::STPSi:
517 return AArch64::STPSpre;
518 case AArch64::STPDi:
519 return AArch64::STPDpre;
520 case AArch64::STPQi:
521 return AArch64::STPQpre;
522 case AArch64::STPWi:
523 return AArch64::STPWpre;
524 case AArch64::STPXi:
525 return AArch64::STPXpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 }
527}
528
529static unsigned getPostIndexedOpcode(unsigned Opc) {
530 switch (Opc) {
531 default:
532 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
533 case AArch64::STRSui:
534 return AArch64::STRSpost;
535 case AArch64::STRDui:
536 return AArch64::STRDpost;
537 case AArch64::STRQui:
538 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000539 case AArch64::STRBBui:
540 return AArch64::STRBBpost;
541 case AArch64::STRHHui:
542 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 case AArch64::STRWui:
544 return AArch64::STRWpost;
545 case AArch64::STRXui:
546 return AArch64::STRXpost;
547 case AArch64::LDRSui:
548 return AArch64::LDRSpost;
549 case AArch64::LDRDui:
550 return AArch64::LDRDpost;
551 case AArch64::LDRQui:
552 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000553 case AArch64::LDRBBui:
554 return AArch64::LDRBBpost;
555 case AArch64::LDRHHui:
556 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000557 case AArch64::LDRWui:
558 return AArch64::LDRWpost;
559 case AArch64::LDRXui:
560 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000561 case AArch64::LDRSWui:
562 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000563 case AArch64::LDPSi:
564 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000565 case AArch64::LDPSWi:
566 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 case AArch64::LDPDi:
568 return AArch64::LDPDpost;
569 case AArch64::LDPQi:
570 return AArch64::LDPQpost;
571 case AArch64::LDPWi:
572 return AArch64::LDPWpost;
573 case AArch64::LDPXi:
574 return AArch64::LDPXpost;
575 case AArch64::STPSi:
576 return AArch64::STPSpost;
577 case AArch64::STPDi:
578 return AArch64::STPDpost;
579 case AArch64::STPQi:
580 return AArch64::STPQpost;
581 case AArch64::STPWi:
582 return AArch64::STPWpost;
583 case AArch64::STPXi:
584 return AArch64::STPXpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000585 }
586}
587
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000588static bool isPairedLdSt(const MachineInstr *MI) {
589 switch (MI->getOpcode()) {
590 default:
591 return false;
592 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000593 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000594 case AArch64::LDPDi:
595 case AArch64::LDPQi:
596 case AArch64::LDPWi:
597 case AArch64::LDPXi:
598 case AArch64::STPSi:
599 case AArch64::STPDi:
600 case AArch64::STPQi:
601 case AArch64::STPWi:
602 case AArch64::STPXi:
603 return true;
604 }
605}
606
607static const MachineOperand &getLdStRegOp(const MachineInstr *MI,
608 unsigned PairedRegOp = 0) {
609 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
610 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
611 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000612}
613
614static const MachineOperand &getLdStBaseOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000615 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
616 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000617}
618
619static const MachineOperand &getLdStOffsetOp(const MachineInstr *MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000620 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
621 return MI->getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000622}
623
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000624static bool isLdOffsetInRangeOfSt(MachineInstr *LoadInst,
625 MachineInstr *StoreInst) {
626 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
627 int LoadSize = getMemScale(LoadInst);
628 int StoreSize = getMemScale(StoreInst);
629 int UnscaledStOffset = isUnscaledLdSt(StoreInst)
630 ? getLdStOffsetOp(StoreInst).getImm()
631 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
632 int UnscaledLdOffset = isUnscaledLdSt(LoadInst)
633 ? getLdStOffsetOp(LoadInst).getImm()
634 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
635 return (UnscaledStOffset <= UnscaledLdOffset) &&
636 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
637}
638
Tim Northover3b0846e2014-05-24 12:50:23 +0000639MachineBasicBlock::iterator
Chad Rosierb5933d72016-02-09 19:02:12 +0000640AArch64LoadStoreOpt::mergeNarrowInsns(MachineBasicBlock::iterator I,
Chad Rosierd7363db2016-02-09 19:09:22 +0000641 MachineBasicBlock::iterator MergeMI,
Chad Rosier96a18a92015-07-21 17:42:04 +0000642 const LdStPairFlags &Flags) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 MachineBasicBlock::iterator NextI = I;
644 ++NextI;
645 // If NextI is the second of the two instructions to be merged, we need
646 // to skip one further. Either way we merge will invalidate the iterator,
647 // and we don't need to scan the new instruction, as it's a pairwise
648 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000649 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000650 ++NextI;
651
Chad Rosierb5933d72016-02-09 19:02:12 +0000652 unsigned Opc = I->getOpcode();
Chad Rosier11eedc92016-02-09 19:17:18 +0000653 bool IsScaled = !isUnscaledLdSt(Opc);
654 int OffsetStride = IsScaled ? 1 : getMemScale(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000655
Chad Rosier96a18a92015-07-21 17:42:04 +0000656 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000658 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000659 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000660 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000661 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000662 const MachineOperand &BaseRegOp =
Chad Rosierd7363db2016-02-09 19:09:22 +0000663 MergeForward ? getLdStBaseOp(MergeMI) : getLdStBaseOp(I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000664
665 // Which register is Rt and which is Rt2 depends on the offset order.
666 MachineInstr *RtMI, *Rt2MI;
Renato Golin6274e522016-02-05 12:14:30 +0000667 if (getLdStOffsetOp(I).getImm() ==
Chad Rosierd7363db2016-02-09 19:09:22 +0000668 getLdStOffsetOp(MergeMI).getImm() + OffsetStride) {
669 RtMI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 Rt2MI = I;
671 } else {
672 RtMI = I;
Chad Rosierd7363db2016-02-09 19:09:22 +0000673 Rt2MI = MergeMI;
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000675
James Molloy5b18b4c2015-10-23 10:41:38 +0000676 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000677 // Change the scaled offset from small to large type.
678 if (IsScaled) {
679 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
680 OffsetImm /= 2;
681 }
682
Chad Rosierc46ef882016-02-09 19:33:42 +0000683 DebugLoc DL = I->getDebugLoc();
684 MachineBasicBlock *MBB = I->getParent();
Jun Bum Limc12c2792015-11-19 18:41:27 +0000685 if (isNarrowLoad(Opc)) {
Chad Rosierd7363db2016-02-09 19:09:22 +0000686 MachineInstr *RtNewDest = MergeForward ? I : MergeMI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000687 // When merging small (< 32 bit) loads for big-endian targets, the order of
688 // the component parts gets swapped.
689 if (!Subtarget->isLittleEndian())
690 std::swap(RtMI, Rt2MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000691 // Construct the new load instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000692 MachineInstr *NewMemMI, *BitExtMI1, *BitExtMI2;
Chad Rosierc46ef882016-02-09 19:33:42 +0000693 NewMemMI =
694 BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
695 .addOperand(getLdStRegOp(RtNewDest))
696 .addOperand(BaseRegOp)
697 .addImm(OffsetImm)
698 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000699
700 DEBUG(
701 dbgs()
702 << "Creating the new load and extract. Replacing instructions:\n ");
703 DEBUG(I->print(dbgs()));
704 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000705 DEBUG(MergeMI->print(dbgs()));
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000706 DEBUG(dbgs() << " with instructions:\n ");
707 DEBUG((NewMemMI)->print(dbgs()));
708
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000709 int Width = getMemScale(I) == 1 ? 8 : 16;
710 int LSBLow = 0;
711 int LSBHigh = Width;
712 int ImmsLow = LSBLow + Width - 1;
713 int ImmsHigh = LSBHigh + Width - 1;
Chad Rosierd7363db2016-02-09 19:09:22 +0000714 MachineInstr *ExtDestMI = MergeForward ? MergeMI : I;
Oliver Stannardd414c992015-11-10 11:04:18 +0000715 if ((ExtDestMI == Rt2MI) == Subtarget->isLittleEndian()) {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000716 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000717 BitExtMI1 =
718 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
719 .addOperand(getLdStRegOp(Rt2MI))
720 .addReg(getLdStRegOp(RtNewDest).getReg())
721 .addImm(LSBHigh)
722 .addImm(ImmsHigh);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000723 // Create the bitfield extract for low bits.
724 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
725 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000726 BitExtMI2 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000727 .addOperand(getLdStRegOp(RtMI))
728 .addReg(getLdStRegOp(RtNewDest).getReg())
729 .addImm(ImmsLow);
730 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000731 BitExtMI2 =
732 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
733 .addOperand(getLdStRegOp(RtMI))
734 .addReg(getLdStRegOp(RtNewDest).getReg())
735 .addImm(LSBLow)
736 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000737 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000738 } else {
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000739 // Create the bitfield extract for low bits.
740 if (RtMI->getOpcode() == getMatchingNonSExtOpcode(RtMI->getOpcode())) {
741 // For unsigned, prefer to use AND for low bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000742 BitExtMI1 = BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::ANDWri))
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000743 .addOperand(getLdStRegOp(RtMI))
744 .addReg(getLdStRegOp(RtNewDest).getReg())
745 .addImm(ImmsLow);
746 } else {
Chad Rosierc46ef882016-02-09 19:33:42 +0000747 BitExtMI1 =
748 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(RtMI)))
749 .addOperand(getLdStRegOp(RtMI))
750 .addReg(getLdStRegOp(RtNewDest).getReg())
751 .addImm(LSBLow)
752 .addImm(ImmsLow);
Jun Bum Lim4c35cca2015-11-19 17:21:41 +0000753 }
754
755 // Create the bitfield extract for high bits.
Chad Rosierc46ef882016-02-09 19:33:42 +0000756 BitExtMI2 =
757 BuildMI(*MBB, InsertionPoint, DL, TII->get(getBitExtrOpcode(Rt2MI)))
758 .addOperand(getLdStRegOp(Rt2MI))
759 .addReg(getLdStRegOp(RtNewDest).getReg())
760 .addImm(LSBHigh)
761 .addImm(ImmsHigh);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000762 }
763 DEBUG(dbgs() << " ");
764 DEBUG((BitExtMI1)->print(dbgs()));
765 DEBUG(dbgs() << " ");
766 DEBUG((BitExtMI2)->print(dbgs()));
767 DEBUG(dbgs() << "\n");
768
769 // Erase the old instructions.
770 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000771 MergeMI->eraseFromParent();
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000772 return NextI;
773 }
Chad Rosier11eedc92016-02-09 19:17:18 +0000774 assert(isNarrowStore(Opc) && "Expected narrow store");
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000775
Tim Northover3b0846e2014-05-24 12:50:23 +0000776 // Construct the new instruction.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000777 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000778 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000779 .addOperand(getLdStRegOp(I))
780 .addOperand(BaseRegOp)
781 .addImm(OffsetImm)
Chad Rosierd7363db2016-02-09 19:09:22 +0000782 .setMemRefs(I->mergeMemRefsWith(*MergeMI));
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000783
Tim Northover3b0846e2014-05-24 12:50:23 +0000784 (void)MIB;
785
Chad Rosierb5933d72016-02-09 19:02:12 +0000786 DEBUG(dbgs() << "Creating wider load/store. Replacing instructions:\n ");
787 DEBUG(I->print(dbgs()));
788 DEBUG(dbgs() << " ");
Chad Rosierd7363db2016-02-09 19:09:22 +0000789 DEBUG(MergeMI->print(dbgs()));
Chad Rosierb5933d72016-02-09 19:02:12 +0000790 DEBUG(dbgs() << " with instruction:\n ");
791 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
792 DEBUG(dbgs() << "\n");
793
794 // Erase the old instructions.
795 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000796 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000797 return NextI;
798}
799
800MachineBasicBlock::iterator
801AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
802 MachineBasicBlock::iterator Paired,
803 const LdStPairFlags &Flags) {
804 MachineBasicBlock::iterator NextI = I;
805 ++NextI;
806 // If NextI is the second of the two instructions to be merged, we need
807 // to skip one further. Either way we merge will invalidate the iterator,
808 // and we don't need to scan the new instruction, as it's a pairwise
809 // instruction, which we're not considering for further action anyway.
810 if (NextI == Paired)
811 ++NextI;
812
813 int SExtIdx = Flags.getSExtIdx();
814 unsigned Opc =
815 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
816 bool IsUnscaled = isUnscaledLdSt(Opc);
817 int OffsetStride = IsUnscaled ? getMemScale(I) : 1;
818
819 bool MergeForward = Flags.getMergeForward();
820 // Insert our new paired instruction after whichever of the paired
821 // instructions MergeForward indicates.
822 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
823 // Also based on MergeForward is from where we copy the base register operand
824 // so we get the flags compatible with the input code.
825 const MachineOperand &BaseRegOp =
826 MergeForward ? getLdStBaseOp(Paired) : getLdStBaseOp(I);
827
828 // Which register is Rt and which is Rt2 depends on the offset order.
829 MachineInstr *RtMI, *Rt2MI;
830 if (getLdStOffsetOp(I).getImm() ==
831 getLdStOffsetOp(Paired).getImm() + OffsetStride) {
832 RtMI = Paired;
833 Rt2MI = I;
834 // Here we swapped the assumption made for SExtIdx.
835 // I.e., we turn ldp I, Paired into ldp Paired, I.
836 // Update the index accordingly.
837 if (SExtIdx != -1)
838 SExtIdx = (SExtIdx + 1) % 2;
839 } else {
840 RtMI = I;
841 Rt2MI = Paired;
842 }
843 int OffsetImm = getLdStOffsetOp(RtMI).getImm();
844 // Handle Unscaled.
Chad Rosier87e33412016-02-09 20:18:07 +0000845 if (IsUnscaled) {
846 assert (!(OffsetImm % OffsetStride) && "Unscaled offset cannot be scaled.");
Chad Rosierb5933d72016-02-09 19:02:12 +0000847 OffsetImm /= OffsetStride;
Chad Rosier87e33412016-02-09 20:18:07 +0000848 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000849
850 // Construct the new instruction.
851 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000852 DebugLoc DL = I->getDebugLoc();
853 MachineBasicBlock *MBB = I->getParent();
854 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Chad Rosierb5933d72016-02-09 19:02:12 +0000855 .addOperand(getLdStRegOp(RtMI))
856 .addOperand(getLdStRegOp(Rt2MI))
857 .addOperand(BaseRegOp)
858 .addImm(OffsetImm);
859 // FIXME: Copy the mem operands from the source instructions. The MI scheduler
860 // needs these to reason about loads/stores.
861
862 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000863
864 DEBUG(dbgs() << "Creating pair load/store. Replacing instructions:\n ");
865 DEBUG(I->print(dbgs()));
866 DEBUG(dbgs() << " ");
867 DEBUG(Paired->print(dbgs()));
868 DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000869 if (SExtIdx != -1) {
870 // Generate the sign extension for the proper result of the ldp.
871 // I.e., with X1, that would be:
872 // %W1<def> = KILL %W1, %X1<imp-def>
873 // %X1<def> = SBFMXri %X1<kill>, 0, 31
874 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
875 // Right now, DstMO has the extended register, since it comes from an
876 // extended opcode.
877 unsigned DstRegX = DstMO.getReg();
878 // Get the W variant of that register.
879 unsigned DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
880 // Update the result of LDP to use the W instead of the X variant.
881 DstMO.setReg(DstRegW);
882 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
883 DEBUG(dbgs() << "\n");
884 // Make the machine verifier happy by providing a definition for
885 // the X register.
886 // Insert this definition right after the generated LDP, i.e., before
887 // InsertionPoint.
888 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000889 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000890 .addReg(DstRegW)
891 .addReg(DstRegX, RegState::Define);
892 MIBKill->getOperand(2).setImplicit();
893 // Create the sign extension.
894 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000895 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000896 .addReg(DstRegX)
897 .addImm(0)
898 .addImm(31);
899 (void)MIBSXTW;
900 DEBUG(dbgs() << " Extend operand:\n ");
901 DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000902 } else {
903 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000904 }
Chad Rosier1c44c5982016-02-09 20:27:45 +0000905 DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000906
907 // Erase the old instructions.
908 I->eraseFromParent();
909 Paired->eraseFromParent();
910
911 return NextI;
912}
913
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000914MachineBasicBlock::iterator
915AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
916 MachineBasicBlock::iterator StoreI) {
917 MachineBasicBlock::iterator NextI = LoadI;
918 ++NextI;
919
920 int LoadSize = getMemScale(LoadI);
921 int StoreSize = getMemScale(StoreI);
922 unsigned LdRt = getLdStRegOp(LoadI).getReg();
923 unsigned StRt = getLdStRegOp(StoreI).getReg();
924 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
925
926 assert((IsStoreXReg ||
927 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
928 "Unexpected RegClass");
929
930 MachineInstr *BitExtMI;
931 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
932 // Remove the load, if the destination register of the loads is the same
933 // register for stored value.
934 if (StRt == LdRt && LoadSize == 8) {
935 DEBUG(dbgs() << "Remove load instruction:\n ");
936 DEBUG(LoadI->print(dbgs()));
937 DEBUG(dbgs() << "\n");
938 LoadI->eraseFromParent();
939 return NextI;
940 }
941 // Replace the load with a mov if the load and store are in the same size.
942 BitExtMI =
943 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
944 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
945 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
946 .addReg(StRt)
947 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
948 } else {
949 // FIXME: Currently we disable this transformation in big-endian targets as
950 // performance and correctness are verified only in little-endian.
951 if (!Subtarget->isLittleEndian())
952 return NextI;
953 bool IsUnscaled = isUnscaledLdSt(LoadI);
954 assert(IsUnscaled == isUnscaledLdSt(StoreI) && "Unsupported ld/st match");
955 assert(LoadSize <= StoreSize && "Invalid load size");
956 int UnscaledLdOffset = IsUnscaled
957 ? getLdStOffsetOp(LoadI).getImm()
958 : getLdStOffsetOp(LoadI).getImm() * LoadSize;
959 int UnscaledStOffset = IsUnscaled
960 ? getLdStOffsetOp(StoreI).getImm()
961 : getLdStOffsetOp(StoreI).getImm() * StoreSize;
962 int Width = LoadSize * 8;
963 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
964 int Imms = Immr + Width - 1;
965 unsigned DestReg = IsStoreXReg
966 ? TRI->getMatchingSuperReg(LdRt, AArch64::sub_32,
967 &AArch64::GPR64RegClass)
968 : LdRt;
969
970 assert((UnscaledLdOffset >= UnscaledStOffset &&
971 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
972 "Invalid offset");
973
974 Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
975 Imms = Immr + Width - 1;
976 if (UnscaledLdOffset == UnscaledStOffset) {
977 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
978 | ((Immr) << 6) // immr
979 | ((Imms) << 0) // imms
980 ;
981
982 BitExtMI =
983 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
984 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
985 DestReg)
986 .addReg(StRt)
987 .addImm(AndMaskEncoded);
988 } else {
989 BitExtMI =
990 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
991 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
992 DestReg)
993 .addReg(StRt)
994 .addImm(Immr)
995 .addImm(Imms);
996 }
997 }
998
999 DEBUG(dbgs() << "Promoting load by replacing :\n ");
1000 DEBUG(StoreI->print(dbgs()));
1001 DEBUG(dbgs() << " ");
1002 DEBUG(LoadI->print(dbgs()));
1003 DEBUG(dbgs() << " with instructions:\n ");
1004 DEBUG(StoreI->print(dbgs()));
1005 DEBUG(dbgs() << " ");
1006 DEBUG((BitExtMI)->print(dbgs()));
1007 DEBUG(dbgs() << "\n");
1008
1009 // Erase the old instructions.
1010 LoadI->eraseFromParent();
1011 return NextI;
1012}
1013
Tim Northover3b0846e2014-05-24 12:50:23 +00001014/// trackRegDefsUses - Remember what registers the specified instruction uses
1015/// and modifies.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001016static void trackRegDefsUses(const MachineInstr *MI, BitVector &ModifiedRegs,
Tim Northover3b0846e2014-05-24 12:50:23 +00001017 BitVector &UsedRegs,
1018 const TargetRegisterInfo *TRI) {
Pete Cooper7be8f8f2015-08-03 19:04:32 +00001019 for (const MachineOperand &MO : MI->operands()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001020 if (MO.isRegMask())
1021 ModifiedRegs.setBitsNotInMask(MO.getRegMask());
1022
1023 if (!MO.isReg())
1024 continue;
1025 unsigned Reg = MO.getReg();
Geoff Berry173b14d2016-02-09 20:47:21 +00001026 if (!Reg)
1027 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00001028 if (MO.isDef()) {
1029 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1030 ModifiedRegs.set(*AI);
1031 } else {
1032 assert(MO.isUse() && "Reg operand not a def and not a use?!?");
1033 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1034 UsedRegs.set(*AI);
1035 }
1036 }
1037}
1038
1039static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001040 // Convert the byte-offset used by unscaled into an "element" offset used
1041 // by the scaled pair load/store instructions.
Renato Golin6274e522016-02-05 12:14:30 +00001042 if (IsUnscaled)
Chad Rosier3dd0e942015-08-18 16:20:03 +00001043 Offset /= OffsetStride;
Renato Golin6274e522016-02-05 12:14:30 +00001044
Chad Rosier3dd0e942015-08-18 16:20:03 +00001045 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001046}
1047
1048// Do alignment, specialized to power of 2 and for signed ints,
1049// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001050// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001051// FIXME: Move this function to include/MathExtras.h?
1052static int alignTo(int Num, int PowOf2) {
1053 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1054}
1055
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001056static bool mayAlias(MachineInstr *MIa, MachineInstr *MIb,
1057 const AArch64InstrInfo *TII) {
1058 // One of the instructions must modify memory.
1059 if (!MIa->mayStore() && !MIb->mayStore())
1060 return false;
1061
1062 // Both instructions must be memory operations.
1063 if (!MIa->mayLoadOrStore() && !MIb->mayLoadOrStore())
1064 return false;
1065
1066 return !TII->areMemAccessesTriviallyDisjoint(MIa, MIb);
1067}
1068
1069static bool mayAlias(MachineInstr *MIa,
1070 SmallVectorImpl<MachineInstr *> &MemInsns,
1071 const AArch64InstrInfo *TII) {
1072 for (auto &MIb : MemInsns)
1073 if (mayAlias(MIa, MIb, TII))
1074 return true;
1075
1076 return false;
1077}
1078
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001079bool AArch64LoadStoreOpt::findMatchingStore(
1080 MachineBasicBlock::iterator I, unsigned Limit,
1081 MachineBasicBlock::iterator &StoreI) {
1082 MachineBasicBlock::iterator E = I->getParent()->begin();
1083 MachineBasicBlock::iterator MBBI = I;
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001084 MachineInstr *LoadMI = I;
1085 unsigned BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001086
1087 // Track which registers have been modified and used between the first insn
1088 // and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001089 ModifiedRegs.reset();
1090 UsedRegs.reset();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001091
Chad Rosier1142f3c2016-02-02 15:22:55 +00001092 // FIXME: We miss the case where the matching store is the first instruction
1093 // in the basic block.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001094 for (unsigned Count = 0; MBBI != E && Count < Limit;) {
1095 --MBBI;
1096 MachineInstr *MI = MBBI;
1097 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1098 // optimization by changing how far we scan.
1099 if (MI->isDebugValue())
1100 continue;
1101 // Now that we know this is a real instruction, count it.
1102 ++Count;
1103
1104 // If the load instruction reads directly from the address to which the
1105 // store instruction writes and the stored value is not modified, we can
1106 // promote the load. Since we do not handle stores with pre-/post-index,
1107 // it's unnecessary to check if BaseReg is modified by the store itself.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001108 if (MI->mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001109 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001110 isLdOffsetInRangeOfSt(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001111 !ModifiedRegs[getLdStRegOp(MI).getReg()]) {
1112 StoreI = MBBI;
1113 return true;
1114 }
1115
1116 if (MI->isCall())
1117 return false;
1118
1119 // Update modified / uses register lists.
1120 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1121
1122 // Otherwise, if the base register is modified, we have no match, so
1123 // return early.
1124 if (ModifiedRegs[BaseReg])
1125 return false;
1126
1127 // If we encounter a store aliased with the load, return early.
Chad Rosier5c6a66c2016-02-09 15:59:57 +00001128 if (MI->mayStore() && mayAlias(LoadMI, MI, TII))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001129 return false;
1130 }
1131 return false;
1132}
1133
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001134/// Scan the instructions looking for a load/store that can be combined with the
1135/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001136MachineBasicBlock::iterator
1137AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001138 LdStPairFlags &Flags, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001139 MachineBasicBlock::iterator E = I->getParent()->end();
1140 MachineBasicBlock::iterator MBBI = I;
1141 MachineInstr *FirstMI = I;
1142 ++MBBI;
1143
Matthias Braunfa3872e2015-05-18 20:27:55 +00001144 unsigned Opc = FirstMI->getOpcode();
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +00001145 bool MayLoad = FirstMI->mayLoad();
Chad Rosier22eb7102015-08-06 17:37:18 +00001146 bool IsUnscaled = isUnscaledLdSt(FirstMI);
Chad Rosierf77e9092015-08-06 15:50:12 +00001147 unsigned Reg = getLdStRegOp(FirstMI).getReg();
1148 unsigned BaseReg = getLdStBaseOp(FirstMI).getReg();
1149 int Offset = getLdStOffsetOp(FirstMI).getImm();
Chad Rosierf11d0402015-10-01 18:17:12 +00001150 int OffsetStride = IsUnscaled ? getMemScale(FirstMI) : 1;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001151 bool IsNarrowStore = isNarrowStore(Opc);
Tim Northover3b0846e2014-05-24 12:50:23 +00001152
1153 // Track which registers have been modified and used between the first insn
1154 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001155 ModifiedRegs.reset();
1156 UsedRegs.reset();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001157
1158 // Remember any instructions that read/write memory between FirstMI and MI.
1159 SmallVector<MachineInstr *, 4> MemInsns;
1160
Tim Northover3b0846e2014-05-24 12:50:23 +00001161 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
1162 MachineInstr *MI = MBBI;
1163 // Skip DBG_VALUE instructions. Otherwise debug info can affect the
1164 // optimization by changing how far we scan.
1165 if (MI->isDebugValue())
1166 continue;
1167
1168 // Now that we know this is a real instruction, count it.
1169 ++Count;
1170
Renato Golin6274e522016-02-05 12:14:30 +00001171 bool CanMergeOpc = Opc == MI->getOpcode();
Chad Rosier18896c02016-02-04 16:01:40 +00001172 Flags.setSExtIdx(-1);
Renato Golin6274e522016-02-05 12:14:30 +00001173 if (!CanMergeOpc) {
1174 bool IsValidLdStrOpc;
1175 unsigned NonSExtOpc = getMatchingNonSExtOpcode(Opc, &IsValidLdStrOpc);
1176 assert(IsValidLdStrOpc &&
1177 "Given Opc should be a Load or Store with an immediate");
1178 // Opc will be the first instruction in the pair.
1179 Flags.setSExtIdx(NonSExtOpc == (unsigned)Opc ? 1 : 0);
1180 CanMergeOpc = NonSExtOpc == getMatchingNonSExtOpcode(MI->getOpcode());
1181 }
1182
1183 if (CanMergeOpc && getLdStOffsetOp(MI).isImm()) {
Chad Rosierc56a9132015-08-10 18:42:45 +00001184 assert(MI->mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001185 // If we've found another instruction with the same opcode, check to see
1186 // if the base and offset are compatible with our starting instruction.
1187 // These instructions all have scaled immediate operands, so we just
1188 // check for +1/-1. Make sure to check the new instruction offset is
1189 // actually an immediate and not a symbolic reference destined for
1190 // a relocation.
1191 //
1192 // Pairwise instructions have a 7-bit signed offset field. Single insns
1193 // have a 12-bit unsigned offset field. To be a valid combine, the
1194 // final offset must be in range.
Chad Rosierf77e9092015-08-06 15:50:12 +00001195 unsigned MIBaseReg = getLdStBaseOp(MI).getReg();
1196 int MIOffset = getLdStOffsetOp(MI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001197 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1198 (Offset + OffsetStride == MIOffset))) {
1199 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1200 // If this is a volatile load/store that otherwise matched, stop looking
1201 // as something is going on that we don't have enough information to
1202 // safely transform. Similarly, stop if we see a hint to avoid pairs.
1203 if (MI->hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1204 return E;
1205 // If the resultant immediate offset of merging these instructions
1206 // is out of range for a pairwise instruction, bail and keep looking.
Renato Golin6274e522016-02-05 12:14:30 +00001207 bool MIIsUnscaled = isUnscaledLdSt(MI);
Jun Bum Limc12c2792015-11-19 18:41:27 +00001208 bool IsNarrowLoad = isNarrowLoad(MI->getOpcode());
1209 if (!IsNarrowLoad &&
Renato Golin6274e522016-02-05 12:14:30 +00001210 !inBoundsForPair(MIIsUnscaled, MinOffset, OffsetStride)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001211 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001212 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001213 continue;
1214 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001215
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001216 if (IsNarrowLoad || IsNarrowStore) {
1217 // If the alignment requirements of the scaled wide load/store
1218 // instruction can't express the offset of the scaled narrow
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001219 // input, bail and keep looking.
1220 if (!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) {
1221 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1222 MemInsns.push_back(MI);
1223 continue;
1224 }
1225 } else {
1226 // If the alignment requirements of the paired (scaled) instruction
1227 // can't express the offset of the unscaled input, bail and keep
1228 // looking.
1229 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1230 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1231 MemInsns.push_back(MI);
1232 continue;
1233 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001234 }
1235 // If the destination register of the loads is the same register, bail
1236 // and keep looking. A load-pair instruction with both destination
1237 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001238 // For narrow stores, allow only when the stored value is the same
1239 // (i.e., WZR).
1240 if ((MayLoad && Reg == getLdStRegOp(MI).getReg()) ||
1241 (IsNarrowStore && Reg != getLdStRegOp(MI).getReg())) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001242 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
Chad Rosierc56a9132015-08-10 18:42:45 +00001243 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001244 continue;
1245 }
1246
1247 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001248 // the two instructions and none of the instructions between the second
1249 // and first alias with the second, we can combine the second into the
1250 // first.
Chad Rosierf77e9092015-08-06 15:50:12 +00001251 if (!ModifiedRegs[getLdStRegOp(MI).getReg()] &&
1252 !(MI->mayLoad() && UsedRegs[getLdStRegOp(MI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001253 !mayAlias(MI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001254 Flags.setMergeForward(false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001255 return MBBI;
1256 }
1257
1258 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001259 // between the two instructions and none of the instructions between the
1260 // first and the second alias with the first, we can combine the first
1261 // into the second.
Chad Rosierf77e9092015-08-06 15:50:12 +00001262 if (!ModifiedRegs[getLdStRegOp(FirstMI).getReg()] &&
Chad Rosier5f668e12015-09-03 14:19:43 +00001263 !(MayLoad && UsedRegs[getLdStRegOp(FirstMI).getReg()]) &&
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001264 !mayAlias(FirstMI, MemInsns, TII)) {
Chad Rosier96a18a92015-07-21 17:42:04 +00001265 Flags.setMergeForward(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001266 return MBBI;
1267 }
1268 // Unable to combine these instructions due to interference in between.
1269 // Keep looking.
1270 }
1271 }
1272
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001273 // If the instruction wasn't a matching load or store. Stop searching if we
1274 // encounter a call instruction that might modify memory.
1275 if (MI->isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001276 return E;
1277
1278 // Update modified / uses register lists.
1279 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1280
1281 // Otherwise, if the base register is modified, we have no match, so
1282 // return early.
1283 if (ModifiedRegs[BaseReg])
1284 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001285
1286 // Update list of instructions that read/write memory.
1287 if (MI->mayLoadOrStore())
1288 MemInsns.push_back(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001289 }
1290 return E;
1291}
1292
1293MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001294AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1295 MachineBasicBlock::iterator Update,
1296 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001297 assert((Update->getOpcode() == AArch64::ADDXri ||
1298 Update->getOpcode() == AArch64::SUBXri) &&
1299 "Unexpected base register update instruction to merge!");
1300 MachineBasicBlock::iterator NextI = I;
1301 // Return the instruction following the merged instruction, which is
1302 // the instruction following our unmerged load. Unless that's the add/sub
1303 // instruction we're merging, in which case it's the one after that.
1304 if (++NextI == Update)
1305 ++NextI;
1306
1307 int Value = Update->getOperand(2).getImm();
1308 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001309 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001310 if (Update->getOpcode() == AArch64::SUBXri)
1311 Value = -Value;
1312
Chad Rosier2dfd3542015-09-23 13:51:44 +00001313 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1314 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001315 MachineInstrBuilder MIB;
1316 if (!isPairedLdSt(I)) {
1317 // Non-paired instruction.
1318 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1319 .addOperand(getLdStRegOp(Update))
1320 .addOperand(getLdStRegOp(I))
1321 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001322 .addImm(Value)
1323 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001324 } else {
1325 // Paired instruction.
Chad Rosier32d4d372015-09-29 16:07:32 +00001326 int Scale = getMemScale(I);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001327 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
1328 .addOperand(getLdStRegOp(Update))
1329 .addOperand(getLdStRegOp(I, 0))
1330 .addOperand(getLdStRegOp(I, 1))
1331 .addOperand(getLdStBaseOp(I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001332 .addImm(Value / Scale)
1333 .setMemRefs(I->memoperands_begin(), I->memoperands_end());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001334 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001335 (void)MIB;
1336
Chad Rosier2dfd3542015-09-23 13:51:44 +00001337 if (IsPreIdx)
1338 DEBUG(dbgs() << "Creating pre-indexed load/store.");
1339 else
1340 DEBUG(dbgs() << "Creating post-indexed load/store.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001341 DEBUG(dbgs() << " Replacing instructions:\n ");
1342 DEBUG(I->print(dbgs()));
1343 DEBUG(dbgs() << " ");
1344 DEBUG(Update->print(dbgs()));
1345 DEBUG(dbgs() << " with instruction:\n ");
1346 DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1347 DEBUG(dbgs() << "\n");
1348
1349 // Erase the old instructions for the block.
1350 I->eraseFromParent();
1351 Update->eraseFromParent();
1352
1353 return NextI;
1354}
1355
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001356bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr *MemMI,
1357 MachineInstr *MI,
1358 unsigned BaseReg, int Offset) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001359 switch (MI->getOpcode()) {
1360 default:
1361 break;
1362 case AArch64::SUBXri:
1363 // Negate the offset for a SUB instruction.
1364 Offset *= -1;
1365 // FALLTHROUGH
1366 case AArch64::ADDXri:
1367 // Make sure it's a vanilla immediate operand, not a relocation or
1368 // anything else we can't handle.
1369 if (!MI->getOperand(2).isImm())
1370 break;
1371 // Watch out for 1 << 12 shifted value.
1372 if (AArch64_AM::getShiftValue(MI->getOperand(3).getImm()))
1373 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001374
1375 // The update instruction source and destination register must be the
1376 // same as the load/store base register.
1377 if (MI->getOperand(0).getReg() != BaseReg ||
1378 MI->getOperand(1).getReg() != BaseReg)
1379 break;
1380
1381 bool IsPairedInsn = isPairedLdSt(MemMI);
1382 int UpdateOffset = MI->getOperand(2).getImm();
1383 // For non-paired load/store instructions, the immediate must fit in a
1384 // signed 9-bit integer.
1385 if (!IsPairedInsn && (UpdateOffset > 255 || UpdateOffset < -256))
1386 break;
1387
1388 // For paired load/store instructions, the immediate must be a multiple of
1389 // the scaling factor. The scaled offset must also fit into a signed 7-bit
1390 // integer.
1391 if (IsPairedInsn) {
Chad Rosier32d4d372015-09-29 16:07:32 +00001392 int Scale = getMemScale(MemMI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001393 if (UpdateOffset % Scale != 0)
1394 break;
1395
1396 int ScaledOffset = UpdateOffset / Scale;
1397 if (ScaledOffset > 64 || ScaledOffset < -64)
1398 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00001399 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001400
1401 // If we have a non-zero Offset, we check that it matches the amount
1402 // we're adding to the register.
1403 if (!Offset || Offset == MI->getOperand(2).getImm())
1404 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001405 break;
1406 }
1407 return false;
1408}
1409
1410MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001411 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001412 MachineBasicBlock::iterator E = I->getParent()->end();
1413 MachineInstr *MemMI = I;
1414 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001415
Chad Rosierf77e9092015-08-06 15:50:12 +00001416 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001417 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001418
Chad Rosierb7c5b912015-10-01 13:43:05 +00001419 // Scan forward looking for post-index opportunities. Updating instructions
1420 // can't be formed if the memory instruction doesn't have the offset we're
1421 // looking for.
1422 if (MIUnscaledOffset != UnscaledOffset)
1423 return E;
1424
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001425 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001426 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001427 bool IsPairedInsn = isPairedLdSt(MemMI);
1428 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1429 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1430 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1431 return E;
1432 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001433
Tim Northover3b0846e2014-05-24 12:50:23 +00001434 // Track which registers have been modified and used between the first insn
1435 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001436 ModifiedRegs.reset();
1437 UsedRegs.reset();
Tim Northover3b0846e2014-05-24 12:50:23 +00001438 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001439 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001440 MachineInstr *MI = MBBI;
Chad Rosierb11c82d2016-01-19 21:27:05 +00001441 // Skip DBG_VALUE instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001442 if (MI->isDebugValue())
1443 continue;
1444
Chad Rosier35706ad2016-02-04 21:26:02 +00001445 // Now that we know this is a real instruction, count it.
1446 ++Count;
1447
Tim Northover3b0846e2014-05-24 12:50:23 +00001448 // If we found a match, return it.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001449 if (isMatchingUpdateInsn(I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001450 return MBBI;
1451
1452 // Update the status of what the instruction clobbered and used.
1453 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1454
1455 // Otherwise, if the base register is used or modified, we have no match, so
1456 // return early.
1457 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1458 return E;
1459 }
1460 return E;
1461}
1462
1463MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001464 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001465 MachineBasicBlock::iterator B = I->getParent()->begin();
1466 MachineBasicBlock::iterator E = I->getParent()->end();
1467 MachineInstr *MemMI = I;
1468 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001469
Chad Rosierf77e9092015-08-06 15:50:12 +00001470 unsigned BaseReg = getLdStBaseOp(MemMI).getReg();
1471 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001472
1473 // If the load/store is the first instruction in the block, there's obviously
1474 // not any matching update. Ditto if the memory offset isn't zero.
1475 if (MBBI == B || Offset != 0)
1476 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001477 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001478 // merge the update.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001479 bool IsPairedInsn = isPairedLdSt(MemMI);
1480 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1481 unsigned DestReg = getLdStRegOp(MemMI, i).getReg();
1482 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1483 return E;
1484 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001485
1486 // Track which registers have been modified and used between the first insn
1487 // (inclusive) and the second insn.
Chad Rosierbba881e2016-02-02 15:02:30 +00001488 ModifiedRegs.reset();
1489 UsedRegs.reset();
Geoff Berry173b14d2016-02-09 20:47:21 +00001490 unsigned Count = 0;
1491 do {
1492 --MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001493 MachineInstr *MI = MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001494
Geoff Berry173b14d2016-02-09 20:47:21 +00001495 // Don't count DBG_VALUE instructions towards the search limit.
1496 if (!MI->isDebugValue())
1497 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001498
Tim Northover3b0846e2014-05-24 12:50:23 +00001499 // If we found a match, return it.
Chad Rosier11c825f2015-09-30 19:44:40 +00001500 if (isMatchingUpdateInsn(I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001501 return MBBI;
1502
1503 // Update the status of what the instruction clobbered and used.
1504 trackRegDefsUses(MI, ModifiedRegs, UsedRegs, TRI);
1505
1506 // Otherwise, if the base register is used or modified, we have no match, so
1507 // return early.
1508 if (ModifiedRegs[BaseReg] || UsedRegs[BaseReg])
1509 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001510 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001511 return E;
1512}
1513
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001514bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1515 MachineBasicBlock::iterator &MBBI) {
1516 MachineInstr *MI = MBBI;
1517 // If this is a volatile load, don't mess with it.
1518 if (MI->hasOrderedMemoryRef())
1519 return false;
1520
1521 // Make sure this is a reg+imm.
1522 // FIXME: It is possible to extend it to handle reg+reg cases.
1523 if (!getLdStOffsetOp(MI).isImm())
1524 return false;
1525
Chad Rosier35706ad2016-02-04 21:26:02 +00001526 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001527 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001528 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001529 ++NumLoadsFromStoresPromoted;
1530 // Promote the load. Keeping the iterator straight is a
1531 // pain, so we let the merge routine tell us what the next instruction
1532 // is after it's done mucking about.
1533 MBBI = promoteLoadFromStore(MBBI, StoreI);
1534 return true;
1535 }
1536 return false;
1537}
1538
Chad Rosier24c46ad2016-02-09 18:10:20 +00001539bool AArch64LoadStoreOpt::isCandidateToMergeOrPair(MachineInstr *MI) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001540 // If this is a volatile load/store, don't mess with it.
1541 if (MI->hasOrderedMemoryRef())
1542 return false;
1543
1544 // Make sure this is a reg+imm (as opposed to an address reloc).
1545 if (!getLdStOffsetOp(MI).isImm())
1546 return false;
1547
Chad Rosiercc5d61f2016-02-09 20:44:41 +00001548 // Can't merge/pair if the instruction modifies the base register.
1549 // e.g., ldr x0, [x0]
1550 unsigned BaseReg = getLdStBaseOp(MI).getReg();
1551 if (MI->modifiesRegister(BaseReg, TRI))
1552 return false;
1553
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001554 // Check if this load/store has a hint to avoid pair formation.
1555 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
1556 if (TII->isLdStPairSuppressed(MI))
1557 return false;
1558
Chad Rosier24c46ad2016-02-09 18:10:20 +00001559 return true;
1560}
1561
1562// Find narrow loads that can be converted into a single wider load with
1563// bitfield extract instructions. Also merge adjacent zero stores into a wider
1564// store.
1565bool AArch64LoadStoreOpt::tryToMergeLdStInst(
1566 MachineBasicBlock::iterator &MBBI) {
1567 assert((isNarrowLoad(MBBI) || isNarrowStore(MBBI)) && "Expected narrow op.");
1568 MachineInstr *MI = MBBI;
1569 MachineBasicBlock::iterator E = MI->getParent()->end();
1570
1571 if (!isCandidateToMergeOrPair(MI))
1572 return false;
1573
Chad Rosierf7cd8ea2016-02-09 21:20:12 +00001574 // For narrow stores, find only the case where the stored value is WZR.
1575 if (isNarrowStore(MI) && getLdStRegOp(MI).getReg() != AArch64::WZR)
1576 return false;
1577
Chad Rosier24c46ad2016-02-09 18:10:20 +00001578 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001579 LdStPairFlags Flags;
Chad Rosierd7363db2016-02-09 19:09:22 +00001580 MachineBasicBlock::iterator MergeMI = findMatchingInsn(MBBI, Flags, LdStLimit);
1581 if (MergeMI != E) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001582 if (isNarrowLoad(MI)) {
1583 ++NumNarrowLoadsPromoted;
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001584 } else if (isNarrowStore(MI)) {
1585 ++NumZeroStoresPromoted;
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001586 }
Chad Rosier24c46ad2016-02-09 18:10:20 +00001587 // Keeping the iterator straight is a pain, so we let the merge routine tell
1588 // us what the next instruction is after it's done mucking about.
Chad Rosierd7363db2016-02-09 19:09:22 +00001589 MBBI = mergeNarrowInsns(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001590 return true;
1591 }
1592 return false;
1593}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001594
Chad Rosier24c46ad2016-02-09 18:10:20 +00001595// Find loads and stores that can be merged into a single load or store pair
1596// instruction.
1597bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
1598 MachineInstr *MI = MBBI;
1599 MachineBasicBlock::iterator E = MI->getParent()->end();
1600
1601 if (!isCandidateToMergeOrPair(MI))
1602 return false;
1603
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001604 // Early exit if the offset is not possible to match. (6 bits of positive
1605 // range, plus allow an extra one in case we find a later insn that matches
1606 // with Offset-1)
1607 bool IsUnscaled = isUnscaledLdSt(MI);
1608 int Offset = getLdStOffsetOp(MI).getImm();
1609 int OffsetStride = IsUnscaled ? getMemScale(MI) : 1;
1610 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1611 return false;
1612
Chad Rosier24c46ad2016-02-09 18:10:20 +00001613 // Look ahead up to LdStLimit instructions for a pairable instruction.
1614 LdStPairFlags Flags;
1615 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, Flags, LdStLimit);
1616 if (Paired != E) {
1617 ++NumPairCreated;
1618 if (isUnscaledLdSt(MI))
1619 ++NumUnscaledPairCreated;
1620 // Keeping the iterator straight is a pain, so we let the merge routine tell
1621 // us what the next instruction is after it's done mucking about.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001622 MBBI = mergePairedInsns(MBBI, Paired, Flags);
1623 return true;
1624 }
1625 return false;
1626}
1627
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001628bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
1629 bool enableNarrowLdOpt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001630 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001631 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001632 // 1) Find loads that directly read from stores and promote them by
1633 // replacing with mov instructions. If the store is wider than the load,
1634 // the load will be replaced with a bitfield extract.
1635 // e.g.,
1636 // str w1, [x0, #4]
1637 // ldrh w2, [x0, #6]
1638 // ; becomes
1639 // str w1, [x0, #4]
1640 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00001641 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001642 MBBI != E;) {
1643 MachineInstr *MI = MBBI;
1644 switch (MI->getOpcode()) {
1645 default:
1646 // Just move on to the next instruction.
1647 ++MBBI;
1648 break;
1649 // Scaled instructions.
1650 case AArch64::LDRBBui:
1651 case AArch64::LDRHHui:
1652 case AArch64::LDRWui:
1653 case AArch64::LDRXui:
1654 // Unscaled instructions.
1655 case AArch64::LDURBBi:
1656 case AArch64::LDURHHi:
1657 case AArch64::LDURWi:
1658 case AArch64::LDURXi: {
1659 if (tryToPromoteLoadFromStore(MBBI)) {
1660 Modified = true;
1661 break;
1662 }
1663 ++MBBI;
1664 break;
1665 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001666 }
1667 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001668 // 2) Find narrow loads that can be converted into a single wider load
1669 // with bitfield extract instructions.
1670 // e.g.,
1671 // ldrh w0, [x2]
1672 // ldrh w1, [x2, #2]
1673 // ; becomes
1674 // ldr w0, [x2]
1675 // ubfx w1, w0, #16, #16
1676 // and w0, w0, #ffff
Jun Bum Lim1de2d442016-02-05 20:02:03 +00001677 //
1678 // Also merge adjacent zero stores into a wider store.
1679 // e.g.,
1680 // strh wzr, [x0]
1681 // strh wzr, [x0, #2]
1682 // ; becomes
1683 // str wzr, [x0]
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001684 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001685 enableNarrowLdOpt && MBBI != E;) {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001686 MachineInstr *MI = MBBI;
1687 switch (MI->getOpcode()) {
1688 default:
1689 // Just move on to the next instruction.
1690 ++MBBI;
1691 break;
1692 // Scaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001693 case AArch64::LDRBBui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001694 case AArch64::LDRHHui:
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001695 case AArch64::LDRSBWui:
1696 case AArch64::LDRSHWui:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001697 case AArch64::STRBBui:
1698 case AArch64::STRHHui:
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001699 // Unscaled instructions.
Jun Bum Lim4c35cca2015-11-19 17:21:41 +00001700 case AArch64::LDURBBi:
1701 case AArch64::LDURHHi:
1702 case AArch64::LDURSBWi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001703 case AArch64::LDURSHWi:
1704 case AArch64::STURBBi:
1705 case AArch64::STURHHi: {
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001706 if (tryToMergeLdStInst(MBBI)) {
1707 Modified = true;
1708 break;
1709 }
1710 ++MBBI;
1711 break;
1712 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001713 }
1714 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001715 // 3) Find loads and stores that can be merged into a single load or store
1716 // pair instruction.
1717 // e.g.,
1718 // ldr x0, [x2]
1719 // ldr x1, [x2, #8]
1720 // ; becomes
1721 // ldp x0, x1, [x2]
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001722 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +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;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001730 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001731 case AArch64::STRSui:
1732 case AArch64::STRDui:
1733 case AArch64::STRQui:
1734 case AArch64::STRXui:
1735 case AArch64::STRWui:
1736 case AArch64::LDRSui:
1737 case AArch64::LDRDui:
1738 case AArch64::LDRQui:
1739 case AArch64::LDRXui:
1740 case AArch64::LDRWui:
Quentin Colombet29f55332015-01-24 01:25:54 +00001741 case AArch64::LDRSWui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001742 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001743 case AArch64::STURSi:
1744 case AArch64::STURDi:
1745 case AArch64::STURQi:
1746 case AArch64::STURWi:
1747 case AArch64::STURXi:
1748 case AArch64::LDURSi:
1749 case AArch64::LDURDi:
1750 case AArch64::LDURQi:
1751 case AArch64::LDURWi:
Quentin Colombet29f55332015-01-24 01:25:54 +00001752 case AArch64::LDURXi:
1753 case AArch64::LDURSWi: {
Chad Rosier24c46ad2016-02-09 18:10:20 +00001754 if (tryToPairLdStInst(MBBI)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001755 Modified = true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001756 break;
1757 }
1758 ++MBBI;
1759 break;
1760 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001761 }
1762 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001763 // 4) Find base register updates that can be merged into the load or store
1764 // as a base-reg writeback.
1765 // e.g.,
1766 // ldr x0, [x2]
1767 // add x2, x2, #4
1768 // ; becomes
1769 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00001770 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
1771 MBBI != E;) {
1772 MachineInstr *MI = MBBI;
1773 // Do update merging. It's simpler to keep this separate from the above
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001774 // switchs, though not strictly necessary.
Matthias Braunfa3872e2015-05-18 20:27:55 +00001775 unsigned Opc = MI->getOpcode();
Tim Northover3b0846e2014-05-24 12:50:23 +00001776 switch (Opc) {
1777 default:
1778 // Just move on to the next instruction.
1779 ++MBBI;
1780 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001781 // Scaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001782 case AArch64::STRSui:
1783 case AArch64::STRDui:
1784 case AArch64::STRQui:
1785 case AArch64::STRXui:
1786 case AArch64::STRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001787 case AArch64::STRHHui:
1788 case AArch64::STRBBui:
Tim Northover3b0846e2014-05-24 12:50:23 +00001789 case AArch64::LDRSui:
1790 case AArch64::LDRDui:
1791 case AArch64::LDRQui:
1792 case AArch64::LDRXui:
1793 case AArch64::LDRWui:
Chad Rosierdabe2532015-09-29 18:26:15 +00001794 case AArch64::LDRHHui:
1795 case AArch64::LDRBBui:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001796 // Unscaled instructions.
Tim Northover3b0846e2014-05-24 12:50:23 +00001797 case AArch64::STURSi:
1798 case AArch64::STURDi:
1799 case AArch64::STURQi:
1800 case AArch64::STURWi:
1801 case AArch64::STURXi:
1802 case AArch64::LDURSi:
1803 case AArch64::LDURDi:
1804 case AArch64::LDURQi:
1805 case AArch64::LDURWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001806 case AArch64::LDURXi:
1807 // Paired instructions.
1808 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +00001809 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001810 case AArch64::LDPDi:
1811 case AArch64::LDPQi:
1812 case AArch64::LDPWi:
1813 case AArch64::LDPXi:
1814 case AArch64::STPSi:
1815 case AArch64::STPDi:
1816 case AArch64::STPQi:
1817 case AArch64::STPWi:
1818 case AArch64::STPXi: {
Tim Northover3b0846e2014-05-24 12:50:23 +00001819 // Make sure this is a reg+imm (as opposed to an address reloc).
Chad Rosierf77e9092015-08-06 15:50:12 +00001820 if (!getLdStOffsetOp(MI).isImm()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001821 ++MBBI;
1822 break;
1823 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001824 // Look forward to try to form a post-index instruction. For example,
1825 // ldr x0, [x20]
1826 // add x20, x20, #32
1827 // merged into:
1828 // ldr x0, [x20], #32
Tim Northover3b0846e2014-05-24 12:50:23 +00001829 MachineBasicBlock::iterator Update =
Chad Rosier35706ad2016-02-04 21:26:02 +00001830 findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001831 if (Update != E) {
1832 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001833 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
Tim Northover3b0846e2014-05-24 12:50:23 +00001834 Modified = true;
1835 ++NumPostFolded;
1836 break;
1837 }
1838 // Don't know how to handle pre/post-index versions, so move to the next
1839 // instruction.
Chad Rosier22eb7102015-08-06 17:37:18 +00001840 if (isUnscaledLdSt(Opc)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001841 ++MBBI;
1842 break;
1843 }
1844
1845 // Look back to try to find a pre-index instruction. For example,
1846 // add x0, x0, #8
1847 // ldr x1, [x0]
1848 // merged into:
1849 // ldr x1, [x0, #8]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001850 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001851 if (Update != E) {
1852 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001853 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001854 Modified = true;
1855 ++NumPreFolded;
1856 break;
1857 }
Chad Rosier7a83d772015-10-01 13:09:44 +00001858 // The immediate in the load/store is scaled by the size of the memory
1859 // operation. The immediate in the add we're looking for,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001860 // however, is not, so adjust here.
Chad Rosier0b15e7c2015-10-01 13:33:31 +00001861 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * getMemScale(MI);
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001862
Tim Northover3b0846e2014-05-24 12:50:23 +00001863 // Look forward to try to find a post-index instruction. For example,
1864 // ldr x1, [x0, #64]
1865 // add x0, x0, #64
1866 // merged into:
1867 // ldr x1, [x0, #64]!
Chad Rosier35706ad2016-02-04 21:26:02 +00001868 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001869 if (Update != E) {
1870 // Merge the update into the ld/st.
Chad Rosier2dfd3542015-09-23 13:51:44 +00001871 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
Tim Northover3b0846e2014-05-24 12:50:23 +00001872 Modified = true;
1873 ++NumPreFolded;
1874 break;
1875 }
1876
1877 // Nothing found. Just move to the next instruction.
1878 ++MBBI;
1879 break;
1880 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001881 }
1882 }
1883
1884 return Modified;
1885}
1886
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001887bool AArch64LoadStoreOpt::enableNarrowLdMerge(MachineFunction &Fn) {
Jun Bum Limc12c2792015-11-19 18:41:27 +00001888 bool ProfitableArch = Subtarget->isCortexA57();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001889 // FIXME: The benefit from converting narrow loads into a wider load could be
1890 // microarchitectural as it assumes that a single load with two bitfield
1891 // extracts is cheaper than two narrow loads. Currently, this conversion is
1892 // enabled only in cortex-a57 on which performance benefits were verified.
Jun Bum Limc12c2792015-11-19 18:41:27 +00001893 return ProfitableArch && !Subtarget->requiresStrictAlign();
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001894}
1895
Tim Northover3b0846e2014-05-24 12:50:23 +00001896bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Oliver Stannardd414c992015-11-10 11:04:18 +00001897 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
1898 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
1899 TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001900
Chad Rosierbba881e2016-02-02 15:02:30 +00001901 // Resize the modified and used register bitfield trackers. We do this once
1902 // per function and then clear the bitfield each time we optimize a load or
1903 // store.
1904 ModifiedRegs.resize(TRI->getNumRegs());
1905 UsedRegs.resize(TRI->getNumRegs());
1906
Tim Northover3b0846e2014-05-24 12:50:23 +00001907 bool Modified = false;
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001908 bool enableNarrowLdOpt = enableNarrowLdMerge(Fn);
Tim Northover3b0846e2014-05-24 12:50:23 +00001909 for (auto &MBB : Fn)
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001910 Modified |= optimizeBlock(MBB, enableNarrowLdOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +00001911
1912 return Modified;
1913}
1914
1915// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep
1916// loads and stores near one another?
1917
Chad Rosier3f8b09d2016-02-09 19:42:19 +00001918// FIXME: When pairing store instructions it's very possible for this pass to
1919// hoist a store with a KILL marker above another use (without a KILL marker).
1920// The resulting IR is invalid, but nothing uses the KILL markers after this
1921// pass, so it's never caused a problem in practice.
1922
Chad Rosier43f5c842015-08-05 12:40:13 +00001923/// createAArch64LoadStoreOptimizationPass - returns an instance of the
1924/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00001925FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
1926 return new AArch64LoadStoreOpt();
1927}