LLVM 20.0.0git
AArch64LoadStoreOptimizer.cpp
Go to the documentation of this file.
1//===- AArch64LoadStoreOptimizer.cpp - AArch64 load/store opt. pass -------===//
2//
3// 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
6//
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// The pass runs after the PrologEpilogInserter where we emit the CFI
13// instructions. In order to preserve the correctness of the unwind informaiton,
14// the pass should not change the order of any two instructions, one of which
15// has the FrameSetup/FrameDestroy flag or, alternatively, apply an add-hoc fix
16// to unwind information.
17//
18//===----------------------------------------------------------------------===//
19
20#include "AArch64InstrInfo.h"
22#include "AArch64Subtarget.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
37#include "llvm/IR/DebugLoc.h"
38#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCDwarf.h"
41#include "llvm/Pass.h"
43#include "llvm/Support/Debug.h"
47#include <cassert>
48#include <cstdint>
49#include <functional>
50#include <iterator>
51#include <limits>
52#include <optional>
53
54using namespace llvm;
55
56#define DEBUG_TYPE "aarch64-ldst-opt"
57
58STATISTIC(NumPairCreated, "Number of load/store pair instructions generated");
59STATISTIC(NumPostFolded, "Number of post-index updates folded");
60STATISTIC(NumPreFolded, "Number of pre-index updates folded");
61STATISTIC(NumUnscaledPairCreated,
62 "Number of load/store from unscaled generated");
63STATISTIC(NumZeroStoresPromoted, "Number of narrow zero stores promoted");
64STATISTIC(NumLoadsFromStoresPromoted, "Number of loads from stores promoted");
65STATISTIC(NumFailedAlignmentCheck, "Number of load/store pair transformation "
66 "not passed the alignment check");
67STATISTIC(NumConstOffsetFolded,
68 "Number of const offset of index address folded");
69
70DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
71 "Controls which pairs are considered for renaming");
72
73// The LdStLimit limits how far we search for load/store pairs.
74static cl::opt<unsigned> LdStLimit("aarch64-load-store-scan-limit",
75 cl::init(20), cl::Hidden);
76
77// The UpdateLimit limits how far we search for update instructions when we form
78// pre-/post-index instructions.
79static cl::opt<unsigned> UpdateLimit("aarch64-update-scan-limit", cl::init(100),
81
82// The LdStConstLimit limits how far we search for const offset instructions
83// when we form index address load/store instructions.
84static cl::opt<unsigned> LdStConstLimit("aarch64-load-store-const-scan-limit",
85 cl::init(10), cl::Hidden);
86
87// Enable register renaming to find additional store pairing opportunities.
88static cl::opt<bool> EnableRenaming("aarch64-load-store-renaming",
89 cl::init(true), cl::Hidden);
90
91#define AARCH64_LOAD_STORE_OPT_NAME "AArch64 load / store optimization pass"
92
93namespace {
94
95using LdStPairFlags = struct LdStPairFlags {
96 // If a matching instruction is found, MergeForward is set to true if the
97 // merge is to remove the first instruction and replace the second with
98 // a pair-wise insn, and false if the reverse is true.
99 bool MergeForward = false;
100
101 // SExtIdx gives the index of the result of the load pair that must be
102 // extended. The value of SExtIdx assumes that the paired load produces the
103 // value in this order: (I, returned iterator), i.e., -1 means no value has
104 // to be extended, 0 means I, and 1 means the returned iterator.
105 int SExtIdx = -1;
106
107 // If not none, RenameReg can be used to rename the result register of the
108 // first store in a pair. Currently this only works when merging stores
109 // forward.
110 std::optional<MCPhysReg> RenameReg;
111
112 LdStPairFlags() = default;
113
114 void setMergeForward(bool V = true) { MergeForward = V; }
115 bool getMergeForward() const { return MergeForward; }
116
117 void setSExtIdx(int V) { SExtIdx = V; }
118 int getSExtIdx() const { return SExtIdx; }
119
120 void setRenameReg(MCPhysReg R) { RenameReg = R; }
121 void clearRenameReg() { RenameReg = std::nullopt; }
122 std::optional<MCPhysReg> getRenameReg() const { return RenameReg; }
123};
124
125struct AArch64LoadStoreOpt : public MachineFunctionPass {
126 static char ID;
127
128 AArch64LoadStoreOpt() : MachineFunctionPass(ID) {
130 }
131
132 AliasAnalysis *AA;
133 const AArch64InstrInfo *TII;
134 const TargetRegisterInfo *TRI;
135 const AArch64Subtarget *Subtarget;
136
137 // Track which register units have been modified and used.
138 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
139 LiveRegUnits DefinedInBB;
140
141 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 }
145
146 // Scan the instructions looking for a load/store that can be combined
147 // with the current instruction into a load/store pair.
148 // Return the matching instruction if one is found, else MBB->end().
150 LdStPairFlags &Flags,
151 unsigned Limit,
152 bool FindNarrowMerge);
153
154 // Scan the instructions looking for a store that writes to the address from
155 // which the current load instruction reads. Return true if one is found.
156 bool findMatchingStore(MachineBasicBlock::iterator I, unsigned Limit,
158
159 // Merge the two instructions indicated into a wider narrow store instruction.
161 mergeNarrowZeroStores(MachineBasicBlock::iterator I,
163 const LdStPairFlags &Flags);
164
165 // Merge the two instructions indicated into a single pair-wise instruction.
167 mergePairedInsns(MachineBasicBlock::iterator I,
169 const LdStPairFlags &Flags);
170
171 // Promote the load that reads directly from the address stored to.
173 promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
175
176 // Scan the instruction list to find a base register update that can
177 // be combined with the current instruction (a load or store) using
178 // pre or post indexed addressing with writeback. Scan forwards.
180 findMatchingUpdateInsnForward(MachineBasicBlock::iterator I,
181 int UnscaledOffset, unsigned Limit);
182
183 // Scan the instruction list to find a register assigned with a const
184 // value that can be combined with the current instruction (a load or store)
185 // using base addressing with writeback. Scan backwards.
187 findMatchingConstOffsetBackward(MachineBasicBlock::iterator I, unsigned Limit,
188 unsigned &Offset);
189
190 // Scan the instruction list to find a base register update that can
191 // be combined with the current instruction (a load or store) using
192 // pre or post indexed addressing with writeback. Scan backwards.
194 findMatchingUpdateInsnBackward(MachineBasicBlock::iterator I, unsigned Limit);
195
196 // Find an instruction that updates the base register of the ld/st
197 // instruction.
198 bool isMatchingUpdateInsn(MachineInstr &MemMI, MachineInstr &MI,
199 unsigned BaseReg, int Offset);
200
201 bool isMatchingMovConstInsn(MachineInstr &MemMI, MachineInstr &MI,
202 unsigned IndexReg, unsigned &Offset);
203
204 // Merge a pre- or post-index base register update into a ld/st instruction.
206 mergeUpdateInsn(MachineBasicBlock::iterator I,
207 MachineBasicBlock::iterator Update, bool IsPreIdx);
208
210 mergeConstOffsetInsn(MachineBasicBlock::iterator I,
211 MachineBasicBlock::iterator Update, unsigned Offset,
212 int Scale);
213
214 // Find and merge zero store instructions.
215 bool tryToMergeZeroStInst(MachineBasicBlock::iterator &MBBI);
216
217 // Find and pair ldr/str instructions.
218 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
219
220 // Find and promote load instructions which read directly from store.
221 bool tryToPromoteLoadFromStore(MachineBasicBlock::iterator &MBBI);
222
223 // Find and merge a base register updates before or after a ld/st instruction.
224 bool tryToMergeLdStUpdate(MachineBasicBlock::iterator &MBBI);
225
226 // Find and merge an index ldr/st instruction into a base ld/st instruction.
227 bool tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI, int Scale);
228
229 bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
230
231 bool runOnMachineFunction(MachineFunction &Fn) override;
232
235 MachineFunctionProperties::Property::NoVRegs);
236 }
237
238 StringRef getPassName() const override { return AARCH64_LOAD_STORE_OPT_NAME; }
239};
240
241char AArch64LoadStoreOpt::ID = 0;
242
243} // end anonymous namespace
244
245INITIALIZE_PASS(AArch64LoadStoreOpt, "aarch64-ldst-opt",
246 AARCH64_LOAD_STORE_OPT_NAME, false, false)
247
248static bool isNarrowStore(unsigned Opc) {
249 switch (Opc) {
250 default:
251 return false;
252 case AArch64::STRBBui:
253 case AArch64::STURBBi:
254 case AArch64::STRHHui:
255 case AArch64::STURHHi:
256 return true;
257 }
258}
259
260// These instruction set memory tag and either keep memory contents unchanged or
261// set it to zero, ignoring the address part of the source register.
262static bool isTagStore(const MachineInstr &MI) {
263 switch (MI.getOpcode()) {
264 default:
265 return false;
266 case AArch64::STGi:
267 case AArch64::STZGi:
268 case AArch64::ST2Gi:
269 case AArch64::STZ2Gi:
270 return true;
271 }
272}
273
274static unsigned getMatchingNonSExtOpcode(unsigned Opc,
275 bool *IsValidLdStrOpc = nullptr) {
276 if (IsValidLdStrOpc)
277 *IsValidLdStrOpc = true;
278 switch (Opc) {
279 default:
280 if (IsValidLdStrOpc)
281 *IsValidLdStrOpc = false;
282 return std::numeric_limits<unsigned>::max();
283 case AArch64::STRDui:
284 case AArch64::STURDi:
285 case AArch64::STRDpre:
286 case AArch64::STRQui:
287 case AArch64::STURQi:
288 case AArch64::STRQpre:
289 case AArch64::STRBBui:
290 case AArch64::STURBBi:
291 case AArch64::STRHHui:
292 case AArch64::STURHHi:
293 case AArch64::STRWui:
294 case AArch64::STRWpre:
295 case AArch64::STURWi:
296 case AArch64::STRXui:
297 case AArch64::STRXpre:
298 case AArch64::STURXi:
299 case AArch64::LDRDui:
300 case AArch64::LDURDi:
301 case AArch64::LDRDpre:
302 case AArch64::LDRQui:
303 case AArch64::LDURQi:
304 case AArch64::LDRQpre:
305 case AArch64::LDRWui:
306 case AArch64::LDURWi:
307 case AArch64::LDRWpre:
308 case AArch64::LDRXui:
309 case AArch64::LDURXi:
310 case AArch64::LDRXpre:
311 case AArch64::STRSui:
312 case AArch64::STURSi:
313 case AArch64::STRSpre:
314 case AArch64::LDRSui:
315 case AArch64::LDURSi:
316 case AArch64::LDRSpre:
317 return Opc;
318 case AArch64::LDRSWui:
319 return AArch64::LDRWui;
320 case AArch64::LDURSWi:
321 return AArch64::LDURWi;
322 case AArch64::LDRSWpre:
323 return AArch64::LDRWpre;
324 }
325}
326
327static unsigned getMatchingWideOpcode(unsigned Opc) {
328 switch (Opc) {
329 default:
330 llvm_unreachable("Opcode has no wide equivalent!");
331 case AArch64::STRBBui:
332 return AArch64::STRHHui;
333 case AArch64::STRHHui:
334 return AArch64::STRWui;
335 case AArch64::STURBBi:
336 return AArch64::STURHHi;
337 case AArch64::STURHHi:
338 return AArch64::STURWi;
339 case AArch64::STURWi:
340 return AArch64::STURXi;
341 case AArch64::STRWui:
342 return AArch64::STRXui;
343 }
344}
345
346static unsigned getMatchingPairOpcode(unsigned Opc) {
347 switch (Opc) {
348 default:
349 llvm_unreachable("Opcode has no pairwise equivalent!");
350 case AArch64::STRSui:
351 case AArch64::STURSi:
352 return AArch64::STPSi;
353 case AArch64::STRSpre:
354 return AArch64::STPSpre;
355 case AArch64::STRDui:
356 case AArch64::STURDi:
357 return AArch64::STPDi;
358 case AArch64::STRDpre:
359 return AArch64::STPDpre;
360 case AArch64::STRQui:
361 case AArch64::STURQi:
362 return AArch64::STPQi;
363 case AArch64::STRQpre:
364 return AArch64::STPQpre;
365 case AArch64::STRWui:
366 case AArch64::STURWi:
367 return AArch64::STPWi;
368 case AArch64::STRWpre:
369 return AArch64::STPWpre;
370 case AArch64::STRXui:
371 case AArch64::STURXi:
372 return AArch64::STPXi;
373 case AArch64::STRXpre:
374 return AArch64::STPXpre;
375 case AArch64::LDRSui:
376 case AArch64::LDURSi:
377 return AArch64::LDPSi;
378 case AArch64::LDRSpre:
379 return AArch64::LDPSpre;
380 case AArch64::LDRDui:
381 case AArch64::LDURDi:
382 return AArch64::LDPDi;
383 case AArch64::LDRDpre:
384 return AArch64::LDPDpre;
385 case AArch64::LDRQui:
386 case AArch64::LDURQi:
387 return AArch64::LDPQi;
388 case AArch64::LDRQpre:
389 return AArch64::LDPQpre;
390 case AArch64::LDRWui:
391 case AArch64::LDURWi:
392 return AArch64::LDPWi;
393 case AArch64::LDRWpre:
394 return AArch64::LDPWpre;
395 case AArch64::LDRXui:
396 case AArch64::LDURXi:
397 return AArch64::LDPXi;
398 case AArch64::LDRXpre:
399 return AArch64::LDPXpre;
400 case AArch64::LDRSWui:
401 case AArch64::LDURSWi:
402 return AArch64::LDPSWi;
403 case AArch64::LDRSWpre:
404 return AArch64::LDPSWpre;
405 }
406}
407
410 unsigned LdOpc = LoadInst.getOpcode();
411 unsigned StOpc = StoreInst.getOpcode();
412 switch (LdOpc) {
413 default:
414 llvm_unreachable("Unsupported load instruction!");
415 case AArch64::LDRBBui:
416 return StOpc == AArch64::STRBBui || StOpc == AArch64::STRHHui ||
417 StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
418 case AArch64::LDURBBi:
419 return StOpc == AArch64::STURBBi || StOpc == AArch64::STURHHi ||
420 StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
421 case AArch64::LDRHHui:
422 return StOpc == AArch64::STRHHui || StOpc == AArch64::STRWui ||
423 StOpc == AArch64::STRXui;
424 case AArch64::LDURHHi:
425 return StOpc == AArch64::STURHHi || StOpc == AArch64::STURWi ||
426 StOpc == AArch64::STURXi;
427 case AArch64::LDRWui:
428 return StOpc == AArch64::STRWui || StOpc == AArch64::STRXui;
429 case AArch64::LDURWi:
430 return StOpc == AArch64::STURWi || StOpc == AArch64::STURXi;
431 case AArch64::LDRXui:
432 return StOpc == AArch64::STRXui;
433 case AArch64::LDURXi:
434 return StOpc == AArch64::STURXi;
435 }
436}
437
438static unsigned getPreIndexedOpcode(unsigned Opc) {
439 // FIXME: We don't currently support creating pre-indexed loads/stores when
440 // the load or store is the unscaled version. If we decide to perform such an
441 // optimization in the future the cases for the unscaled loads/stores will
442 // need to be added here.
443 switch (Opc) {
444 default:
445 llvm_unreachable("Opcode has no pre-indexed equivalent!");
446 case AArch64::STRSui:
447 return AArch64::STRSpre;
448 case AArch64::STRDui:
449 return AArch64::STRDpre;
450 case AArch64::STRQui:
451 return AArch64::STRQpre;
452 case AArch64::STRBBui:
453 return AArch64::STRBBpre;
454 case AArch64::STRHHui:
455 return AArch64::STRHHpre;
456 case AArch64::STRWui:
457 return AArch64::STRWpre;
458 case AArch64::STRXui:
459 return AArch64::STRXpre;
460 case AArch64::LDRSui:
461 return AArch64::LDRSpre;
462 case AArch64::LDRDui:
463 return AArch64::LDRDpre;
464 case AArch64::LDRQui:
465 return AArch64::LDRQpre;
466 case AArch64::LDRBBui:
467 return AArch64::LDRBBpre;
468 case AArch64::LDRHHui:
469 return AArch64::LDRHHpre;
470 case AArch64::LDRWui:
471 return AArch64::LDRWpre;
472 case AArch64::LDRXui:
473 return AArch64::LDRXpre;
474 case AArch64::LDRSWui:
475 return AArch64::LDRSWpre;
476 case AArch64::LDPSi:
477 return AArch64::LDPSpre;
478 case AArch64::LDPSWi:
479 return AArch64::LDPSWpre;
480 case AArch64::LDPDi:
481 return AArch64::LDPDpre;
482 case AArch64::LDPQi:
483 return AArch64::LDPQpre;
484 case AArch64::LDPWi:
485 return AArch64::LDPWpre;
486 case AArch64::LDPXi:
487 return AArch64::LDPXpre;
488 case AArch64::STPSi:
489 return AArch64::STPSpre;
490 case AArch64::STPDi:
491 return AArch64::STPDpre;
492 case AArch64::STPQi:
493 return AArch64::STPQpre;
494 case AArch64::STPWi:
495 return AArch64::STPWpre;
496 case AArch64::STPXi:
497 return AArch64::STPXpre;
498 case AArch64::STGi:
499 return AArch64::STGPreIndex;
500 case AArch64::STZGi:
501 return AArch64::STZGPreIndex;
502 case AArch64::ST2Gi:
503 return AArch64::ST2GPreIndex;
504 case AArch64::STZ2Gi:
505 return AArch64::STZ2GPreIndex;
506 case AArch64::STGPi:
507 return AArch64::STGPpre;
508 }
509}
510
511static unsigned getBaseAddressOpcode(unsigned Opc) {
512 // TODO: Add more index address loads/stores.
513 switch (Opc) {
514 default:
515 llvm_unreachable("Opcode has no base address equivalent!");
516 case AArch64::LDRBBroX:
517 return AArch64::LDRBBui;
518 }
519}
520
521static unsigned getPostIndexedOpcode(unsigned Opc) {
522 switch (Opc) {
523 default:
524 llvm_unreachable("Opcode has no post-indexed wise equivalent!");
525 case AArch64::STRSui:
526 case AArch64::STURSi:
527 return AArch64::STRSpost;
528 case AArch64::STRDui:
529 case AArch64::STURDi:
530 return AArch64::STRDpost;
531 case AArch64::STRQui:
532 case AArch64::STURQi:
533 return AArch64::STRQpost;
534 case AArch64::STRBBui:
535 return AArch64::STRBBpost;
536 case AArch64::STRHHui:
537 return AArch64::STRHHpost;
538 case AArch64::STRWui:
539 case AArch64::STURWi:
540 return AArch64::STRWpost;
541 case AArch64::STRXui:
542 case AArch64::STURXi:
543 return AArch64::STRXpost;
544 case AArch64::LDRSui:
545 case AArch64::LDURSi:
546 return AArch64::LDRSpost;
547 case AArch64::LDRDui:
548 case AArch64::LDURDi:
549 return AArch64::LDRDpost;
550 case AArch64::LDRQui:
551 case AArch64::LDURQi:
552 return AArch64::LDRQpost;
553 case AArch64::LDRBBui:
554 return AArch64::LDRBBpost;
555 case AArch64::LDRHHui:
556 return AArch64::LDRHHpost;
557 case AArch64::LDRWui:
558 case AArch64::LDURWi:
559 return AArch64::LDRWpost;
560 case AArch64::LDRXui:
561 case AArch64::LDURXi:
562 return AArch64::LDRXpost;
563 case AArch64::LDRSWui:
564 return AArch64::LDRSWpost;
565 case AArch64::LDPSi:
566 return AArch64::LDPSpost;
567 case AArch64::LDPSWi:
568 return AArch64::LDPSWpost;
569 case AArch64::LDPDi:
570 return AArch64::LDPDpost;
571 case AArch64::LDPQi:
572 return AArch64::LDPQpost;
573 case AArch64::LDPWi:
574 return AArch64::LDPWpost;
575 case AArch64::LDPXi:
576 return AArch64::LDPXpost;
577 case AArch64::STPSi:
578 return AArch64::STPSpost;
579 case AArch64::STPDi:
580 return AArch64::STPDpost;
581 case AArch64::STPQi:
582 return AArch64::STPQpost;
583 case AArch64::STPWi:
584 return AArch64::STPWpost;
585 case AArch64::STPXi:
586 return AArch64::STPXpost;
587 case AArch64::STGi:
588 return AArch64::STGPostIndex;
589 case AArch64::STZGi:
590 return AArch64::STZGPostIndex;
591 case AArch64::ST2Gi:
592 return AArch64::ST2GPostIndex;
593 case AArch64::STZ2Gi:
594 return AArch64::STZ2GPostIndex;
595 case AArch64::STGPi:
596 return AArch64::STGPpost;
597 }
598}
599
601
602 unsigned OpcA = FirstMI.getOpcode();
603 unsigned OpcB = MI.getOpcode();
604
605 switch (OpcA) {
606 default:
607 return false;
608 case AArch64::STRSpre:
609 return (OpcB == AArch64::STRSui) || (OpcB == AArch64::STURSi);
610 case AArch64::STRDpre:
611 return (OpcB == AArch64::STRDui) || (OpcB == AArch64::STURDi);
612 case AArch64::STRQpre:
613 return (OpcB == AArch64::STRQui) || (OpcB == AArch64::STURQi);
614 case AArch64::STRWpre:
615 return (OpcB == AArch64::STRWui) || (OpcB == AArch64::STURWi);
616 case AArch64::STRXpre:
617 return (OpcB == AArch64::STRXui) || (OpcB == AArch64::STURXi);
618 case AArch64::LDRSpre:
619 return (OpcB == AArch64::LDRSui) || (OpcB == AArch64::LDURSi);
620 case AArch64::LDRDpre:
621 return (OpcB == AArch64::LDRDui) || (OpcB == AArch64::LDURDi);
622 case AArch64::LDRQpre:
623 return (OpcB == AArch64::LDRQui) || (OpcB == AArch64::LDURQi);
624 case AArch64::LDRWpre:
625 return (OpcB == AArch64::LDRWui) || (OpcB == AArch64::LDURWi);
626 case AArch64::LDRXpre:
627 return (OpcB == AArch64::LDRXui) || (OpcB == AArch64::LDURXi);
628 case AArch64::LDRSWpre:
629 return (OpcB == AArch64::LDRSWui) || (OpcB == AArch64::LDURSWi);
630 }
631}
632
633// Returns the scale and offset range of pre/post indexed variants of MI.
634static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale,
635 int &MinOffset, int &MaxOffset) {
636 bool IsPaired = AArch64InstrInfo::isPairedLdSt(MI);
637 bool IsTagStore = isTagStore(MI);
638 // ST*G and all paired ldst have the same scale in pre/post-indexed variants
639 // as in the "unsigned offset" variant.
640 // All other pre/post indexed ldst instructions are unscaled.
641 Scale = (IsTagStore || IsPaired) ? AArch64InstrInfo::getMemScale(MI) : 1;
642
643 if (IsPaired) {
644 MinOffset = -64;
645 MaxOffset = 63;
646 } else {
647 MinOffset = -256;
648 MaxOffset = 255;
649 }
650}
651
653 unsigned PairedRegOp = 0) {
654 assert(PairedRegOp < 2 && "Unexpected register operand idx.");
655 bool IsPreLdSt = AArch64InstrInfo::isPreLdSt(MI);
656 if (IsPreLdSt)
657 PairedRegOp += 1;
658 unsigned Idx =
659 AArch64InstrInfo::isPairedLdSt(MI) || IsPreLdSt ? PairedRegOp : 0;
660 return MI.getOperand(Idx);
661}
662
665 const AArch64InstrInfo *TII) {
666 assert(isMatchingStore(LoadInst, StoreInst) && "Expect only matched ld/st.");
667 int LoadSize = TII->getMemScale(LoadInst);
668 int StoreSize = TII->getMemScale(StoreInst);
669 int UnscaledStOffset =
670 TII->hasUnscaledLdStOffset(StoreInst)
673 int UnscaledLdOffset =
674 TII->hasUnscaledLdStOffset(LoadInst)
677 return (UnscaledStOffset <= UnscaledLdOffset) &&
678 (UnscaledLdOffset + LoadSize <= (UnscaledStOffset + StoreSize));
679}
680
682 unsigned Opc = MI.getOpcode();
683 return (Opc == AArch64::STRWui || Opc == AArch64::STURWi ||
684 isNarrowStore(Opc)) &&
685 getLdStRegOp(MI).getReg() == AArch64::WZR;
686}
687
689 switch (MI.getOpcode()) {
690 default:
691 return false;
692 // Scaled instructions.
693 case AArch64::LDRBBui:
694 case AArch64::LDRHHui:
695 case AArch64::LDRWui:
696 case AArch64::LDRXui:
697 // Unscaled instructions.
698 case AArch64::LDURBBi:
699 case AArch64::LDURHHi:
700 case AArch64::LDURWi:
701 case AArch64::LDURXi:
702 return true;
703 }
704}
705
707 unsigned Opc = MI.getOpcode();
708 switch (Opc) {
709 default:
710 return false;
711 // Scaled instructions.
712 case AArch64::STRSui:
713 case AArch64::STRDui:
714 case AArch64::STRQui:
715 case AArch64::STRXui:
716 case AArch64::STRWui:
717 case AArch64::STRHHui:
718 case AArch64::STRBBui:
719 case AArch64::LDRSui:
720 case AArch64::LDRDui:
721 case AArch64::LDRQui:
722 case AArch64::LDRXui:
723 case AArch64::LDRWui:
724 case AArch64::LDRHHui:
725 case AArch64::LDRBBui:
726 case AArch64::STGi:
727 case AArch64::STZGi:
728 case AArch64::ST2Gi:
729 case AArch64::STZ2Gi:
730 case AArch64::STGPi:
731 // Unscaled instructions.
732 case AArch64::STURSi:
733 case AArch64::STURDi:
734 case AArch64::STURQi:
735 case AArch64::STURWi:
736 case AArch64::STURXi:
737 case AArch64::LDURSi:
738 case AArch64::LDURDi:
739 case AArch64::LDURQi:
740 case AArch64::LDURWi:
741 case AArch64::LDURXi:
742 // Paired instructions.
743 case AArch64::LDPSi:
744 case AArch64::LDPSWi:
745 case AArch64::LDPDi:
746 case AArch64::LDPQi:
747 case AArch64::LDPWi:
748 case AArch64::LDPXi:
749 case AArch64::STPSi:
750 case AArch64::STPDi:
751 case AArch64::STPQi:
752 case AArch64::STPWi:
753 case AArch64::STPXi:
754 // Make sure this is a reg+imm (as opposed to an address reloc).
756 return false;
757
758 return true;
759 }
760}
761
762// Make sure this is a reg+reg Ld/St
763static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale) {
764 unsigned Opc = MI.getOpcode();
765 switch (Opc) {
766 default:
767 return false;
768 // Scaled instructions.
769 // TODO: Add more index address loads/stores.
770 case AArch64::LDRBBroX:
771 Scale = 1;
772 return true;
773 }
774}
775
776static bool isRewritableImplicitDef(unsigned Opc) {
777 switch (Opc) {
778 default:
779 return false;
780 case AArch64::ORRWrs:
781 case AArch64::ADDWri:
782 return true;
783 }
784}
785
787AArch64LoadStoreOpt::mergeNarrowZeroStores(MachineBasicBlock::iterator I,
789 const LdStPairFlags &Flags) {
791 "Expected promotable zero stores.");
792
793 MachineBasicBlock::iterator E = I->getParent()->end();
795 // If NextI is the second of the two instructions to be merged, we need
796 // to skip one further. Either way we merge will invalidate the iterator,
797 // and we don't need to scan the new instruction, as it's a pairwise
798 // instruction, which we're not considering for further action anyway.
799 if (NextI == MergeMI)
800 NextI = next_nodbg(NextI, E);
801
802 unsigned Opc = I->getOpcode();
803 unsigned MergeMIOpc = MergeMI->getOpcode();
804 bool IsScaled = !TII->hasUnscaledLdStOffset(Opc);
805 bool IsMergedMIScaled = !TII->hasUnscaledLdStOffset(MergeMIOpc);
806 int OffsetStride = IsScaled ? TII->getMemScale(*I) : 1;
807 int MergeMIOffsetStride = IsMergedMIScaled ? TII->getMemScale(*MergeMI) : 1;
808
809 bool MergeForward = Flags.getMergeForward();
810 // Insert our new paired instruction after whichever of the paired
811 // instructions MergeForward indicates.
812 MachineBasicBlock::iterator InsertionPoint = MergeForward ? MergeMI : I;
813 // Also based on MergeForward is from where we copy the base register operand
814 // so we get the flags compatible with the input code.
815 const MachineOperand &BaseRegOp =
816 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*MergeMI)
817 : AArch64InstrInfo::getLdStBaseOp(*I);
818
819 // Which register is Rt and which is Rt2 depends on the offset order.
820 int64_t IOffsetInBytes =
821 AArch64InstrInfo::getLdStOffsetOp(*I).getImm() * OffsetStride;
822 int64_t MIOffsetInBytes =
824 MergeMIOffsetStride;
825 // Select final offset based on the offset order.
826 int64_t OffsetImm;
827 if (IOffsetInBytes > MIOffsetInBytes)
828 OffsetImm = MIOffsetInBytes;
829 else
830 OffsetImm = IOffsetInBytes;
831
832 int NewOpcode = getMatchingWideOpcode(Opc);
833 bool FinalIsScaled = !TII->hasUnscaledLdStOffset(NewOpcode);
834
835 // Adjust final offset if the result opcode is a scaled store.
836 if (FinalIsScaled) {
837 int NewOffsetStride = FinalIsScaled ? TII->getMemScale(NewOpcode) : 1;
838 assert(((OffsetImm % NewOffsetStride) == 0) &&
839 "Offset should be a multiple of the store memory scale");
840 OffsetImm = OffsetImm / NewOffsetStride;
841 }
842
843 // Construct the new instruction.
844 DebugLoc DL = I->getDebugLoc();
845 MachineBasicBlock *MBB = I->getParent();
847 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(getMatchingWideOpcode(Opc)))
848 .addReg(isNarrowStore(Opc) ? AArch64::WZR : AArch64::XZR)
849 .add(BaseRegOp)
850 .addImm(OffsetImm)
851 .cloneMergedMemRefs({&*I, &*MergeMI})
852 .setMIFlags(I->mergeFlagsWith(*MergeMI));
853 (void)MIB;
854
855 LLVM_DEBUG(dbgs() << "Creating wider store. Replacing instructions:\n ");
856 LLVM_DEBUG(I->print(dbgs()));
857 LLVM_DEBUG(dbgs() << " ");
858 LLVM_DEBUG(MergeMI->print(dbgs()));
859 LLVM_DEBUG(dbgs() << " with instruction:\n ");
860 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
861 LLVM_DEBUG(dbgs() << "\n");
862
863 // Erase the old instructions.
864 I->eraseFromParent();
865 MergeMI->eraseFromParent();
866 return NextI;
867}
868
869// Apply Fn to all instructions between MI and the beginning of the block, until
870// a def for DefReg is reached. Returns true, iff Fn returns true for all
871// visited instructions. Stop after visiting Limit iterations.
873 const TargetRegisterInfo *TRI, unsigned Limit,
874 std::function<bool(MachineInstr &, bool)> &Fn) {
875 auto MBB = MI.getParent();
876 for (MachineInstr &I :
877 instructionsWithoutDebug(MI.getReverseIterator(), MBB->instr_rend())) {
878 if (!Limit)
879 return false;
880 --Limit;
881
882 bool isDef = any_of(I.operands(), [DefReg, TRI](MachineOperand &MOP) {
883 return MOP.isReg() && MOP.isDef() && !MOP.isDebug() && MOP.getReg() &&
884 TRI->regsOverlap(MOP.getReg(), DefReg);
885 });
886 if (!Fn(I, isDef))
887 return false;
888 if (isDef)
889 break;
890 }
891 return true;
892}
893
895 const TargetRegisterInfo *TRI) {
896
897 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
898 if (MOP.isReg() && MOP.isKill())
899 Units.removeReg(MOP.getReg());
900
901 for (const MachineOperand &MOP : phys_regs_and_masks(MI))
902 if (MOP.isReg() && !MOP.isKill())
903 Units.addReg(MOP.getReg());
904}
905
907AArch64LoadStoreOpt::mergePairedInsns(MachineBasicBlock::iterator I,
909 const LdStPairFlags &Flags) {
910 MachineBasicBlock::iterator E = I->getParent()->end();
912 // If NextI is the second of the two instructions to be merged, we need
913 // to skip one further. Either way we merge will invalidate the iterator,
914 // and we don't need to scan the new instruction, as it's a pairwise
915 // instruction, which we're not considering for further action anyway.
916 if (NextI == Paired)
917 NextI = next_nodbg(NextI, E);
918
919 int SExtIdx = Flags.getSExtIdx();
920 unsigned Opc =
921 SExtIdx == -1 ? I->getOpcode() : getMatchingNonSExtOpcode(I->getOpcode());
922 bool IsUnscaled = TII->hasUnscaledLdStOffset(Opc);
923 int OffsetStride = IsUnscaled ? TII->getMemScale(*I) : 1;
924
925 bool MergeForward = Flags.getMergeForward();
926
927 std::optional<MCPhysReg> RenameReg = Flags.getRenameReg();
928 if (RenameReg) {
929 MCRegister RegToRename = getLdStRegOp(*I).getReg();
930 DefinedInBB.addReg(*RenameReg);
931
932 // Return the sub/super register for RenameReg, matching the size of
933 // OriginalReg.
934 auto GetMatchingSubReg =
935 [this, RenameReg](const TargetRegisterClass *C) -> MCPhysReg {
936 for (MCPhysReg SubOrSuper :
937 TRI->sub_and_superregs_inclusive(*RenameReg)) {
938 if (C->contains(SubOrSuper))
939 return SubOrSuper;
940 }
941 llvm_unreachable("Should have found matching sub or super register!");
942 };
943
944 std::function<bool(MachineInstr &, bool)> UpdateMIs =
945 [this, RegToRename, GetMatchingSubReg, MergeForward](MachineInstr &MI,
946 bool IsDef) {
947 if (IsDef) {
948 bool SeenDef = false;
949 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
950 MachineOperand &MOP = MI.getOperand(OpIdx);
951 // Rename the first explicit definition and all implicit
952 // definitions matching RegToRename.
953 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
954 (!MergeForward || !SeenDef ||
955 (MOP.isDef() && MOP.isImplicit())) &&
956 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
957 assert((MOP.isImplicit() ||
958 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
959 "Need renamable operands");
960 Register MatchingReg;
961 if (const TargetRegisterClass *RC =
962 MI.getRegClassConstraint(OpIdx, TII, TRI))
963 MatchingReg = GetMatchingSubReg(RC);
964 else {
965 if (!isRewritableImplicitDef(MI.getOpcode()))
966 continue;
967 MatchingReg = GetMatchingSubReg(
968 TRI->getMinimalPhysRegClass(MOP.getReg()));
969 }
970 MOP.setReg(MatchingReg);
971 SeenDef = true;
972 }
973 }
974 } else {
975 for (unsigned OpIdx = 0; OpIdx < MI.getNumOperands(); ++OpIdx) {
976 MachineOperand &MOP = MI.getOperand(OpIdx);
977 if (MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
978 TRI->regsOverlap(MOP.getReg(), RegToRename)) {
979 assert((MOP.isImplicit() ||
980 (MOP.isRenamable() && !MOP.isEarlyClobber())) &&
981 "Need renamable operands");
982 Register MatchingReg;
983 if (const TargetRegisterClass *RC =
984 MI.getRegClassConstraint(OpIdx, TII, TRI))
985 MatchingReg = GetMatchingSubReg(RC);
986 else
987 MatchingReg = GetMatchingSubReg(
988 TRI->getMinimalPhysRegClass(MOP.getReg()));
989 assert(MatchingReg != AArch64::NoRegister &&
990 "Cannot find matching regs for renaming");
991 MOP.setReg(MatchingReg);
992 }
993 }
994 }
995 LLVM_DEBUG(dbgs() << "Renamed " << MI);
996 return true;
997 };
998 forAllMIsUntilDef(MergeForward ? *I : *std::prev(Paired), RegToRename, TRI,
999 UINT32_MAX, UpdateMIs);
1000
1001#if !defined(NDEBUG)
1002 // For forward merging store:
1003 // Make sure the register used for renaming is not used between the
1004 // paired instructions. That would trash the content before the new
1005 // paired instruction.
1006 MCPhysReg RegToCheck = *RenameReg;
1007 // For backward merging load:
1008 // Make sure the register being renamed is not used between the
1009 // paired instructions. That would trash the content after the new
1010 // paired instruction.
1011 if (!MergeForward)
1012 RegToCheck = RegToRename;
1013 for (auto &MI :
1015 MergeForward ? std::next(I) : I,
1016 MergeForward ? std::next(Paired) : Paired))
1017 assert(all_of(MI.operands(),
1018 [this, RegToCheck](const MachineOperand &MOP) {
1019 return !MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1020 MOP.isUndef() ||
1021 !TRI->regsOverlap(MOP.getReg(), RegToCheck);
1022 }) &&
1023 "Rename register used between paired instruction, trashing the "
1024 "content");
1025#endif
1026 }
1027
1028 // Insert our new paired instruction after whichever of the paired
1029 // instructions MergeForward indicates.
1030 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
1031 // Also based on MergeForward is from where we copy the base register operand
1032 // so we get the flags compatible with the input code.
1033 const MachineOperand &BaseRegOp =
1034 MergeForward ? AArch64InstrInfo::getLdStBaseOp(*Paired)
1035 : AArch64InstrInfo::getLdStBaseOp(*I);
1036
1038 int PairedOffset = AArch64InstrInfo::getLdStOffsetOp(*Paired).getImm();
1039 bool PairedIsUnscaled = TII->hasUnscaledLdStOffset(Paired->getOpcode());
1040 if (IsUnscaled != PairedIsUnscaled) {
1041 // We're trying to pair instructions that differ in how they are scaled. If
1042 // I is scaled then scale the offset of Paired accordingly. Otherwise, do
1043 // the opposite (i.e., make Paired's offset unscaled).
1044 int MemSize = TII->getMemScale(*Paired);
1045 if (PairedIsUnscaled) {
1046 // If the unscaled offset isn't a multiple of the MemSize, we can't
1047 // pair the operations together.
1048 assert(!(PairedOffset % TII->getMemScale(*Paired)) &&
1049 "Offset should be a multiple of the stride!");
1050 PairedOffset /= MemSize;
1051 } else {
1052 PairedOffset *= MemSize;
1053 }
1054 }
1055
1056 // Which register is Rt and which is Rt2 depends on the offset order.
1057 // However, for pre load/stores the Rt should be the one of the pre
1058 // load/store.
1059 MachineInstr *RtMI, *Rt2MI;
1060 if (Offset == PairedOffset + OffsetStride &&
1062 RtMI = &*Paired;
1063 Rt2MI = &*I;
1064 // Here we swapped the assumption made for SExtIdx.
1065 // I.e., we turn ldp I, Paired into ldp Paired, I.
1066 // Update the index accordingly.
1067 if (SExtIdx != -1)
1068 SExtIdx = (SExtIdx + 1) % 2;
1069 } else {
1070 RtMI = &*I;
1071 Rt2MI = &*Paired;
1072 }
1073 int OffsetImm = AArch64InstrInfo::getLdStOffsetOp(*RtMI).getImm();
1074 // Scale the immediate offset, if necessary.
1075 if (TII->hasUnscaledLdStOffset(RtMI->getOpcode())) {
1076 assert(!(OffsetImm % TII->getMemScale(*RtMI)) &&
1077 "Unscaled offset cannot be scaled.");
1078 OffsetImm /= TII->getMemScale(*RtMI);
1079 }
1080
1081 // Construct the new instruction.
1083 DebugLoc DL = I->getDebugLoc();
1084 MachineBasicBlock *MBB = I->getParent();
1085 MachineOperand RegOp0 = getLdStRegOp(*RtMI);
1086 MachineOperand RegOp1 = getLdStRegOp(*Rt2MI);
1087 MachineOperand &PairedRegOp = RtMI == &*Paired ? RegOp0 : RegOp1;
1088 // Kill flags may become invalid when moving stores for pairing.
1089 if (RegOp0.isUse()) {
1090 if (!MergeForward) {
1091 // Clear kill flags on store if moving upwards. Example:
1092 // STRWui kill %w0, ...
1093 // USE %w1
1094 // STRWui kill %w1 ; need to clear kill flag when moving STRWui upwards
1095 // We are about to move the store of w1, so its kill flag may become
1096 // invalid; not the case for w0.
1097 // Since w1 is used between the stores, the kill flag on w1 is cleared
1098 // after merging.
1099 // STPWi kill %w0, %w1, ...
1100 // USE %w1
1101 for (auto It = std::next(I); It != Paired && PairedRegOp.isKill(); ++It)
1102 if (It->readsRegister(PairedRegOp.getReg(), TRI))
1103 PairedRegOp.setIsKill(false);
1104 } else {
1105 // Clear kill flags of the first stores register. Example:
1106 // STRWui %w1, ...
1107 // USE kill %w1 ; need to clear kill flag when moving STRWui downwards
1108 // STRW %w0
1110 for (MachineInstr &MI : make_range(std::next(I), Paired))
1111 MI.clearRegisterKills(Reg, TRI);
1112 }
1113 }
1114
1115 unsigned int MatchPairOpcode = getMatchingPairOpcode(Opc);
1116 MIB = BuildMI(*MBB, InsertionPoint, DL, TII->get(MatchPairOpcode));
1117
1118 // Adds the pre-index operand for pre-indexed ld/st pairs.
1119 if (AArch64InstrInfo::isPreLdSt(*RtMI))
1120 MIB.addReg(BaseRegOp.getReg(), RegState::Define);
1121
1122 MIB.add(RegOp0)
1123 .add(RegOp1)
1124 .add(BaseRegOp)
1125 .addImm(OffsetImm)
1126 .cloneMergedMemRefs({&*I, &*Paired})
1127 .setMIFlags(I->mergeFlagsWith(*Paired));
1128
1129 (void)MIB;
1130
1131 LLVM_DEBUG(
1132 dbgs() << "Creating pair load/store. Replacing instructions:\n ");
1133 LLVM_DEBUG(I->print(dbgs()));
1134 LLVM_DEBUG(dbgs() << " ");
1135 LLVM_DEBUG(Paired->print(dbgs()));
1136 LLVM_DEBUG(dbgs() << " with instruction:\n ");
1137 if (SExtIdx != -1) {
1138 // Generate the sign extension for the proper result of the ldp.
1139 // I.e., with X1, that would be:
1140 // %w1 = KILL %w1, implicit-def %x1
1141 // %x1 = SBFMXri killed %x1, 0, 31
1142 MachineOperand &DstMO = MIB->getOperand(SExtIdx);
1143 // Right now, DstMO has the extended register, since it comes from an
1144 // extended opcode.
1145 Register DstRegX = DstMO.getReg();
1146 // Get the W variant of that register.
1147 Register DstRegW = TRI->getSubReg(DstRegX, AArch64::sub_32);
1148 // Update the result of LDP to use the W instead of the X variant.
1149 DstMO.setReg(DstRegW);
1150 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1151 LLVM_DEBUG(dbgs() << "\n");
1152 // Make the machine verifier happy by providing a definition for
1153 // the X register.
1154 // Insert this definition right after the generated LDP, i.e., before
1155 // InsertionPoint.
1156 MachineInstrBuilder MIBKill =
1157 BuildMI(*MBB, InsertionPoint, DL, TII->get(TargetOpcode::KILL), DstRegW)
1158 .addReg(DstRegW)
1159 .addReg(DstRegX, RegState::Define);
1160 MIBKill->getOperand(2).setImplicit();
1161 // Create the sign extension.
1162 MachineInstrBuilder MIBSXTW =
1163 BuildMI(*MBB, InsertionPoint, DL, TII->get(AArch64::SBFMXri), DstRegX)
1164 .addReg(DstRegX)
1165 .addImm(0)
1166 .addImm(31);
1167 (void)MIBSXTW;
1168 LLVM_DEBUG(dbgs() << " Extend operand:\n ");
1169 LLVM_DEBUG(((MachineInstr *)MIBSXTW)->print(dbgs()));
1170 } else {
1171 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
1172 }
1173 LLVM_DEBUG(dbgs() << "\n");
1174
1175 if (MergeForward)
1176 for (const MachineOperand &MOP : phys_regs_and_masks(*I))
1177 if (MOP.isReg() && MOP.isKill())
1178 DefinedInBB.addReg(MOP.getReg());
1179
1180 // Erase the old instructions.
1181 I->eraseFromParent();
1182 Paired->eraseFromParent();
1183
1184 return NextI;
1185}
1186
1188AArch64LoadStoreOpt::promoteLoadFromStore(MachineBasicBlock::iterator LoadI,
1191 next_nodbg(LoadI, LoadI->getParent()->end());
1192
1193 int LoadSize = TII->getMemScale(*LoadI);
1194 int StoreSize = TII->getMemScale(*StoreI);
1195 Register LdRt = getLdStRegOp(*LoadI).getReg();
1196 const MachineOperand &StMO = getLdStRegOp(*StoreI);
1197 Register StRt = getLdStRegOp(*StoreI).getReg();
1198 bool IsStoreXReg = TRI->getRegClass(AArch64::GPR64RegClassID)->contains(StRt);
1199
1200 assert((IsStoreXReg ||
1201 TRI->getRegClass(AArch64::GPR32RegClassID)->contains(StRt)) &&
1202 "Unexpected RegClass");
1203
1204 MachineInstr *BitExtMI;
1205 if (LoadSize == StoreSize && (LoadSize == 4 || LoadSize == 8)) {
1206 // Remove the load, if the destination register of the loads is the same
1207 // register for stored value.
1208 if (StRt == LdRt && LoadSize == 8) {
1209 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1210 LoadI->getIterator())) {
1211 if (MI.killsRegister(StRt, TRI)) {
1212 MI.clearRegisterKills(StRt, TRI);
1213 break;
1214 }
1215 }
1216 LLVM_DEBUG(dbgs() << "Remove load instruction:\n ");
1217 LLVM_DEBUG(LoadI->print(dbgs()));
1218 LLVM_DEBUG(dbgs() << "\n");
1219 LoadI->eraseFromParent();
1220 return NextI;
1221 }
1222 // Replace the load with a mov if the load and store are in the same size.
1223 BitExtMI =
1224 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1225 TII->get(IsStoreXReg ? AArch64::ORRXrs : AArch64::ORRWrs), LdRt)
1226 .addReg(IsStoreXReg ? AArch64::XZR : AArch64::WZR)
1227 .add(StMO)
1229 .setMIFlags(LoadI->getFlags());
1230 } else {
1231 // FIXME: Currently we disable this transformation in big-endian targets as
1232 // performance and correctness are verified only in little-endian.
1233 if (!Subtarget->isLittleEndian())
1234 return NextI;
1235 bool IsUnscaled = TII->hasUnscaledLdStOffset(*LoadI);
1236 assert(IsUnscaled == TII->hasUnscaledLdStOffset(*StoreI) &&
1237 "Unsupported ld/st match");
1238 assert(LoadSize <= StoreSize && "Invalid load size");
1239 int UnscaledLdOffset =
1240 IsUnscaled
1242 : AArch64InstrInfo::getLdStOffsetOp(*LoadI).getImm() * LoadSize;
1243 int UnscaledStOffset =
1244 IsUnscaled
1246 : AArch64InstrInfo::getLdStOffsetOp(*StoreI).getImm() * StoreSize;
1247 int Width = LoadSize * 8;
1248 Register DestReg =
1249 IsStoreXReg ? Register(TRI->getMatchingSuperReg(
1250 LdRt, AArch64::sub_32, &AArch64::GPR64RegClass))
1251 : LdRt;
1252
1253 assert((UnscaledLdOffset >= UnscaledStOffset &&
1254 (UnscaledLdOffset + LoadSize) <= UnscaledStOffset + StoreSize) &&
1255 "Invalid offset");
1256
1257 int Immr = 8 * (UnscaledLdOffset - UnscaledStOffset);
1258 int Imms = Immr + Width - 1;
1259 if (UnscaledLdOffset == UnscaledStOffset) {
1260 uint32_t AndMaskEncoded = ((IsStoreXReg ? 1 : 0) << 12) // N
1261 | ((Immr) << 6) // immr
1262 | ((Imms) << 0) // imms
1263 ;
1264
1265 BitExtMI =
1266 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1267 TII->get(IsStoreXReg ? AArch64::ANDXri : AArch64::ANDWri),
1268 DestReg)
1269 .add(StMO)
1270 .addImm(AndMaskEncoded)
1271 .setMIFlags(LoadI->getFlags());
1272 } else {
1273 BitExtMI =
1274 BuildMI(*LoadI->getParent(), LoadI, LoadI->getDebugLoc(),
1275 TII->get(IsStoreXReg ? AArch64::UBFMXri : AArch64::UBFMWri),
1276 DestReg)
1277 .add(StMO)
1278 .addImm(Immr)
1279 .addImm(Imms)
1280 .setMIFlags(LoadI->getFlags());
1281 }
1282 }
1283
1284 // Clear kill flags between store and load.
1285 for (MachineInstr &MI : make_range(StoreI->getIterator(),
1286 BitExtMI->getIterator()))
1287 if (MI.killsRegister(StRt, TRI)) {
1288 MI.clearRegisterKills(StRt, TRI);
1289 break;
1290 }
1291
1292 LLVM_DEBUG(dbgs() << "Promoting load by replacing :\n ");
1293 LLVM_DEBUG(StoreI->print(dbgs()));
1294 LLVM_DEBUG(dbgs() << " ");
1295 LLVM_DEBUG(LoadI->print(dbgs()));
1296 LLVM_DEBUG(dbgs() << " with instructions:\n ");
1297 LLVM_DEBUG(StoreI->print(dbgs()));
1298 LLVM_DEBUG(dbgs() << " ");
1299 LLVM_DEBUG((BitExtMI)->print(dbgs()));
1300 LLVM_DEBUG(dbgs() << "\n");
1301
1302 // Erase the old instructions.
1303 LoadI->eraseFromParent();
1304 return NextI;
1305}
1306
1307static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride) {
1308 // Convert the byte-offset used by unscaled into an "element" offset used
1309 // by the scaled pair load/store instructions.
1310 if (IsUnscaled) {
1311 // If the byte-offset isn't a multiple of the stride, there's no point
1312 // trying to match it.
1313 if (Offset % OffsetStride)
1314 return false;
1315 Offset /= OffsetStride;
1316 }
1317 return Offset <= 63 && Offset >= -64;
1318}
1319
1320// Do alignment, specialized to power of 2 and for signed ints,
1321// avoiding having to do a C-style cast from uint_64t to int when
1322// using alignTo from include/llvm/Support/MathExtras.h.
1323// FIXME: Move this function to include/MathExtras.h?
1324static int alignTo(int Num, int PowOf2) {
1325 return (Num + PowOf2 - 1) & ~(PowOf2 - 1);
1326}
1327
1328static bool mayAlias(MachineInstr &MIa,
1330 AliasAnalysis *AA) {
1331 for (MachineInstr *MIb : MemInsns) {
1332 if (MIa.mayAlias(AA, *MIb, /*UseTBAA*/ false)) {
1333 LLVM_DEBUG(dbgs() << "Aliasing with: "; MIb->dump());
1334 return true;
1335 }
1336 }
1337
1338 LLVM_DEBUG(dbgs() << "No aliases found\n");
1339 return false;
1340}
1341
1342bool AArch64LoadStoreOpt::findMatchingStore(
1343 MachineBasicBlock::iterator I, unsigned Limit,
1345 MachineBasicBlock::iterator B = I->getParent()->begin();
1347 MachineInstr &LoadMI = *I;
1349
1350 // If the load is the first instruction in the block, there's obviously
1351 // not any matching store.
1352 if (MBBI == B)
1353 return false;
1354
1355 // Track which register units have been modified and used between the first
1356 // insn and the second insn.
1357 ModifiedRegUnits.clear();
1358 UsedRegUnits.clear();
1359
1360 unsigned Count = 0;
1361 do {
1362 MBBI = prev_nodbg(MBBI, B);
1363 MachineInstr &MI = *MBBI;
1364
1365 // Don't count transient instructions towards the search limit since there
1366 // may be different numbers of them if e.g. debug information is present.
1367 if (!MI.isTransient())
1368 ++Count;
1369
1370 // If the load instruction reads directly from the address to which the
1371 // store instruction writes and the stored value is not modified, we can
1372 // promote the load. Since we do not handle stores with pre-/post-index,
1373 // it's unnecessary to check if BaseReg is modified by the store itself.
1374 // Also we can't handle stores without an immediate offset operand,
1375 // while the operand might be the address for a global variable.
1376 if (MI.mayStore() && isMatchingStore(LoadMI, MI) &&
1379 isLdOffsetInRangeOfSt(LoadMI, MI, TII) &&
1380 ModifiedRegUnits.available(getLdStRegOp(MI).getReg())) {
1381 StoreI = MBBI;
1382 return true;
1383 }
1384
1385 if (MI.isCall())
1386 return false;
1387
1388 // Update modified / uses register units.
1389 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1390
1391 // Otherwise, if the base register is modified, we have no match, so
1392 // return early.
1393 if (!ModifiedRegUnits.available(BaseReg))
1394 return false;
1395
1396 // If we encounter a store aliased with the load, return early.
1397 if (MI.mayStore() && LoadMI.mayAlias(AA, MI, /*UseTBAA*/ false))
1398 return false;
1399 } while (MBBI != B && Count < Limit);
1400 return false;
1401}
1402
1403static bool needsWinCFI(const MachineFunction *MF) {
1404 return MF->getTarget().getMCAsmInfo()->usesWindowsCFI() &&
1406}
1407
1408// Returns true if FirstMI and MI are candidates for merging or pairing.
1409// Otherwise, returns false.
1411 LdStPairFlags &Flags,
1412 const AArch64InstrInfo *TII) {
1413 // If this is volatile or if pairing is suppressed, not a candidate.
1414 if (MI.hasOrderedMemoryRef() || TII->isLdStPairSuppressed(MI))
1415 return false;
1416
1417 // We should have already checked FirstMI for pair suppression and volatility.
1418 assert(!FirstMI.hasOrderedMemoryRef() &&
1419 !TII->isLdStPairSuppressed(FirstMI) &&
1420 "FirstMI shouldn't get here if either of these checks are true.");
1421
1422 if (needsWinCFI(MI.getMF()) && (MI.getFlag(MachineInstr::FrameSetup) ||
1424 return false;
1425
1426 unsigned OpcA = FirstMI.getOpcode();
1427 unsigned OpcB = MI.getOpcode();
1428
1429 // Opcodes match: If the opcodes are pre ld/st there is nothing more to check.
1430 if (OpcA == OpcB)
1431 return !AArch64InstrInfo::isPreLdSt(FirstMI);
1432
1433 // Two pre ld/st of different opcodes cannot be merged either
1435 return false;
1436
1437 // Try to match a sign-extended load/store with a zero-extended load/store.
1438 bool IsValidLdStrOpc, PairIsValidLdStrOpc;
1439 unsigned NonSExtOpc = getMatchingNonSExtOpcode(OpcA, &IsValidLdStrOpc);
1440 assert(IsValidLdStrOpc &&
1441 "Given Opc should be a Load or Store with an immediate");
1442 // OpcA will be the first instruction in the pair.
1443 if (NonSExtOpc == getMatchingNonSExtOpcode(OpcB, &PairIsValidLdStrOpc)) {
1444 Flags.setSExtIdx(NonSExtOpc == (unsigned)OpcA ? 1 : 0);
1445 return true;
1446 }
1447
1448 // If the second instruction isn't even a mergable/pairable load/store, bail
1449 // out.
1450 if (!PairIsValidLdStrOpc)
1451 return false;
1452
1453 // FIXME: We don't support merging narrow stores with mixed scaled/unscaled
1454 // offsets.
1455 if (isNarrowStore(OpcA) || isNarrowStore(OpcB))
1456 return false;
1457
1458 // The STR<S,D,Q,W,X>pre - STR<S,D,Q,W,X>ui and
1459 // LDR<S,D,Q,W,X,SW>pre-LDR<S,D,Q,W,X,SW>ui
1460 // are candidate pairs that can be merged.
1461 if (isPreLdStPairCandidate(FirstMI, MI))
1462 return true;
1463
1464 // Try to match an unscaled load/store with a scaled load/store.
1465 return TII->hasUnscaledLdStOffset(OpcA) != TII->hasUnscaledLdStOffset(OpcB) &&
1467
1468 // FIXME: Can we also match a mixed sext/zext unscaled/scaled pair?
1469}
1470
1471static bool canRenameMOP(const MachineOperand &MOP,
1472 const TargetRegisterInfo *TRI) {
1473 if (MOP.isReg()) {
1474 auto *RegClass = TRI->getMinimalPhysRegClass(MOP.getReg());
1475 // Renaming registers with multiple disjunct sub-registers (e.g. the
1476 // result of a LD3) means that all sub-registers are renamed, potentially
1477 // impacting other instructions we did not check. Bail out.
1478 // Note that this relies on the structure of the AArch64 register file. In
1479 // particular, a subregister cannot be written without overwriting the
1480 // whole register.
1481 if (RegClass->HasDisjunctSubRegs) {
1482 LLVM_DEBUG(
1483 dbgs()
1484 << " Cannot rename operands with multiple disjunct subregisters ("
1485 << MOP << ")\n");
1486 return false;
1487 }
1488
1489 // We cannot rename arbitrary implicit-defs, the specific rule to rewrite
1490 // them must be known. For example, in ORRWrs the implicit-def
1491 // corresponds to the result register.
1492 if (MOP.isImplicit() && MOP.isDef()) {
1494 return false;
1495 return TRI->isSuperOrSubRegisterEq(
1496 MOP.getParent()->getOperand(0).getReg(), MOP.getReg());
1497 }
1498 }
1499 return MOP.isImplicit() ||
1500 (MOP.isRenamable() && !MOP.isEarlyClobber() && !MOP.isTied());
1501}
1502
1503static bool
1506 const TargetRegisterInfo *TRI) {
1507 if (!FirstMI.mayStore())
1508 return false;
1509
1510 // Check if we can find an unused register which we can use to rename
1511 // the register used by the first load/store.
1512
1513 auto RegToRename = getLdStRegOp(FirstMI).getReg();
1514 // For now, we only rename if the store operand gets killed at the store.
1515 if (!getLdStRegOp(FirstMI).isKill() &&
1516 !any_of(FirstMI.operands(),
1517 [TRI, RegToRename](const MachineOperand &MOP) {
1518 return MOP.isReg() && !MOP.isDebug() && MOP.getReg() &&
1519 MOP.isImplicit() && MOP.isKill() &&
1520 TRI->regsOverlap(RegToRename, MOP.getReg());
1521 })) {
1522 LLVM_DEBUG(dbgs() << " Operand not killed at " << FirstMI);
1523 return false;
1524 }
1525
1526 bool FoundDef = false;
1527
1528 // For each instruction between FirstMI and the previous def for RegToRename,
1529 // we
1530 // * check if we can rename RegToRename in this instruction
1531 // * collect the registers used and required register classes for RegToRename.
1532 std::function<bool(MachineInstr &, bool)> CheckMIs = [&](MachineInstr &MI,
1533 bool IsDef) {
1534 LLVM_DEBUG(dbgs() << "Checking " << MI);
1535 // Currently we do not try to rename across frame-setup instructions.
1536 if (MI.getFlag(MachineInstr::FrameSetup)) {
1537 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1538 << "currently\n");
1539 return false;
1540 }
1541
1542 UsedInBetween.accumulate(MI);
1543
1544 // For a definition, check that we can rename the definition and exit the
1545 // loop.
1546 FoundDef = IsDef;
1547
1548 // For defs, check if we can rename the first def of RegToRename.
1549 if (FoundDef) {
1550 // For some pseudo instructions, we might not generate code in the end
1551 // (e.g. KILL) and we would end up without a correct def for the rename
1552 // register.
1553 // TODO: This might be overly conservative and we could handle those cases
1554 // in multiple ways:
1555 // 1. Insert an extra copy, to materialize the def.
1556 // 2. Skip pseudo-defs until we find an non-pseudo def.
1557 if (MI.isPseudo()) {
1558 LLVM_DEBUG(dbgs() << " Cannot rename pseudo/bundle instruction\n");
1559 return false;
1560 }
1561
1562 for (auto &MOP : MI.operands()) {
1563 if (!MOP.isReg() || !MOP.isDef() || MOP.isDebug() || !MOP.getReg() ||
1564 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1565 continue;
1566 if (!canRenameMOP(MOP, TRI)) {
1567 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1568 return false;
1569 }
1570 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1571 }
1572 return true;
1573 } else {
1574 for (auto &MOP : MI.operands()) {
1575 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1576 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1577 continue;
1578
1579 if (!canRenameMOP(MOP, TRI)) {
1580 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1581 return false;
1582 }
1583 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1584 }
1585 }
1586 return true;
1587 };
1588
1589 if (!forAllMIsUntilDef(FirstMI, RegToRename, TRI, LdStLimit, CheckMIs))
1590 return false;
1591
1592 if (!FoundDef) {
1593 LLVM_DEBUG(dbgs() << " Did not find definition for register in BB\n");
1594 return false;
1595 }
1596 return true;
1597}
1598
1599// We want to merge the second load into the first by rewriting the usages of
1600// the same reg between first (incl.) and second (excl.). We don't need to care
1601// about any insns before FirstLoad or after SecondLoad.
1602// 1. The second load writes new value into the same reg.
1603// - The renaming is impossible to impact later use of the reg.
1604// - The second load always trash the value written by the first load which
1605// means the reg must be killed before the second load.
1606// 2. The first load must be a def for the same reg so we don't need to look
1607// into anything before it.
1609 MachineInstr &FirstLoad, MachineInstr &SecondLoad,
1610 LiveRegUnits &UsedInBetween,
1612 const TargetRegisterInfo *TRI) {
1613 if (FirstLoad.isPseudo())
1614 return false;
1615
1616 UsedInBetween.accumulate(FirstLoad);
1617 auto RegToRename = getLdStRegOp(FirstLoad).getReg();
1618 bool Success = std::all_of(
1619 FirstLoad.getIterator(), SecondLoad.getIterator(),
1620 [&](MachineInstr &MI) {
1621 LLVM_DEBUG(dbgs() << "Checking " << MI);
1622 // Currently we do not try to rename across frame-setup instructions.
1623 if (MI.getFlag(MachineInstr::FrameSetup)) {
1624 LLVM_DEBUG(dbgs() << " Cannot rename framesetup instructions "
1625 << "currently\n");
1626 return false;
1627 }
1628
1629 for (auto &MOP : MI.operands()) {
1630 if (!MOP.isReg() || MOP.isDebug() || !MOP.getReg() ||
1631 !TRI->regsOverlap(MOP.getReg(), RegToRename))
1632 continue;
1633 if (!canRenameMOP(MOP, TRI)) {
1634 LLVM_DEBUG(dbgs() << " Cannot rename " << MOP << " in " << MI);
1635 return false;
1636 }
1637 RequiredClasses.insert(TRI->getMinimalPhysRegClass(MOP.getReg()));
1638 }
1639
1640 return true;
1641 });
1642 return Success;
1643}
1644
1645// Check if we can find a physical register for renaming \p Reg. This register
1646// must:
1647// * not be defined already in \p DefinedInBB; DefinedInBB must contain all
1648// defined registers up to the point where the renamed register will be used,
1649// * not used in \p UsedInBetween; UsedInBetween must contain all accessed
1650// registers in the range the rename register will be used,
1651// * is available in all used register classes (checked using RequiredClasses).
1652static std::optional<MCPhysReg> tryToFindRegisterToRename(
1653 const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB,
1654 LiveRegUnits &UsedInBetween,
1656 const TargetRegisterInfo *TRI) {
1658
1659 // Checks if any sub- or super-register of PR is callee saved.
1660 auto AnySubOrSuperRegCalleePreserved = [&MF, TRI](MCPhysReg PR) {
1661 return any_of(TRI->sub_and_superregs_inclusive(PR),
1662 [&MF, TRI](MCPhysReg SubOrSuper) {
1663 return TRI->isCalleeSavedPhysReg(SubOrSuper, MF);
1664 });
1665 };
1666
1667 // Check if PR or one of its sub- or super-registers can be used for all
1668 // required register classes.
1669 auto CanBeUsedForAllClasses = [&RequiredClasses, TRI](MCPhysReg PR) {
1670 return all_of(RequiredClasses, [PR, TRI](const TargetRegisterClass *C) {
1671 return any_of(
1672 TRI->sub_and_superregs_inclusive(PR),
1673 [C](MCPhysReg SubOrSuper) { return C->contains(SubOrSuper); });
1674 });
1675 };
1676
1677 auto *RegClass = TRI->getMinimalPhysRegClass(Reg);
1678 for (const MCPhysReg &PR : *RegClass) {
1679 if (DefinedInBB.available(PR) && UsedInBetween.available(PR) &&
1680 !RegInfo.isReserved(PR) && !AnySubOrSuperRegCalleePreserved(PR) &&
1681 CanBeUsedForAllClasses(PR)) {
1682 DefinedInBB.addReg(PR);
1683 LLVM_DEBUG(dbgs() << "Found rename register " << printReg(PR, TRI)
1684 << "\n");
1685 return {PR};
1686 }
1687 }
1688 LLVM_DEBUG(dbgs() << "No rename register found from "
1689 << TRI->getRegClassName(RegClass) << "\n");
1690 return std::nullopt;
1691}
1692
1693// For store pairs: returns a register from FirstMI to the beginning of the
1694// block that can be renamed.
1695// For load pairs: returns a register from FirstMI to MI that can be renamed.
1696static std::optional<MCPhysReg> findRenameRegForSameLdStRegPair(
1697 std::optional<bool> MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI,
1698 Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween,
1700 const TargetRegisterInfo *TRI) {
1701 std::optional<MCPhysReg> RenameReg;
1702 if (!DebugCounter::shouldExecute(RegRenamingCounter))
1703 return RenameReg;
1704
1705 auto *RegClass = TRI->getMinimalPhysRegClass(getLdStRegOp(FirstMI).getReg());
1706 MachineFunction &MF = *FirstMI.getParent()->getParent();
1707 if (!RegClass || !MF.getRegInfo().tracksLiveness())
1708 return RenameReg;
1709
1710 const bool IsLoad = FirstMI.mayLoad();
1711
1712 if (!MaybeCanRename) {
1713 if (IsLoad)
1714 MaybeCanRename = {canRenameUntilSecondLoad(FirstMI, MI, UsedInBetween,
1715 RequiredClasses, TRI)};
1716 else
1717 MaybeCanRename = {
1718 canRenameUpToDef(FirstMI, UsedInBetween, RequiredClasses, TRI)};
1719 }
1720
1721 if (*MaybeCanRename) {
1722 RenameReg = tryToFindRegisterToRename(MF, Reg, DefinedInBB, UsedInBetween,
1723 RequiredClasses, TRI);
1724 }
1725 return RenameReg;
1726}
1727
1728/// Scan the instructions looking for a load/store that can be combined with the
1729/// current instruction into a wider equivalent or a load/store pair.
1731AArch64LoadStoreOpt::findMatchingInsn(MachineBasicBlock::iterator I,
1732 LdStPairFlags &Flags, unsigned Limit,
1733 bool FindNarrowMerge) {
1734 MachineBasicBlock::iterator E = I->getParent()->end();
1736 MachineBasicBlock::iterator MBBIWithRenameReg;
1737 MachineInstr &FirstMI = *I;
1738 MBBI = next_nodbg(MBBI, E);
1739
1740 bool MayLoad = FirstMI.mayLoad();
1741 bool IsUnscaled = TII->hasUnscaledLdStOffset(FirstMI);
1742 Register Reg = getLdStRegOp(FirstMI).getReg();
1743 Register BaseReg = AArch64InstrInfo::getLdStBaseOp(FirstMI).getReg();
1745 int OffsetStride = IsUnscaled ? TII->getMemScale(FirstMI) : 1;
1746 bool IsPromotableZeroStore = isPromotableZeroStoreInst(FirstMI);
1747
1748 std::optional<bool> MaybeCanRename;
1749 if (!EnableRenaming)
1750 MaybeCanRename = {false};
1751
1753 LiveRegUnits UsedInBetween;
1754 UsedInBetween.init(*TRI);
1755
1756 Flags.clearRenameReg();
1757
1758 // Track which register units have been modified and used between the first
1759 // insn (inclusive) and the second insn.
1760 ModifiedRegUnits.clear();
1761 UsedRegUnits.clear();
1762
1763 // Remember any instructions that read/write memory between FirstMI and MI.
1765
1766 LLVM_DEBUG(dbgs() << "Find match for: "; FirstMI.dump());
1767 for (unsigned Count = 0; MBBI != E && Count < Limit;
1768 MBBI = next_nodbg(MBBI, E)) {
1769 MachineInstr &MI = *MBBI;
1770 LLVM_DEBUG(dbgs() << "Analysing 2nd insn: "; MI.dump());
1771
1772 UsedInBetween.accumulate(MI);
1773
1774 // Don't count transient instructions towards the search limit since there
1775 // may be different numbers of them if e.g. debug information is present.
1776 if (!MI.isTransient())
1777 ++Count;
1778
1779 Flags.setSExtIdx(-1);
1780 if (areCandidatesToMergeOrPair(FirstMI, MI, Flags, TII) &&
1782 assert(MI.mayLoadOrStore() && "Expected memory operation.");
1783 // If we've found another instruction with the same opcode, check to see
1784 // if the base and offset are compatible with our starting instruction.
1785 // These instructions all have scaled immediate operands, so we just
1786 // check for +1/-1. Make sure to check the new instruction offset is
1787 // actually an immediate and not a symbolic reference destined for
1788 // a relocation.
1791 bool MIIsUnscaled = TII->hasUnscaledLdStOffset(MI);
1792 if (IsUnscaled != MIIsUnscaled) {
1793 // We're trying to pair instructions that differ in how they are scaled.
1794 // If FirstMI is scaled then scale the offset of MI accordingly.
1795 // Otherwise, do the opposite (i.e., make MI's offset unscaled).
1796 int MemSize = TII->getMemScale(MI);
1797 if (MIIsUnscaled) {
1798 // If the unscaled offset isn't a multiple of the MemSize, we can't
1799 // pair the operations together: bail and keep looking.
1800 if (MIOffset % MemSize) {
1801 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1802 UsedRegUnits, TRI);
1803 MemInsns.push_back(&MI);
1804 continue;
1805 }
1806 MIOffset /= MemSize;
1807 } else {
1808 MIOffset *= MemSize;
1809 }
1810 }
1811
1812 bool IsPreLdSt = isPreLdStPairCandidate(FirstMI, MI);
1813
1814 if (BaseReg == MIBaseReg) {
1815 // If the offset of the second ld/st is not equal to the size of the
1816 // destination register it can’t be paired with a pre-index ld/st
1817 // pair. Additionally if the base reg is used or modified the operations
1818 // can't be paired: bail and keep looking.
1819 if (IsPreLdSt) {
1820 bool IsOutOfBounds = MIOffset != TII->getMemScale(MI);
1821 bool IsBaseRegUsed = !UsedRegUnits.available(
1823 bool IsBaseRegModified = !ModifiedRegUnits.available(
1825 // If the stored value and the address of the second instruction is
1826 // the same, it needs to be using the updated register and therefore
1827 // it must not be folded.
1828 bool IsMIRegTheSame =
1829 TRI->regsOverlap(getLdStRegOp(MI).getReg(),
1831 if (IsOutOfBounds || IsBaseRegUsed || IsBaseRegModified ||
1832 IsMIRegTheSame) {
1833 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1834 UsedRegUnits, TRI);
1835 MemInsns.push_back(&MI);
1836 continue;
1837 }
1838 } else {
1839 if ((Offset != MIOffset + OffsetStride) &&
1840 (Offset + OffsetStride != MIOffset)) {
1841 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1842 UsedRegUnits, TRI);
1843 MemInsns.push_back(&MI);
1844 continue;
1845 }
1846 }
1847
1848 int MinOffset = Offset < MIOffset ? Offset : MIOffset;
1849 if (FindNarrowMerge) {
1850 // If the alignment requirements of the scaled wide load/store
1851 // instruction can't express the offset of the scaled narrow input,
1852 // bail and keep looking. For promotable zero stores, allow only when
1853 // the stored value is the same (i.e., WZR).
1854 if ((!IsUnscaled && alignTo(MinOffset, 2) != MinOffset) ||
1855 (IsPromotableZeroStore && Reg != getLdStRegOp(MI).getReg())) {
1856 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1857 UsedRegUnits, TRI);
1858 MemInsns.push_back(&MI);
1859 continue;
1860 }
1861 } else {
1862 // Pairwise instructions have a 7-bit signed offset field. Single
1863 // insns have a 12-bit unsigned offset field. If the resultant
1864 // immediate offset of merging these instructions is out of range for
1865 // a pairwise instruction, bail and keep looking.
1866 if (!inBoundsForPair(IsUnscaled, MinOffset, OffsetStride)) {
1867 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1868 UsedRegUnits, TRI);
1869 MemInsns.push_back(&MI);
1870 LLVM_DEBUG(dbgs() << "Offset doesn't fit in immediate, "
1871 << "keep looking.\n");
1872 continue;
1873 }
1874 // If the alignment requirements of the paired (scaled) instruction
1875 // can't express the offset of the unscaled input, bail and keep
1876 // looking.
1877 if (IsUnscaled && (alignTo(MinOffset, OffsetStride) != MinOffset)) {
1878 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1879 UsedRegUnits, TRI);
1880 MemInsns.push_back(&MI);
1882 << "Offset doesn't fit due to alignment requirements, "
1883 << "keep looking.\n");
1884 continue;
1885 }
1886 }
1887
1888 // If the BaseReg has been modified, then we cannot do the optimization.
1889 // For example, in the following pattern
1890 // ldr x1 [x2]
1891 // ldr x2 [x3]
1892 // ldr x4 [x2, #8],
1893 // the first and third ldr cannot be converted to ldp x1, x4, [x2]
1894 if (!ModifiedRegUnits.available(BaseReg))
1895 return E;
1896
1897 const bool SameLoadReg = MayLoad && TRI->isSuperOrSubRegisterEq(
1898 Reg, getLdStRegOp(MI).getReg());
1899
1900 // If the Rt of the second instruction (destination register of the
1901 // load) was not modified or used between the two instructions and none
1902 // of the instructions between the second and first alias with the
1903 // second, we can combine the second into the first.
1904 bool RtNotModified =
1905 ModifiedRegUnits.available(getLdStRegOp(MI).getReg());
1906 bool RtNotUsed = !(MI.mayLoad() && !SameLoadReg &&
1907 !UsedRegUnits.available(getLdStRegOp(MI).getReg()));
1908
1909 LLVM_DEBUG(dbgs() << "Checking, can combine 2nd into 1st insn:\n"
1910 << "Reg '" << getLdStRegOp(MI) << "' not modified: "
1911 << (RtNotModified ? "true" : "false") << "\n"
1912 << "Reg '" << getLdStRegOp(MI) << "' not used: "
1913 << (RtNotUsed ? "true" : "false") << "\n");
1914
1915 if (RtNotModified && RtNotUsed && !mayAlias(MI, MemInsns, AA)) {
1916 // For pairs loading into the same reg, try to find a renaming
1917 // opportunity to allow the renaming of Reg between FirstMI and MI
1918 // and combine MI into FirstMI; otherwise bail and keep looking.
1919 if (SameLoadReg) {
1920 std::optional<MCPhysReg> RenameReg =
1921 findRenameRegForSameLdStRegPair(MaybeCanRename, FirstMI, MI,
1922 Reg, DefinedInBB, UsedInBetween,
1923 RequiredClasses, TRI);
1924 if (!RenameReg) {
1925 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits,
1926 UsedRegUnits, TRI);
1927 MemInsns.push_back(&MI);
1928 LLVM_DEBUG(dbgs() << "Can't find reg for renaming, "
1929 << "keep looking.\n");
1930 continue;
1931 }
1932 Flags.setRenameReg(*RenameReg);
1933 }
1934
1935 Flags.setMergeForward(false);
1936 if (!SameLoadReg)
1937 Flags.clearRenameReg();
1938 return MBBI;
1939 }
1940
1941 // Likewise, if the Rt of the first instruction is not modified or used
1942 // between the two instructions and none of the instructions between the
1943 // first and the second alias with the first, we can combine the first
1944 // into the second.
1945 RtNotModified = !(
1946 MayLoad && !UsedRegUnits.available(getLdStRegOp(FirstMI).getReg()));
1947
1948 LLVM_DEBUG(dbgs() << "Checking, can combine 1st into 2nd insn:\n"
1949 << "Reg '" << getLdStRegOp(FirstMI)
1950 << "' not modified: "
1951 << (RtNotModified ? "true" : "false") << "\n");
1952
1953 if (RtNotModified && !mayAlias(FirstMI, MemInsns, AA)) {
1954 if (ModifiedRegUnits.available(getLdStRegOp(FirstMI).getReg())) {
1955 Flags.setMergeForward(true);
1956 Flags.clearRenameReg();
1957 return MBBI;
1958 }
1959
1960 std::optional<MCPhysReg> RenameReg = findRenameRegForSameLdStRegPair(
1961 MaybeCanRename, FirstMI, MI, Reg, DefinedInBB, UsedInBetween,
1962 RequiredClasses, TRI);
1963 if (RenameReg) {
1964 Flags.setMergeForward(true);
1965 Flags.setRenameReg(*RenameReg);
1966 MBBIWithRenameReg = MBBI;
1967 }
1968 }
1969 LLVM_DEBUG(dbgs() << "Unable to combine these instructions due to "
1970 << "interference in between, keep looking.\n");
1971 }
1972 }
1973
1974 if (Flags.getRenameReg())
1975 return MBBIWithRenameReg;
1976
1977 // If the instruction wasn't a matching load or store. Stop searching if we
1978 // encounter a call instruction that might modify memory.
1979 if (MI.isCall()) {
1980 LLVM_DEBUG(dbgs() << "Found a call, stop looking.\n");
1981 return E;
1982 }
1983
1984 // Update modified / uses register units.
1985 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
1986
1987 // Otherwise, if the base register is modified, we have no match, so
1988 // return early.
1989 if (!ModifiedRegUnits.available(BaseReg)) {
1990 LLVM_DEBUG(dbgs() << "Base reg is modified, stop looking.\n");
1991 return E;
1992 }
1993
1994 // Update list of instructions that read/write memory.
1995 if (MI.mayLoadOrStore())
1996 MemInsns.push_back(&MI);
1997 }
1998 return E;
1999}
2000
2003 assert((MI.getOpcode() == AArch64::SUBXri ||
2004 MI.getOpcode() == AArch64::ADDXri) &&
2005 "Expected a register update instruction");
2006 auto End = MI.getParent()->end();
2007 if (MaybeCFI == End ||
2008 MaybeCFI->getOpcode() != TargetOpcode::CFI_INSTRUCTION ||
2009 !(MI.getFlag(MachineInstr::FrameSetup) ||
2010 MI.getFlag(MachineInstr::FrameDestroy)) ||
2011 MI.getOperand(0).getReg() != AArch64::SP)
2012 return End;
2013
2014 const MachineFunction &MF = *MI.getParent()->getParent();
2015 unsigned CFIIndex = MaybeCFI->getOperand(0).getCFIIndex();
2016 const MCCFIInstruction &CFI = MF.getFrameInstructions()[CFIIndex];
2017 switch (CFI.getOperation()) {
2020 return MaybeCFI;
2021 default:
2022 return End;
2023 }
2024}
2025
2027AArch64LoadStoreOpt::mergeUpdateInsn(MachineBasicBlock::iterator I,
2029 bool IsPreIdx) {
2030 assert((Update->getOpcode() == AArch64::ADDXri ||
2031 Update->getOpcode() == AArch64::SUBXri) &&
2032 "Unexpected base register update instruction to merge!");
2033 MachineBasicBlock::iterator E = I->getParent()->end();
2035
2036 // If updating the SP and the following instruction is CFA offset related CFI
2037 // instruction move it after the merged instruction.
2039 IsPreIdx ? maybeMoveCFI(*Update, next_nodbg(Update, E)) : E;
2040
2041 // Return the instruction following the merged instruction, which is
2042 // the instruction following our unmerged load. Unless that's the add/sub
2043 // instruction we're merging, in which case it's the one after that.
2044 if (NextI == Update)
2045 NextI = next_nodbg(NextI, E);
2046
2047 int Value = Update->getOperand(2).getImm();
2048 assert(AArch64_AM::getShiftValue(Update->getOperand(3).getImm()) == 0 &&
2049 "Can't merge 1 << 12 offset into pre-/post-indexed load / store");
2050 if (Update->getOpcode() == AArch64::SUBXri)
2051 Value = -Value;
2052
2053 unsigned NewOpc = IsPreIdx ? getPreIndexedOpcode(I->getOpcode())
2056 int Scale, MinOffset, MaxOffset;
2057 getPrePostIndexedMemOpInfo(*I, Scale, MinOffset, MaxOffset);
2059 // Non-paired instruction.
2060 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2061 .add(Update->getOperand(0))
2062 .add(getLdStRegOp(*I))
2064 .addImm(Value / Scale)
2065 .setMemRefs(I->memoperands())
2066 .setMIFlags(I->mergeFlagsWith(*Update));
2067 } else {
2068 // Paired instruction.
2069 MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2070 .add(Update->getOperand(0))
2071 .add(getLdStRegOp(*I, 0))
2072 .add(getLdStRegOp(*I, 1))
2074 .addImm(Value / Scale)
2075 .setMemRefs(I->memoperands())
2076 .setMIFlags(I->mergeFlagsWith(*Update));
2077 }
2078 if (CFI != E) {
2079 MachineBasicBlock *MBB = I->getParent();
2080 MBB->splice(std::next(MIB.getInstr()->getIterator()), MBB, CFI);
2081 }
2082
2083 if (IsPreIdx) {
2084 ++NumPreFolded;
2085 LLVM_DEBUG(dbgs() << "Creating pre-indexed load/store.");
2086 } else {
2087 ++NumPostFolded;
2088 LLVM_DEBUG(dbgs() << "Creating post-indexed load/store.");
2089 }
2090 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2091 LLVM_DEBUG(I->print(dbgs()));
2092 LLVM_DEBUG(dbgs() << " ");
2093 LLVM_DEBUG(Update->print(dbgs()));
2094 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2095 LLVM_DEBUG(((MachineInstr *)MIB)->print(dbgs()));
2096 LLVM_DEBUG(dbgs() << "\n");
2097
2098 // Erase the old instructions for the block.
2099 I->eraseFromParent();
2100 Update->eraseFromParent();
2101
2102 return NextI;
2103}
2104
2106AArch64LoadStoreOpt::mergeConstOffsetInsn(MachineBasicBlock::iterator I,
2108 unsigned Offset, int Scale) {
2109 assert((Update->getOpcode() == AArch64::MOVKWi) &&
2110 "Unexpected const mov instruction to merge!");
2111 MachineBasicBlock::iterator E = I->getParent()->end();
2113 MachineBasicBlock::iterator PrevI = prev_nodbg(Update, E);
2114 MachineInstr &MemMI = *I;
2115 unsigned Mask = (1 << 12) * Scale - 1;
2116 unsigned Low = Offset & Mask;
2117 unsigned High = Offset - Low;
2120 MachineInstrBuilder AddMIB, MemMIB;
2121
2122 // Add IndexReg, BaseReg, High (the BaseReg may be SP)
2123 AddMIB =
2124 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(AArch64::ADDXri))
2125 .addDef(IndexReg)
2126 .addUse(BaseReg)
2127 .addImm(High >> 12) // shifted value
2128 .addImm(12); // shift 12
2129 (void)AddMIB;
2130 // Ld/St DestReg, IndexReg, Imm12
2131 unsigned NewOpc = getBaseAddressOpcode(I->getOpcode());
2132 MemMIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), TII->get(NewOpc))
2133 .add(getLdStRegOp(MemMI))
2135 .addImm(Low / Scale)
2136 .setMemRefs(I->memoperands())
2137 .setMIFlags(I->mergeFlagsWith(*Update));
2138 (void)MemMIB;
2139
2140 ++NumConstOffsetFolded;
2141 LLVM_DEBUG(dbgs() << "Creating base address load/store.\n");
2142 LLVM_DEBUG(dbgs() << " Replacing instructions:\n ");
2143 LLVM_DEBUG(PrevI->print(dbgs()));
2144 LLVM_DEBUG(dbgs() << " ");
2145 LLVM_DEBUG(Update->print(dbgs()));
2146 LLVM_DEBUG(dbgs() << " ");
2147 LLVM_DEBUG(I->print(dbgs()));
2148 LLVM_DEBUG(dbgs() << " with instruction:\n ");
2149 LLVM_DEBUG(((MachineInstr *)AddMIB)->print(dbgs()));
2150 LLVM_DEBUG(dbgs() << " ");
2151 LLVM_DEBUG(((MachineInstr *)MemMIB)->print(dbgs()));
2152 LLVM_DEBUG(dbgs() << "\n");
2153
2154 // Erase the old instructions for the block.
2155 I->eraseFromParent();
2156 PrevI->eraseFromParent();
2157 Update->eraseFromParent();
2158
2159 return NextI;
2160}
2161
2162bool AArch64LoadStoreOpt::isMatchingUpdateInsn(MachineInstr &MemMI,
2164 unsigned BaseReg, int Offset) {
2165 switch (MI.getOpcode()) {
2166 default:
2167 break;
2168 case AArch64::SUBXri:
2169 case AArch64::ADDXri:
2170 // Make sure it's a vanilla immediate operand, not a relocation or
2171 // anything else we can't handle.
2172 if (!MI.getOperand(2).isImm())
2173 break;
2174 // Watch out for 1 << 12 shifted value.
2175 if (AArch64_AM::getShiftValue(MI.getOperand(3).getImm()))
2176 break;
2177
2178 // The update instruction source and destination register must be the
2179 // same as the load/store base register.
2180 if (MI.getOperand(0).getReg() != BaseReg ||
2181 MI.getOperand(1).getReg() != BaseReg)
2182 break;
2183
2184 int UpdateOffset = MI.getOperand(2).getImm();
2185 if (MI.getOpcode() == AArch64::SUBXri)
2186 UpdateOffset = -UpdateOffset;
2187
2188 // The immediate must be a multiple of the scaling factor of the pre/post
2189 // indexed instruction.
2190 int Scale, MinOffset, MaxOffset;
2191 getPrePostIndexedMemOpInfo(MemMI, Scale, MinOffset, MaxOffset);
2192 if (UpdateOffset % Scale != 0)
2193 break;
2194
2195 // Scaled offset must fit in the instruction immediate.
2196 int ScaledOffset = UpdateOffset / Scale;
2197 if (ScaledOffset > MaxOffset || ScaledOffset < MinOffset)
2198 break;
2199
2200 // If we have a non-zero Offset, we check that it matches the amount
2201 // we're adding to the register.
2202 if (!Offset || Offset == UpdateOffset)
2203 return true;
2204 break;
2205 }
2206 return false;
2207}
2208
2209bool AArch64LoadStoreOpt::isMatchingMovConstInsn(MachineInstr &MemMI,
2211 unsigned IndexReg,
2212 unsigned &Offset) {
2213 // The update instruction source and destination register must be the
2214 // same as the load/store index register.
2215 if (MI.getOpcode() == AArch64::MOVKWi &&
2216 TRI->isSuperOrSubRegisterEq(IndexReg, MI.getOperand(1).getReg())) {
2217
2218 // movz + movk hold a large offset of a Ld/St instruction.
2219 MachineBasicBlock::iterator B = MI.getParent()->begin();
2221 // Skip the scene when the MI is the first instruction of a block.
2222 if (MBBI == B)
2223 return false;
2224 MBBI = prev_nodbg(MBBI, B);
2225 MachineInstr &MovzMI = *MBBI;
2226 if (MovzMI.getOpcode() == AArch64::MOVZWi) {
2227 unsigned Low = MovzMI.getOperand(1).getImm();
2228 unsigned High = MI.getOperand(2).getImm() << MI.getOperand(3).getImm();
2229 Offset = High + Low;
2230 // 12-bit optionally shifted immediates are legal for adds.
2231 return Offset >> 24 == 0;
2232 }
2233 }
2234 return false;
2235}
2236
2237MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnForward(
2238 MachineBasicBlock::iterator I, int UnscaledOffset, unsigned Limit) {
2239 MachineBasicBlock::iterator E = I->getParent()->end();
2240 MachineInstr &MemMI = *I;
2242
2244 int MIUnscaledOffset = AArch64InstrInfo::getLdStOffsetOp(MemMI).getImm() *
2245 TII->getMemScale(MemMI);
2246
2247 // Scan forward looking for post-index opportunities. Updating instructions
2248 // can't be formed if the memory instruction doesn't have the offset we're
2249 // looking for.
2250 if (MIUnscaledOffset != UnscaledOffset)
2251 return E;
2252
2253 // If the base register overlaps a source/destination register, we can't
2254 // merge the update. This does not apply to tag store instructions which
2255 // ignore the address part of the source register.
2256 // This does not apply to STGPi as well, which does not have unpredictable
2257 // behavior in this case unlike normal stores, and always performs writeback
2258 // after reading the source register value.
2259 if (!isTagStore(MemMI) && MemMI.getOpcode() != AArch64::STGPi) {
2260 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2261 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2262 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2263 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2264 return E;
2265 }
2266 }
2267
2268 // Track which register units have been modified and used between the first
2269 // insn (inclusive) and the second insn.
2270 ModifiedRegUnits.clear();
2271 UsedRegUnits.clear();
2272 MBBI = next_nodbg(MBBI, E);
2273
2274 // We can't post-increment the stack pointer if any instruction between
2275 // the memory access (I) and the increment (MBBI) can access the memory
2276 // region defined by [SP, MBBI].
2277 const bool BaseRegSP = BaseReg == AArch64::SP;
2278 if (BaseRegSP && needsWinCFI(I->getMF())) {
2279 // FIXME: For now, we always block the optimization over SP in windows
2280 // targets as it requires to adjust the unwind/debug info, messing up
2281 // the unwind info can actually cause a miscompile.
2282 return E;
2283 }
2284
2285 for (unsigned Count = 0; MBBI != E && Count < Limit;
2286 MBBI = next_nodbg(MBBI, E)) {
2287 MachineInstr &MI = *MBBI;
2288
2289 // Don't count transient instructions towards the search limit since there
2290 // may be different numbers of them if e.g. debug information is present.
2291 if (!MI.isTransient())
2292 ++Count;
2293
2294 // If we found a match, return it.
2295 if (isMatchingUpdateInsn(*I, MI, BaseReg, UnscaledOffset))
2296 return MBBI;
2297
2298 // Update the status of what the instruction clobbered and used.
2299 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2300
2301 // Otherwise, if the base register is used or modified, we have no match, so
2302 // return early.
2303 // If we are optimizing SP, do not allow instructions that may load or store
2304 // in between the load and the optimized value update.
2305 if (!ModifiedRegUnits.available(BaseReg) ||
2306 !UsedRegUnits.available(BaseReg) ||
2307 (BaseRegSP && MBBI->mayLoadOrStore()))
2308 return E;
2309 }
2310 return E;
2311}
2312
2313MachineBasicBlock::iterator AArch64LoadStoreOpt::findMatchingUpdateInsnBackward(
2314 MachineBasicBlock::iterator I, unsigned Limit) {
2315 MachineBasicBlock::iterator B = I->getParent()->begin();
2316 MachineBasicBlock::iterator E = I->getParent()->end();
2317 MachineInstr &MemMI = *I;
2319 MachineFunction &MF = *MemMI.getMF();
2320
2323
2324 // If the load/store is the first instruction in the block, there's obviously
2325 // not any matching update. Ditto if the memory offset isn't zero.
2326 if (MBBI == B || Offset != 0)
2327 return E;
2328 // If the base register overlaps a destination register, we can't
2329 // merge the update.
2330 if (!isTagStore(MemMI)) {
2331 bool IsPairedInsn = AArch64InstrInfo::isPairedLdSt(MemMI);
2332 for (unsigned i = 0, e = IsPairedInsn ? 2 : 1; i != e; ++i) {
2333 Register DestReg = getLdStRegOp(MemMI, i).getReg();
2334 if (DestReg == BaseReg || TRI->isSubRegister(BaseReg, DestReg))
2335 return E;
2336 }
2337 }
2338
2339 const bool BaseRegSP = BaseReg == AArch64::SP;
2340 if (BaseRegSP && needsWinCFI(I->getMF())) {
2341 // FIXME: For now, we always block the optimization over SP in windows
2342 // targets as it requires to adjust the unwind/debug info, messing up
2343 // the unwind info can actually cause a miscompile.
2344 return E;
2345 }
2346
2347 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
2348 unsigned RedZoneSize =
2349 Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
2350
2351 // Track which register units have been modified and used between the first
2352 // insn (inclusive) and the second insn.
2353 ModifiedRegUnits.clear();
2354 UsedRegUnits.clear();
2355 unsigned Count = 0;
2356 bool MemAcessBeforeSPPreInc = false;
2357 do {
2358 MBBI = prev_nodbg(MBBI, B);
2359 MachineInstr &MI = *MBBI;
2360
2361 // Don't count transient instructions towards the search limit since there
2362 // may be different numbers of them if e.g. debug information is present.
2363 if (!MI.isTransient())
2364 ++Count;
2365
2366 // If we found a match, return it.
2367 if (isMatchingUpdateInsn(*I, MI, BaseReg, Offset)) {
2368 // Check that the update value is within our red zone limit (which may be
2369 // zero).
2370 if (MemAcessBeforeSPPreInc && MBBI->getOperand(2).getImm() > RedZoneSize)
2371 return E;
2372 return MBBI;
2373 }
2374
2375 // Update the status of what the instruction clobbered and used.
2376 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2377
2378 // Otherwise, if the base register is used or modified, we have no match, so
2379 // return early.
2380 if (!ModifiedRegUnits.available(BaseReg) ||
2381 !UsedRegUnits.available(BaseReg))
2382 return E;
2383 // Keep track if we have a memory access before an SP pre-increment, in this
2384 // case we need to validate later that the update amount respects the red
2385 // zone.
2386 if (BaseRegSP && MBBI->mayLoadOrStore())
2387 MemAcessBeforeSPPreInc = true;
2388 } while (MBBI != B && Count < Limit);
2389 return E;
2390}
2391
2393AArch64LoadStoreOpt::findMatchingConstOffsetBackward(
2394 MachineBasicBlock::iterator I, unsigned Limit, unsigned &Offset) {
2395 MachineBasicBlock::iterator B = I->getParent()->begin();
2396 MachineBasicBlock::iterator E = I->getParent()->end();
2397 MachineInstr &MemMI = *I;
2399
2400 // If the load is the first instruction in the block, there's obviously
2401 // not any matching load or store.
2402 if (MBBI == B)
2403 return E;
2404
2405 // Make sure the IndexReg is killed and the shift amount is zero.
2406 // TODO: Relex this restriction to extend, simplify processing now.
2407 if (!AArch64InstrInfo::getLdStOffsetOp(MemMI).isKill() ||
2409 (AArch64InstrInfo::getLdStAmountOp(MemMI).getImm() != 0))
2410 return E;
2411
2413
2414 // Track which register units have been modified and used between the first
2415 // insn (inclusive) and the second insn.
2416 ModifiedRegUnits.clear();
2417 UsedRegUnits.clear();
2418 unsigned Count = 0;
2419 do {
2420 MBBI = prev_nodbg(MBBI, B);
2421 MachineInstr &MI = *MBBI;
2422
2423 // Don't count transient instructions towards the search limit since there
2424 // may be different numbers of them if e.g. debug information is present.
2425 if (!MI.isTransient())
2426 ++Count;
2427
2428 // If we found a match, return it.
2429 if (isMatchingMovConstInsn(*I, MI, IndexReg, Offset)) {
2430 return MBBI;
2431 }
2432
2433 // Update the status of what the instruction clobbered and used.
2434 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
2435
2436 // Otherwise, if the index register is used or modified, we have no match,
2437 // so return early.
2438 if (!ModifiedRegUnits.available(IndexReg) ||
2439 !UsedRegUnits.available(IndexReg))
2440 return E;
2441
2442 } while (MBBI != B && Count < Limit);
2443 return E;
2444}
2445
2446bool AArch64LoadStoreOpt::tryToPromoteLoadFromStore(
2448 MachineInstr &MI = *MBBI;
2449 // If this is a volatile load, don't mess with it.
2450 if (MI.hasOrderedMemoryRef())
2451 return false;
2452
2453 if (needsWinCFI(MI.getMF()) && MI.getFlag(MachineInstr::FrameDestroy))
2454 return false;
2455
2456 // Make sure this is a reg+imm.
2457 // FIXME: It is possible to extend it to handle reg+reg cases.
2459 return false;
2460
2461 // Look backward up to LdStLimit instructions.
2463 if (findMatchingStore(MBBI, LdStLimit, StoreI)) {
2464 ++NumLoadsFromStoresPromoted;
2465 // Promote the load. Keeping the iterator straight is a
2466 // pain, so we let the merge routine tell us what the next instruction
2467 // is after it's done mucking about.
2468 MBBI = promoteLoadFromStore(MBBI, StoreI);
2469 return true;
2470 }
2471 return false;
2472}
2473
2474// Merge adjacent zero stores into a wider store.
2475bool AArch64LoadStoreOpt::tryToMergeZeroStInst(
2477 assert(isPromotableZeroStoreInst(*MBBI) && "Expected narrow store.");
2478 MachineInstr &MI = *MBBI;
2479 MachineBasicBlock::iterator E = MI.getParent()->end();
2480
2481 if (!TII->isCandidateToMergeOrPair(MI))
2482 return false;
2483
2484 // Look ahead up to LdStLimit instructions for a mergable instruction.
2485 LdStPairFlags Flags;
2487 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ true);
2488 if (MergeMI != E) {
2489 ++NumZeroStoresPromoted;
2490
2491 // Keeping the iterator straight is a pain, so we let the merge routine tell
2492 // us what the next instruction is after it's done mucking about.
2493 MBBI = mergeNarrowZeroStores(MBBI, MergeMI, Flags);
2494 return true;
2495 }
2496 return false;
2497}
2498
2499// Find loads and stores that can be merged into a single load or store pair
2500// instruction.
2501bool AArch64LoadStoreOpt::tryToPairLdStInst(MachineBasicBlock::iterator &MBBI) {
2502 MachineInstr &MI = *MBBI;
2503 MachineBasicBlock::iterator E = MI.getParent()->end();
2504
2505 if (!TII->isCandidateToMergeOrPair(MI))
2506 return false;
2507
2508 // If disable-ldp feature is opted, do not emit ldp.
2509 if (MI.mayLoad() && Subtarget->hasDisableLdp())
2510 return false;
2511
2512 // If disable-stp feature is opted, do not emit stp.
2513 if (MI.mayStore() && Subtarget->hasDisableStp())
2514 return false;
2515
2516 // Early exit if the offset is not possible to match. (6 bits of positive
2517 // range, plus allow an extra one in case we find a later insn that matches
2518 // with Offset-1)
2519 bool IsUnscaled = TII->hasUnscaledLdStOffset(MI);
2521 int OffsetStride = IsUnscaled ? TII->getMemScale(MI) : 1;
2522 // Allow one more for offset.
2523 if (Offset > 0)
2524 Offset -= OffsetStride;
2525 if (!inBoundsForPair(IsUnscaled, Offset, OffsetStride))
2526 return false;
2527
2528 // Look ahead up to LdStLimit instructions for a pairable instruction.
2529 LdStPairFlags Flags;
2531 findMatchingInsn(MBBI, Flags, LdStLimit, /* FindNarrowMerge = */ false);
2532 if (Paired != E) {
2533 // Keeping the iterator straight is a pain, so we let the merge routine tell
2534 // us what the next instruction is after it's done mucking about.
2535 auto Prev = std::prev(MBBI);
2536
2537 // Fetch the memoperand of the load/store that is a candidate for
2538 // combination.
2540 MI.memoperands_empty() ? nullptr : MI.memoperands().front();
2541
2542 // If a load/store arrives and ldp/stp-aligned-only feature is opted, check
2543 // that the alignment of the source pointer is at least double the alignment
2544 // of the type.
2545 if ((MI.mayLoad() && Subtarget->hasLdpAlignedOnly()) ||
2546 (MI.mayStore() && Subtarget->hasStpAlignedOnly())) {
2547 // If there is no size/align information, cancel the transformation.
2548 if (!MemOp || !MemOp->getMemoryType().isValid()) {
2549 NumFailedAlignmentCheck++;
2550 return false;
2551 }
2552
2553 // Get the needed alignments to check them if
2554 // ldp-aligned-only/stp-aligned-only features are opted.
2555 uint64_t MemAlignment = MemOp->getAlign().value();
2556 uint64_t TypeAlignment = Align(MemOp->getSize().getValue()).value();
2557
2558 if (MemAlignment < 2 * TypeAlignment) {
2559 NumFailedAlignmentCheck++;
2560 return false;
2561 }
2562 }
2563
2564 ++NumPairCreated;
2565 if (TII->hasUnscaledLdStOffset(MI))
2566 ++NumUnscaledPairCreated;
2567
2568 MBBI = mergePairedInsns(MBBI, Paired, Flags);
2569 // Collect liveness info for instructions between Prev and the new position
2570 // MBBI.
2571 for (auto I = std::next(Prev); I != MBBI; I++)
2572 updateDefinedRegisters(*I, DefinedInBB, TRI);
2573
2574 return true;
2575 }
2576 return false;
2577}
2578
2579bool AArch64LoadStoreOpt::tryToMergeLdStUpdate
2581 MachineInstr &MI = *MBBI;
2582 MachineBasicBlock::iterator E = MI.getParent()->end();
2584
2585 // Look forward to try to form a post-index instruction. For example,
2586 // ldr x0, [x20]
2587 // add x20, x20, #32
2588 // merged into:
2589 // ldr x0, [x20], #32
2590 Update = findMatchingUpdateInsnForward(MBBI, 0, UpdateLimit);
2591 if (Update != E) {
2592 // Merge the update into the ld/st.
2593 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/false);
2594 return true;
2595 }
2596
2597 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2598 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2599 return false;
2600
2601 // Look back to try to find a pre-index instruction. For example,
2602 // add x0, x0, #8
2603 // ldr x1, [x0]
2604 // merged into:
2605 // ldr x1, [x0, #8]!
2606 Update = findMatchingUpdateInsnBackward(MBBI, UpdateLimit);
2607 if (Update != E) {
2608 // Merge the update into the ld/st.
2609 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2610 return true;
2611 }
2612
2613 // The immediate in the load/store is scaled by the size of the memory
2614 // operation. The immediate in the add we're looking for,
2615 // however, is not, so adjust here.
2616 int UnscaledOffset =
2618
2619 // Look forward to try to find a pre-index instruction. For example,
2620 // ldr x1, [x0, #64]
2621 // add x0, x0, #64
2622 // merged into:
2623 // ldr x1, [x0, #64]!
2624 Update = findMatchingUpdateInsnForward(MBBI, UnscaledOffset, UpdateLimit);
2625 if (Update != E) {
2626 // Merge the update into the ld/st.
2627 MBBI = mergeUpdateInsn(MBBI, Update, /*IsPreIdx=*/true);
2628 return true;
2629 }
2630
2631 return false;
2632}
2633
2634bool AArch64LoadStoreOpt::tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI,
2635 int Scale) {
2636 MachineInstr &MI = *MBBI;
2637 MachineBasicBlock::iterator E = MI.getParent()->end();
2639
2640 // Don't know how to handle unscaled pre/post-index versions below, so bail.
2641 if (TII->hasUnscaledLdStOffset(MI.getOpcode()))
2642 return false;
2643
2644 // Look back to try to find a const offset for index LdSt instruction. For
2645 // example,
2646 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2647 // ldr x1, [x0, x8]
2648 // merged into:
2649 // add x8, x0, a * (1<<12)
2650 // ldr x1, [x8, imm12]
2651 unsigned Offset;
2652 Update = findMatchingConstOffsetBackward(MBBI, LdStConstLimit, Offset);
2653 if (Update != E && (Offset & (Scale - 1)) == 0) {
2654 // Merge the imm12 into the ld/st.
2655 MBBI = mergeConstOffsetInsn(MBBI, Update, Offset, Scale);
2656 return true;
2657 }
2658
2659 return false;
2660}
2661
2662bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
2663 bool EnableNarrowZeroStOpt) {
2664
2665 bool Modified = false;
2666 // Four tranformations to do here:
2667 // 1) Find loads that directly read from stores and promote them by
2668 // replacing with mov instructions. If the store is wider than the load,
2669 // the load will be replaced with a bitfield extract.
2670 // e.g.,
2671 // str w1, [x0, #4]
2672 // ldrh w2, [x0, #6]
2673 // ; becomes
2674 // str w1, [x0, #4]
2675 // lsr w2, w1, #16
2677 MBBI != E;) {
2678 if (isPromotableLoadFromStore(*MBBI) && tryToPromoteLoadFromStore(MBBI))
2679 Modified = true;
2680 else
2681 ++MBBI;
2682 }
2683 // 2) Merge adjacent zero stores into a wider store.
2684 // e.g.,
2685 // strh wzr, [x0]
2686 // strh wzr, [x0, #2]
2687 // ; becomes
2688 // str wzr, [x0]
2689 // e.g.,
2690 // str wzr, [x0]
2691 // str wzr, [x0, #4]
2692 // ; becomes
2693 // str xzr, [x0]
2694 if (EnableNarrowZeroStOpt)
2696 MBBI != E;) {
2697 if (isPromotableZeroStoreInst(*MBBI) && tryToMergeZeroStInst(MBBI))
2698 Modified = true;
2699 else
2700 ++MBBI;
2701 }
2702 // 3) Find loads and stores that can be merged into a single load or store
2703 // pair instruction.
2704 // e.g.,
2705 // ldr x0, [x2]
2706 // ldr x1, [x2, #8]
2707 // ; becomes
2708 // ldp x0, x1, [x2]
2709
2711 DefinedInBB.clear();
2712 DefinedInBB.addLiveIns(MBB);
2713 }
2714
2716 MBBI != E;) {
2717 // Track currently live registers up to this point, to help with
2718 // searching for a rename register on demand.
2719 updateDefinedRegisters(*MBBI, DefinedInBB, TRI);
2720 if (TII->isPairableLdStInst(*MBBI) && tryToPairLdStInst(MBBI))
2721 Modified = true;
2722 else
2723 ++MBBI;
2724 }
2725 // 4) Find base register updates that can be merged into the load or store
2726 // as a base-reg writeback.
2727 // e.g.,
2728 // ldr x0, [x2]
2729 // add x2, x2, #4
2730 // ; becomes
2731 // ldr x0, [x2], #4
2733 MBBI != E;) {
2734 if (isMergeableLdStUpdate(*MBBI) && tryToMergeLdStUpdate(MBBI))
2735 Modified = true;
2736 else
2737 ++MBBI;
2738 }
2739
2740 // 5) Find a register assigned with a const value that can be combined with
2741 // into the load or store. e.g.,
2742 // mov x8, #LargeImm ; = a * (1<<12) + imm12
2743 // ldr x1, [x0, x8]
2744 // ; becomes
2745 // add x8, x0, a * (1<<12)
2746 // ldr x1, [x8, imm12]
2748 MBBI != E;) {
2749 int Scale;
2750 if (isMergeableIndexLdSt(*MBBI, Scale) && tryToMergeIndexLdSt(MBBI, Scale))
2751 Modified = true;
2752 else
2753 ++MBBI;
2754 }
2755
2756 return Modified;
2757}
2758
2759bool AArch64LoadStoreOpt::runOnMachineFunction(MachineFunction &Fn) {
2760 if (skipFunction(Fn.getFunction()))
2761 return false;
2762
2763 Subtarget = &Fn.getSubtarget<AArch64Subtarget>();
2764 TII = static_cast<const AArch64InstrInfo *>(Subtarget->getInstrInfo());
2765 TRI = Subtarget->getRegisterInfo();
2766 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2767
2768 // Resize the modified and used register unit trackers. We do this once
2769 // per function and then clear the register units each time we optimize a load
2770 // or store.
2771 ModifiedRegUnits.init(*TRI);
2772 UsedRegUnits.init(*TRI);
2773 DefinedInBB.init(*TRI);
2774
2775 bool Modified = false;
2776 bool enableNarrowZeroStOpt = !Subtarget->requiresStrictAlign();
2777 for (auto &MBB : Fn) {
2778 auto M = optimizeBlock(MBB, enableNarrowZeroStOpt);
2779 Modified |= M;
2780 }
2781
2782 return Modified;
2783}
2784
2785// FIXME: Do we need/want a pre-alloc pass like ARM has to try to keep loads and
2786// stores near one another? Note: The pre-RA instruction scheduler already has
2787// hooks to try and schedule pairable loads/stores together to improve pairing
2788// opportunities. Thus, pre-RA pairing pass may not be worth the effort.
2789
2790// FIXME: When pairing store instructions it's very possible for this pass to
2791// hoist a store with a KILL marker above another use (without a KILL marker).
2792// The resulting IR is invalid, but nothing uses the KILL markers after this
2793// pass, so it's never caused a problem in practice.
2794
2795/// createAArch64LoadStoreOptimizationPass - returns an instance of the
2796/// load / store optimization pass.
2798 return new AArch64LoadStoreOpt();
2799}
#define Success
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static cl::opt< bool > EnableRenaming("aarch64-load-store-renaming", cl::init(true), cl::Hidden)
static MachineOperand & getLdStRegOp(MachineInstr &MI, unsigned PairedRegOp=0)
static bool isPromotableLoadFromStore(MachineInstr &MI)
static void getPrePostIndexedMemOpInfo(const MachineInstr &MI, int &Scale, int &MinOffset, int &MaxOffset)
static bool inBoundsForPair(bool IsUnscaled, int Offset, int OffsetStride)
static unsigned getMatchingPairOpcode(unsigned Opc)
static bool isMergeableLdStUpdate(MachineInstr &MI)
static bool areCandidatesToMergeOrPair(MachineInstr &FirstMI, MachineInstr &MI, LdStPairFlags &Flags, const AArch64InstrInfo *TII)
static std::optional< MCPhysReg > tryToFindRegisterToRename(const MachineFunction &MF, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool needsWinCFI(const MachineFunction *MF)
static bool canRenameUntilSecondLoad(MachineInstr &FirstLoad, MachineInstr &SecondLoad, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static std::optional< MCPhysReg > findRenameRegForSameLdStRegPair(std::optional< bool > MaybeCanRename, MachineInstr &FirstMI, MachineInstr &MI, Register Reg, LiveRegUnits &DefinedInBB, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static bool mayAlias(MachineInstr &MIa, SmallVectorImpl< MachineInstr * > &MemInsns, AliasAnalysis *AA)
static cl::opt< unsigned > LdStLimit("aarch64-load-store-scan-limit", cl::init(20), cl::Hidden)
static bool canRenameMOP(const MachineOperand &MOP, const TargetRegisterInfo *TRI)
static unsigned getPreIndexedOpcode(unsigned Opc)
#define AARCH64_LOAD_STORE_OPT_NAME
static cl::opt< unsigned > UpdateLimit("aarch64-update-scan-limit", cl::init(100), cl::Hidden)
static bool isPromotableZeroStoreInst(MachineInstr &MI)
static unsigned getMatchingWideOpcode(unsigned Opc)
static unsigned getMatchingNonSExtOpcode(unsigned Opc, bool *IsValidLdStrOpc=nullptr)
static MachineBasicBlock::iterator maybeMoveCFI(MachineInstr &MI, MachineBasicBlock::iterator MaybeCFI)
static int alignTo(int Num, int PowOf2)
static bool isTagStore(const MachineInstr &MI)
static unsigned isMatchingStore(MachineInstr &LoadInst, MachineInstr &StoreInst)
static bool forAllMIsUntilDef(MachineInstr &MI, MCPhysReg DefReg, const TargetRegisterInfo *TRI, unsigned Limit, std::function< bool(MachineInstr &, bool)> &Fn)
static bool isRewritableImplicitDef(unsigned Opc)
static unsigned getPostIndexedOpcode(unsigned Opc)
#define DEBUG_TYPE
static cl::opt< unsigned > LdStConstLimit("aarch64-load-store-const-scan-limit", cl::init(10), cl::Hidden)
static bool isLdOffsetInRangeOfSt(MachineInstr &LoadInst, MachineInstr &StoreInst, const AArch64InstrInfo *TII)
static bool isPreLdStPairCandidate(MachineInstr &FirstMI, MachineInstr &MI)
static bool isMergeableIndexLdSt(MachineInstr &MI, int &Scale)
static void updateDefinedRegisters(MachineInstr &MI, LiveRegUnits &Units, const TargetRegisterInfo *TRI)
static bool canRenameUpToDef(MachineInstr &FirstMI, LiveRegUnits &UsedInBetween, SmallPtrSetImpl< const TargetRegisterClass * > &RequiredClasses, const TargetRegisterInfo *TRI)
static unsigned getBaseAddressOpcode(unsigned Opc)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
Definition: DebugCounter.h:190
#define LLVM_DEBUG(X)
Definition: Debug.h:101
bool End
Definition: ELF_riscv.cpp:480
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t High
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool isImm(const MachineOperand &MO, MachineRegisterInfo *MRI)
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, DomTreeUpdater *DTU)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
static const MachineOperand & getLdStOffsetOp(const MachineInstr &MI)
Returns the immediate offset operator of a load/store.
static const MachineOperand & getLdStAmountOp(const MachineInstr &MI)
Returns the shift amount operator of a load/store.
static bool isPreLdSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load/store.
static bool isPairedLdSt(const MachineInstr &MI)
Returns whether the instruction is a paired load/store.
static int getMemScale(unsigned Opc)
Scaling factor for (scaled or unscaled) load or store.
static const MachineOperand & getLdStBaseOp(const MachineInstr &MI)
Returns the base register operator of a load/store.
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
const AArch64TargetLowering * getTargetLowering() const override
unsigned getRedZoneSize(const Function &F) const
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
static bool shouldExecute(unsigned CounterName)
Definition: DebugCounter.h:87
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
bool needsUnwindTableEntry() const
True if this function needs an unwind table.
Definition: Function.h:680
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
A set of register units used to track register liveness.
Definition: LiveRegUnits.h:30
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
Definition: LiveRegUnits.h:47
bool available(MCPhysReg Reg) const
Returns true if no part of physical register Reg is live.
Definition: LiveRegUnits.h:116
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
Definition: LiveRegUnits.h:73
void addReg(MCPhysReg Reg)
Adds register units covered by physical register Reg.
Definition: LiveRegUnits.h:86
void removeReg(MCPhysReg Reg)
Removes all register units covered by physical register Reg.
Definition: LiveRegUnits.h:102
void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
An instruction for reading from memory.
Definition: Instructions.h:174
bool usesWindowsCFI() const
Definition: MCAsmInfo.h:759
OpType getOperation() const
Definition: MCDwarf.h:680
Wrapper class representing physical registers. Should be passed by value.
Definition: MCRegister.h:33
reverse_instr_iterator instr_rend()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const std::vector< MCCFIInstruction > & getFrameInstructions() const
Returns a reference to a list of cfi instructions in the function's prologue.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:569
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:346
bool mayAlias(AAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:685
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
Definition: MachineInstr.h:930
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:579
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
void setImplicit(bool Val=true)
int64_t getImm() const
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dump() const
Definition: Pass.cpp:136
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:346
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:367
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:502
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:290
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition: Value.h:74
self_iterator getIterator()
Definition: ilist_node.h:132
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ Define
Register definition.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
constexpr double e
Definition: MathExtras.h:47
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:480
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< filter_iterator< ConstMIBundleOperands, bool(*)(const MachineOperand &)> > phys_regs_and_masks(const MachineInstr &MI)
Returns an iterator range over all physical register and mask operands for MI and bundled instruction...
Definition: LiveRegUnits.h:166
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
FunctionPass * createAArch64LoadStoreOptimizationPass()
createAArch64LoadStoreOptimizationPass - returns an instance of the load / store optimization pass.
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
void initializeAArch64LoadStoreOptPass(PassRegistry &)
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85