LLVM 24.0.0git
RISCVLoadStoreOptimizer.cpp
Go to the documentation of this file.
1//===----- RISCVLoadStoreOptimizer.cpp ------------------------------------===//
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// Load/Store Pairing: It identifies pairs of load or store instructions
10// operating on consecutive memory locations and merges them into a single
11// paired instruction, leveraging hardware support for paired memory accesses.
12// Much of the pairing logic is adapted from the AArch64LoadStoreOpt pass.
13//
14// Post-allocation Zilsd decomposition: Fixes invalid LD/SD instructions if
15// register allocation didn't provide suitable consecutive registers.
16//
17// NOTE: The AArch64LoadStoreOpt pass performs additional optimizations such as
18// merging zero store instructions, promoting loads that read directly from a
19// preceding store, and merging base register updates with load/store
20// instructions (via pre-/post-indexed addressing). These advanced
21// transformations are not yet implemented in the RISC-V pass but represent
22// potential future enhancements for further optimizing RISC-V memory
23// operations.
24//
25//===----------------------------------------------------------------------===//
26
27#include "RISCV.h"
28#include "RISCVTargetMachine.h"
30#include "llvm/ADT/Statistic.h"
34#include "llvm/CodeGen/Passes.h"
35#include "llvm/IR/Analysis.h"
37#include "llvm/Support/Debug.h"
39
40using namespace llvm;
41
42#define DEBUG_TYPE "riscv-load-store-opt"
43#define RISCV_LOAD_STORE_OPT_NAME "RISC-V Load / Store Optimizer"
44
45STATISTIC(NumLD2LW, "Number of LD instructions split back to LW");
46STATISTIC(NumSD2SW, "Number of SD instructions split back to SW");
47
48namespace {
49
50class RISCVLoadStoreOptLegacy : public MachineFunctionPass {
51public:
52 static char ID;
53 bool runOnMachineFunction(MachineFunction &Fn) override;
54
55 RISCVLoadStoreOptLegacy() : MachineFunctionPass(ID) {}
56
57 MachineFunctionProperties getRequiredProperties() const override {
58 return MachineFunctionProperties().setNoVRegs();
59 }
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AU.setPreservesCFG();
63 AU.addRequired<AAResultsWrapperPass>();
64 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
66 }
67
68 StringRef getPassName() const override { return RISCV_LOAD_STORE_OPT_NAME; }
69};
70
71class RISCVLoadStoreOptImpl {
72 // Find and pair load/store instructions.
73 bool tryToPairLdStInst(MachineBasicBlock::iterator &MBBI);
74
75 // Convert load/store pairs to single instructions.
76 bool tryConvertToLdStPair(MachineBasicBlock::iterator First,
78 bool tryConvertToXqcilsmLdStPair(MachineFunction *MF,
81 bool tryConvertToXqcilsmMultiLdSt(MachineBasicBlock::iterator &First);
82 bool tryConvertToMIPSLdStPair(MachineFunction *MF,
85
86 // Scan the instructions looking for a load/store that can be combined
87 // with the current instruction into a load/store pair.
88 // Return the matching instruction if one is found, else MBB->end().
90 bool &MergeForward);
91
93 mergePairedInsns(MachineBasicBlock::iterator I,
94 MachineBasicBlock::iterator Paired, bool MergeForward);
95
96 // Post reg-alloc zilsd part
97 bool fixInvalidRegPairOp(MachineBasicBlock &MBB,
99 bool isValidZilsdRegPair(Register First, Register Second);
100 void splitLdSdIntoTwo(MachineBasicBlock &MBB,
101 MachineBasicBlock::iterator &MBBI, bool IsLoad);
102
103 AliasAnalysis *AA;
104 const RISCVInstrInfo *TII;
105 const RISCVRegisterInfo *TRI;
106 const RISCVSubtarget *STI = nullptr;
107 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
108
109public:
110 bool runOnMachineFunction(MachineFunction &MF,
111 function_ref<AliasAnalysis *()> GetAA);
112};
113} // end anonymous namespace
114
115char RISCVLoadStoreOptLegacy::ID = 0;
117 false, false)
118
119bool RISCVLoadStoreOptImpl::runOnMachineFunction(
121
122 bool MadeChange = false;
123 STI = &MF.getSubtarget<RISCVSubtarget>();
124 TII = STI->getInstrInfo();
125 TRI = STI->getRegisterInfo();
126 AA = GetAA();
127 ModifiedRegUnits.init(*TRI);
128 UsedRegUnits.init(*TRI);
129
130 if (STI->useMIPSLoadStorePairs() || STI->hasVendorXqcilsm()) {
131 for (MachineBasicBlock &MBB : MF) {
132 LLVM_DEBUG(dbgs() << "MBB: " << MBB.getName() << "\n");
133
134 for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
135 MBBI != E;) {
136 if (TII->isPairableLdStInstOpc(MBBI->getOpcode()) &&
137 tryToPairLdStInst(MBBI))
138 MadeChange = true;
139 else
140 ++MBBI;
141 }
142 }
143 }
144
145 if (!STI->is64Bit() && STI->hasStdExtZilsd()) {
146 for (auto &MBB : MF) {
147 for (auto MBBI = MBB.begin(), E = MBB.end(); MBBI != E;) {
148 if (fixInvalidRegPairOp(MBB, MBBI)) {
149 MadeChange = true;
150 // Iterator was updated by fixInvalidRegPairOp
151 } else {
152 ++MBBI;
153 }
154 }
155 }
156 }
157
158 return MadeChange;
159}
160
161// Find loads and stores that can be merged into a single load or store pair
162// instruction.
163bool RISCVLoadStoreOptImpl::tryToPairLdStInst(
165 MachineInstr &MI = *MBBI;
166
167 // If this is volatile, it is not a candidate.
168 if (MI.hasOrderedMemoryRef())
169 return false;
170
171 if (!TII->isLdStSafeToPair(MI, TRI))
172 return false;
173
174 // If Xqcilsm is available, first try to form a multi-instruction group (>2).
175 if (!STI->is64Bit() && STI->hasVendorXqcilsm()) {
176 if (tryConvertToXqcilsmMultiLdSt(MBBI))
177 return true;
178 }
179
180 // Look ahead for a pairable instruction.
181 MachineBasicBlock::iterator E = MI.getParent()->end();
182 bool MergeForward;
183 MachineBasicBlock::iterator Paired = findMatchingInsn(MBBI, MergeForward);
184 if (Paired != E) {
185 MBBI = mergePairedInsns(MBBI, Paired, MergeForward);
186 return true;
187 }
188 return false;
189}
190
191static bool isMemOpAligned(MachineInstr &MI, Align RequiredAlignment) {
192 const MachineMemOperand *MMO = *MI.memoperands_begin();
193 Align MMOAlign = MMO->getAlign();
194 return MMOAlign >= RequiredAlignment;
195}
196
197// Convert set of 3 or more LW/SW instructions to QC_LWMI/QC_SWMI/QC_SETWMI.
198// For now this only handles consecutive loads and stores traversing the basic
199// block top-down.
200// TODO: Traverse the basic block bottom-up as well.
201bool RISCVLoadStoreOptImpl::tryConvertToXqcilsmMultiLdSt(
203 MachineInstr &FirstMI = *FirstIt;
204 MachineFunction *MF = FirstMI.getMF();
205
206 if (STI->is64Bit() || !STI->hasVendorXqcilsm())
207 return false;
208
209 unsigned Opc = FirstMI.getOpcode();
210 if (Opc != RISCV::LW && Opc != RISCV::SW)
211 return false;
212
213 if (!FirstMI.hasOneMemOperand())
214 return false;
215
216 if (!isMemOpAligned(FirstMI, Align(4)))
217 return false;
218
219 // Require simple reg+imm addressing.
220 const MachineOperand &BaseOp = FirstMI.getOperand(1);
221 const MachineOperand &OffOp = FirstMI.getOperand(2);
222 if (!BaseOp.isReg() || !OffOp.isImm())
223 return false;
224
225 Register Base = BaseOp.getReg();
226 int64_t BaseOff = OffOp.getImm();
227
228 if (!isShiftedUInt<5, 2>(BaseOff))
229 return false;
230
231 Register StartReg = FirstMI.getOperand(0).getReg();
232 bool IsLoad = (Opc == RISCV::LW);
233
234 // Load rd cannot be x0 and must not clobber the base register.
235 if (IsLoad) {
236 if (StartReg == RISCV::X0)
237 return false;
238 if (StartReg == Base)
239 return false;
240 }
241
242 // Collect a set of consecutive matching instructions.
243 SmallVector<MachineInstr *, 8> Group;
244 Group.push_back(&FirstMI);
245
246 MachineBasicBlock::iterator E = FirstIt->getParent()->end();
248 int64_t ExpectedOff = BaseOff + 4;
249 unsigned Index = 1;
250 enum class StoreMode { Unknown, Setwmi, Swmi };
251 StoreMode SMode = StoreMode::Unknown;
252
253 while (It != E) {
254 MachineInstr &MI = *It;
255
256 if (!TII->isPairableLdStInstOpc(MI.getOpcode()))
257 break;
258 if (MI.getOpcode() != Opc)
259 break;
260 if (!TII->isLdStSafeToPair(MI, TRI))
261 break;
262 if (!MI.hasOneMemOperand())
263 break;
264 if (!isMemOpAligned(MI, Align(4)))
265 break;
266
267 const MachineOperand &BaseMIOp = MI.getOperand(1);
268 const MachineOperand &OffsetMIOp = MI.getOperand(2);
269 if (!BaseMIOp.isReg() || !OffsetMIOp.isImm())
270 break;
271 if (BaseMIOp.getReg() != Base)
272 break;
273 int64_t Off = OffsetMIOp.getImm();
274 if (Off != ExpectedOff)
275 break;
276
277 Register Reg = MI.getOperand(0).getReg();
278 if (IsLoad) {
279 // For loads, require consecutive destination registers.
280 if (Reg != StartReg + Index)
281 break;
282 if (Reg == Base)
283 break;
284 } else {
285 // For stores, decide mode based on the second instruction and then
286 // enforce the same for the rest.
287 if (SMode == StoreMode::Unknown) {
288 if (Reg == StartReg)
289 SMode = StoreMode::Setwmi;
290 else if (Reg == StartReg + 1)
291 SMode = StoreMode::Swmi;
292 else
293 break;
294 } else if (SMode == StoreMode::Setwmi) {
295 if (Reg != StartReg)
296 break;
297 } else {
298 if (Reg != StartReg + Index)
299 break;
300 }
301 }
302
303 // Passed checks, extend the group.
304 Group.push_back(&MI);
305 ++Index;
306 ExpectedOff += 4;
307 It = next_nodbg(It, E);
308 }
309
310 // We only handle more than 2 here. Pairs are handled in
311 // tryConvertToXqcilsmLdStPair.
312 unsigned Len = Group.size();
313 if (Len < 3 || Len > 31)
314 return false;
315
316 unsigned NewOpc;
317 RegState StartRegState;
318 bool AddImplicitRegs = true;
319
320 if (IsLoad) {
321 NewOpc = RISCV::QC_LWMI;
322 StartRegState = RegState::Define;
323 } else {
324 assert(SMode != StoreMode::Unknown &&
325 "Group should be large enough to know the store mode");
326 if (SMode == StoreMode::Setwmi) {
327 NewOpc = RISCV::QC_SETWMI;
328 // Kill if any of the individual stores killed the reg.
329 bool StartKill = false;
330 for (MachineInstr *MI : Group)
331 StartKill |= MI->getOperand(0).isKill();
332 StartRegState = getKillRegState(StartKill);
333 AddImplicitRegs = false;
334 } else {
335 // SWMI requires consecutive source regs and rd != x0.
336 if (StartReg == RISCV::X0)
337 return false;
338 NewOpc = RISCV::QC_SWMI;
339 StartRegState = getKillRegState(Group.front()->getOperand(0).isKill());
340 }
341 }
342
343 // Aggregate kill on base.
344 bool BaseKill = false;
345 for (MachineInstr *MI : Group)
346 BaseKill |= MI->getOperand(1).isKill();
347
348 // Build the new instruction.
349 DebugLoc DL = FirstMI.getDebugLoc();
350 if (!DL)
351 DL = Group.back()->getDebugLoc();
352 MachineInstrBuilder MIB = BuildMI(*MF, DL, TII->get(NewOpc));
353 MIB.addReg(StartReg, StartRegState)
354 .addReg(Base, getKillRegState(BaseKill))
355 .addImm(Len)
356 .addImm(BaseOff);
357
358 // Merge memory references.
359 MIB.cloneMergedMemRefs(Group);
360
361 if (AddImplicitRegs) {
362 // Add implicit operands for the additional registers.
363 for (unsigned i = 1; i < Len; ++i) {
364 Register R = StartReg + i;
365 RegState State;
366 if (IsLoad)
367 State = RegState::ImplicitDefine;
368 else
369 State = RegState::Implicit |
370 getKillRegState(Group[i]->getOperand(0).isKill());
371 MIB.addReg(R, State);
372 }
373 }
374
375 // Insert before the first instruction and remove all in the group.
376 MachineBasicBlock *MBB = FirstIt->getParent();
377 MachineBasicBlock::iterator NewIt = MBB->insert(FirstIt, MIB);
378 for (MachineInstr *MI : Group)
379 MI->removeFromParent();
380
381 // Advance the cursor to the next non-debug instruction after the group.
382 FirstIt = next_nodbg(NewIt, MBB->end());
383 return true;
384}
385
386bool RISCVLoadStoreOptImpl::tryConvertToXqcilsmLdStPair(
389 unsigned Opc = First->getOpcode();
390 if ((Opc != RISCV::LW && Opc != RISCV::SW) || Second->getOpcode() != Opc)
391 return false;
392
393 const auto &FirstOp1 = First->getOperand(1);
394 const auto &SecondOp1 = Second->getOperand(1);
395 const auto &FirstOp2 = First->getOperand(2);
396 const auto &SecondOp2 = Second->getOperand(2);
397
398 // Require simple reg+imm addressing for both.
399 if (!FirstOp1.isReg() || !SecondOp1.isReg() || !FirstOp2.isImm() ||
400 !SecondOp2.isImm())
401 return false;
402
403 Register Base1 = FirstOp1.getReg();
404 Register Base2 = SecondOp1.getReg();
405
406 if (Base1 != Base2)
407 return false;
408
409 if (!First->hasOneMemOperand() || !Second->hasOneMemOperand())
410 return false;
411
412 if (!isMemOpAligned(*First, Align(4)) || !isMemOpAligned(*Second, Align(4)))
413 return false;
414
415 const auto &FirstOp0 = First->getOperand(0);
416 const auto &SecondOp0 = Second->getOperand(0);
417
418 int64_t Off1 = FirstOp2.getImm();
419 int64_t Off2 = SecondOp2.getImm();
420 assert(Off1 < Off2 && "Expected instructions to be ordered by offset");
421
422 if (!isShiftedUInt<5, 2>(Off1) || (Off2 - Off1 != 4))
423 return false;
424
425 Register StartReg = FirstOp0.getReg();
426 Register NextReg = SecondOp0.getReg();
427
428 unsigned XqciOpc;
429 RegState StartRegState;
430 RegState NextRegState = {};
431 bool AddNextReg = true;
432
433 if (Opc == RISCV::LW) {
434
435 if (StartReg == RISCV::X0)
436 return false;
437
438 // If the base reg gets overwritten by one of the loads bail out.
439 if (StartReg == Base1 || NextReg == Base1)
440 return false;
441
442 // The registers need to be consecutive.
443 if (NextReg != StartReg + 1)
444 return false;
445
446 XqciOpc = RISCV::QC_LWMI;
447 StartRegState = RegState::Define;
448 NextRegState = RegState::ImplicitDefine;
449 } else {
450 assert(Opc == RISCV::SW && "Expected a SW instruction");
451 if (StartReg == NextReg) {
452 XqciOpc = RISCV::QC_SETWMI;
453 StartRegState = getKillRegState(FirstOp0.isKill() || SecondOp0.isKill());
454 AddNextReg = false;
455 } else if (NextReg == StartReg + 1 && StartReg != RISCV::X0) {
456 XqciOpc = RISCV::QC_SWMI;
457 StartRegState = getKillRegState(FirstOp0.isKill());
458 NextRegState = RegState::Implicit | getKillRegState(SecondOp0.isKill());
459 } else {
460 return false;
461 }
462 }
463
464 DebugLoc DL =
465 First->getDebugLoc() ? First->getDebugLoc() : Second->getDebugLoc();
466 MachineInstrBuilder MIB = BuildMI(*MF, DL, TII->get(XqciOpc));
467 MIB.addReg(StartReg, StartRegState)
468 .addReg(Base1, getKillRegState(FirstOp1.isKill() || SecondOp1.isKill()))
469 .addImm(2)
470 .addImm(Off1)
471 .cloneMergedMemRefs({&*First, &*Second});
472
473 if (AddNextReg)
474 MIB.addReg(NextReg, NextRegState);
475
476 First->getParent()->insert(First, MIB);
477 First->removeFromParent();
478 Second->removeFromParent();
479
480 return true;
481}
482
483bool RISCVLoadStoreOptImpl::tryConvertToMIPSLdStPair(
486 // Try converting to SWP/LWP/LDP/SDP.
487 // SWP/LWP requires 8-byte alignment whereas LDP/SDP needs 16-byte alignment.
488 unsigned PairOpc;
489 Align RequiredAlignment;
490 switch (First->getOpcode()) {
491 default:
492 llvm_unreachable("Unsupported load/store instruction for pairing");
493 case RISCV::SW:
494 PairOpc = RISCV::MIPS_SWP;
495 RequiredAlignment = Align(8);
496 break;
497 case RISCV::LW:
498 PairOpc = RISCV::MIPS_LWP;
499 RequiredAlignment = Align(8);
500 break;
501 case RISCV::SD:
502 PairOpc = RISCV::MIPS_SDP;
503 RequiredAlignment = Align(16);
504 break;
505 case RISCV::LD:
506 PairOpc = RISCV::MIPS_LDP;
507 RequiredAlignment = Align(16);
508 break;
509 }
510
511 if (!First->hasOneMemOperand())
512 return false;
513
514 if (!isMemOpAligned(*First, RequiredAlignment))
515 return false;
516
517 int64_t Offset = First->getOperand(2).getImm();
518 if (!isUInt<7>(Offset))
519 return false;
520
521 MachineInstrBuilder MIB = BuildMI(
522 *MF, First->getDebugLoc() ? First->getDebugLoc() : Second->getDebugLoc(),
523 TII->get(PairOpc));
524 MIB.add(First->getOperand(0))
525 .add(Second->getOperand(0))
526 .add(First->getOperand(1))
527 .add(First->getOperand(2))
528 .cloneMergedMemRefs({&*First, &*Second});
529
530 First->getParent()->insert(First, MIB);
531
532 First->removeFromParent();
533 Second->removeFromParent();
534
535 return true;
536}
537
538// Merge two adjacent load/store instructions into a paired instruction.
539// This function calls the vendor specific implementation that seelects the
540// appropriate paired opcode, verifies that the memory operand is properly
541// aligned, and checks that the offset is valid. If all conditions are met, it
542// builds and inserts the paired instruction.
543bool RISCVLoadStoreOptImpl::tryConvertToLdStPair(
545 MachineFunction *MF = First->getMF();
546
547 // Try converting to QC_LWMI/QC_SWMI if the XQCILSM extension is enabled.
548 if (!STI->is64Bit() && STI->hasVendorXqcilsm())
549 return tryConvertToXqcilsmLdStPair(MF, First, Second);
550
551 // Else try to convert them into MIPS Paired Loads/Stores.
552 return tryConvertToMIPSLdStPair(MF, First, Second);
553}
554
555static bool mayAlias(MachineInstr &MIa,
557 AliasAnalysis *AA) {
558 for (MachineInstr *MIb : MemInsns)
559 if (MIa.mayAlias(AA, *MIb, /*UseTBAA*/ false))
560 return true;
561
562 return false;
563}
564
565// Scan the instructions looking for a load/store that can be combined with the
566// current instruction into a wider equivalent or a load/store pair.
567// TODO: Extend pairing logic to consider reordering both instructions
568// to a safe "middle" position rather than only merging forward/backward.
569// This requires more sophisticated checks for aliasing, register
570// liveness, and potential scheduling hazards.
572RISCVLoadStoreOptImpl::findMatchingInsn(MachineBasicBlock::iterator I,
573 bool &MergeForward) {
574 MachineBasicBlock::iterator E = I->getParent()->end();
576 MachineInstr &FirstMI = *I;
577 MBBI = next_nodbg(MBBI, E);
578
579 bool MayLoad = FirstMI.mayLoad();
580 Register Reg = FirstMI.getOperand(0).getReg();
581 Register BaseReg = FirstMI.getOperand(1).getReg();
582 int64_t Offset = FirstMI.getOperand(2).getImm();
583 int64_t OffsetStride = (*FirstMI.memoperands_begin())->getSize().getValue();
584
585 MergeForward = false;
586
587 // Track which register units have been modified and used between the first
588 // insn (inclusive) and the second insn.
589 ModifiedRegUnits.clear();
590 UsedRegUnits.clear();
591
592 // Remember any instructions that read/write memory between FirstMI and MI.
593 SmallVector<MachineInstr *, 4> MemInsns;
594
595 for (unsigned Count = 0;
596 MBBI != E && Count < STI->getCLOpts().load_store_scan_limit;
597 MBBI = next_nodbg(MBBI, E)) {
598 MachineInstr &MI = *MBBI;
599
600 // Don't count transient instructions towards the search limit since there
601 // may be different numbers of them if e.g. debug information is present.
602 if (!MI.isTransient())
603 ++Count;
604
605 if (MI.getOpcode() == FirstMI.getOpcode() &&
606 TII->isLdStSafeToPair(MI, TRI)) {
607 Register MIBaseReg = MI.getOperand(1).getReg();
608 int64_t MIOffset = MI.getOperand(2).getImm();
609
610 if (BaseReg == MIBaseReg) {
611 if ((Offset != MIOffset + OffsetStride) &&
612 (Offset + OffsetStride != MIOffset)) {
613 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
614 TRI);
615 MemInsns.push_back(&MI);
616 continue;
617 }
618
619 // If the destination register of one load is the same register or a
620 // sub/super register of the other load, bail and keep looking.
621 if (MayLoad &&
622 TRI->isSuperOrSubRegisterEq(Reg, MI.getOperand(0).getReg())) {
623 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits,
624 TRI);
625 MemInsns.push_back(&MI);
626 continue;
627 }
628
629 // If the BaseReg has been modified, then we cannot do the optimization.
630 if (!ModifiedRegUnits.available(BaseReg))
631 return E;
632
633 // If the Rt of the second instruction was not modified or used between
634 // the two instructions and none of the instructions between the second
635 // and first alias with the second, we can combine the second into the
636 // first.
637 if (ModifiedRegUnits.available(MI.getOperand(0).getReg()) &&
638 !(MI.mayLoad() &&
639 !UsedRegUnits.available(MI.getOperand(0).getReg())) &&
640 !mayAlias(MI, MemInsns, AA)) {
641
642 MergeForward = false;
643 return MBBI;
644 }
645
646 // Likewise, if the Rt of the first instruction is not modified or used
647 // between the two instructions and none of the instructions between the
648 // first and the second alias with the first, we can combine the first
649 // into the second.
650 if (!(MayLoad &&
651 !UsedRegUnits.available(FirstMI.getOperand(0).getReg())) &&
652 !mayAlias(FirstMI, MemInsns, AA)) {
653
654 if (ModifiedRegUnits.available(FirstMI.getOperand(0).getReg())) {
655 MergeForward = true;
656 return MBBI;
657 }
658 }
659 // Unable to combine these instructions due to interference in between.
660 // Keep looking.
661 }
662 }
663
664 // If the instruction wasn't a matching load or store. Stop searching if we
665 // encounter a call instruction that might modify memory.
666 if (MI.isCall())
667 return E;
668
669 // Update modified / uses register units.
670 LiveRegUnits::accumulateUsedDefed(MI, ModifiedRegUnits, UsedRegUnits, TRI);
671
672 // Otherwise, if the base register is modified, we have no match, so
673 // return early.
674 if (!ModifiedRegUnits.available(BaseReg))
675 return E;
676
677 // Update list of instructions that read/write memory.
678 if (MI.mayLoadOrStore())
679 MemInsns.push_back(&MI);
680 }
681 return E;
682}
683
685RISCVLoadStoreOptImpl::mergePairedInsns(MachineBasicBlock::iterator I,
687 bool MergeForward) {
688 MachineBasicBlock::iterator E = I->getParent()->end();
690 // If NextI is the second of the two instructions to be merged, skip one
691 // further for now. For the MIPS load/store, the merge will invalidate the
692 // iterator, and we don't need to scan the new instruction, as it's a pairwise
693 // instruction, which we're not considering for further action anyway. For the
694 // Xqcilsm load/store, we may not want to do this as the second instruction
695 // could possibly be the first in another pair if we do not merge here. This
696 // is handled in the else block after the call to tryConvertToLdStPair below.
697 if (NextI == Paired)
698 NextI = next_nodbg(NextI, E);
699
700 // Insert our new paired instruction after whichever of the paired
701 // instructions MergeForward indicates.
702 MachineBasicBlock::iterator InsertionPoint = MergeForward ? Paired : I;
703 MachineBasicBlock::iterator DeletionPoint = MergeForward ? I : Paired;
704 int Offset = I->getOperand(2).getImm();
705 int PairedOffset = Paired->getOperand(2).getImm();
706 bool InsertAfter = (Offset < PairedOffset) ^ MergeForward;
707
708 if (!MergeForward)
709 Paired->getOperand(1).setIsKill(false);
710
711 // Kill flags may become invalid when moving stores for pairing.
712 if (I->getOperand(0).isUse()) {
713 if (!MergeForward) {
714 // Check if the Paired store's source register has a kill flag and clear
715 // it only if there are intermediate uses between I and Paired.
716 MachineOperand &PairedRegOp = Paired->getOperand(0);
717 if (PairedRegOp.isKill()) {
718 for (auto It = std::next(I); It != Paired; ++It) {
719 if (It->readsRegister(PairedRegOp.getReg(), TRI)) {
720 PairedRegOp.setIsKill(false);
721 break;
722 }
723 }
724 }
725 } else {
726 // Clear kill flags of the first store's register in the forward
727 // direction.
728 Register Reg = I->getOperand(0).getReg();
729 for (MachineInstr &MI : make_range(std::next(I), std::next(Paired)))
730 MI.clearRegisterKills(Reg, TRI);
731 }
732 }
733
734 // Remember the original position of the instruction we're moving so we can
735 // restore it if we fail to form a pair.
736 MachineBasicBlock::iterator OrigNext = std::next(DeletionPoint);
737
738 MachineInstr *ToInsert = DeletionPoint->removeFromParent();
739 MachineBasicBlock &MBB = *InsertionPoint->getParent();
740 MachineBasicBlock::iterator First, Second, Moved;
741
742 if (!InsertAfter) {
743 First = MBB.insert(InsertionPoint, ToInsert);
744 Second = InsertionPoint;
745 Moved = First;
746 } else {
747 Second = MBB.insertAfter(InsertionPoint, ToInsert);
748 First = InsertionPoint;
749 Moved = Second;
750 }
751
752 if (tryConvertToLdStPair(First, Second)) {
753 LLVM_DEBUG(dbgs() << "Pairing load/store:\n ");
754 LLVM_DEBUG(prev_nodbg(NextI, MBB.begin())->print(dbgs()));
755 } else if (!STI->is64Bit() && STI->hasVendorXqcilsm()) {
756 // We were unable to form the pair, so move the instruction back to it's
757 // original place. Point NextI to the next non-debug instruction after the
758 // first instruction we had wanted to merge.
759 MachineInstr *MovedMI = Moved->removeFromParent();
760 MBB.insert(OrigNext, MovedMI);
761 NextI = next_nodbg(I, E);
762 }
763
764 return NextI;
765}
766
767//===----------------------------------------------------------------------===//
768// Post reg-alloc zilsd pass implementation
769//===----------------------------------------------------------------------===//
770
771bool RISCVLoadStoreOptImpl::isValidZilsdRegPair(Register First,
772 Register Second) {
773 // Special case: First register can not be zero unless both registers are
774 // zeros.
775 // Spec says: LD instructions with destination x0 are processed as any other
776 // load, but the result is discarded entirely and x1 is not written. If using
777 // x0 as src of SD, the entire 64-bit operand is zero — i.e., register x1 is
778 // not accessed.
779 if (First == RISCV::X0)
780 return Second == RISCV::X0;
781
782 // Check if registers form a valid even/odd pair for Zilsd
783 unsigned FirstNum = TRI->getEncodingValue(First);
784 unsigned SecondNum = TRI->getEncodingValue(Second);
785
786 // Must be consecutive and first must be even
787 return (FirstNum % 2 == 0) && (SecondNum == FirstNum + 1);
788}
789
790void RISCVLoadStoreOptImpl::splitLdSdIntoTwo(MachineBasicBlock &MBB,
792 bool IsLoad) {
793 MachineInstr *MI = &*MBBI;
794 DebugLoc DL = MI->getDebugLoc();
795
796 const MachineOperand &FirstOp = MI->getOperand(0);
797 const MachineOperand &SecondOp = MI->getOperand(1);
798 const MachineOperand &BaseOp = MI->getOperand(2);
799 Register FirstReg = FirstOp.getReg();
800 Register SecondReg = SecondOp.getReg();
801 Register BaseReg = BaseOp.getReg();
802
803 // Handle both immediate and symbolic operands for offset
804 const MachineOperand &OffsetOp = MI->getOperand(3);
805 int BaseOffset;
806 if (OffsetOp.isImm())
807 BaseOffset = OffsetOp.getImm();
808 else
809 // For symbolic operands, extract the embedded offset
810 BaseOffset = OffsetOp.getOffset();
811
812 unsigned Opc = IsLoad ? RISCV::LW : RISCV::SW;
813 MachineInstrBuilder MIB1, MIB2;
814
815 // Create two separate instructions
816 if (IsLoad) {
817 // It's possible that first register is same as base register, when we split
818 // it becomes incorrect because base register is overwritten, e.g.
819 // X10, X13 = PseudoLD_RV32_OPT killed X10, 0
820 // =>
821 // X10 = LW X10, 0
822 // X13 = LW killed X10, 4
823 // we can just switch the order to resolve that:
824 // X13 = LW X10, 4
825 // X10 = LW killed X10, 0
826 if (FirstReg == BaseReg) {
827 MIB2 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
828 .addDef(SecondReg, getDeadRegState(SecondOp.isDead()))
829 .addReg(BaseReg);
830 MIB1 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
831 .addDef(FirstReg, getDeadRegState(FirstOp.isDead()))
832 .addReg(BaseReg, getKillRegState(BaseOp.isKill()));
833
834 } else {
835 MIB1 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
836 .addDef(FirstReg, getDeadRegState(FirstOp.isDead()))
837 .addReg(BaseReg);
838
839 MIB2 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
840 .addDef(SecondReg, getDeadRegState(SecondOp.isDead()))
841 .addReg(BaseReg, getKillRegState(BaseOp.isKill()));
842 }
843
844 ++NumLD2LW;
845 LLVM_DEBUG(dbgs() << "Split LD back to two LW instructions\n");
846 } else {
847 assert(
848 FirstReg != SecondReg &&
849 "First register and second register is impossible to be same register");
850 MIB1 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
851 .addReg(FirstReg, getKillRegState(FirstOp.isKill()))
852 .addReg(BaseReg);
853
854 MIB2 = BuildMI(MBB, MBBI, DL, TII->get(Opc))
855 .addReg(SecondReg, getKillRegState(SecondOp.isKill()))
856 .addReg(BaseReg, getKillRegState(BaseOp.isKill()));
857
858 ++NumSD2SW;
859 LLVM_DEBUG(dbgs() << "Split SD back to two SW instructions\n");
860 }
861
862 // Add offset operands - preserve symbolic references
863 MIB1.add(OffsetOp);
864 if (OffsetOp.isImm())
865 MIB2.addImm(BaseOffset + 4);
866 else if (OffsetOp.isGlobal())
867 MIB2.addGlobalAddress(OffsetOp.getGlobal(), BaseOffset + 4,
868 OffsetOp.getTargetFlags());
869 else if (OffsetOp.isCPI())
870 MIB2.addConstantPoolIndex(OffsetOp.getIndex(), BaseOffset + 4,
871 OffsetOp.getTargetFlags());
872 else if (OffsetOp.isBlockAddress())
873 MIB2.addBlockAddress(OffsetOp.getBlockAddress(), BaseOffset + 4,
874 OffsetOp.getTargetFlags());
875
876 // Copy memory operands if the original instruction had them
877 // FIXME: This is overly conservative; the new instruction accesses 4 bytes,
878 // not 8.
879 MIB1.cloneMemRefs(*MI);
880 MIB2.cloneMemRefs(*MI);
881
882 // Remove the original paired instruction and update iterator
883 MBBI = MBB.erase(MBBI);
884}
885
886bool RISCVLoadStoreOptImpl::fixInvalidRegPairOp(
887 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI) {
888 MachineInstr *MI = &*MBBI;
889 unsigned Opcode = MI->getOpcode();
890
891 // Check if this is a Zilsd pseudo that needs fixing
892 if (Opcode != RISCV::PseudoLD_RV32_OPT && Opcode != RISCV::PseudoSD_RV32_OPT)
893 return false;
894
895 bool IsLoad = Opcode == RISCV::PseudoLD_RV32_OPT;
896
897 const MachineOperand &FirstOp = MI->getOperand(0);
898 const MachineOperand &SecondOp = MI->getOperand(1);
899 Register FirstReg = FirstOp.getReg();
900 Register SecondReg = SecondOp.getReg();
901
902 if (!isValidZilsdRegPair(FirstReg, SecondReg)) {
903 // Need to split back into two instructions
904 splitLdSdIntoTwo(MBB, MBBI, IsLoad);
905 return true;
906 }
907
908 // Registers are valid, convert to real LD/SD instruction
909 const MachineOperand &BaseOp = MI->getOperand(2);
910 Register BaseReg = BaseOp.getReg();
911 DebugLoc DL = MI->getDebugLoc();
912 // Handle both immediate and symbolic operands for offset
913 const MachineOperand &OffsetOp = MI->getOperand(3);
914
915 unsigned RealOpc = IsLoad ? RISCV::LD_RV32 : RISCV::SD_RV32;
916
917 // Create register pair from the two individual registers
918 MCRegister RegPair = TRI->getMatchingSuperReg(FirstReg, RISCV::sub_gpr_even,
919 &RISCV::GPRPairRegClass);
920 // Create the real LD/SD instruction with register pair
921 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(RealOpc));
922
923 if (IsLoad) {
924 // For LD, the register pair is the destination
925 MIB.addDef(RegPair, getDeadRegState(FirstOp.isDead() && SecondOp.isDead()));
926 } else {
927 // For SD, the register pair is the source
928 MIB.addReg(RegPair, getKillRegState(FirstOp.isKill() && SecondOp.isKill()));
929 }
930
931 MIB.addReg(BaseReg, getKillRegState(BaseOp.isKill()))
932 .add(OffsetOp)
933 .cloneMemRefs(*MI);
934
935 LLVM_DEBUG(dbgs() << "Converted pseudo to real instruction: " << *MIB
936 << "\n");
937
938 // Remove the pseudo instruction and update iterator
939 MBBI = MBB.erase(MBBI);
940
941 return true;
942}
943
944// Returns an instance of the Load / Store Optimization pass.
946 return new RISCVLoadStoreOptLegacy();
947}
948
949bool RISCVLoadStoreOptLegacy::runOnMachineFunction(MachineFunction &MF) {
950 if (skipFunction(MF.getFunction()))
951 return false;
952 RISCVLoadStoreOptImpl Impl;
953 return Impl.runOnMachineFunction(MF, [&]() {
954 return &getAnalysis<AAResultsWrapperPass>().getAAResults();
955 });
956}
957
958PreservedAnalyses
961 RISCVLoadStoreOptImpl Impl;
962 bool Changed = Impl.runOnMachineFunction(MF, [&]() {
964 .getManager()
965 .getResult<AAManager>(MF.getFunction());
966 });
970}
static bool mayAlias(MachineInstr &MIa, SmallVectorImpl< MachineInstr * > &MemInsns, AliasAnalysis *AA)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define RISCV_LOAD_STORE_OPT_NAME
static bool isMemOpAligned(MachineInstr &MI, Align RequiredAlignment)
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
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...
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void clear()
Clears the set.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
MachineInstrBundleIterator< MachineInstr > iterator
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.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addBlockAddress(const BlockAddress *BA, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI bool mayAlias(BatchAAResults *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.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const RISCVOptions & getCLOpts() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
An efficient, type-erasing, non-owning reference to a callable.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Unknown
Not known to have no common set bits.
RegState
Flags to represent properties of register accesses.
constexpr RegState getKillRegState(bool B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr RegState getDeadRegState(bool B)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createRISCVLoadStoreOptLegacyPass()
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39