blob: d24e6d63f15736c60373b55d044022fcbebc832a [file] [log] [blame]
Eugene Zelenko96d933d2017-07-25 23:51:02 +00001//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that performs load / store related peephole
10// optimizations. This pass should be run after register allocation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64InstrInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000015#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "MCTargetDesc/AArch64AddressingModes.h"
17#include "llvm/ADT/BitVector.h"
Chad Rosierce8e5ab2015-05-21 21:36:46 +000018#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000020#include "llvm/ADT/StringRef.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/ADT/iterator_range.h"
Eugene Zelenko96d933d2017-07-25 23:51:02 +000022#include "llvm/Analysis/AliasAnalysis.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000023#include "llvm/CodeGen/MachineBasicBlock.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000024#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstr.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000028#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000029#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000030#include "llvm/IR/DebugLoc.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/Pass.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Florian Hahn17554b82019-12-11 09:59:18 +000035#include "llvm/Support/DebugCounter.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000036#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11f69072017-01-25 00:29:26 +000038#include <cassert>
39#include <cstdint>
Florian Hahn17554b82019-12-11 09:59:18 +000040#include <functional>
Eugene Zelenko11f69072017-01-25 00:29:26 +000041#include <iterator>
42#include <limits>
43
Tim Northover3b0846e2014-05-24 12:50:23 +000044using namespace llvm;
45
46#define DEBUG_TYPE "aarch64-ldst-opt"
47
Tim Northover3b0846e2014-05-24 12:50:23 +000048STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
49STATISTIC(NumPostFolded, "Number of post-index updates folded");
50STATISTIC(NumPreFolded, "Number of pre-index updates folded");
51STATISTIC(NumUnscaledPairCreated,
52 "Number of load/store from unscaled generated");
Jun Bum Lim80ec0d32015-11-20 21:14:07 +000053STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +000054STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
Tim Northover3b0846e2014-05-24 12:50:23 +000055
Florian Hahn17554b82019-12-11 09:59:18 +000056DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
57 "Controls which pairs are considered for renaming");
58
Chad Rosier35706ad2016-02-04 21:26:02 +000059// The LdStLimit limits how far we search for load/store pairs.
60static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +000061 cl::init(20), cl::Hidden);
Tim Northover3b0846e2014-05-24 12:50:23 +000062
Chad Rosier35706ad2016-02-04 21:26:02 +000063// The UpdateLimit limits how far we search for update instructions when we form
64// pre-/post-index instructions.
65static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
66 cl::Hidden);
67
Chad Rosier96530b32015-08-05 13:44:51 +000068#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
69
Tim Northover3b0846e2014-05-24 12:50:23 +000070namespace {
Chad Rosier96a18a92015-07-21 17:42:04 +000071
Eugene Zelenko96d933d2017-07-25 23:51:02 +000072using LdStPairFlags = struct LdStPairFlags {
Chad Rosier96a18a92015-07-21 17:42:04 +000073 // If a matching instruction is found, MergeForward is set to true if the
74 // merge is to remove the first instruction and replace the second with
75 // a pair-wise insn, and false if the reverse is true.
Eugene Zelenko11f69072017-01-25 00:29:26 +000076 bool MergeForward = false;
Chad Rosier96a18a92015-07-21 17:42:04 +000077
78 // SExtIdx gives the index of the result of the load pair that must be
79 // extended. The value of SExtIdx assumes that the paired load produces the
80 // value in this order: (I, returned iterator), i.e., -1 means no value has
81 // to be extended, 0 means I, and 1 means the returned iterator.
Eugene Zelenko11f69072017-01-25 00:29:26 +000082 int SExtIdx = -1;
Chad Rosier96a18a92015-07-21 17:42:04 +000083
Florian Hahn17554b82019-12-11 09:59:18 +000084 // If not none, RenameReg can be used to rename the result register of the
85 // first store in a pair. Currently this only works when merging stores
86 // forward.
87 Optional<MCPhysReg> RenameReg = None;
88
Eugene Zelenko11f69072017-01-25 00:29:26 +000089 LdStPairFlags() = default;
Chad Rosier96a18a92015-07-21 17:42:04 +000090
91 void setMergeForward(bool V = true) { MergeForward = V; }
92 bool getMergeForward() const { return MergeForward; }
93
94 void setSExtIdx(int V) { SExtIdx = V; }
95 int getSExtIdx() const { return SExtIdx; }
Florian Hahn17554b82019-12-11 09:59:18 +000096
97 void setRenameReg(MCPhysReg R) { RenameReg = R; }
98 void clearRenameReg() { RenameReg = None; }
99 Optional<MCPhysReg> getRenameReg() const { return RenameReg; }
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000100};
Chad Rosier96a18a92015-07-21 17:42:04 +0000101
Tim Northover3b0846e2014-05-24 12:50:23 +0000102struct AArch64LoadStoreOpt : public MachineFunctionPass {
103 static char ID;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000104
Jun Bum Lim22fe15e2015-11-06 16:27:47 +0000105 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
Chad Rosier96530b32015-08-05 13:44:51 +0000106 initializeAArch64LoadStoreOptPass(*PassRegistry::getPassRegistry());
107 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000108
Chad Rosiera69dcb62017-03-17 14:19:55 +0000109 AliasAnalysis *AA;
Tim Northover3b0846e2014-05-24 12:50:23 +0000110 const AArch64InstrInfo *TII;
111 const TargetRegisterInfo *TRI;
Oliver Stannardd414c992015-11-10 11:04:18 +0000112 const AArch64Subtarget *Subtarget;
Tim Northover3b0846e2014-05-24 12:50:23 +0000113
Jun Bum Lim47aece12018-04-27 18:44:37 +0000114 // Track which register units have been modified and used.
115 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
Florian Hahn17554b82019-12-11 09:59:18 +0000116 LiveRegUnits DefinedInBB;
Chad Rosierbba881e2016-02-02 15:02:30 +0000117
Eugene Zelenko96d933d2017-07-25 23:51:02 +0000118 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiera69dcb62017-03-17 14:19:55 +0000119 AU.addRequired<AAResultsWrapperPass>();
120 MachineFunctionPass::getAnalysisUsage(AU);
121 }
122
Tim Northover3b0846e2014-05-24 12:50:23 +0000123 // Scan the instructions looking for a load/store that can be combined
124 // with the current instruction into a load/store pair.
125 // Return the matching instruction if one is found, else MBB->end().
Tim Northover3b0846e2014-05-24 12:50:23 +0000126 MachineBasicBlock::iterator findMatchingInsn(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000127 LdStPairFlags &Flags,
Jun Bum Limcf974432016-03-31 14:47:24 +0000128 unsigned Limit,
129 bool FindNarrowMerge);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000130
131 // Scan the instructions looking for a store that writes to the address from
132 // which the current load instruction reads. Return true if one is found.
133 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
134 MachineBasicBlock::iterator &StoreI);
135
Chad Rosierd6daac42016-11-07 15:27:22 +0000136 // Merge the two instructions indicated into a wider narrow store instruction.
Chad Rosierb5933d72016-02-09 19:02:12 +0000137 MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000138 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
139 MachineBasicBlock::iterator MergeMI,
140 const LdStPairFlags &Flags);
Chad Rosierb5933d72016-02-09 19:02:12 +0000141
Tim Northover3b0846e2014-05-24 12:50:23 +0000142 // Merge the two instructions indicated into a single pair-wise instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 MachineBasicBlock::iterator
144 mergePairedInsns(MachineBasicBlock::iterator I,
Chad Rosier96a18a92015-07-21 17:42:04 +0000145 MachineBasicBlock::iterator Paired,
Chad Rosierfe5399f2015-07-21 17:47:56 +0000146 const LdStPairFlags &Flags);
Tim Northover3b0846e2014-05-24 12:50:23 +0000147
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000148 // Promote the load that reads directly from the address stored to.
149 MachineBasicBlock::iterator
150 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
151 MachineBasicBlock::iterator StoreI);
152
Tim Northover3b0846e2014-05-24 12:50:23 +0000153 // Scan the instruction list to find a base register update that can
154 // be combined with the current instruction (a load or store) using
155 // pre or post indexed addressing with writeback. Scan forwards.
156 MachineBasicBlock::iterator
Chad Rosier234bf6f2016-01-18 21:56:40 +0000157 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
Chad Rosier35706ad2016-02-04 21:26:02 +0000158 int UnscaledOffset, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000159
160 // Scan the instruction list to find a base register update that can
161 // be combined with the current instruction (a load or store) using
162 // pre or post indexed addressing with writeback. Scan backwards.
163 MachineBasicBlock::iterator
Chad Rosier35706ad2016-02-04 21:26:02 +0000164 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +0000165
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000166 // Find an instruction that updates the base register of the ld/st
167 // instruction.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000168 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000169 unsigned BaseReg, int Offset);
170
Chad Rosier2dfd3542015-09-23 13:51:44 +0000171 // Merge a pre- or post-index base register update into a ld/st instruction.
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +0000173 mergeUpdateInsn(MachineBasicBlock::iterator I,
174 MachineBasicBlock::iterator Update, bool IsPreIdx);
Tim Northover3b0846e2014-05-24 12:50:23 +0000175
Chad Rosierd6daac42016-11-07 15:27:22 +0000176 // Find and merge zero store instructions.
177 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000178
Chad Rosier24c46ad2016-02-09 18:10:20 +0000179 // Find and pair ldr/str instructions.
180 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
181
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000182 // Find and promote load instructions which read directly from store.
183 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
184
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000185 // Find and merge a base register updates before or after a ld/st instruction.
186 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
187
Chad Rosierd6daac42016-11-07 15:27:22 +0000188 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
Tim Northover3b0846e2014-05-24 12:50:23 +0000189
190 bool runOnMachineFunction(MachineFunction &Fn) override;
191
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000192 MachineFunctionProperties getRequiredProperties() const override {
193 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000194 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000195 }
196
Mehdi Amini117296c2016-10-01 02:56:57 +0000197 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000198};
Eugene Zelenko11f69072017-01-25 00:29:26 +0000199
Tim Northover3b0846e2014-05-24 12:50:23 +0000200char AArch64LoadStoreOpt::ID = 0;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000201
202} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000203
Chad Rosier96530b32015-08-05 13:44:51 +0000204INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
205 AARCH64_LOAD_STORE_OPT_NAME, false, false)
206
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000207static bool isNarrowStore(unsigned Opc) {
208 switch (Opc) {
209 default:
210 return false;
211 case AArch64::STRBBui:
212 case AArch64::STURBBi:
213 case AArch64::STRHHui:
214 case AArch64::STURHHi:
215 return true;
216 }
217}
218
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000219// These instruction set memory tag and either keep memory contents unchanged or
220// set it to zero, ignoring the address part of the source register.
221static bool isTagStore(const MachineInstr &MI) {
222 switch (MI.getOpcode()) {
223 default:
224 return false;
225 case AArch64::STGOffset:
226 case AArch64::STZGOffset:
227 case AArch64::ST2GOffset:
228 case AArch64::STZ2GOffset:
229 return true;
230 }
231}
232
Quentin Colombet66b61632015-03-06 22:42:10 +0000233static unsigned getMatchingNonSExtOpcode(unsigned Opc,
234 bool *IsValidLdStrOpc = nullptr) {
235 if (IsValidLdStrOpc)
236 *IsValidLdStrOpc = true;
237 switch (Opc) {
238 default:
239 if (IsValidLdStrOpc)
240 *IsValidLdStrOpc = false;
Eugene Zelenko11f69072017-01-25 00:29:26 +0000241 return std::numeric_limits<unsigned>::max();
Quentin Colombet66b61632015-03-06 22:42:10 +0000242 case AArch64::STRDui:
243 case AArch64::STURDi:
244 case AArch64::STRQui:
245 case AArch64::STURQi:
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000246 case AArch64::STRBBui:
247 case AArch64::STURBBi:
248 case AArch64::STRHHui:
249 case AArch64::STURHHi:
Quentin Colombet66b61632015-03-06 22:42:10 +0000250 case AArch64::STRWui:
251 case AArch64::STURWi:
252 case AArch64::STRXui:
253 case AArch64::STURXi:
254 case AArch64::LDRDui:
255 case AArch64::LDURDi:
256 case AArch64::LDRQui:
257 case AArch64::LDURQi:
258 case AArch64::LDRWui:
259 case AArch64::LDURWi:
260 case AArch64::LDRXui:
261 case AArch64::LDURXi:
262 case AArch64::STRSui:
263 case AArch64::STURSi:
264 case AArch64::LDRSui:
265 case AArch64::LDURSi:
266 return Opc;
267 case AArch64::LDRSWui:
268 return AArch64::LDRWui;
269 case AArch64::LDURSWi:
270 return AArch64::LDURWi;
271 }
272}
273
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000274static unsigned getMatchingWideOpcode(unsigned Opc) {
275 switch (Opc) {
276 default:
277 llvm_unreachable("Opcode has no wide equivalent!");
278 case AArch64::STRBBui:
279 return AArch64::STRHHui;
280 case AArch64::STRHHui:
281 return AArch64::STRWui;
282 case AArch64::STURBBi:
283 return AArch64::STURHHi;
284 case AArch64::STURHHi:
285 return AArch64::STURWi;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000286 case AArch64::STURWi:
287 return AArch64::STURXi;
288 case AArch64::STRWui:
289 return AArch64::STRXui;
Jun Bum Lim1de2d442016-02-05 20:02:03 +0000290 }
291}
292
Tim Northover3b0846e2014-05-24 12:50:23 +0000293static unsigned getMatchingPairOpcode(unsigned Opc) {
294 switch (Opc) {
295 default:
296 llvm_unreachable("Opcode has no pairwise equivalent!");
297 case AArch64::STRSui:
298 case AArch64::STURSi:
299 return AArch64::STPSi;
300 case AArch64::STRDui:
301 case AArch64::STURDi:
302 return AArch64::STPDi;
303 case AArch64::STRQui:
304 case AArch64::STURQi:
305 return AArch64::STPQi;
306 case AArch64::STRWui:
307 case AArch64::STURWi:
308 return AArch64::STPWi;
309 case AArch64::STRXui:
310 case AArch64::STURXi:
311 return AArch64::STPXi;
312 case AArch64::LDRSui:
313 case AArch64::LDURSi:
314 return AArch64::LDPSi;
315 case AArch64::LDRDui:
316 case AArch64::LDURDi:
317 return AArch64::LDPDi;
318 case AArch64::LDRQui:
319 case AArch64::LDURQi:
320 return AArch64::LDPQi;
321 case AArch64::LDRWui:
322 case AArch64::LDURWi:
323 return AArch64::LDPWi;
324 case AArch64::LDRXui:
325 case AArch64::LDURXi:
326 return AArch64::LDPXi;
Quentin Colombet29f55332015-01-24 01:25:54 +0000327 case AArch64::LDRSWui:
328 case AArch64::LDURSWi:
329 return AArch64::LDPSWi;
Tim Northover3b0846e2014-05-24 12:50:23 +0000330 }
331}
332
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000333static unsigned isMatchingStore(MachineInstr &LoadInst,
334 MachineInstr &StoreInst) {
335 unsigned LdOpc = LoadInst.getOpcode();
336 unsigned StOpc = StoreInst.getOpcode();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000337 switch (LdOpc) {
338 default:
339 llvm_unreachable("Unsupported load instruction!");
340 case AArch64::LDRBBui:
341 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
342 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
343 case AArch64::LDURBBi:
344 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
345 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
346 case AArch64::LDRHHui:
347 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
348 StOpc == AArch64::STRXui;
349 case AArch64::LDURHHi:
350 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
351 StOpc == AArch64::STURXi;
352 case AArch64::LDRWui:
353 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
354 case AArch64::LDURWi:
355 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
356 case AArch64::LDRXui:
357 return StOpc == AArch64::STRXui;
358 case AArch64::LDURXi:
359 return StOpc == AArch64::STURXi;
360 }
361}
362
Tim Northover3b0846e2014-05-24 12:50:23 +0000363static unsigned getPreIndexedOpcode(unsigned Opc) {
Chad Rosier14fc82a2017-08-04 16:44:06 +0000364 // FIXME: We don't currently support creating pre-indexed loads/stores when
365 // the load or store is the unscaled version. If we decide to perform such an
366 // optimization in the future the cases for the unscaled loads/stores will
367 // need to be added here.
Tim Northover3b0846e2014-05-24 12:50:23 +0000368 switch (Opc) {
369 default:
370 llvm_unreachable("Opcode has no pre-indexed equivalent!");
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000371 case AArch64::STRSui:
372 return AArch64::STRSpre;
373 case AArch64::STRDui:
374 return AArch64::STRDpre;
375 case AArch64::STRQui:
376 return AArch64::STRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000377 case AArch64::STRBBui:
378 return AArch64::STRBBpre;
379 case AArch64::STRHHui:
380 return AArch64::STRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000381 case AArch64::STRWui:
382 return AArch64::STRWpre;
383 case AArch64::STRXui:
384 return AArch64::STRXpre;
385 case AArch64::LDRSui:
386 return AArch64::LDRSpre;
387 case AArch64::LDRDui:
388 return AArch64::LDRDpre;
389 case AArch64::LDRQui:
390 return AArch64::LDRQpre;
Chad Rosierdabe2532015-09-29 18:26:15 +0000391 case AArch64::LDRBBui:
392 return AArch64::LDRBBpre;
393 case AArch64::LDRHHui:
394 return AArch64::LDRHHpre;
Tilmann Scheller5d8d72c2014-06-04 12:40:35 +0000395 case AArch64::LDRWui:
396 return AArch64::LDRWpre;
397 case AArch64::LDRXui:
398 return AArch64::LDRXpre;
Quentin Colombet29f55332015-01-24 01:25:54 +0000399 case AArch64::LDRSWui:
400 return AArch64::LDRSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000401 case AArch64::LDPSi:
402 return AArch64::LDPSpre;
Chad Rosier43150122015-09-29 20:39:55 +0000403 case AArch64::LDPSWi:
404 return AArch64::LDPSWpre;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000405 case AArch64::LDPDi:
406 return AArch64::LDPDpre;
407 case AArch64::LDPQi:
408 return AArch64::LDPQpre;
409 case AArch64::LDPWi:
410 return AArch64::LDPWpre;
411 case AArch64::LDPXi:
412 return AArch64::LDPXpre;
413 case AArch64::STPSi:
414 return AArch64::STPSpre;
415 case AArch64::STPDi:
416 return AArch64::STPDpre;
417 case AArch64::STPQi:
418 return AArch64::STPQpre;
419 case AArch64::STPWi:
420 return AArch64::STPWpre;
421 case AArch64::STPXi:
422 return AArch64::STPXpre;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000423 case AArch64::STGOffset:
424 return AArch64::STGPreIndex;
425 case AArch64::STZGOffset:
426 return AArch64::STZGPreIndex;
427 case AArch64::ST2GOffset:
428 return AArch64::ST2GPreIndex;
429 case AArch64::STZ2GOffset:
430 return AArch64::STZ2GPreIndex;
431 case AArch64::STGPi:
432 return AArch64::STGPpre;
Tim Northover3b0846e2014-05-24 12:50:23 +0000433 }
434}
435
436static unsigned getPostIndexedOpcode(unsigned Opc) {
437 switch (Opc) {
438 default:
439 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
440 case AArch64::STRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000441 case AArch64::STURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000442 return AArch64::STRSpost;
443 case AArch64::STRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000444 case AArch64::STURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000445 return AArch64::STRDpost;
446 case AArch64::STRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000447 case AArch64::STURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000448 return AArch64::STRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000449 case AArch64::STRBBui:
450 return AArch64::STRBBpost;
451 case AArch64::STRHHui:
452 return AArch64::STRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 case AArch64::STRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000454 case AArch64::STURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000455 return AArch64::STRWpost;
456 case AArch64::STRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000457 case AArch64::STURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000458 return AArch64::STRXpost;
459 case AArch64::LDRSui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000460 case AArch64::LDURSi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000461 return AArch64::LDRSpost;
462 case AArch64::LDRDui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000463 case AArch64::LDURDi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000464 return AArch64::LDRDpost;
465 case AArch64::LDRQui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000466 case AArch64::LDURQi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000467 return AArch64::LDRQpost;
Chad Rosierdabe2532015-09-29 18:26:15 +0000468 case AArch64::LDRBBui:
469 return AArch64::LDRBBpost;
470 case AArch64::LDRHHui:
471 return AArch64::LDRHHpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000472 case AArch64::LDRWui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000473 case AArch64::LDURWi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000474 return AArch64::LDRWpost;
475 case AArch64::LDRXui:
Chad Rosier14fc82a2017-08-04 16:44:06 +0000476 case AArch64::LDURXi:
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 return AArch64::LDRXpost;
Quentin Colombet29f55332015-01-24 01:25:54 +0000478 case AArch64::LDRSWui:
479 return AArch64::LDRSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000480 case AArch64::LDPSi:
481 return AArch64::LDPSpost;
Chad Rosier43150122015-09-29 20:39:55 +0000482 case AArch64::LDPSWi:
483 return AArch64::LDPSWpost;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000484 case AArch64::LDPDi:
485 return AArch64::LDPDpost;
486 case AArch64::LDPQi:
487 return AArch64::LDPQpost;
488 case AArch64::LDPWi:
489 return AArch64::LDPWpost;
490 case AArch64::LDPXi:
491 return AArch64::LDPXpost;
492 case AArch64::STPSi:
493 return AArch64::STPSpost;
494 case AArch64::STPDi:
495 return AArch64::STPDpost;
496 case AArch64::STPQi:
497 return AArch64::STPQpost;
498 case AArch64::STPWi:
499 return AArch64::STPWpost;
500 case AArch64::STPXi:
501 return AArch64::STPXpost;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000502 case AArch64::STGOffset:
503 return AArch64::STGPostIndex;
504 case AArch64::STZGOffset:
505 return AArch64::STZGPostIndex;
506 case AArch64::ST2GOffset:
507 return AArch64::ST2GPostIndex;
508 case AArch64::STZ2GOffset:
509 return AArch64::STZ2GPostIndex;
510 case AArch64::STGPi:
511 return AArch64::STGPpost;
Tim Northover3b0846e2014-05-24 12:50:23 +0000512 }
513}
514
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000515static bool isPairedLdSt(const MachineInstr &MI) {
516 switch (MI.getOpcode()) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000517 default:
518 return false;
519 case AArch64::LDPSi:
Chad Rosier43150122015-09-29 20:39:55 +0000520 case AArch64::LDPSWi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000521 case AArch64::LDPDi:
522 case AArch64::LDPQi:
523 case AArch64::LDPWi:
524 case AArch64::LDPXi:
525 case AArch64::STPSi:
526 case AArch64::STPDi:
527 case AArch64::STPQi:
528 case AArch64::STPWi:
529 case AArch64::STPXi:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000530 case AArch64::STGPi:
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000531 return true;
532 }
533}
534
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000535// Returns the scale and offset range of pre/post indexed variants of MI.
536static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
537 int &MinOffset, int &MaxOffset) {
538 bool IsPaired = isPairedLdSt(MI);
539 bool IsTagStore = isTagStore(MI);
540 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
541 // as in the "unsigned offset" variant.
542 // All other pre/post indexed ldst instructions are unscaled.
Jay Foad97ca7c22019-12-11 10:29:23 +0000543 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000544
545 if (IsPaired) {
546 MinOffset = -64;
547 MaxOffset = 63;
548 } else {
549 MinOffset = -256;
550 MaxOffset = 255;
551 }
552}
553
Florian Hahn17554b82019-12-11 09:59:18 +0000554static MachineOperand &getLdStRegOp(MachineInstr &MI,
555 unsigned PairedRegOp = 0) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000556 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
557 unsigned Idx = isPairedLdSt(MI) ? PairedRegOp : 0;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000558 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000559}
560
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000561static const MachineOperand &getLdStBaseOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000562 unsigned Idx = isPairedLdSt(MI) ? 2 : 1;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000563 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000564}
565
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000566static const MachineOperand &getLdStOffsetOp(const MachineInstr &MI) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +0000567 unsigned Idx = isPairedLdSt(MI) ? 3 : 2;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000568 return MI.getOperand(Idx);
Chad Rosierf77e9092015-08-06 15:50:12 +0000569}
570
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000571static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst,
572 MachineInstr &StoreInst,
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000573 const AArch64InstrInfo *TII) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000574 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000575 int LoadSize = TII->getMemScale(LoadInst);
576 int StoreSize = TII->getMemScale(StoreInst);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000577 int UnscaledStOffset = TII->isUnscaledLdSt(StoreInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000578 ? getLdStOffsetOp(StoreInst).getImm()
579 : getLdStOffsetOp(StoreInst).getImm() * StoreSize;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000580 int UnscaledLdOffset = TII->isUnscaledLdSt(LoadInst)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +0000581 ? getLdStOffsetOp(LoadInst).getImm()
582 : getLdStOffsetOp(LoadInst).getImm() * LoadSize;
583 return (UnscaledStOffset <= UnscaledLdOffset) &&
584 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
585}
586
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000587static bool isPromotableZeroStoreInst(MachineInstr &MI) {
Chad Rosierd6daac42016-11-07 15:27:22 +0000588 unsigned Opc = MI.getOpcode();
589 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
590 isNarrowStore(Opc)) &&
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000591 getLdStRegOp(MI).getReg() == AArch64::WZR;
592}
593
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000594static bool isPromotableLoadFromStore(MachineInstr &MI) {
595 switch (MI.getOpcode()) {
596 default:
597 return false;
598 // Scaled instructions.
599 case AArch64::LDRBBui:
600 case AArch64::LDRHHui:
601 case AArch64::LDRWui:
602 case AArch64::LDRXui:
603 // Unscaled instructions.
604 case AArch64::LDURBBi:
605 case AArch64::LDURHHi:
606 case AArch64::LDURWi:
607 case AArch64::LDURXi:
608 return true;
609 }
610}
611
612static bool isMergeableLdStUpdate(MachineInstr &MI) {
613 unsigned Opc = MI.getOpcode();
614 switch (Opc) {
615 default:
616 return false;
617 // Scaled instructions.
618 case AArch64::STRSui:
619 case AArch64::STRDui:
620 case AArch64::STRQui:
621 case AArch64::STRXui:
622 case AArch64::STRWui:
623 case AArch64::STRHHui:
624 case AArch64::STRBBui:
625 case AArch64::LDRSui:
626 case AArch64::LDRDui:
627 case AArch64::LDRQui:
628 case AArch64::LDRXui:
629 case AArch64::LDRWui:
630 case AArch64::LDRHHui:
631 case AArch64::LDRBBui:
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +0000632 case AArch64::STGOffset:
633 case AArch64::STZGOffset:
634 case AArch64::ST2GOffset:
635 case AArch64::STZ2GOffset:
636 case AArch64::STGPi:
Evandro Menezes5ba804b2017-11-15 21:06:22 +0000637 // Unscaled instructions.
638 case AArch64::STURSi:
639 case AArch64::STURDi:
640 case AArch64::STURQi:
641 case AArch64::STURWi:
642 case AArch64::STURXi:
643 case AArch64::LDURSi:
644 case AArch64::LDURDi:
645 case AArch64::LDURQi:
646 case AArch64::LDURWi:
647 case AArch64::LDURXi:
648 // Paired instructions.
649 case AArch64::LDPSi:
650 case AArch64::LDPSWi:
651 case AArch64::LDPDi:
652 case AArch64::LDPQi:
653 case AArch64::LDPWi:
654 case AArch64::LDPXi:
655 case AArch64::STPSi:
656 case AArch64::STPDi:
657 case AArch64::STPQi:
658 case AArch64::STPWi:
659 case AArch64::STPXi:
660 // Make sure this is a reg+imm (as opposed to an address reloc).
661 if (!getLdStOffsetOp(MI).isImm())
662 return false;
663
664 return true;
665 }
666}
667
Tim Northover3b0846e2014-05-24 12:50:23 +0000668MachineBasicBlock::iterator
Chad Rosierd6daac42016-11-07 15:27:22 +0000669AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
670 MachineBasicBlock::iterator MergeMI,
671 const LdStPairFlags &Flags) {
672 assert(isPromotableZeroStoreInst(*I) && isPromotableZeroStoreInst(*MergeMI) &&
673 "Expected promotable zero stores.");
674
Tim Northover3b0846e2014-05-24 12:50:23 +0000675 MachineBasicBlock::iterator NextI = I;
676 ++NextI;
677 // If NextI is the second of the two instructions to be merged, we need
678 // to skip one further. Either way we merge will invalidate the iterator,
679 // and we don't need to scan the new instruction, as it's a pairwise
680 // instruction, which we're not considering for further action anyway.
Chad Rosierd7363db2016-02-09 19:09:22 +0000681 if (NextI == MergeMI)
Tim Northover3b0846e2014-05-24 12:50:23 +0000682 ++NextI;
683
Chad Rosierb5933d72016-02-09 19:02:12 +0000684 unsigned Opc = I->getOpcode();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000685 bool IsScaled = !TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000686 int OffsetStride = IsScaled ? 1 : TII->getMemScale(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000687
Chad Rosier96a18a92015-07-21 17:42:04 +0000688 bool MergeForward = Flags.getMergeForward();
Tim Northover3b0846e2014-05-24 12:50:23 +0000689 // Insert our new paired instruction after whichever of the paired
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000690 // instructions MergeForward indicates.
Chad Rosierd7363db2016-02-09 19:09:22 +0000691 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
Tilmann Scheller4aad3bd2014-06-04 12:36:28 +0000692 // Also based on MergeForward is from where we copy the base register operand
Tim Northover3b0846e2014-05-24 12:50:23 +0000693 // so we get the flags compatible with the input code.
Chad Rosierf77e9092015-08-06 15:50:12 +0000694 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000695 MergeForward ? getLdStBaseOp(*MergeMI) : getLdStBaseOp(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000696
697 // Which register is Rt and which is Rt2 depends on the offset order.
Davide Italiano5df60662016-11-07 19:11:25 +0000698 MachineInstr *RtMI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000699 if (getLdStOffsetOp(*I).getImm() ==
Davide Italiano5df60662016-11-07 19:11:25 +0000700 getLdStOffsetOp(*MergeMI).getImm() + OffsetStride)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000701 RtMI = &*MergeMI;
Davide Italiano5df60662016-11-07 19:11:25 +0000702 else
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000703 RtMI = &*I;
Jun Bum Limc9879ec2015-10-27 19:16:03 +0000704
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000705 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier11eedc92016-02-09 19:17:18 +0000706 // Change the scaled offset from small to large type.
707 if (IsScaled) {
708 assert(((OffsetImm & 1) == 0) && "Unexpected offset to merge");
709 OffsetImm /= 2;
710 }
711
Chad Rosierd6daac42016-11-07 15:27:22 +0000712 // Construct the new instruction.
Chad Rosierc46ef882016-02-09 19:33:42 +0000713 DebugLoc DL = I->getDebugLoc();
714 MachineBasicBlock *MBB = I->getParent();
Jun Bum Lim80ec0d32015-11-20 21:14:07 +0000715 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000716 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
Jun Bum Lim397eb7b2016-02-12 15:25:39 +0000717 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
Diana Picus116bbab2017-01-13 09:58:52 +0000718 .add(BaseRegOp)
Chad Rosierb5933d72016-02-09 19:02:12 +0000719 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000720 .cloneMergedMemRefs({&*I, &*MergeMI})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000721 .setMIFlags(I->mergeFlagsWith(*MergeMI));
Tim Northover3b0846e2014-05-24 12:50:23 +0000722 (void)MIB;
723
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000724 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
725 LLVM_DEBUG(I->print(dbgs()));
726 LLVM_DEBUG(dbgs() << " ");
727 LLVM_DEBUG(MergeMI->print(dbgs()));
728 LLVM_DEBUG(dbgs() << " with instruction:\n ");
729 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
730 LLVM_DEBUG(dbgs() << "\n");
Chad Rosierb5933d72016-02-09 19:02:12 +0000731
732 // Erase the old instructions.
733 I->eraseFromParent();
Chad Rosierd7363db2016-02-09 19:09:22 +0000734 MergeMI->eraseFromParent();
Chad Rosierb5933d72016-02-09 19:02:12 +0000735 return NextI;
736}
737
Florian Hahn17554b82019-12-11 09:59:18 +0000738// Apply Fn to all instructions between MI and the beginning of the block, until
739// a def for DefReg is reached. Returns true, iff Fn returns true for all
740// visited instructions. Stop after visiting Limit iterations.
741static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg,
742 const TargetRegisterInfo *TRI, unsigned Limit,
743 std::function<bool(MachineInstr &, bool)> &Fn) {
744 auto MBB = MI.getParent();
745 for (MachineBasicBlock::reverse_iterator I = MI.getReverseIterator(),
746 E = MBB->rend();
747 I != E; I++) {
748 if (!Limit)
749 return false;
750 --Limit;
751
752 bool isDef = any_of(I->operands(), [DefReg, TRI](MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000753 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000754 TRI->regsOverlap(MOP.getReg(), DefReg);
755 });
756 if (!Fn(*I, isDef))
757 return false;
758 if (isDef)
759 break;
760 }
761 return true;
762}
763
764static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units,
765 const TargetRegisterInfo *TRI) {
766
767 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
768 if (MOP.isReg() && MOP.isKill())
769 Units.removeReg(MOP.getReg());
770
771 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
772 if (MOP.isReg() && !MOP.isKill())
773 Units.addReg(MOP.getReg());
774}
775
Chad Rosierb5933d72016-02-09 19:02:12 +0000776MachineBasicBlock::iterator
777AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
778 MachineBasicBlock::iterator Paired,
779 const LdStPairFlags &Flags) {
780 MachineBasicBlock::iterator NextI = I;
781 ++NextI;
782 // If NextI is the second of the two instructions to be merged, we need
783 // to skip one further. Either way we merge will invalidate the iterator,
784 // and we don't need to scan the new instruction, as it's a pairwise
785 // instruction, which we're not considering for further action anyway.
786 if (NextI == Paired)
787 ++NextI;
788
789 int SExtIdx = Flags.getSExtIdx();
790 unsigned Opc =
791 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000792 bool IsUnscaled = TII->isUnscaledLdSt(Opc);
Jay Foad97ca7c22019-12-11 10:29:23 +0000793 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
Chad Rosierb5933d72016-02-09 19:02:12 +0000794
795 bool MergeForward = Flags.getMergeForward();
Florian Hahn17554b82019-12-11 09:59:18 +0000796
797 Optional<MCPhysReg> RenameReg = Flags.getRenameReg();
798 if (MergeForward && RenameReg) {
799 MCRegister RegToRename = getLdStRegOp(*I).getReg();
800 DefinedInBB.addReg(*RenameReg);
801
802 // Return the sub/super register for RenameReg, matching the size of
803 // OriginalReg.
804 auto GetMatchingSubReg = [this,
805 RenameReg](MCPhysReg OriginalReg) -> MCPhysReg {
806 for (MCPhysReg SubOrSuper : TRI->sub_and_superregs_inclusive(*RenameReg))
807 if (TRI->getMinimalPhysRegClass(OriginalReg) ==
808 TRI->getMinimalPhysRegClass(SubOrSuper))
809 return SubOrSuper;
810 llvm_unreachable("Should have found matching sub or super register!");
811 };
812
813 std::function<bool(MachineInstr &, bool)> UpdateMIs =
814 [this, RegToRename, GetMatchingSubReg](MachineInstr &MI, bool IsDef) {
815 if (IsDef) {
816 bool SeenDef = false;
817 for (auto &MOP : MI.operands()) {
818 // Rename the first explicit definition and all implicit
819 // definitions matching RegToRename.
Florian Hahn2675a3c2019-12-11 17:17:29 +0000820 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
Florian Hahn17554b82019-12-11 09:59:18 +0000821 (!SeenDef || (MOP.isDef() && MOP.isImplicit())) &&
822 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
823 assert((MOP.isImplicit() ||
824 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
825 "Need renamable operands");
826 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
827 SeenDef = true;
828 }
829 }
830 } else {
831 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000832 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
833 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
Florian Hahn17554b82019-12-11 09:59:18 +0000834 assert(MOP.isImplicit() ||
835 (MOP.isRenamable() && !MOP.isEarlyClobber()) &&
836 "Need renamable operands");
837 MOP.setReg(GetMatchingSubReg(MOP.getReg()));
838 }
839 }
840 }
841 LLVM_DEBUG(dbgs() << "Renamed " << MI << "\n");
842 return true;
843 };
844 forAllMIsUntilDef(*I, RegToRename, TRI, LdStLimit, UpdateMIs);
845
Fangrui Song25e21a02019-12-11 10:59:45 -0800846#if !defined(NDEBUG)
Florian Hahn17554b82019-12-11 09:59:18 +0000847 // Make sure the register used for renaming is not used between the paired
848 // instructions. That would trash the content before the new paired
849 // instruction.
850 for (auto &MI :
851 iterator_range<MachineInstrBundleIterator<llvm::MachineInstr>>(
852 std::next(I), std::next(Paired)))
853 assert(all_of(MI.operands(),
854 [this, &RenameReg](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +0000855 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +0000856 !TRI->regsOverlap(MOP.getReg(), *RenameReg);
857 }) &&
858 "Rename register used between paired instruction, trashing the "
859 "content");
Fangrui Song25e21a02019-12-11 10:59:45 -0800860#endif
Florian Hahn17554b82019-12-11 09:59:18 +0000861 }
862
Chad Rosierb5933d72016-02-09 19:02:12 +0000863 // Insert our new paired instruction after whichever of the paired
864 // instructions MergeForward indicates.
865 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
866 // Also based on MergeForward is from where we copy the base register operand
867 // so we get the flags compatible with the input code.
868 const MachineOperand &BaseRegOp =
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000869 MergeForward ? getLdStBaseOp(*Paired) : getLdStBaseOp(*I);
Chad Rosierb5933d72016-02-09 19:02:12 +0000870
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000871 int Offset = getLdStOffsetOp(*I).getImm();
872 int PairedOffset = getLdStOffsetOp(*Paired).getImm();
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000873 bool PairedIsUnscaled = TII->isUnscaledLdSt(Paired->getOpcode());
Chad Rosier00f9d232016-02-11 14:25:08 +0000874 if (IsUnscaled != PairedIsUnscaled) {
875 // We're trying to pair instructions that differ in how they are scaled. If
876 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
877 // the opposite (i.e., make Paired's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +0000878 int MemSize = TII->getMemScale(*Paired);
Chad Rosier00f9d232016-02-11 14:25:08 +0000879 if (PairedIsUnscaled) {
880 // If the unscaled offset isn't a multiple of the MemSize, we can't
881 // pair the operations together.
Jay Foad97ca7c22019-12-11 10:29:23 +0000882 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000883 "Offset should be a multiple of the stride!");
884 PairedOffset /= MemSize;
885 } else {
886 PairedOffset *= MemSize;
887 }
888 }
889
Chad Rosierb5933d72016-02-09 19:02:12 +0000890 // Which register is Rt and which is Rt2 depends on the offset order.
891 MachineInstr *RtMI, *Rt2MI;
Chad Rosier00f9d232016-02-11 14:25:08 +0000892 if (Offset == PairedOffset + OffsetStride) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000893 RtMI = &*Paired;
894 Rt2MI = &*I;
Chad Rosierb5933d72016-02-09 19:02:12 +0000895 // Here we swapped the assumption made for SExtIdx.
896 // I.e., we turn ldp I, Paired into ldp Paired, I.
897 // Update the index accordingly.
898 if (SExtIdx != -1)
899 SExtIdx = (SExtIdx + 1) % 2;
900 } else {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000901 RtMI = &*I;
902 Rt2MI = &*Paired;
Chad Rosierb5933d72016-02-09 19:02:12 +0000903 }
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +0000904 int OffsetImm = getLdStOffsetOp(*RtMI).getImm();
Chad Rosier00f9d232016-02-11 14:25:08 +0000905 // Scale the immediate offset, if necessary.
Chad Rosiere4e15ba2016-03-09 17:29:48 +0000906 if (TII->isUnscaledLdSt(RtMI->getOpcode())) {
Jay Foad97ca7c22019-12-11 10:29:23 +0000907 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
Chad Rosier00f9d232016-02-11 14:25:08 +0000908 "Unscaled offset cannot be scaled.");
Jay Foad97ca7c22019-12-11 10:29:23 +0000909 OffsetImm /= TII->getMemScale(*RtMI);
Chad Rosier87e33412016-02-09 20:18:07 +0000910 }
Chad Rosierb5933d72016-02-09 19:02:12 +0000911
912 // Construct the new instruction.
913 MachineInstrBuilder MIB;
Chad Rosierc46ef882016-02-09 19:33:42 +0000914 DebugLoc DL = I->getDebugLoc();
915 MachineBasicBlock *MBB = I->getParent();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000916 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
917 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
918 // Kill flags may become invalid when moving stores for pairing.
919 if (RegOp0.isUse()) {
920 if (!MergeForward) {
921 // Clear kill flags on store if moving upwards. Example:
922 // STRWui %w0, ...
923 // USE %w1
924 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
925 RegOp0.setIsKill(false);
926 RegOp1.setIsKill(false);
927 } else {
928 // Clear kill flags of the first stores register. Example:
929 // STRWui %w1, ...
930 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
931 // STRW %w0
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000932 Register Reg = getLdStRegOp(*I).getReg();
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000933 for (MachineInstr &MI : make_range(std::next(I), Paired))
934 MI.clearRegisterKills(Reg, TRI);
935 }
936 }
Chad Rosierc46ef882016-02-09 19:33:42 +0000937 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingPairOpcode(Opc)))
Matthias Braun2e8c11e2017-01-20 18:04:27 +0000938 .add(RegOp0)
939 .add(RegOp1)
Diana Picus116bbab2017-01-13 09:58:52 +0000940 .add(BaseRegOp)
Chad Rosiere40b9512016-03-08 17:16:38 +0000941 .addImm(OffsetImm)
Chandler Carruthc73c0302018-08-16 21:30:05 +0000942 .cloneMergedMemRefs({&*I, &*Paired})
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +0000943 .setMIFlags(I->mergeFlagsWith(*Paired));
Chad Rosierb5933d72016-02-09 19:02:12 +0000944
945 (void)MIB;
Tim Northover3b0846e2014-05-24 12:50:23 +0000946
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000947 LLVM_DEBUG(
948 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
949 LLVM_DEBUG(I->print(dbgs()));
950 LLVM_DEBUG(dbgs() << " ");
951 LLVM_DEBUG(Paired->print(dbgs()));
952 LLVM_DEBUG(dbgs() << " with instruction:\n ");
Quentin Colombet66b61632015-03-06 22:42:10 +0000953 if (SExtIdx != -1) {
954 // Generate the sign extension for the proper result of the ldp.
955 // I.e., with X1, that would be:
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000956 // %w1 = KILL %w1, implicit-def %x1
957 // %x1 = SBFMXri killed %x1, 0, 31
Quentin Colombet66b61632015-03-06 22:42:10 +0000958 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
959 // Right now, DstMO has the extended register, since it comes from an
960 // extended opcode.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000961 Register DstRegX = DstMO.getReg();
Quentin Colombet66b61632015-03-06 22:42:10 +0000962 // Get the W variant of that register.
Daniel Sanders5ae66e52019-08-12 22:40:53 +0000963 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
Quentin Colombet66b61632015-03-06 22:42:10 +0000964 // Update the result of LDP to use the W instead of the X variant.
965 DstMO.setReg(DstRegW);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000966 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
967 LLVM_DEBUG(dbgs() << "\n");
Quentin Colombet66b61632015-03-06 22:42:10 +0000968 // Make the machine verifier happy by providing a definition for
969 // the X register.
970 // Insert this definition right after the generated LDP, i.e., before
971 // InsertionPoint.
972 MachineInstrBuilder MIBKill =
Chad Rosierc46ef882016-02-09 19:33:42 +0000973 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
Quentin Colombet66b61632015-03-06 22:42:10 +0000974 .addReg(DstRegW)
975 .addReg(DstRegX, RegState::Define);
976 MIBKill->getOperand(2).setImplicit();
977 // Create the sign extension.
978 MachineInstrBuilder MIBSXTW =
Chad Rosierc46ef882016-02-09 19:33:42 +0000979 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
Quentin Colombet66b61632015-03-06 22:42:10 +0000980 .addReg(DstRegX)
981 .addImm(0)
982 .addImm(31);
983 (void)MIBSXTW;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000984 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
985 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000986 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000987 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
Quentin Colombet66b61632015-03-06 22:42:10 +0000988 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000989 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000990
Florian Hahn17554b82019-12-11 09:59:18 +0000991 if (MergeForward)
992 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
993 if (MOP.isReg() && MOP.isKill())
994 DefinedInBB.addReg(MOP.getReg());
995
Tim Northover3b0846e2014-05-24 12:50:23 +0000996 // Erase the old instructions.
997 I->eraseFromParent();
998 Paired->eraseFromParent();
999
1000 return NextI;
1001}
1002
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001003MachineBasicBlock::iterator
1004AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1005 MachineBasicBlock::iterator StoreI) {
1006 MachineBasicBlock::iterator NextI = LoadI;
1007 ++NextI;
1008
Jay Foad97ca7c22019-12-11 10:29:23 +00001009 int LoadSize = TII->getMemScale(*LoadI);
1010 int StoreSize = TII->getMemScale(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001011 Register LdRt = getLdStRegOp(*LoadI).getReg();
Florian Hahn80e48512017-06-21 08:47:23 +00001012 const MachineOperand &StMO = getLdStRegOp(*StoreI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001013 Register StRt = getLdStRegOp(*StoreI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001014 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1015
1016 assert((IsStoreXReg ||
1017 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1018 "Unexpected RegClass");
1019
1020 MachineInstr *BitExtMI;
1021 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1022 // Remove the load, if the destination register of the loads is the same
1023 // register for stored value.
1024 if (StRt == LdRt && LoadSize == 8) {
Tim Northover9ac3e422017-06-26 18:49:25 +00001025 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1026 LoadI->getIterator())) {
1027 if (MI.killsRegister(StRt, TRI)) {
1028 MI.clearRegisterKills(StRt, TRI);
1029 break;
1030 }
1031 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001032 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1033 LLVM_DEBUG(LoadI->print(dbgs()));
1034 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001035 LoadI->eraseFromParent();
1036 return NextI;
1037 }
1038 // Replace the load with a mov if the load and store are in the same size.
1039 BitExtMI =
1040 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1041 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1042 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
Florian Hahn80e48512017-06-21 08:47:23 +00001043 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001044 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
1045 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001046 } else {
1047 // FIXME: Currently we disable this transformation in big-endian targets as
1048 // performance and correctness are verified only in little-endian.
1049 if (!Subtarget->isLittleEndian())
1050 return NextI;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001051 bool IsUnscaled = TII->isUnscaledLdSt(*LoadI);
1052 assert(IsUnscaled == TII->isUnscaledLdSt(*StoreI) &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001053 "Unsupported ld/st match");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001054 assert(LoadSize <= StoreSize && "Invalid load size");
1055 int UnscaledLdOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001056 ? getLdStOffsetOp(*LoadI).getImm()
1057 : getLdStOffsetOp(*LoadI).getImm() * LoadSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001058 int UnscaledStOffset = IsUnscaled
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001059 ? getLdStOffsetOp(*StoreI).getImm()
1060 : getLdStOffsetOp(*StoreI).getImm() * StoreSize;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001061 int Width = LoadSize * 8;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001062 unsigned DestReg =
1063 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1064 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1065 : LdRt;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001066
1067 assert((UnscaledLdOffset >= UnscaledStOffset &&
1068 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1069 "Invalid offset");
1070
Simon Pilgrime461e9a2019-05-08 16:29:39 +00001071 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1072 int Imms = Immr + Width - 1;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001073 if (UnscaledLdOffset == UnscaledStOffset) {
1074 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1075 | ((Immr) << 6) // immr
1076 | ((Imms) << 0) // imms
1077 ;
1078
1079 BitExtMI =
1080 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1081 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1082 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001083 .add(StMO)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001084 .addImm(AndMaskEncoded)
1085 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001086 } else {
1087 BitExtMI =
1088 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1089 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1090 DestReg)
Florian Hahn80e48512017-06-21 08:47:23 +00001091 .add(StMO)
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001092 .addImm(Immr)
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001093 .addImm(Imms)
1094 .setMIFlags(LoadI->getFlags());
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001095 }
1096 }
Matthias Braun76bb4132016-12-16 23:55:43 +00001097
Matthias Braund9a59a82017-02-17 23:15:03 +00001098 // Clear kill flags between store and load.
1099 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1100 BitExtMI->getIterator()))
Florian Hahn8552e592017-06-21 09:51:52 +00001101 if (MI.killsRegister(StRt, TRI)) {
1102 MI.clearRegisterKills(StRt, TRI);
1103 break;
1104 }
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001105
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001106 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1107 LLVM_DEBUG(StoreI->print(dbgs()));
1108 LLVM_DEBUG(dbgs() << " ");
1109 LLVM_DEBUG(LoadI->print(dbgs()));
1110 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1111 LLVM_DEBUG(StoreI->print(dbgs()));
1112 LLVM_DEBUG(dbgs() << " ");
1113 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1114 LLVM_DEBUG(dbgs() << "\n");
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001115
1116 // Erase the old instructions.
1117 LoadI->eraseFromParent();
1118 return NextI;
1119}
1120
Tim Northover3b0846e2014-05-24 12:50:23 +00001121static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
Chad Rosier3dd0e942015-08-18 16:20:03 +00001122 // Convert the byte-offset used by unscaled into an "element" offset used
1123 // by the scaled pair load/store instructions.
Chad Rosier00f9d232016-02-11 14:25:08 +00001124 if (IsUnscaled) {
1125 // If the byte-offset isn't a multiple of the stride, there's no point
1126 // trying to match it.
1127 if (Offset % OffsetStride)
1128 return false;
Chad Rosier3dd0e942015-08-18 16:20:03 +00001129 Offset /= OffsetStride;
Chad Rosier00f9d232016-02-11 14:25:08 +00001130 }
Chad Rosier3dd0e942015-08-18 16:20:03 +00001131 return Offset <= 63 && Offset >= -64;
Tim Northover3b0846e2014-05-24 12:50:23 +00001132}
1133
1134// Do alignment, specialized to power of 2 and for signed ints,
1135// avoiding having to do a C-style cast from uint_64t to int when
Rui Ueyamada00f2f2016-01-14 21:06:47 +00001136// using alignTo from include/llvm/Support/MathExtras.h.
Tim Northover3b0846e2014-05-24 12:50:23 +00001137// FIXME: Move this function to include/MathExtras.h?
1138static int alignTo(int Num, int PowOf2) {
1139 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1140}
1141
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001142static bool mayAlias(MachineInstr &MIa, MachineInstr &MIb,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001143 AliasAnalysis *AA) {
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001144 // One of the instructions must modify memory.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001145 if (!MIa.mayStore() && !MIb.mayStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001146 return false;
1147
1148 // Both instructions must be memory operations.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001149 if (!MIa.mayLoadOrStore() && !MIb.mayLoadOrStore())
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001150 return false;
1151
Chad Rosiera69dcb62017-03-17 14:19:55 +00001152 return MIa.mayAlias(AA, MIb, /*UseTBAA*/false);
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001153}
1154
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001155static bool mayAlias(MachineInstr &MIa,
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001156 SmallVectorImpl<MachineInstr *> &MemInsns,
Chad Rosiera69dcb62017-03-17 14:19:55 +00001157 AliasAnalysis *AA) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001158 for (MachineInstr *MIb : MemInsns)
Chad Rosiera69dcb62017-03-17 14:19:55 +00001159 if (mayAlias(MIa, *MIb, AA))
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001160 return true;
1161
1162 return false;
1163}
1164
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001165bool AArch64LoadStoreOpt::findMatchingStore(
1166 MachineBasicBlock::iterator I, unsigned Limit,
1167 MachineBasicBlock::iterator &StoreI) {
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001168 MachineBasicBlock::iterator B = I->getParent()->begin();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001169 MachineBasicBlock::iterator MBBI = I;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001170 MachineInstr &LoadMI = *I;
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001171 Register BaseReg = getLdStBaseOp(LoadMI).getReg();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001172
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001173 // If the load is the first instruction in the block, there's obviously
1174 // not any matching store.
1175 if (MBBI == B)
1176 return false;
1177
Jun Bum Lim47aece12018-04-27 18:44:37 +00001178 // Track which register units have been modified and used between the first
1179 // insn and the second insn.
1180 ModifiedRegUnits.clear();
1181 UsedRegUnits.clear();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001182
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001183 unsigned Count = 0;
1184 do {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001185 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001186 MachineInstr &MI = *MBBI;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001187
Geoff Berry4ff2e362016-07-21 15:20:25 +00001188 // Don't count transient instructions towards the search limit since there
1189 // may be different numbers of them if e.g. debug information is present.
1190 if (!MI.isTransient())
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001191 ++Count;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001192
1193 // If the load instruction reads directly from the address to which the
1194 // store instruction writes and the stored value is not modified, we can
1195 // promote the load. Since we do not handle stores with pre-/post-index,
1196 // it's unnecessary to check if BaseReg is modified by the store itself.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001197 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001198 BaseReg == getLdStBaseOp(MI).getReg() &&
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001199 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001200 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001201 StoreI = MBBI;
1202 return true;
1203 }
1204
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001205 if (MI.isCall())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001206 return false;
1207
Jun Bum Lim47aece12018-04-27 18:44:37 +00001208 // Update modified / uses register units.
1209 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001210
1211 // Otherwise, if the base register is modified, we have no match, so
1212 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001213 if (!ModifiedRegUnits.available(BaseReg))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001214 return false;
1215
1216 // If we encounter a store aliased with the load, return early.
Chad Rosiera69dcb62017-03-17 14:19:55 +00001217 if (MI.mayStore() && mayAlias(LoadMI, MI, AA))
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001218 return false;
Jun Bum Lim633b2d82016-02-11 16:18:24 +00001219 } while (MBBI != B && Count < Limit);
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001220 return false;
1221}
1222
Chad Rosierc5083c22016-06-10 20:47:14 +00001223// Returns true if FirstMI and MI are candidates for merging or pairing.
1224// Otherwise, returns false.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001225static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI,
Chad Rosierc5083c22016-06-10 20:47:14 +00001226 LdStPairFlags &Flags,
1227 const AArch64InstrInfo *TII) {
1228 // If this is volatile or if pairing is suppressed, not a candidate.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001229 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
Chad Rosierc5083c22016-06-10 20:47:14 +00001230 return false;
1231
1232 // We should have already checked FirstMI for pair suppression and volatility.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001233 assert(!FirstMI.hasOrderedMemoryRef() &&
1234 !TII->isLdStPairSuppressed(FirstMI) &&
Chad Rosierc5083c22016-06-10 20:47:14 +00001235 "FirstMI shouldn't get here if either of these checks are true.");
1236
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001237 unsigned OpcA = FirstMI.getOpcode();
1238 unsigned OpcB = MI.getOpcode();
Chad Rosierc5083c22016-06-10 20:47:14 +00001239
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001240 // Opcodes match: nothing more to check.
1241 if (OpcA == OpcB)
1242 return true;
1243
1244 // Try to match a sign-extended load/store with a zero-extended load/store.
1245 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1246 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1247 assert(IsValidLdStrOpc &&
1248 "Given Opc should be a Load or Store with an immediate");
1249 // OpcA will be the first instruction in the pair.
1250 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1251 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1252 return true;
1253 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001254
Chad Rosierd6daac42016-11-07 15:27:22 +00001255 // If the second instruction isn't even a mergable/pairable load/store, bail
1256 // out.
Chad Rosier00f9d232016-02-11 14:25:08 +00001257 if (!PairIsValidLdStrOpc)
1258 return false;
1259
Chad Rosierd6daac42016-11-07 15:27:22 +00001260 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1261 // offsets.
1262 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
Chad Rosier00f9d232016-02-11 14:25:08 +00001263 return false;
1264
1265 // Try to match an unscaled load/store with a scaled load/store.
Chad Rosiere4e15ba2016-03-09 17:29:48 +00001266 return TII->isUnscaledLdSt(OpcA) != TII->isUnscaledLdSt(OpcB) &&
Chad Rosier00f9d232016-02-11 14:25:08 +00001267 getMatchingPairOpcode(OpcA) == getMatchingPairOpcode(OpcB);
1268
1269 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001270}
1271
Florian Hahn17554b82019-12-11 09:59:18 +00001272static bool
1273canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween,
1274 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1275 const TargetRegisterInfo *TRI) {
1276 if (!FirstMI.mayStore())
1277 return false;
1278
1279 // Check if we can find an unused register which we can use to rename
1280 // the register used by the first load/store.
1281 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1282 MachineFunction &MF = *FirstMI.getParent()->getParent();
1283 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1284 return false;
1285
1286 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1287 // For now, we only rename if the store operand gets killed at the store.
1288 if (!getLdStRegOp(FirstMI).isKill() &&
1289 !any_of(FirstMI.operands(),
1290 [TRI, RegToRename](const MachineOperand &MOP) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001291 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1292 MOP.isImplicit() && MOP.isKill() &&
Florian Hahn17554b82019-12-11 09:59:18 +00001293 TRI->regsOverlap(RegToRename, MOP.getReg());
1294 })) {
1295 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI << "\n");
1296 return false;
1297 }
1298 auto canRenameMOP = [](const MachineOperand &MOP) {
1299 return MOP.isImplicit() ||
1300 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1301 };
1302
1303 bool FoundDef = false;
1304
1305 // For each instruction between FirstMI and the previous def for RegToRename,
1306 // we
1307 // * check if we can rename RegToRename in this instruction
1308 // * collect the registers used and required register classes for RegToRename.
1309 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1310 bool IsDef) {
1311 LLVM_DEBUG(dbgs() << "Checking " << MI << "\n");
1312 // Currently we do not try to rename across frame-setup instructions.
1313 if (MI.getFlag(MachineInstr::FrameSetup)) {
1314 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions currently ("
1315 << MI << ")\n");
1316 return false;
1317 }
1318
1319 UsedInBetween.accumulate(MI);
1320
1321 // For a definition, check that we can rename the definition and exit the
1322 // loop.
1323 FoundDef = IsDef;
1324
1325 // For defs, check if we can rename the first def of RegToRename.
1326 if (FoundDef) {
1327 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001328 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
Florian Hahn17554b82019-12-11 09:59:18 +00001329 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1330 continue;
1331 if (!canRenameMOP(MOP)) {
1332 LLVM_DEBUG(dbgs()
1333 << " Cannot rename " << MOP << " in " << MI << "\n");
1334 return false;
1335 }
1336 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1337 }
1338 return true;
1339 } else {
1340 for (auto &MOP : MI.operands()) {
Florian Hahn2675a3c2019-12-11 17:17:29 +00001341 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1342 !TRI->regsOverlap(MOP.getReg(), RegToRename))
Florian Hahn17554b82019-12-11 09:59:18 +00001343 continue;
1344
1345 if (!canRenameMOP(MOP)) {
1346 LLVM_DEBUG(dbgs()
1347 << " Cannot rename " << MOP << " in " << MI << "\n");
1348 return false;
1349 }
1350 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1351 }
1352 }
1353 return true;
1354 };
1355
1356 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1357 return false;
1358
1359 if (!FoundDef) {
1360 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1361 return false;
1362 }
1363 return true;
1364}
1365
1366// Check if we can find a physical register for renaming. This register must:
1367// * not be defined up to FirstMI (checking DefinedInBB)
1368// * not used between the MI and the defining instruction of the register to
1369// rename (checked using UsedInBetween).
1370// * is available in all used register classes (checked using RequiredClasses).
1371static Optional<MCPhysReg> tryToFindRegisterToRename(
1372 MachineInstr &FirstMI, MachineInstr &MI, LiveRegUnits &DefinedInBB,
1373 LiveRegUnits &UsedInBetween,
1374 SmallPtrSetImpl<const TargetRegisterClass *> &RequiredClasses,
1375 const TargetRegisterInfo *TRI) {
1376 auto &MF = *FirstMI.getParent()->getParent();
1377
1378 // Checks if any sub- or super-register of PR is callee saved.
1379 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1380 return any_of(TRI->sub_and_superregs_inclusive(PR),
1381 [&MF, TRI](MCPhysReg SubOrSuper) {
1382 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1383 });
1384 };
1385
1386 // Check if PR or one of its sub- or super-registers can be used for all
1387 // required register classes.
1388 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1389 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1390 return any_of(TRI->sub_and_superregs_inclusive(PR),
1391 [C, TRI](MCPhysReg SubOrSuper) {
1392 return C == TRI->getMinimalPhysRegClass(SubOrSuper);
1393 });
1394 });
1395 };
1396
1397 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1398 for (const MCPhysReg &PR : *RegClass) {
1399 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1400 !AnySubOrSuperRegCalleePreserved(PR) && CanBeUsedForAllClasses(PR)) {
1401 DefinedInBB.addReg(PR);
1402 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1403 << "\n");
1404 return {PR};
1405 }
1406 }
1407 LLVM_DEBUG(dbgs() << "No rename register found from "
1408 << TRI->getRegClassName(RegClass) << "\n");
1409 return None;
1410}
1411
Chad Rosier9f4ec2e2016-02-10 18:49:28 +00001412/// Scan the instructions looking for a load/store that can be combined with the
1413/// current instruction into a wider equivalent or a load/store pair.
Tim Northover3b0846e2014-05-24 12:50:23 +00001414MachineBasicBlock::iterator
1415AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
Jun Bum Limcf974432016-03-31 14:47:24 +00001416 LdStPairFlags &Flags, unsigned Limit,
1417 bool FindNarrowMerge) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001418 MachineBasicBlock::iterator E = I->getParent()->end();
1419 MachineBasicBlock::iterator MBBI = I;
Florian Hahn17554b82019-12-11 09:59:18 +00001420 MachineBasicBlock::iterator MBBIWithRenameReg;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001421 MachineInstr &FirstMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001422 ++MBBI;
1423
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001424 bool MayLoad = FirstMI.mayLoad();
1425 bool IsUnscaled = TII->isUnscaledLdSt(FirstMI);
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001426 Register Reg = getLdStRegOp(FirstMI).getReg();
1427 Register BaseReg = getLdStBaseOp(FirstMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001428 int Offset = getLdStOffsetOp(FirstMI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001429 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001430 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001431
Florian Hahn17554b82019-12-11 09:59:18 +00001432 Optional<bool> MaybeCanRename = None;
1433 SmallPtrSet<const TargetRegisterClass *, 5> RequiredClasses;
1434 LiveRegUnits UsedInBetween;
1435 UsedInBetween.init(*TRI);
1436
1437 Flags.clearRenameReg();
1438
Jun Bum Lim47aece12018-04-27 18:44:37 +00001439 // Track which register units have been modified and used between the first
1440 // insn (inclusive) and the second insn.
1441 ModifiedRegUnits.clear();
1442 UsedRegUnits.clear();
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001443
1444 // Remember any instructions that read/write memory between FirstMI and MI.
1445 SmallVector<MachineInstr *, 4> MemInsns;
1446
Tim Northover3b0846e2014-05-24 12:50:23 +00001447 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001448 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001449
Florian Hahn17554b82019-12-11 09:59:18 +00001450 UsedInBetween.accumulate(MI);
1451
Geoff Berry4ff2e362016-07-21 15:20:25 +00001452 // Don't count transient instructions towards the search limit since there
1453 // may be different numbers of them if e.g. debug information is present.
1454 if (!MI.isTransient())
1455 ++Count;
Tim Northover3b0846e2014-05-24 12:50:23 +00001456
Chad Rosier18896c02016-02-04 16:01:40 +00001457 Flags.setSExtIdx(-1);
Chad Rosierc5083c22016-06-10 20:47:14 +00001458 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
Chad Rosierc3f6cb92016-02-10 19:45:48 +00001459 getLdStOffsetOp(MI).isImm()) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001460 assert(MI.mayLoadOrStore() && "Expected memory operation.");
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 // If we've found another instruction with the same opcode, check to see
1462 // if the base and offset are compatible with our starting instruction.
1463 // These instructions all have scaled immediate operands, so we just
1464 // check for +1/-1. Make sure to check the new instruction offset is
1465 // actually an immediate and not a symbolic reference destined for
1466 // a relocation.
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001467 Register MIBaseReg = getLdStBaseOp(MI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001468 int MIOffset = getLdStOffsetOp(MI).getImm();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001469 bool MIIsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001470 if (IsUnscaled != MIIsUnscaled) {
1471 // We're trying to pair instructions that differ in how they are scaled.
1472 // If FirstMI is scaled then scale the offset of MI accordingly.
1473 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
Jay Foad97ca7c22019-12-11 10:29:23 +00001474 int MemSize = TII->getMemScale(MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001475 if (MIIsUnscaled) {
1476 // If the unscaled offset isn't a multiple of the MemSize, we can't
1477 // pair the operations together: bail and keep looking.
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001478 if (MIOffset % MemSize) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001479 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1480 UsedRegUnits, TRI);
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001481 MemInsns.push_back(&MI);
Chad Rosier00f9d232016-02-11 14:25:08 +00001482 continue;
Eli Friedmanf184e4b2016-08-12 20:39:51 +00001483 }
Chad Rosier00f9d232016-02-11 14:25:08 +00001484 MIOffset /= MemSize;
1485 } else {
1486 MIOffset *= MemSize;
1487 }
1488 }
1489
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 if (BaseReg == MIBaseReg && ((Offset == MIOffset + OffsetStride) ||
1491 (Offset + OffsetStride == MIOffset))) {
1492 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
Jun Bum Limcf974432016-03-31 14:47:24 +00001493 if (FindNarrowMerge) {
Jun Bum Lim80ec0d32015-11-20 21:14:07 +00001494 // If the alignment requirements of the scaled wide load/store
Jun Bum Limcf974432016-03-31 14:47:24 +00001495 // instruction can't express the offset of the scaled narrow input,
1496 // bail and keep looking. For promotable zero stores, allow only when
1497 // the stored value is the same (i.e., WZR).
1498 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1499 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001500 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1501 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001502 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001503 continue;
1504 }
1505 } else {
Chad Rosierd1f6c842016-06-10 20:49:18 +00001506 // Pairwise instructions have a 7-bit signed offset field. Single
1507 // insns have a 12-bit unsigned offset field. If the resultant
1508 // immediate offset of merging these instructions is out of range for
1509 // a pairwise instruction, bail and keep looking.
Jun Bum Limcf974432016-03-31 14:47:24 +00001510 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001511 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1512 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001513 MemInsns.push_back(&MI);
Jun Bum Limcf974432016-03-31 14:47:24 +00001514 continue;
1515 }
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001516 // If the alignment requirements of the paired (scaled) instruction
1517 // can't express the offset of the unscaled input, bail and keep
1518 // looking.
1519 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001520 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1521 UsedRegUnits, TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001522 MemInsns.push_back(&MI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001523 continue;
1524 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001525 }
1526 // If the destination register of the loads is the same register, bail
1527 // and keep looking. A load-pair instruction with both destination
1528 // registers the same is UNPREDICTABLE and will result in an exception.
Jun Bum Limcf974432016-03-31 14:47:24 +00001529 if (MayLoad && Reg == getLdStRegOp(MI).getReg()) {
Jun Bum Lim47aece12018-04-27 18:44:37 +00001530 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
1531 TRI);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001532 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001533 continue;
1534 }
1535
1536 // If the Rt of the second instruction was not modified or used between
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001537 // the two instructions and none of the instructions between the second
1538 // and first alias with the second, we can combine the second into the
1539 // first.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001540 if (ModifiedRegUnits.available(getLdStRegOp(MI).getReg()) &&
1541 !(MI.mayLoad() &&
1542 !UsedRegUnits.available(getLdStRegOp(MI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001543 !mayAlias(MI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001544
Chad Rosier96a18a92015-07-21 17:42:04 +00001545 Flags.setMergeForward(false);
Florian Hahn17554b82019-12-11 09:59:18 +00001546 Flags.clearRenameReg();
Tim Northover3b0846e2014-05-24 12:50:23 +00001547 return MBBI;
1548 }
1549
1550 // Likewise, if the Rt of the first instruction is not modified or used
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001551 // between the two instructions and none of the instructions between the
1552 // first and the second alias with the first, we can combine the first
1553 // into the second.
Florian Hahn17554b82019-12-11 09:59:18 +00001554 if (!(MayLoad &&
Jun Bum Lim47aece12018-04-27 18:44:37 +00001555 !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg())) &&
Chad Rosiera69dcb62017-03-17 14:19:55 +00001556 !mayAlias(FirstMI, MemInsns, AA)) {
Florian Hahn17554b82019-12-11 09:59:18 +00001557
1558 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1559 Flags.setMergeForward(true);
1560 Flags.clearRenameReg();
1561 return MBBI;
1562 }
1563
1564 if (DebugCounter::shouldExecute(RegRenamingCounter)) {
1565 if (!MaybeCanRename)
1566 MaybeCanRename = {canRenameUpToDef(FirstMI, UsedInBetween,
1567 RequiredClasses, TRI)};
1568
1569 if (*MaybeCanRename) {
1570 Optional<MCPhysReg> MaybeRenameReg = tryToFindRegisterToRename(
1571 FirstMI, MI, DefinedInBB, UsedInBetween, RequiredClasses,
1572 TRI);
1573 if (MaybeRenameReg) {
1574 Flags.setRenameReg(*MaybeRenameReg);
1575 Flags.setMergeForward(true);
1576 MBBIWithRenameReg = MBBI;
1577 }
1578 }
1579 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001580 }
1581 // Unable to combine these instructions due to interference in between.
1582 // Keep looking.
1583 }
1584 }
1585
Florian Hahn17554b82019-12-11 09:59:18 +00001586 if (Flags.getRenameReg())
1587 return MBBIWithRenameReg;
1588
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001589 // If the instruction wasn't a matching load or store. Stop searching if we
1590 // encounter a call instruction that might modify memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001591 if (MI.isCall())
Tim Northover3b0846e2014-05-24 12:50:23 +00001592 return E;
1593
Jun Bum Lim47aece12018-04-27 18:44:37 +00001594 // Update modified / uses register units.
1595 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001596
1597 // Otherwise, if the base register is modified, we have no match, so
1598 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001599 if (!ModifiedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001600 return E;
Chad Rosierce8e5ab2015-05-21 21:36:46 +00001601
1602 // Update list of instructions that read/write memory.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001603 if (MI.mayLoadOrStore())
1604 MemInsns.push_back(&MI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001605 }
1606 return E;
1607}
1608
1609MachineBasicBlock::iterator
Chad Rosier2dfd3542015-09-23 13:51:44 +00001610AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
1611 MachineBasicBlock::iterator Update,
1612 bool IsPreIdx) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001613 assert((Update->getOpcode() == AArch64::ADDXri ||
1614 Update->getOpcode() == AArch64::SUBXri) &&
1615 "Unexpected base register update instruction to merge!");
1616 MachineBasicBlock::iterator NextI = I;
1617 // Return the instruction following the merged instruction, which is
1618 // the instruction following our unmerged load. Unless that's the add/sub
1619 // instruction we're merging, in which case it's the one after that.
1620 if (++NextI == Update)
1621 ++NextI;
1622
1623 int Value = Update->getOperand(2).getImm();
1624 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
Chad Rosier2dfd3542015-09-23 13:51:44 +00001625 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
Tim Northover3b0846e2014-05-24 12:50:23 +00001626 if (Update->getOpcode() == AArch64::SUBXri)
1627 Value = -Value;
1628
Chad Rosier2dfd3542015-09-23 13:51:44 +00001629 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
1630 : getPostIndexedOpcode(I->getOpcode());
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001631 MachineInstrBuilder MIB;
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001632 int Scale, MinOffset, MaxOffset;
1633 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001634 if (!isPairedLdSt(*I)) {
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001635 // Non-paired instruction.
1636 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001637 .add(getLdStRegOp(*Update))
1638 .add(getLdStRegOp(*I))
1639 .add(getLdStBaseOp(*I))
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001640 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001641 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001642 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001643 } else {
1644 // Paired instruction.
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001645 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
Diana Picus116bbab2017-01-13 09:58:52 +00001646 .add(getLdStRegOp(*Update))
1647 .add(getLdStRegOp(*I, 0))
1648 .add(getLdStRegOp(*I, 1))
1649 .add(getLdStBaseOp(*I))
Chad Rosier3ada75f2016-01-28 15:38:24 +00001650 .addImm(Value / Scale)
Chandler Carruthc73c0302018-08-16 21:30:05 +00001651 .setMemRefs(I->memoperands())
Francis Visoiu Mistrih084e7d82018-03-14 17:10:58 +00001652 .setMIFlags(I->mergeFlagsWith(*Update));
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001653 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001654 (void)MIB;
1655
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001656 if (IsPreIdx) {
1657 ++NumPreFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001658 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001659 } else {
1660 ++NumPostFolded;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001661 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001662 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001663 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
1664 LLVM_DEBUG(I->print(dbgs()));
1665 LLVM_DEBUG(dbgs() << " ");
1666 LLVM_DEBUG(Update->print(dbgs()));
1667 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1668 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1669 LLVM_DEBUG(dbgs() << "\n");
Tim Northover3b0846e2014-05-24 12:50:23 +00001670
1671 // Erase the old instructions for the block.
1672 I->eraseFromParent();
1673 Update->eraseFromParent();
1674
1675 return NextI;
1676}
1677
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001678bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
1679 MachineInstr &MI,
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001680 unsigned BaseReg, int Offset) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001681 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001682 default:
1683 break;
1684 case AArch64::SUBXri:
Tim Northover3b0846e2014-05-24 12:50:23 +00001685 case AArch64::ADDXri:
1686 // Make sure it's a vanilla immediate operand, not a relocation or
1687 // anything else we can't handle.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001688 if (!MI.getOperand(2).isImm())
Tim Northover3b0846e2014-05-24 12:50:23 +00001689 break;
1690 // Watch out for 1 << 12 shifted value.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001691 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
Tim Northover3b0846e2014-05-24 12:50:23 +00001692 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001693
1694 // The update instruction source and destination register must be the
1695 // same as the load/store base register.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001696 if (MI.getOperand(0).getReg() != BaseReg ||
1697 MI.getOperand(1).getReg() != BaseReg)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001698 break;
1699
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001700 int UpdateOffset = MI.getOperand(2).getImm();
Eli Friedman8585e9d2016-08-12 20:28:02 +00001701 if (MI.getOpcode() == AArch64::SUBXri)
1702 UpdateOffset = -UpdateOffset;
1703
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001704 // The immediate must be a multiple of the scaling factor of the pre/post
1705 // indexed instruction.
1706 int Scale, MinOffset, MaxOffset;
1707 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
1708 if (UpdateOffset % Scale != 0)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001709 break;
1710
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001711 // Scaled offset must fit in the instruction immediate.
1712 int ScaledOffset = UpdateOffset / Scale;
1713 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
1714 break;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001715
1716 // If we have a non-zero Offset, we check that it matches the amount
1717 // we're adding to the register.
Eli Friedman8585e9d2016-08-12 20:28:02 +00001718 if (!Offset || Offset == UpdateOffset)
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001719 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00001720 break;
1721 }
1722 return false;
1723}
1724
1725MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001726 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001727 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001728 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001729 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001730
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001731 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Jay Foad97ca7c22019-12-11 10:29:23 +00001732 int MIUnscaledOffset = getLdStOffsetOp(MemMI).getImm() * TII->getMemScale(MemMI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001733
Chad Rosierb7c5b912015-10-01 13:43:05 +00001734 // Scan forward looking for post-index opportunities. Updating instructions
1735 // can't be formed if the memory instruction doesn't have the offset we're
1736 // looking for.
1737 if (MIUnscaledOffset != UnscaledOffset)
1738 return E;
1739
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001740 // If the base register overlaps a source/destination register, we can't
1741 // merge the update. This does not apply to tag store instructions which
1742 // ignore the address part of the source register.
1743 // This does not apply to STGPi as well, which does not have unpredictable
1744 // behavior in this case unlike normal stores, and always performs writeback
1745 // after reading the source register value.
1746 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
1747 bool IsPairedInsn = isPairedLdSt(MemMI);
1748 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1749 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1750 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1751 return E;
1752 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001753 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001754
Jun Bum Lim47aece12018-04-27 18:44:37 +00001755 // Track which register units have been modified and used between the first
1756 // insn (inclusive) and the second insn.
1757 ModifiedRegUnits.clear();
1758 UsedRegUnits.clear();
Tim Northover3b0846e2014-05-24 12:50:23 +00001759 ++MBBI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001760 for (unsigned Count = 0; MBBI != E && Count < Limit; ++MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001761 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001762
Geoff Berry4ff2e362016-07-21 15:20:25 +00001763 // Don't count transient instructions towards the search limit since there
1764 // may be different numbers of them if e.g. debug information is present.
1765 if (!MI.isTransient())
1766 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001767
Tim Northover3b0846e2014-05-24 12:50:23 +00001768 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001769 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001770 return MBBI;
1771
1772 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001773 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001774
1775 // Otherwise, if the base register is used or modified, we have no match, so
1776 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001777 if (!ModifiedRegUnits.available(BaseReg) ||
1778 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001779 return E;
1780 }
1781 return E;
1782}
1783
1784MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
Chad Rosier35706ad2016-02-04 21:26:02 +00001785 MachineBasicBlock::iterator I, unsigned Limit) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001786 MachineBasicBlock::iterator B = I->getParent()->begin();
1787 MachineBasicBlock::iterator E = I->getParent()->end();
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001788 MachineInstr &MemMI = *I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001789 MachineBasicBlock::iterator MBBI = I;
Tim Northover3b0846e2014-05-24 12:50:23 +00001790
Daniel Sanders5ae66e52019-08-12 22:40:53 +00001791 Register BaseReg = getLdStBaseOp(MemMI).getReg();
Chad Rosierf77e9092015-08-06 15:50:12 +00001792 int Offset = getLdStOffsetOp(MemMI).getImm();
Tim Northover3b0846e2014-05-24 12:50:23 +00001793
1794 // If the load/store is the first instruction in the block, there's obviously
1795 // not any matching update. Ditto if the memory offset isn't zero.
1796 if (MBBI == B || Offset != 0)
1797 return E;
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001798 // If the base register overlaps a destination register, we can't
Tim Northover3b0846e2014-05-24 12:50:23 +00001799 // merge the update.
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001800 if (!isTagStore(MemMI)) {
1801 bool IsPairedInsn = isPairedLdSt(MemMI);
1802 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
1803 Register DestReg = getLdStRegOp(MemMI, i).getReg();
1804 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
1805 return E;
1806 }
Chad Rosier1bbd7fb2015-09-25 17:48:17 +00001807 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001808
Jun Bum Lim47aece12018-04-27 18:44:37 +00001809 // Track which register units have been modified and used between the first
1810 // insn (inclusive) and the second insn.
1811 ModifiedRegUnits.clear();
1812 UsedRegUnits.clear();
Geoff Berry173b14d2016-02-09 20:47:21 +00001813 unsigned Count = 0;
1814 do {
1815 --MBBI;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001816 MachineInstr &MI = *MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00001817
Geoff Berry4ff2e362016-07-21 15:20:25 +00001818 // Don't count transient instructions towards the search limit since there
1819 // may be different numbers of them if e.g. debug information is present.
1820 if (!MI.isTransient())
Geoff Berry173b14d2016-02-09 20:47:21 +00001821 ++Count;
Chad Rosier35706ad2016-02-04 21:26:02 +00001822
Tim Northover3b0846e2014-05-24 12:50:23 +00001823 // If we found a match, return it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001824 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00001825 return MBBI;
1826
1827 // Update the status of what the instruction clobbered and used.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001828 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
Tim Northover3b0846e2014-05-24 12:50:23 +00001829
1830 // Otherwise, if the base register is used or modified, we have no match, so
1831 // return early.
Jun Bum Lim47aece12018-04-27 18:44:37 +00001832 if (!ModifiedRegUnits.available(BaseReg) ||
1833 !UsedRegUnits.available(BaseReg))
Tim Northover3b0846e2014-05-24 12:50:23 +00001834 return E;
Geoff Berry173b14d2016-02-09 20:47:21 +00001835 } while (MBBI != B && Count < Limit);
Tim Northover3b0846e2014-05-24 12:50:23 +00001836 return E;
1837}
1838
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001839bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
1840 MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001841 MachineInstr &MI = *MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001842 // If this is a volatile load, don't mess with it.
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001843 if (MI.hasOrderedMemoryRef())
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001844 return false;
1845
1846 // Make sure this is a reg+imm.
1847 // FIXME: It is possible to extend it to handle reg+reg cases.
1848 if (!getLdStOffsetOp(MI).isImm())
1849 return false;
1850
Chad Rosier35706ad2016-02-04 21:26:02 +00001851 // Look backward up to LdStLimit instructions.
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001852 MachineBasicBlock::iterator StoreI;
Chad Rosier35706ad2016-02-04 21:26:02 +00001853 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001854 ++NumLoadsFromStoresPromoted;
1855 // Promote the load. Keeping the iterator straight is a
1856 // pain, so we let the merge routine tell us what the next instruction
1857 // is after it's done mucking about.
1858 MBBI = promoteLoadFromStore(MBBI, StoreI);
1859 return true;
1860 }
1861 return false;
1862}
1863
Chad Rosierd6daac42016-11-07 15:27:22 +00001864// Merge adjacent zero stores into a wider store.
1865bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
Chad Rosier24c46ad2016-02-09 18:10:20 +00001866 MachineBasicBlock::iterator &MBBI) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001867 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001868 MachineInstr &MI = *MBBI;
1869 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001870
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001871 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001872 return false;
1873
1874 // Look ahead up to LdStLimit instructions for a mergable instruction.
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001875 LdStPairFlags Flags;
Jun Bum Lim397eb7b2016-02-12 15:25:39 +00001876 MachineBasicBlock::iterator MergeMI =
Jun Bum Limcf974432016-03-31 14:47:24 +00001877 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
Chad Rosierd7363db2016-02-09 19:09:22 +00001878 if (MergeMI != E) {
Chad Rosierd6daac42016-11-07 15:27:22 +00001879 ++NumZeroStoresPromoted;
1880
Chad Rosier24c46ad2016-02-09 18:10:20 +00001881 // Keeping the iterator straight is a pain, so we let the merge routine tell
1882 // us what the next instruction is after it's done mucking about.
Chad Rosierd6daac42016-11-07 15:27:22 +00001883 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001884 return true;
1885 }
1886 return false;
1887}
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001888
Chad Rosier24c46ad2016-02-09 18:10:20 +00001889// Find loads and stores that can be merged into a single load or store pair
1890// instruction.
1891bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001892 MachineInstr &MI = *MBBI;
1893 MachineBasicBlock::iterator E = MI.getParent()->end();
Chad Rosier24c46ad2016-02-09 18:10:20 +00001894
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001895 if (!TII->isCandidateToMergeOrPair(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001896 return false;
1897
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001898 // Early exit if the offset is not possible to match. (6 bits of positive
1899 // range, plus allow an extra one in case we find a later insn that matches
1900 // with Offset-1)
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001901 bool IsUnscaled = TII->isUnscaledLdSt(MI);
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001902 int Offset = getLdStOffsetOp(MI).getImm();
Jay Foad97ca7c22019-12-11 10:29:23 +00001903 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
Nirav Dave0f9d1112017-01-04 21:21:46 +00001904 // Allow one more for offset.
1905 if (Offset > 0)
1906 Offset -= OffsetStride;
Chad Rosierfc3bf1f2016-02-10 15:52:46 +00001907 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
1908 return false;
1909
Chad Rosier24c46ad2016-02-09 18:10:20 +00001910 // Look ahead up to LdStLimit instructions for a pairable instruction.
1911 LdStPairFlags Flags;
Jun Bum Limcf974432016-03-31 14:47:24 +00001912 MachineBasicBlock::iterator Paired =
1913 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
Chad Rosier24c46ad2016-02-09 18:10:20 +00001914 if (Paired != E) {
1915 ++NumPairCreated;
Duncan P. N. Exon Smithab53fd92016-07-08 20:29:42 +00001916 if (TII->isUnscaledLdSt(MI))
Chad Rosier24c46ad2016-02-09 18:10:20 +00001917 ++NumUnscaledPairCreated;
1918 // Keeping the iterator straight is a pain, so we let the merge routine tell
1919 // us what the next instruction is after it's done mucking about.
Florian Hahn17554b82019-12-11 09:59:18 +00001920 auto Prev = std::prev(MBBI);
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001921 MBBI = mergePairedInsns(MBBI, Paired, Flags);
Florian Hahn17554b82019-12-11 09:59:18 +00001922 // Collect liveness info for instructions between Prev and the new position
1923 // MBBI.
1924 for (auto I = std::next(Prev); I != MBBI; I++)
1925 updateDefinedRegisters(*I, DefinedInBB, TRI);
1926
Jun Bum Limc9879ec2015-10-27 19:16:03 +00001927 return true;
1928 }
1929 return false;
1930}
1931
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001932bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
1933 (MachineBasicBlock::iterator &MBBI) {
1934 MachineInstr &MI = *MBBI;
1935 MachineBasicBlock::iterator E = MI.getParent()->end();
1936 MachineBasicBlock::iterator Update;
1937
1938 // Look forward to try to form a post-index instruction. For example,
1939 // ldr x0, [x20]
1940 // add x20, x20, #32
1941 // merged into:
1942 // ldr x0, [x20], #32
1943 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
1944 if (Update != E) {
1945 // Merge the update into the ld/st.
1946 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
1947 return true;
1948 }
1949
1950 // Don't know how to handle unscaled pre/post-index versions below, so bail.
1951 if (TII->isUnscaledLdSt(MI.getOpcode()))
1952 return false;
1953
1954 // Look back to try to find a pre-index instruction. For example,
1955 // add x0, x0, #8
1956 // ldr x1, [x0]
1957 // merged into:
1958 // ldr x1, [x0, #8]!
1959 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
1960 if (Update != E) {
1961 // Merge the update into the ld/st.
1962 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1963 return true;
1964 }
1965
1966 // The immediate in the load/store is scaled by the size of the memory
1967 // operation. The immediate in the add we're looking for,
1968 // however, is not, so adjust here.
Jay Foad97ca7c22019-12-11 10:29:23 +00001969 int UnscaledOffset = getLdStOffsetOp(MI).getImm() * TII->getMemScale(MI);
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001970
Evgeniy Stepanovc2bda3e2019-09-20 17:36:27 +00001971 // Look forward to try to find a pre-index instruction. For example,
Evandro Menezes5ba804b2017-11-15 21:06:22 +00001972 // ldr x1, [x0, #64]
1973 // add x0, x0, #64
1974 // merged into:
1975 // ldr x1, [x0, #64]!
1976 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
1977 if (Update != E) {
1978 // Merge the update into the ld/st.
1979 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
1980 return true;
1981 }
1982
1983 return false;
1984}
1985
Jun Bum Lim22fe15e2015-11-06 16:27:47 +00001986bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
Chad Rosierd6daac42016-11-07 15:27:22 +00001987 bool EnableNarrowZeroStOpt) {
Florian Hahn17554b82019-12-11 09:59:18 +00001988
Tim Northover3b0846e2014-05-24 12:50:23 +00001989 bool Modified = false;
Chad Rosierdbdb1d62016-02-01 21:38:31 +00001990 // Four tranformations to do here:
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00001991 // 1) Find loads that directly read from stores and promote them by
1992 // replacing with mov instructions. If the store is wider than the load,
1993 // the load will be replaced with a bitfield extract.
1994 // e.g.,
1995 // str w1, [x0, #4]
1996 // ldrh w2, [x0, #6]
1997 // ; becomes
1998 // str w1, [x0, #4]
NAKAMURA Takumife1202c2016-06-20 00:37:41 +00001999 // lsr w2, w1, #16
Tim Northover3b0846e2014-05-24 12:50:23 +00002000 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002001 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002002 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2003 Modified = true;
2004 else
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002005 ++MBBI;
Jun Bum Lim6755c3b2015-12-22 16:36:16 +00002006 }
Chad Rosierd6daac42016-11-07 15:27:22 +00002007 // 2) Merge adjacent zero stores into a wider store.
Jun Bum Lim1de2d442016-02-05 20:02:03 +00002008 // e.g.,
2009 // strh wzr, [x0]
2010 // strh wzr, [x0, #2]
2011 // ; becomes
2012 // str wzr, [x0]
Chad Rosierd6daac42016-11-07 15:27:22 +00002013 // e.g.,
2014 // str wzr, [x0]
2015 // str wzr, [x0, #4]
2016 // ; becomes
2017 // str xzr, [x0]
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002018 if (EnableNarrowZeroStOpt)
2019 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2020 MBBI != E;) {
2021 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002022 Modified = true;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002023 else
Jun Bum Lim33be4992016-05-06 15:08:57 +00002024 ++MBBI;
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002025 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002026 // 3) Find loads and stores that can be merged into a single load or store
2027 // pair instruction.
2028 // e.g.,
2029 // ldr x0, [x2]
2030 // ldr x1, [x2, #8]
2031 // ; becomes
2032 // ldp x0, x1, [x2]
Florian Hahn17554b82019-12-11 09:59:18 +00002033
2034 if (MBB.getParent()->getRegInfo().tracksLiveness()) {
2035 DefinedInBB.clear();
2036 DefinedInBB.addLiveIns(MBB);
2037 }
2038
Jun Bum Limc9879ec2015-10-27 19:16:03 +00002039 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
Tim Northover3b0846e2014-05-24 12:50:23 +00002040 MBBI != E;) {
Florian Hahn17554b82019-12-11 09:59:18 +00002041 // Track currently live registers up to this point, to help with
2042 // searching for a rename register on demand.
2043 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
Geoff Berry22dfbc52016-08-12 15:26:00 +00002044 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2045 Modified = true;
2046 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002047 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002048 }
Chad Rosierdbdb1d62016-02-01 21:38:31 +00002049 // 4) Find base register updates that can be merged into the load or store
2050 // as a base-reg writeback.
2051 // e.g.,
2052 // ldr x0, [x2]
2053 // add x2, x2, #4
2054 // ; becomes
2055 // ldr x0, [x2], #4
Tim Northover3b0846e2014-05-24 12:50:23 +00002056 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
2057 MBBI != E;) {
Evandro Menezes5ba804b2017-11-15 21:06:22 +00002058 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2059 Modified = true;
2060 else
Tim Northover3b0846e2014-05-24 12:50:23 +00002061 ++MBBI;
Tim Northover3b0846e2014-05-24 12:50:23 +00002062 }
2063
2064 return Modified;
2065}
2066
2067bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002068 if (skipFunction(Fn.getFunction()))
Andrew Kaylor1ac98bb2016-04-25 21:58:52 +00002069 return false;
2070
Oliver Stannardd414c992015-11-10 11:04:18 +00002071 Subtarget = &static_cast<const AArch64Subtarget &>(Fn.getSubtarget());
2072 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2073 TRI = Subtarget->getRegisterInfo();
Chad Rosiera69dcb62017-03-17 14:19:55 +00002074 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Tim Northover3b0846e2014-05-24 12:50:23 +00002075
Jun Bum Lim47aece12018-04-27 18:44:37 +00002076 // Resize the modified and used register unit trackers. We do this once
2077 // per function and then clear the register units each time we optimize a load
2078 // or store.
2079 ModifiedRegUnits.init(*TRI);
2080 UsedRegUnits.init(*TRI);
Florian Hahn17554b82019-12-11 09:59:18 +00002081 DefinedInBB.init(*TRI);
Chad Rosierbba881e2016-02-02 15:02:30 +00002082
Tim Northover3b0846e2014-05-24 12:50:23 +00002083 bool Modified = false;
Chad Rosier10c7aaa2016-11-11 14:10:12 +00002084 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
Florian Hahn17554b82019-12-11 09:59:18 +00002085 for (auto &MBB : Fn) {
2086 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2087 Modified |= M;
2088 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002089
2090 return Modified;
2091}
2092
Chad Rosier8ade0342016-11-11 19:52:45 +00002093// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2094// stores near one another? Note: The pre-RA instruction scheduler already has
2095// hooks to try and schedule pairable loads/stores together to improve pairing
2096// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
Tim Northover3b0846e2014-05-24 12:50:23 +00002097
Chad Rosier3f8b09d2016-02-09 19:42:19 +00002098// FIXME: When pairing store instructions it's very possible for this pass to
2099// hoist a store with a KILL marker above another use (without a KILL marker).
2100// The resulting IR is invalid, but nothing uses the KILL markers after this
2101// pass, so it's never caused a problem in practice.
2102
Chad Rosier43f5c842015-08-05 12:40:13 +00002103/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2104/// load / store optimization pass.
Tim Northover3b0846e2014-05-24 12:50:23 +00002105FunctionPass *llvm::createAArch64LoadStoreOptimizationPass() {
2106 return new AArch64LoadStoreOpt();
2107}