[AArch64] Fold UMOV(lane 0) + GPR store in FPR store#199139
Conversation
Summary: Problem: LLVM generates `umov w8, v0.h[0]` + `strh w8, [x0]` instead of `str h0, [x0]` when storing vector lane 0 to memory, specifically when SimplifyCFG merges stores across branches -- splitting the extractelement and store into different basic blocks and preventing the existing DAG combine from firing. Root cause: SimplifyCFG creates a PHI + merged store in a successor block. SelectionDAG ISel processes each block independently, so it lowers the extract to `UMOV` (GPR) in the predecessor and the store sees only a GPR value via the PHI. Late tail duplication puts the store back in the same block, but the `UMOV` is already baked in. Fix: Added a post-RA peephole in `AArch64LoadStoreOptimizer` (step 6 in `optimizeBlock`) that recognizes `UMOVvi*_idx0` + GPR store patterns and replaces them with direct FPR sub-register stores. The peephole: - Handles all element sizes: i8 (`bsub`), i16 (`hsub`), i32 (`ssub`), i64 (`dsub`) - Correctly updates liveness by clearing intervening kill flags on the vector register - Bails out if the GPR value has other uses, the vector register is clobbered, or the store doesn't kill the GPR Test Plan: Added `llvm/test/CodeGen/AArch64/ldst-opt-umov-fpr-store.mir` -- new test with 6 positive and 3 negative cases Reviewers: Subscribers: Differential Revision: https://phabricator.intern.facebook.com/D105060655
|
Hello @kunalspathak 👋 Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description. Frequently asked questionsHow do I add reviewers? This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically. You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using What if there are no comments? If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers. Are any special GitHub settings required to contribute to LLVM? We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details. If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse. Thank you, |
|
@llvm/pr-subscribers-backend-aarch64 Author: Kunal Pathak (kunalspathak) ChangesProblem: LLVM generates https://godbolt.org/z/v5G9ohMPa Root cause: SimplifyCFG creates a PHI + merged store in a successor block. SelectionDAG ISel processes each block independently, so it lowers the extract to Fix: Added a post-RA peephole in
Assisted-by: Claude Fixes: #137086 cc: @MatzeB @efriedma-quic Full diff: https://github.com/llvm/llvm-project/pull/199139.diff 2 Files Affected:
diff --git a/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp b/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp
index 34d46e5c37569..2844001199deb 100644
--- a/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp
+++ b/llvm/lib/Target/AArch64/AArch64LoadStoreOptimizer.cpp
@@ -65,6 +65,8 @@ STATISTIC(NumFailedAlignmentCheck, "Number of load/store pair transformation "
"not passed the alignment check");
STATISTIC(NumConstOffsetFolded,
"Number of const offset of index address folded");
+STATISTIC(NumUMOVFoldedToFPRStore,
+ "Number of UMOV + GPR stores folded to FPR stores");
DEBUG_COUNTER(RegRenamingCounter, DEBUG_TYPE "-reg-renaming",
"Controls which pairs are considered for renaming");
@@ -219,6 +221,9 @@ struct AArch64LoadStoreOpt {
// Find and merge an index ldr/st instruction into a base ld/st instruction.
bool tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI, int Scale);
+ // Replace a UMOV (lane 0) + GPR store with a direct FPR sub-register store.
+ bool tryToReplaceUMOVStore(MachineBasicBlock::iterator &MBBI);
+
bool optimizeBlock(MachineBasicBlock &MBB, bool EnableNarrowZeroStOpt);
bool runOnMachineFunction(MachineFunction &MF);
@@ -3012,6 +3017,110 @@ bool AArch64LoadStoreOpt::tryToMergeIndexLdSt(MachineBasicBlock::iterator &MBBI,
return false;
}
+// Given a UMOV-lane-0 opcode and a GPR store opcode, return the corresponding
+// FPR store opcode and the sub-register index to extract from the vector, or
+// return false if the combination is not supported.
+static bool getUMOVToFPRStoreInfo(unsigned UMOVOpc, unsigned GPRStoreOpc,
+ unsigned &FPRStoreOpc, unsigned &SubRegIdx) {
+ switch (UMOVOpc) {
+ case AArch64::UMOVvi8_idx0:
+ if (GPRStoreOpc != AArch64::STRBBui)
+ return false;
+ FPRStoreOpc = AArch64::STRBui;
+ SubRegIdx = AArch64::bsub;
+ return true;
+ case AArch64::UMOVvi16_idx0:
+ if (GPRStoreOpc != AArch64::STRHHui)
+ return false;
+ FPRStoreOpc = AArch64::STRHui;
+ SubRegIdx = AArch64::hsub;
+ return true;
+ case AArch64::UMOVvi32_idx0:
+ if (GPRStoreOpc != AArch64::STRWui)
+ return false;
+ FPRStoreOpc = AArch64::STRSui;
+ SubRegIdx = AArch64::ssub;
+ return true;
+ case AArch64::UMOVvi64_idx0:
+ if (GPRStoreOpc != AArch64::STRXui)
+ return false;
+ FPRStoreOpc = AArch64::STRDui;
+ SubRegIdx = AArch64::dsub;
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AArch64LoadStoreOpt::tryToReplaceUMOVStore(
+ MachineBasicBlock::iterator &MBBI) {
+ MachineInstr &StoreMI = *MBBI;
+ unsigned StoreOpc = StoreMI.getOpcode();
+
+ if (StoreOpc != AArch64::STRBBui && StoreOpc != AArch64::STRHHui &&
+ StoreOpc != AArch64::STRWui && StoreOpc != AArch64::STRXui)
+ return false;
+
+ MachineBasicBlock *MBB = StoreMI.getParent();
+ unsigned FPRStoreOpc = 0, SubRegIdx = 0;
+ MCPhysReg StoreValReg = StoreMI.getOperand(0).getReg();
+
+ if (!StoreMI.getOperand(0).isKill())
+ return false;
+
+ // Scan backward to find the UMOV that defines the store's value register.
+ MachineInstr *UMOVMI = nullptr;
+ for (auto It = MBBI; It != MBB->begin() && !UMOVMI;) {
+ MachineInstr &MI = *--It;
+ if (MI.readsRegister(StoreValReg, TRI))
+ return false;
+ if (MI.definesRegister(StoreValReg, TRI)) {
+ if (!getUMOVToFPRStoreInfo(MI.getOpcode(), StoreMI.getOpcode(),
+ FPRStoreOpc, SubRegIdx))
+ return false;
+ UMOVMI = &MI;
+ }
+ }
+ if (!UMOVMI)
+ return false;
+
+ MCPhysReg VecReg = UMOVMI->getOperand(1).getReg();
+
+ // Check that no instruction between UMOV and store clobbers the vector
+ // register. Also track whether VecReg is killed anywhere from the UMOV
+ // (inclusive) through the intervening instructions -- we need this to decide
+ // whether the FPR sub-register can be marked killed on the new store.
+ bool VecRegKilled = UMOVMI->killsRegister(VecReg, TRI);
+ for (auto It = std::next(UMOVMI->getIterator()); It != MBBI; ++It) {
+ if (It->modifiesRegister(VecReg, TRI))
+ return false;
+ if (!VecRegKilled && It->killsRegister(VecReg, TRI))
+ VecRegKilled = true;
+ }
+
+ // Safe to proceed. Clear kill flags on the vector register between UMOV and
+ // the new store so the FPR sub-register stays live.
+ UMOVMI->clearRegisterKills(VecReg, TRI);
+ for (auto It = std::next(UMOVMI->getIterator()); It != MBBI; ++It)
+ It->clearRegisterKills(VecReg, TRI);
+
+ LLVM_DEBUG(dbgs() << "Folding UMOV + store: " << *UMOVMI << " + "
+ << StoreMI);
+
+ MCPhysReg FPRReg = TRI->getSubReg(VecReg, SubRegIdx);
+ BuildMI(*MBB, MBBI, StoreMI.getDebugLoc(), TII->get(FPRStoreOpc))
+ .addReg(FPRReg, getKillRegState(VecRegKilled))
+ .add(StoreMI.getOperand(1))
+ .add(StoreMI.getOperand(2))
+ .setMemRefs(StoreMI.memoperands());
+
+ MBBI = MBB->erase(MBBI);
+ UMOVMI->eraseFromParent();
+
+ ++NumUMOVFoldedToFPRStore;
+ return true;
+}
+
bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
bool EnableNarrowZeroStOpt) {
AArch64FunctionInfo &AFI = *MBB.getParent()->getInfo<AArch64FunctionInfo>();
@@ -3114,6 +3223,20 @@ bool AArch64LoadStoreOpt::optimizeBlock(MachineBasicBlock &MBB,
++MBBI;
}
+ // 6) Replace UMOV (lane 0) + GPR store with a direct FPR sub-register store.
+ // e.g.,
+ // umov w8, v0.h[0]
+ // strh w8, [x0]
+ // ; becomes
+ // str h0, [x0]
+ for (MachineBasicBlock::iterator MBBI = MBB.begin(), E = MBB.end();
+ MBBI != E;) {
+ if (tryToReplaceUMOVStore(MBBI))
+ Modified = true;
+ else
+ ++MBBI;
+ }
+
return Modified;
}
diff --git a/llvm/test/CodeGen/AArch64/ldst-opt-umov-fpr-store.mir b/llvm/test/CodeGen/AArch64/ldst-opt-umov-fpr-store.mir
new file mode 100644
index 0000000000000..5758cbebdb376
--- /dev/null
+++ b/llvm/test/CodeGen/AArch64/ldst-opt-umov-fpr-store.mir
@@ -0,0 +1,169 @@
+# RUN: llc -mtriple=aarch64-linux-gnu -run-pass=aarch64-ldst-opt -o - %s | FileCheck %s
+
+# Test that UMOV (lane 0) + GPR store is folded into a direct FPR store
+# when the UMOV result has no other uses.
+
+---
+# UMOVvi16_idx0 + STRHHui → STRHui, with intervening ST1i8 that kills the
+# vector register.
+# CHECK-LABEL: name: umov_i16_to_fpr_store
+# CHECK: ST1i8 renamable $q0
+# CHECK-NEXT: STRHui killed $h0
+# CHECK-NOT: UMOVvi16_idx0
+# CHECK-NOT: STRHHui
+name: umov_i16_to_fpr_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0, $x1
+
+ renamable $w8 = UMOVvi16_idx0 renamable $q0, 0
+ ST1i8 killed renamable $q0, 8, killed renamable $x1 :: (store (s8))
+ STRHHui killed renamable $w8, killed renamable $x0, 0 :: (store (s16))
+ RET undef $lr
+...
+---
+# UMOVvi8_idx0 + STRBBui → STRBui
+# CHECK-LABEL: name: umov_i8_to_fpr_store
+# CHECK: STRBui killed $b0
+# CHECK-NOT: UMOVvi8_idx0
+# CHECK-NOT: STRBBui
+name: umov_i8_to_fpr_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0
+
+ renamable $w8 = UMOVvi8_idx0 killed renamable $q0, 0
+ STRBBui killed renamable $w8, killed renamable $x0, 0 :: (store (s8))
+ RET undef $lr
+...
+---
+# UMOVvi32_idx0 + STRWui → STRSui
+# CHECK-LABEL: name: umov_i32_to_fpr_store
+# CHECK: STRSui killed $s0
+# CHECK-NOT: UMOVvi32_idx0
+# CHECK-NOT: STRWui
+name: umov_i32_to_fpr_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0
+
+ renamable $w8 = UMOVvi32_idx0 killed renamable $q0, 0
+ STRWui killed renamable $w8, killed renamable $x0, 0 :: (store (s32))
+ RET undef $lr
+...
+---
+# UMOVvi64_idx0 + STRXui → STRDui
+# CHECK-LABEL: name: umov_i64_to_fpr_store
+# CHECK: STRDui killed $d0
+# CHECK-NOT: UMOVvi64_idx0
+# CHECK-NOT: STRXui
+name: umov_i64_to_fpr_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0
+
+ renamable $x8 = UMOVvi64_idx0 killed renamable $q0, 0
+ STRXui killed renamable $x8, killed renamable $x0, 0 :: (store (s64))
+ RET undef $lr
+...
+---
+# Negative: UMOV result is modified before the store.
+# CHECK-LABEL: name: umov_i16_used_before_store
+# CHECK: UMOVvi16_idx0
+# CHECK: EORWrr
+# CHECK: STRHHui
+name: umov_i16_used_before_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0, $w9
+
+ renamable $w8 = UMOVvi16_idx0 killed renamable $q0, 0
+ renamable $w8 = EORWrr killed renamable $w8, killed renamable $w9
+ STRHHui killed renamable $w8, killed renamable $x0, 0 :: (store (s16))
+ RET undef $lr
+...
+---
+# Negative: The vector register is clobbered between UMOV and store.
+# CHECK-LABEL: name: umov_i16_vec_clobbered
+# CHECK: UMOVvi16_idx0
+# CHECK: ORRv16i8
+# CHECK: STRHHui
+name: umov_i16_vec_clobbered
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $q1, $x0
+
+ renamable $w8 = UMOVvi16_idx0 renamable $q0, 0
+ renamable $q0 = ORRv16i8 killed renamable $q0, killed renamable $q1
+ STRHHui killed renamable $w8, killed renamable $x0, 0 :: (store (s16))
+ RET undef $lr
+...
+---
+# Negative: The GPR result is not killed at the store (has a later use).
+# CHECK-LABEL: name: umov_i16_not_killed
+# CHECK: UMOVvi16_idx0
+# CHECK: STRHHui renamable $w8
+# CHECK: STRHHui killed renamable $w8
+name: umov_i16_not_killed
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0, $x1
+
+ renamable $w8 = UMOVvi16_idx0 killed renamable $q0, 0
+ STRHHui renamable $w8, renamable $x0, 0 :: (store (s16))
+ STRHHui killed renamable $w8, killed renamable $x1, 0 :: (store (s16))
+ RET undef $lr
+...
+---
+# Multiple folds in one block: two independent UMOV+store pairs using
+# different vector registers and different element sizes.
+# CHECK-LABEL: name: umov_multiple_folds
+# CHECK: ORRv16i8
+# CHECK-NEXT: ST1i8 renamable $q0
+# CHECK-NEXT: STRHui killed $h0
+# CHECK-NEXT: STRSui killed $s1
+# CHECK-NOT: UMOVvi16_idx0
+# CHECK-NOT: UMOVvi32_idx0
+# CHECK-NOT: STRHHui
+# CHECK-NOT: STRWui
+name: umov_multiple_folds
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $q1, $x0, $x1, $x2
+
+ renamable $q0 = ORRv16i8 killed renamable $q0, renamable $q1
+ renamable $w8 = UMOVvi16_idx0 renamable $q0, 0
+ ST1i8 killed renamable $q0, 8, killed renamable $x2 :: (store (s8))
+ STRHHui killed renamable $w8, killed renamable $x0, 0 :: (store (s16))
+ renamable $w9 = UMOVvi32_idx0 killed renamable $q1, 0
+ STRWui killed renamable $w9, killed renamable $x1, 0 :: (store (s32))
+ RET undef $lr
+...
+---
+# Vector register still live after the store (used via $s0 alias).
+# The fold should happen but the FPR sub-register must NOT be killed.
+# CHECK-LABEL: name: umov_i16_vec_live_after_store
+# CHECK: STRHui $h0
+# CHECK-NEXT: renamable $w9 = FMOVSWr renamable $s0
+# CHECK-NOT: UMOVvi16_idx0
+# CHECK-NOT: STRHHui
+name: umov_i16_vec_live_after_store
+tracksRegLiveness: true
+body: |
+ bb.0:
+ liveins: $q0, $x0, $x1
+
+ renamable $w8 = UMOVvi16_idx0 renamable $q0, 0
+ STRHHui killed renamable $w8, killed renamable $x0, 0 :: (store (s16))
+ renamable $w9 = FMOVSWr renamable $s0
+ STRWui killed renamable $w9, killed renamable $x1, 0 :: (store (s32))
+ RET undef $lr
+...
|
🪟 Windows x64 Test Results
✅ The build succeeded and all tests passed. |
🐧 Linux x64 Test Results
✅ The build succeeded and all tests passed. |
davemgreen
left a comment
There was a problem hiding this comment.
Do you have an llvm ir test case for this, to show where it comes up?
|
Test failures seems unrelated and are reported below: |
Sure, here's a minimal IR test case that shows where this comes up: define void @extract_store_post_simplifycfg(ptr %p, <8 x i16> %vec, i32 %cond) {
entry:
%tobool = icmp eq i32 %cond, 0
br i1 %tobool, label %if.else, label %if.then
if.then:
call void asm sideeffect "", ""()
%or = or <8 x i16> %vec, <i16 18, i16 0, i16 0, i16 0, i16 0, i16 0, i16 0, i16 0>
%lane.then = extractelement <8 x i16> %or, i64 0
br label %if.end
if.else:
%lane.else = extractelement <8 x i16> %vec, i64 0
%xor = xor i16 %lane.else, 52
br label %if.end
if.end:
%storemerge = phi i16 [ %xor, %if.else ], [ %lane.then, %if.then ]
store i16 %storemerge, ptr %p, align 2
ret void
}This is what the IR looks like after SimplifyCFG merges the stores from both branches into a PHI + single store in MIR after ISel shows the separation clearly: After tail duplication sinks the store, we end up with I've added this as a |
|
@davemgreen - do you need more information? |
davemgreen
left a comment
There was a problem hiding this comment.
@davemgreen - do you need more information?
No, just thinking about it. I remember seeing this come up in #137086 now, the comments from @MatzeB and @efriedma-quic are still pertinent. It doesn't fit anywhere very nicely. I think GISel has the best chance of doing this well if it can eventually treat an xor on either regbank, but does not currently know how to do that properly. It can be better if we can do this kind of transform inside ISel so it can make use of all the other combines happening at the same time.
Doing it here might be the least-worst option. It is currently only handling certain types of stores, not all addressing modes. (And it only handles one-way I guess, not fpr->gpr too, but I'm not sure that is worth making it more complex for). Should it handle other store types?
I agree this doesn't fit anywhere very cleanly. ISel has already committed to GPR by the time tail duplication re-creates the store, and there's no mechanism to revisit that decision. GISel handling xor on either regbank would be the "right" fix long-term, but as you pointed it's not there yet.
Yes that's what I concluded.
I've extended this to handle unscaled immediate and register-offset stores in addition to the unsigned-immediate ones, so it now covers the common non-pre/post addressing modes. Pre/post-indexed stores have a different operand layout (writeback tied def on operand 0) and are unlikely to appear with For the FPR to GPR direction — I don't think it's worth the complexity right now. The GPR to FPR case is what |
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
davemgreen
left a comment
There was a problem hiding this comment.
It looks like the extra opcodes helped this trigger more. Post and pre inc might help more cases too (but you don't need to do that here).
Address feedback and added few tests.
94161b8 to
ee7fe75
Compare
davemgreen
left a comment
There was a problem hiding this comment.
Thanks. Are you happy for us to hit merge? I never know who has access.
I don't have merge access. @MatzeB is this ok to merge? |
|
@kunalspathak Congratulations on having your first Pull Request (PR) merged into the LLVM Project! Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR. Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues. How to do this, and the rest of the post-merge process, is covered in detail here. If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again. If you don't get any reports, no action is required from you. Your changes are working as expected, well done! |
Problem: LLVM generates
umov w8, v0.h[0]+strh w8, [x0]instead ofstr h0, [x0]when storing vector lane 0 to memory, specifically when SimplifyCFG merges stores across branches -- splitting the extractelement and store into different basic blocks and preventing the existing DAG combine from firing.https://godbolt.org/z/v5G9ohMPa
Root cause: SimplifyCFG creates a PHI + merged store in a successor block. SelectionDAG ISel processes each block independently, so it lowers the extract to
UMOV(GPR) in the predecessor and the store sees only a GPR value via the PHI. Late tail duplication puts the store back in the same block, but theUMOVis already baked in.Fix: Added a post-RA peephole in
AArch64LoadStoreOptimizer(step 6 inoptimizeBlock) that recognizesUMOVvi*_idx0+ GPR store patterns and replaces them with direct FPR sub-register stores. The peephole:bsub), i16 (hsub), i32 (ssub), i64 (dsub)Assisted-by: Claude
Fixes: #137086
cc: @MatzeB @efriedma-quic