https://github.com/ParkHanbum updated 
https://github.com/llvm/llvm-project/pull/233350

>From c9eea354b1efa08be86112efd85fe44f55ae4a91 Mon Sep 17 00:00:00 2001
From: hanbeom <[email protected]>
Date: Sun, 8 Nov 2026 01:40:27 +0900
Subject: [PATCH 1/5] [AggressiveInstCombine][NFC] Add masked store narrowing
 tests

Cover byte offsets, shared operands, and cross-block load/store pairs,
including clobbers on a branch and a loop backedge. Exercise a restored
word in the default O2 pipeline.
---
 .../narrow-masked-store.ll                    | 830 ++++++++++++++++++
 .../narrow-masked-store-after-early-cse.ll    |  26 +
 2 files changed, 856 insertions(+)
 create mode 100644 
llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
 create mode 100644 
llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll

diff --git a/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll 
b/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
new file mode 100644
index 00000000000000..e035d5d67bb644
--- /dev/null
+++ b/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
@@ -0,0 +1,830 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --check-globals all --version 6
+; RUN: opt -passes=aggressive-instcombine -data-layout=e-p:64:64 -S < %s | 
FileCheck %s
+; RUN: opt -passes=aggressive-instcombine -data-layout=E-p:64:64 -S < %s | 
FileCheck %s
+
+; Insert a register value into the third byte.
+define void @issue_i32_middle(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @issue_i32_middle(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 8
+; CHECK-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[SHIFTED]], 16711680
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 8
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 8
+  %shifted = shl i32 %x, 16
+  %insert = and i32 %shifted, 16711680
+  %clear = and i32 %old, -16711681
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 8
+  ret void
+}
+
+define void @narrow_i16_low(ptr %p, i16 %x) {
+; CHECK-LABEL: define void @narrow_i16_low(
+; CHECK-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i16 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i16 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i16 [[INSERT]], [[CLEAR]]
+; CHECK-NEXT:    store i16 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i16, ptr %p, align 4
+  %insert = and i16 %x, 255
+  %clear = and i16 %old, -256
+  %new = or disjoint i16 %insert, %clear
+  store i16 %new, ptr %p, align 4
+  ret void
+}
+
+define void @narrow_i64_high(ptr %p, i64 %x) {
+; CHECK-LABEL: define void @narrow_i64_high(
+; CHECK-SAME: ptr [[P:%.*]], i64 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i64, ptr [[P]], align 8
+; CHECK-NEXT:    [[INSERT:%.*]] = and i64 [[X]], -72057594037927936
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i64 [[OLD]], 72057594037927935
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i64 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i64 [[NEW]], ptr [[P]], align 8
+; CHECK-NEXT:    ret void
+;
+  %old = load i64, ptr %p, align 8
+  %insert = and i64 %x, -72057594037927936
+  %clear = and i64 %old, 72057594037927935
+  %new = or disjoint i64 %clear, %insert
+  store i64 %new, ptr %p, align 8
+  ret void
+}
+
+define void @narrow_i128_middle(ptr %p, i128 %x) {
+; CHECK-LABEL: define void @narrow_i128_middle(
+; CHECK-SAME: ptr [[P:%.*]], i128 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i128, ptr [[P]], align 16
+; CHECK-NEXT:    [[SHIFTED:%.*]] = shl nuw i128 [[X]], 40
+; CHECK-NEXT:    [[INSERT:%.*]] = and i128 [[SHIFTED]], 280375465082880
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i128 [[OLD]], -280375465082881
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i128 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i128 [[NEW]], ptr [[P]], align 16
+; CHECK-NEXT:    ret void
+;
+; Enable these LE and BE checks with the narrowing change.
+; LE-LABEL: define void @narrow_i128_middle(
+; LE-SAME: ptr [[P:%.*]], i128 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = trunc i128 [[X]] to i8
+; LE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 5
+; LE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @narrow_i128_middle(
+; BE-SAME: ptr [[P:%.*]], i128 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = trunc i128 [[X]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 10
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 2
+; BE-NEXT:    ret void
+;
+  %old = load i128, ptr %p, align 16
+  %shifted = shl nuw i128 %x, 40
+  %insert = and i128 %shifted, 280375465082880
+  %clear = and i128 %old, -280375465082881
+  %new = or disjoint i128 %clear, %insert
+  store i128 %new, ptr %p, align 16
+  ret void
+}
+
+; Both the OR and AND may have their operands commuted.
+define void @commuted(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @commuted(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 65280, [[X]]
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 -65281, [[OLD]]
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[INSERT]], [[CLEAR]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 65280, %x
+  %clear = and i32 -65281, %old
+  %new = or disjoint i32 %insert, %clear
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; Do not split a byte store from a merged word that has another consumer.
+define i32 @shared_merge(ptr %p, i32 %x) {
+; CHECK-LABEL: define i32 @shared_merge(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret i32 [[NEW]]
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret i32 %new
+}
+
+; A load in a dominating block can supply the preserved bytes.
+define void @cross_block(ptr %p, i32 %x, i1 %condition) {
+; CHECK-LABEL: define void @cross_block(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i1 [[CONDITION:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    br i1 [[CONDITION]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
+; CHECK:       [[UPDATE]]:
+; CHECK-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[SHIFTED]], 16711680
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    br label %[[EXIT]]
+; CHECK:       [[EXIT]]:
+; CHECK-NEXT:    ret void
+;
+entry:
+  %old = load i32, ptr %p, align 4
+  br i1 %condition, label %update, label %exit
+update:
+  %shifted = shl i32 %x, 16
+  %insert = and i32 %shifted, 16711680
+  %clear = and i32 %old, -16711681
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  br label %exit
+exit:
+  ret void
+}
+
+; Narrowing must not leave clobbered bytes in place of the old loaded bytes.
+define void @clobber_store(ptr %p, i32 %x, i32 %clobber) {
+; CHECK-LABEL: define void @clobber_store(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[CLOBBER:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    store i32 [[CLOBBER]], ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  store i32 %clobber, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+declare void @may_write(ptr)
+
+define void @clobber_call(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @clobber_call(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    call void @may_write(ptr [[P]])
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  call void @may_write(ptr %p)
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+define void @different_pointer(ptr %p, ptr %q, i32 %x) {
+; CHECK-LABEL: define void @different_pointer(
+; CHECK-SAME: ptr [[P:%.*]], ptr [[Q:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[Q]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %q, align 4
+  ret void
+}
+
+; A shifted byte must start on a byte boundary.
+define void @misaligned_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @misaligned_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 510
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -511
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 510
+  %clear = and i32 %old, -511
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; The insertion mask must be the complement of the preserved mask.
+define void @noncomplementary_insert_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @noncomplementary_insert_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 511
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %clear = and i32 %old, -256
+  %insert = and i32 %x, 511
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+define void @volatile_load(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @volatile_load(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load volatile i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load volatile i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+define void @atomic_store(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @atomic_store(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store atomic i32 [[NEW]], ptr [[P]] unordered, align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store atomic i32 %new, ptr %p unordered, align 4
+  ret void
+}
+
+; A swifterror value cannot be used as the base of a byte-offset GEP.
+define void @swift_error(ptr swifterror %p, i32 %x) {
+; CHECK-LABEL: define void @swift_error(
+; CHECK-SAME: ptr swifterror [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[SHIFTED]], 16711680
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[INSERT]], [[CLEAR]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %shifted = shl i32 %x, 16
+  %insert = and i32 %shifted, 16711680
+  %clear = and i32 %old, -16711681
+  %new = or disjoint i32 %insert, %clear
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; Match the canonical disjoint merge.
+define void @plain_or(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @plain_or(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; Require explicit complementary masks.
+define void @disjoint_zext(ptr %p, i8 %x) {
+; CHECK-LABEL: define void @disjoint_zext(
+; CHECK-SAME: ptr [[P:%.*]], i8 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = zext i8 [[X]] to i32
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = zext i8 %x to i32
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; Narrowing must not change the width of a volatile store.
+define void @volatile_store(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @volatile_store(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store volatile i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store volatile i32 %new, ptr %p, align 4
+  ret void
+}
+
+; The matched load must also be simple.
+define void @atomic_load(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @atomic_load(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load atomic i32, ptr [[P]] unordered, align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load atomic i32, ptr %p unordered, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; There is no narrower access to create from an i8 store.
+define void @byte_store(ptr %p, i8 %x) {
+; CHECK-LABEL: define void @byte_store(
+; CHECK-SAME: ptr [[P:%.*]], i8 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i8, ptr [[P]], align 1
+; CHECK-NEXT:    [[INSERT:%.*]] = and i8 [[X]], -1
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i8 [[OLD]], 0
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i8 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i8 [[NEW]], ptr [[P]], align 1
+; CHECK-NEXT:    ret void
+;
+  %old = load i8, ptr %p, align 1
+  %insert = and i8 %x, -1
+  %clear = and i8 %old, 0
+  %new = or disjoint i8 %clear, %insert
+  store i8 %new, ptr %p, align 1
+  ret void
+}
+
+; A partial most-significant byte is outside this transform.
+define void @non_byte_integer(ptr %p, i12 %x) {
+; CHECK-LABEL: define void @non_byte_integer(
+; CHECK-SAME: ptr [[P:%.*]], i12 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i12, ptr [[P]], align 2
+; CHECK-NEXT:    [[INSERT:%.*]] = and i12 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i12 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i12 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i12 [[NEW]], ptr [[P]], align 2
+; CHECK-NEXT:    ret void
+;
+  %old = load i12, ptr %p, align 2
+  %insert = and i12 %x, 255
+  %clear = and i12 %old, -256
+  %new = or disjoint i12 %clear, %insert
+  store i12 %new, ptr %p, align 2
+  ret void
+}
+
+; Even a splat mask does not make a vector a scalar integer word.
+define void @vector_store(ptr %p, <2 x i32> %x) {
+; CHECK-LABEL: define void @vector_store(
+; CHECK-SAME: ptr [[P:%.*]], <2 x i32> [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load <2 x i32>, ptr [[P]], align 8
+; CHECK-NEXT:    [[INSERT:%.*]] = and <2 x i32> [[X]], splat (i32 255)
+; CHECK-NEXT:    [[CLEAR:%.*]] = and <2 x i32> [[OLD]], splat (i32 -256)
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint <2 x i32> [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store <2 x i32> [[NEW]], ptr [[P]], align 8
+; CHECK-NEXT:    ret void
+;
+  %old = load <2 x i32>, ptr %p, align 8
+  %insert = and <2 x i32> %x, <i32 255, i32 255>
+  %clear = and <2 x i32> %old, <i32 -256, i32 -256>
+  %new = or disjoint <2 x i32> %clear, %insert
+  store <2 x i32> %new, ptr %p, align 8
+  ret void
+}
+
+; Eight set bits in separate runs are not a single byte.
+define void @noncontiguous_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @noncontiguous_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 3855
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -3856
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 3855
+  %clear = and i32 %old, -3856
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; A four-bit field must not overwrite the rest of its byte.
+define void @partial_byte_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @partial_byte_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 15
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 15
+  %clear = and i32 %old, -16
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; Both masks must be constants, even when their relationship is explicit.
+define void @dynamic_masks(ptr %p, i32 %x, i32 %mask) {
+; CHECK-LABEL: define void @dynamic_masks(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[MASK:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[KEEP:%.*]] = xor i32 [[MASK]], -1
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], [[MASK]]
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], [[KEEP]]
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %keep = xor i32 %mask, -1
+  %insert = and i32 %x, %mask
+  %clear = and i32 %old, %keep
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; A partial clobber of a preserved byte must also prevent narrowing. Byte 1 is
+; preserved on both endiannesses when only the least significant byte changes.
+define void @overlapping_byte_store(ptr %p, i32 %x, i8 %clobber) {
+; CHECK-LABEL: define void @overlapping_byte_store(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i8 [[CLOBBER:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[Q:%.*]] = getelementptr inbounds i8, ptr [[P]], i64 1
+; CHECK-NEXT:    store i8 [[CLOBBER]], ptr [[Q]], align 1
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %q = getelementptr inbounds i8, ptr %p, i64 1
+  store i8 %clobber, ptr %q, align 1
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; The intervening stores are still clobbers when this pass runs alone.
+define void @restored_word(ptr %p, i32 %x, i32 %clobber) {
+; CHECK-LABEL: define void @restored_word(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[CLOBBER:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    store i32 [[CLOBBER]], ptr [[P]], align 4
+; CHECK-NEXT:    store i32 [[OLD]], ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  store i32 %clobber, ptr %p, align 4
+  store i32 %old, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+declare void @read_only(ptr) memory(read)
+
+; A read-only call does not clobber the word. It need not be nounwind: the
+; replacement store stays after the call, so an exception bypasses either 
store.
+define void @read_only_call(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @read_only_call(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    call void @read_only(ptr [[P]])
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  call void @read_only(ptr %p)
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; MemorySSA can skip a provably non-overlapping store.
+define void @nonoverlapping_store(ptr %p, i32 %x, i32 %other) {
+; CHECK-LABEL: define void @nonoverlapping_store(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[OTHER:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[Q:%.*]] = getelementptr inbounds i8, ptr [[P]], i64 4
+; CHECK-NEXT:    store i32 [[OTHER]], ptr [[Q]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %q = getelementptr inbounds i8, ptr %p, i64 4
+  store i32 %other, ptr %q, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}
+
+; The byte GEP preserves the address space and does not strengthen alignment.
+define void @address_space(ptr addrspace(1) %p, i32 %x) {
+; CHECK-LABEL: define void @address_space(
+; CHECK-SAME: ptr addrspace(1) [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr addrspace(1) [[P]], align 1
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr addrspace(1) [[P]], align 1
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr addrspace(1) %p, align 1
+  %insert = and i32 %x, 16711680
+  %clear = and i32 %old, -16711681
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr addrspace(1) %p, align 1
+  ret void
+}
+
+; Select the tbaa.struct field at the new byte address, preserve alias scopes,
+; and discard the old whole-word tbaa.struct description.
+define void @aa_metadata(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @aa_metadata(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4, !tbaa.struct 
[[TBAA_STRUCT0:![0-9]+]], !alias.scope [[META10:![0-9]+]], !noalias 
[[META13:![0-9]+]], !llvm.access.group [[ACC_GRP15:![0-9]+]]
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 16711680
+  %clear = and i32 %old, -16711681
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4, !tbaa.struct !0, !alias.scope !10, !noalias 
!13, !llvm.access.group !15
+  ret void
+}
+
+; The old word is also used by the branch, as in glslang.
+define void @cross_block_live_load(ptr %p, i16 %x) {
+; CHECK-LABEL: define void @cross_block_live_load(
+; CHECK-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 2
+; CHECK-NEXT:    [[NEEDS_UPDATE:%.*]] = icmp uge i16 [[OLD]], -256
+; CHECK-NEXT:    br i1 [[NEEDS_UPDATE]], label %[[UPDATE:.*]], label 
%[[EXIT:.*]]
+; CHECK:       [[UPDATE]]:
+; CHECK-NEXT:    [[INSERT:%.*]] = and i16 [[X]], -256
+; CHECK-NEXT:    [[KEEP:%.*]] = and i16 [[OLD]], 255
+; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i16 [[INSERT]], [[KEEP]]
+; CHECK-NEXT:    store i16 [[MERGED]], ptr [[P]], align 2
+; CHECK-NEXT:    br label %[[EXIT]]
+; CHECK:       [[EXIT]]:
+; CHECK-NEXT:    ret void
+;
+entry:
+  %old = load i16, ptr %p, align 2
+  %needs.update = icmp uge i16 %old, -256
+  br i1 %needs.update, label %update, label %exit
+
+update:
+  %insert = and i16 %x, -256
+  %keep = and i16 %old, 255
+  %merged = or disjoint i16 %insert, %keep
+  store i16 %merged, ptr %p, align 2
+  br label %exit
+
+exit:
+  ret void
+}
+
+; A single clobbering path is enough to make narrowing unsafe.
+define void @clobber_on_one_path(ptr %p, i32 %x, i1 %c) {
+; CHECK-LABEL: define void @clobber_on_one_path(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i1 [[C:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    br i1 [[C]], label %[[CLOBBER:.*]], label %[[UPDATE:.*]]
+; CHECK:       [[CLOBBER]]:
+; CHECK-NEXT:    [[CLOBBER_PTR:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; CHECK-NEXT:    store i8 0, ptr [[CLOBBER_PTR]], align 1
+; CHECK-NEXT:    br label %[[UPDATE]]
+; CHECK:       [[UPDATE]]:
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], -16777216
+; CHECK-NEXT:    [[KEEP:%.*]] = and i32 [[OLD]], 16777215
+; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i32 [[INSERT]], [[KEEP]]
+; CHECK-NEXT:    store i32 [[MERGED]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+entry:
+  %old = load i32, ptr %p, align 4
+  br i1 %c, label %clobber, label %update
+
+clobber:
+  %clobber.ptr = getelementptr i8, ptr %p, i64 1
+  store i8 0, ptr %clobber.ptr, align 1
+  br label %update
+
+update:
+  %insert = and i32 %x, -16777216
+  %keep = and i32 %old, 16777215
+  %merged = or disjoint i32 %insert, %keep
+  store i32 %merged, ptr %p, align 4
+  ret void
+}
+
+; The second iteration restores the original value of the clobbered byte.
+define void @clobber_on_backedge(ptr %p, i32 %x) {
+; CHECK-LABEL: define void @clobber_on_backedge(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*]]:
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    br label %[[UPDATE:.*]]
+; CHECK:       [[UPDATE]]:
+; CHECK-NEXT:    [[AGAIN:%.*]] = phi i1 [ true, %[[ENTRY]] ], [ false, 
%[[CLOBBER:.*]] ]
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], -16777216
+; CHECK-NEXT:    [[KEEP:%.*]] = and i32 [[OLD]], 16777215
+; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i32 [[INSERT]], [[KEEP]]
+; CHECK-NEXT:    store i32 [[MERGED]], ptr [[P]], align 4
+; CHECK-NEXT:    br i1 [[AGAIN]], label %[[CLOBBER]], label %[[EXIT:.*]]
+; CHECK:       [[CLOBBER]]:
+; CHECK-NEXT:    [[CLOBBER_PTR:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; CHECK-NEXT:    store i8 0, ptr [[CLOBBER_PTR]], align 1
+; CHECK-NEXT:    br label %[[UPDATE]]
+; CHECK:       [[EXIT]]:
+; CHECK-NEXT:    ret void
+;
+entry:
+  %old = load i32, ptr %p, align 4
+  br label %update
+
+update:
+  %again = phi i1 [ true, %entry ], [ false, %clobber ]
+  %insert = and i32 %x, -16777216
+  %keep = and i32 %old, 16777215
+  %merged = or disjoint i32 %insert, %keep
+  store i32 %merged, ptr %p, align 4
+  br i1 %again, label %clobber, label %exit
+
+clobber:
+  %clobber.ptr = getelementptr i8, ptr %p, i64 1
+  store i8 0, ptr %clobber.ptr, align 1
+  br label %update
+
+exit:
+  ret void
+}
+
+; The merge dies but the insertion mask has another user.
+define i32 @shared_insert_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define i32 @shared_insert_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
+; CHECK-NEXT:    [[KEEP:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i32 [[INSERT]], [[KEEP]]
+; CHECK-NEXT:    store i32 [[MERGED]], ptr [[P]], align 4
+; CHECK-NEXT:    ret i32 [[INSERT]]
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 16711680
+  %keep = and i32 %old, -16711681
+  %merged = or disjoint i32 %insert, %keep
+  store i32 %merged, ptr %p, align 4
+  ret i32 %insert
+}
+
+; The merge dies but the preservation mask has another user.
+define i32 @shared_keep_mask(ptr %p, i32 %x) {
+; CHECK-LABEL: define i32 @shared_keep_mask(
+; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
+; CHECK-NEXT:    [[KEEP:%.*]] = and i32 [[OLD]], -16711681
+; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i32 [[INSERT]], [[KEEP]]
+; CHECK-NEXT:    store i32 [[MERGED]], ptr [[P]], align 4
+; CHECK-NEXT:    ret i32 [[KEEP]]
+;
+  %old = load i32, ptr %p, align 4
+  %insert = and i32 %x, 16711680
+  %keep = and i32 %old, -16711681
+  %merged = or disjoint i32 %insert, %keep
+  store i32 %merged, ptr %p, align 4
+  ret i32 %keep
+}
+
+!0 = !{i64 0, i64 1, !1, i64 1, i64 1, !2, i64 2, i64 1, !3, i64 3, i64 1, !4}
+!1 = !{!5, !5, i64 0}
+!2 = !{!6, !6, i64 0}
+!3 = !{!7, !7, i64 0}
+!4 = !{!8, !8, i64 0}
+!5 = !{!"byte0", !9, i64 0}
+!6 = !{!"byte1", !9, i64 0}
+!7 = !{!"byte2", !9, i64 0}
+!8 = !{!"byte3", !9, i64 0}
+!9 = !{!"root"}
+!10 = !{!11}
+!11 = distinct !{!11, !12, !"scope"}
+!12 = distinct !{!12, i1 false, !"domain"}
+!13 = !{!14}
+!14 = distinct !{!14, !12, !"other"}
+!15 = distinct !{}
+;.
+; CHECK: attributes #[[ATTR0:[0-9]+]] = { memory(read) }
+;.
+; CHECK: [[TBAA_STRUCT0]] = !{i64 0, i64 1, [[META1:![0-9]+]], i64 1, i64 1, 
[[META4:![0-9]+]], i64 2, i64 1, [[META6:![0-9]+]], i64 3, i64 1, 
[[META8:![0-9]+]]}
+; CHECK: [[META1]] = !{[[META2:![0-9]+]], [[META2]], i64 0}
+; CHECK: [[META2]] = !{!"byte0", [[META3:![0-9]+]], i64 0}
+; CHECK: [[META3]] = !{!"root"}
+; CHECK: [[META4]] = !{[[META5:![0-9]+]], [[META5]], i64 0}
+; CHECK: [[META5]] = !{!"byte1", [[META3]], i64 0}
+; CHECK: [[META6]] = !{[[META7:![0-9]+]], [[META7]], i64 0}
+; CHECK: [[META7]] = !{!"byte2", [[META3]], i64 0}
+; CHECK: [[META8]] = !{[[META9:![0-9]+]], [[META9]], i64 0}
+; CHECK: [[META9]] = !{!"byte3", [[META3]], i64 0}
+; CHECK: [[META10]] = !{[[META11:![0-9]+]]}
+; CHECK: [[META11]] = distinct !{[[META11]], [[META12:![0-9]+]], !"scope"}
+; CHECK: [[META12]] = distinct !{[[META12]], i1 false, !"domain"}
+; CHECK: [[META13]] = !{[[META14:![0-9]+]]}
+; CHECK: [[META14]] = distinct !{[[META14]], [[META12]], !"other"}
+; CHECK: [[ACC_GRP15]] = distinct !{}
+;.
diff --git 
a/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll 
b/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll
new file mode 100644
index 00000000000000..3b9f5a8a286dd4
--- /dev/null
+++ b/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll
@@ -0,0 +1,26 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 6
+; RUN: opt -passes='default<O2>' -S < %s | FileCheck %s
+
+target datalayout = "e-p:64:64"
+
+; EarlyCSE removes the two intervening stores before AggressiveInstCombine
+; sees the masked store.
+define void @restored_word(ptr %p, i32 %x, i32 %clobber) {
+; CHECK-LABEL: define void @restored_word(
+; CHECK-SAME: ptr nofree captures(none) [[P:%.*]], i32 [[X:%.*]], i32 
[[CLOBBER:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
+; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
+; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
+; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
+; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-NEXT:    ret void
+;
+  %old = load i32, ptr %p, align 4
+  store i32 %clobber, ptr %p, align 4
+  store i32 %old, ptr %p, align 4
+  %insert = and i32 %x, 255
+  %clear = and i32 %old, -256
+  %new = or disjoint i32 %clear, %insert
+  store i32 %new, ptr %p, align 4
+  ret void
+}

>From 08b52411f269ee17474bffc7e657fa508b4ffa90 Mon Sep 17 00:00:00 2001
From: hanbeom <[email protected]>
Date: Sun, 8 Nov 2026 16:17:09 +0900
Subject: [PATCH 2/5] [AggressiveInstCombine] Narrow masked stores to a single
 byte

Narrow masked read-modify-write stores that replace a single byte.
For an N-bit word with N > 8 and N % 8 == 0, let

    Shift = 8 * K, where 0 <= K < N / 8
    Mask = 0xff << Shift
    Offset = K for little-endian layouts
    Offset = N / 8 - 1 - K for big-endian layouts

If MemorySSA proves the word at P is unchanged since the load, fold

    store_N(P, (load_N(P) & ~Mask) | (X & Mask))
      => store_8(P + Offset, trunc_8(lshr(X, Shift)))

Run this fold after merging consecutive stores in each block and before
final simplification can remove the insertion masks.
---
 .../AggressiveInstCombine.cpp                 | 115 +++++++
 .../narrow-masked-store.ll                    | 323 +++++++++++-------
 .../narrow-masked-store-after-early-cse.ll    |   9 +-
 3 files changed, 315 insertions(+), 132 deletions(-)

diff --git 
a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp 
b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
index 1d282437f85fc7..286fbaf6052380 100644
--- a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
+++ b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
@@ -21,6 +21,7 @@
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/GlobalsModRef.h"
+#include "llvm/Analysis/MemorySSA.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
@@ -33,12 +34,14 @@
 #include "llvm/IR/MDBuilder.h"
 #include "llvm/IR/PatternMatch.h"
 #include "llvm/IR/ProfDataUtils.h"
+#include "llvm/IR/ValueHandle.h"
 #include "llvm/ProfileData/InstrProf.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/BuildLibCalls.h"
 #include "llvm/Transforms/Utils/Local.h"
+#include <memory>
 
 using namespace llvm;
 using namespace PatternMatch;
@@ -1795,6 +1798,114 @@ static bool foldConsecutiveStores(BasicBlock &BB, const 
DataLayout &DL,
   return MadeChange;
 }
 
+struct MaskedStore {
+  StoreInst *Store;
+  Value *Insert;
+  unsigned Shift;
+  unsigned Offset;
+};
+
+/// Match a masked read-modify-write that can be narrowed to one byte.
+///
+///   store ((load Ptr & ~Mask) or disjoint (Insert & Mask)), Ptr
+///     -> store i8 trunc(Insert >> Shift), Ptr + Offset
+///
+/// The load and store can be in different blocks if the loaded word is still
+/// available at the store.
+static std::optional<MaskedStore>
+matchMaskedStore(StoreInst &SI, AliasAnalysis &AA, DominatorTree &DT,
+                 std::unique_ptr<MemorySSA> &MSSA) {
+  auto *Ty = dyn_cast<IntegerType>(SI.getValueOperand()->getType());
+  Value *Ptr = SI.getPointerOperand();
+  if (!Ty || Ty->getBitWidth() <= 8 || Ty->getBitWidth() % 8 ||
+      Ptr->isSwiftError())
+    return std::nullopt;
+
+  Value *Old, *Insert;
+  const APInt *KeepMask, *InsertMask;
+  // Require the merge and both masks to die. Replacing these three
+  // instructions with a shift, a truncate and an address offset then
+  // cannot increase the instruction count.
+  if (!match(SI.getValueOperand(),
+             m_OneUse(m_c_DisjointOr(
+                 m_OneUse(m_c_And(m_Value(Old, m_LoadSimple(m_Specific(Ptr))),
+                                  m_APInt(KeepMask))),
+                 m_OneUse(m_c_And(m_Value(Insert), m_APInt(InsertMask)))))))
+    return std::nullopt;
+
+  unsigned Shift, MaskWidth;
+  if (*InsertMask != ~*KeepMask ||
+      !InsertMask->isShiftedMask(Shift, MaskWidth) || MaskWidth != 8 ||
+      Shift % 8)
+    return std::nullopt;
+
+  auto *LI = cast<LoadInst>(Old);
+  if (!MSSA)
+    MSSA = std::make_unique<MemorySSA>(*SI.getFunction(), &AA, &DT);
+  auto *LoadAccess = MSSA->getMemoryAccess(LI);
+  auto *StoreAccess = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(&SI));
+  if (!LoadAccess || !StoreAccess)
+    return std::nullopt;
+
+  // The wide store writes back the preserved bytes from LI. Conservatively
+  // prove that the entire word is unchanged by checking that the clobber
+  // immediately before SI dominates LI. Start before SI's own MemoryDef.
+  MemoryLocation Loc = MemoryLocation::get(LI).getWithoutAATags();
+  MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
+      StoreAccess->getDefiningAccess(), Loc);
+  if (!MSSA->dominates(Clobber, LoadAccess))
+    return std::nullopt;
+
+  const DataLayout &DL = SI.getDataLayout();
+  unsigned Offset =
+      DL.isLittleEndian() ? Shift / 8 : Ty->getBitWidth() / 8 - Shift / 8 - 1;
+  return MaskedStore{&SI, Insert, Shift, Offset};
+}
+
+static bool narrowMatchedStores(ArrayRef<MaskedStore> Stores) {
+  if (Stores.empty())
+    return false;
+
+  for (const MaskedStore &Candidate : Stores) {
+    StoreInst &SI = *Candidate.Store;
+    unsigned Offset = Candidate.Offset;
+    Value *Ptr = SI.getPointerOperand();
+    Type *ByteTy = Type::getInt8Ty(SI.getContext());
+    IRBuilder<> Builder(&SI);
+    Value *Byte = Candidate.Insert;
+    if (Candidate.Shift)
+      Byte = Builder.CreateLShr(Byte, Candidate.Shift);
+    Byte = Builder.CreateTrunc(Byte, ByteTy);
+    if (Offset)
+      Ptr = Builder.CreateConstGEP1_64(ByteTy, Ptr, Offset);
+    Align Alignment = commonAlignment(SI.getAlign(), Offset);
+    StoreInst *NewSI = Builder.CreateAlignedStore(Byte, Ptr, Alignment);
+    NewSI->setAAMetadata(SI.getAAMetadata().adjustForAccess(Offset, 1));
+    NewSI->copyMetadata(SI, {LLVMContext::MD_access_group});
+    SI.eraseFromParent();
+  }
+  return true;
+}
+
+static bool narrowMaskedStores(BasicBlock &BB, DominatorTree &DT,
+                               AliasAnalysis &AA) {
+  SmallVector<MaskedStore, 4> Stores;
+  // Finish all MemorySSA queries before replacing any stores in the block.
+  {
+    std::unique_ptr<MemorySSA> MSSA;
+    for (Instruction &I : BB) {
+      auto *SI = dyn_cast<StoreInst>(&I);
+      if (!SI || !SI->isSimple())
+        continue;
+      if (std::optional<MaskedStore> Candidate =
+              matchMaskedStore(*SI, AA, DT, MSSA))
+        Stores.push_back(*Candidate);
+    }
+  }
+
+  return narrowMatchedStores(Stores);
+}
+
 /// Combine away instructions providing they are still equivalent when compared
 /// against 0. i.e do they have any bits set.
 static Value *optimizeShiftInOrChain(Value *V, IRBuilder<> &Builder) {
@@ -2689,6 +2800,10 @@ static bool foldUnusualPatterns(Function &F, 
DominatorTree &DT,
 
     // Do this separately to avoid redundantly scanning stores multiple times.
     MadeChange |= foldConsecutiveStores(BB, DL, TTI, AA);
+
+    // Merge this block's original stores first. Narrow before final
+    // simplification can remove the insertion mask required for matching.
+    MadeChange |= narrowMaskedStores(BB, DT, AA);
   }
 
   // We're done with transforms, so remove dead instructions.
diff --git a/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll 
b/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
index e035d5d67bb644..450f200e4c135a 100644
--- a/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
+++ b/llvm/test/Transforms/AggressiveInstCombine/narrow-masked-store.ll
@@ -1,18 +1,26 @@
 ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --check-globals all --version 6
-; RUN: opt -passes=aggressive-instcombine -data-layout=e-p:64:64 -S < %s | 
FileCheck %s
-; RUN: opt -passes=aggressive-instcombine -data-layout=E-p:64:64 -S < %s | 
FileCheck %s
+; RUN: opt -passes=aggressive-instcombine -data-layout=e-p:64:64 -S < %s | 
FileCheck %s --check-prefixes=CHECK,LE
+; RUN: opt -passes=aggressive-instcombine -data-layout=E-p:64:64 -S < %s | 
FileCheck %s --check-prefixes=CHECK,BE
 
 ; Insert a register value into the third byte.
 define void @issue_i32_middle(ptr %p, i32 %x) {
-; CHECK-LABEL: define void @issue_i32_middle(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 8
-; CHECK-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[SHIFTED]], 16711680
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 8
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @issue_i32_middle(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; LE-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; LE-NEXT:    [[TMP1:%.*]] = lshr i32 [[SHIFTED]], 16
+; LE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; LE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 2
+; LE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 2
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @issue_i32_middle(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; BE-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; BE-NEXT:    [[TMP1:%.*]] = lshr i32 [[SHIFTED]], 16
+; BE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; BE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; BE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 1
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 8
   %shifted = shl i32 %x, 16
@@ -24,14 +32,18 @@ define void @issue_i32_middle(ptr %p, i32 %x) {
 }
 
 define void @narrow_i16_low(ptr %p, i16 %x) {
-; CHECK-LABEL: define void @narrow_i16_low(
-; CHECK-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 4
-; CHECK-NEXT:    [[INSERT:%.*]] = and i16 [[X]], 255
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i16 [[OLD]], -256
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i16 [[INSERT]], [[CLEAR]]
-; CHECK-NEXT:    store i16 [[NEW]], ptr [[P]], align 4
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @narrow_i16_low(
+; LE-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = trunc i16 [[X]] to i8
+; LE-NEXT:    store i8 [[TMP1]], ptr [[P]], align 4
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @narrow_i16_low(
+; BE-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = trunc i16 [[X]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; BE-NEXT:    ret void
 ;
   %old = load i16, ptr %p, align 4
   %insert = and i16 %x, 255
@@ -42,14 +54,20 @@ define void @narrow_i16_low(ptr %p, i16 %x) {
 }
 
 define void @narrow_i64_high(ptr %p, i64 %x) {
-; CHECK-LABEL: define void @narrow_i64_high(
-; CHECK-SAME: ptr [[P:%.*]], i64 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i64, ptr [[P]], align 8
-; CHECK-NEXT:    [[INSERT:%.*]] = and i64 [[X]], -72057594037927936
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i64 [[OLD]], 72057594037927935
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i64 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i64 [[NEW]], ptr [[P]], align 8
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @narrow_i64_high(
+; LE-SAME: ptr [[P:%.*]], i64 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = lshr i64 [[X]], 56
+; LE-NEXT:    [[TMP2:%.*]] = trunc i64 [[TMP1]] to i8
+; LE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 7
+; LE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 1
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @narrow_i64_high(
+; BE-SAME: ptr [[P:%.*]], i64 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = lshr i64 [[X]], 56
+; BE-NEXT:    [[TMP2:%.*]] = trunc i64 [[TMP1]] to i8
+; BE-NEXT:    store i8 [[TMP2]], ptr [[P]], align 8
+; BE-NEXT:    ret void
 ;
   %old = load i64, ptr %p, align 8
   %insert = and i64 %x, -72057594037927936
@@ -60,17 +78,6 @@ define void @narrow_i64_high(ptr %p, i64 %x) {
 }
 
 define void @narrow_i128_middle(ptr %p, i128 %x) {
-; CHECK-LABEL: define void @narrow_i128_middle(
-; CHECK-SAME: ptr [[P:%.*]], i128 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i128, ptr [[P]], align 16
-; CHECK-NEXT:    [[SHIFTED:%.*]] = shl nuw i128 [[X]], 40
-; CHECK-NEXT:    [[INSERT:%.*]] = and i128 [[SHIFTED]], 280375465082880
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i128 [[OLD]], -280375465082881
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i128 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i128 [[NEW]], ptr [[P]], align 16
-; CHECK-NEXT:    ret void
-;
-; Enable these LE and BE checks with the narrowing change.
 ; LE-LABEL: define void @narrow_i128_middle(
 ; LE-SAME: ptr [[P:%.*]], i128 [[X:%.*]]) {
 ; LE-NEXT:    [[TMP1:%.*]] = trunc i128 [[X]] to i8
@@ -96,14 +103,21 @@ define void @narrow_i128_middle(ptr %p, i128 %x) {
 
 ; Both the OR and AND may have their operands commuted.
 define void @commuted(ptr %p, i32 %x) {
-; CHECK-LABEL: define void @commuted(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 65280, [[X]]
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 -65281, [[OLD]]
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[INSERT]], [[CLEAR]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @commuted(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 8
+; LE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; LE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; LE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 1
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @commuted(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 8
+; BE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; BE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 2
+; BE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 2
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 4
   %insert = and i32 65280, %x
@@ -134,20 +148,33 @@ define i32 @shared_merge(ptr %p, i32 %x) {
 
 ; A load in a dominating block can supply the preserved bytes.
 define void @cross_block(ptr %p, i32 %x, i1 %condition) {
-; CHECK-LABEL: define void @cross_block(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i1 [[CONDITION:%.*]]) {
-; CHECK-NEXT:  [[ENTRY:.*:]]
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    br i1 [[CONDITION]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
-; CHECK:       [[UPDATE]]:
-; CHECK-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[SHIFTED]], 16711680
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
-; CHECK-NEXT:    br label %[[EXIT]]
-; CHECK:       [[EXIT]]:
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @cross_block(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i1 [[CONDITION:%.*]]) {
+; LE-NEXT:  [[ENTRY:.*:]]
+; LE-NEXT:    br i1 [[CONDITION]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
+; LE:       [[UPDATE]]:
+; LE-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; LE-NEXT:    [[TMP0:%.*]] = lshr i32 [[SHIFTED]], 16
+; LE-NEXT:    [[TMP1:%.*]] = trunc i32 [[TMP0]] to i8
+; LE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 2
+; LE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 2
+; LE-NEXT:    br label %[[EXIT]]
+; LE:       [[EXIT]]:
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @cross_block(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i1 [[CONDITION:%.*]]) {
+; BE-NEXT:  [[ENTRY:.*:]]
+; BE-NEXT:    br i1 [[CONDITION]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
+; BE:       [[UPDATE]]:
+; BE-NEXT:    [[SHIFTED:%.*]] = shl i32 [[X]], 16
+; BE-NEXT:    [[TMP0:%.*]] = lshr i32 [[SHIFTED]], 16
+; BE-NEXT:    [[TMP1:%.*]] = trunc i32 [[TMP0]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; BE-NEXT:    br label %[[EXIT]]
+; BE:       [[EXIT]]:
+; BE-NEXT:    ret void
 ;
 entry:
   %old = load i32, ptr %p, align 4
@@ -563,15 +590,20 @@ declare void @read_only(ptr) memory(read)
 ; A read-only call does not clobber the word. It need not be nounwind: the
 ; replacement store stays after the call, so an exception bypasses either 
store.
 define void @read_only_call(ptr %p, i32 %x) {
-; CHECK-LABEL: define void @read_only_call(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    call void @read_only(ptr [[P]])
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @read_only_call(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; LE-NEXT:    call void @read_only(ptr [[P]])
+; LE-NEXT:    [[TMP1:%.*]] = trunc i32 [[X]] to i8
+; LE-NEXT:    store i8 [[TMP1]], ptr [[P]], align 4
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @read_only_call(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; BE-NEXT:    call void @read_only(ptr [[P]])
+; BE-NEXT:    [[TMP1:%.*]] = trunc i32 [[X]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 3
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 4
   call void @read_only(ptr %p)
@@ -584,16 +616,22 @@ define void @read_only_call(ptr %p, i32 %x) {
 
 ; MemorySSA can skip a provably non-overlapping store.
 define void @nonoverlapping_store(ptr %p, i32 %x, i32 %other) {
-; CHECK-LABEL: define void @nonoverlapping_store(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[OTHER:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    [[Q:%.*]] = getelementptr inbounds i8, ptr [[P]], i64 4
-; CHECK-NEXT:    store i32 [[OTHER]], ptr [[Q]], align 4
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @nonoverlapping_store(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[OTHER:%.*]]) {
+; LE-NEXT:    [[Q:%.*]] = getelementptr inbounds i8, ptr [[P]], i64 4
+; LE-NEXT:    store i32 [[OTHER]], ptr [[Q]], align 4
+; LE-NEXT:    [[TMP1:%.*]] = trunc i32 [[X]] to i8
+; LE-NEXT:    store i8 [[TMP1]], ptr [[P]], align 4
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @nonoverlapping_store(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]], i32 [[OTHER:%.*]]) {
+; BE-NEXT:    [[Q:%.*]] = getelementptr inbounds i8, ptr [[P]], i64 4
+; BE-NEXT:    store i32 [[OTHER]], ptr [[Q]], align 4
+; BE-NEXT:    [[TMP1:%.*]] = trunc i32 [[X]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 3
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 4
   %q = getelementptr inbounds i8, ptr %p, i64 4
@@ -607,14 +645,21 @@ define void @nonoverlapping_store(ptr %p, i32 %x, i32 
%other) {
 
 ; The byte GEP preserves the address space and does not strengthen alignment.
 define void @address_space(ptr addrspace(1) %p, i32 %x) {
-; CHECK-LABEL: define void @address_space(
-; CHECK-SAME: ptr addrspace(1) [[P:%.*]], i32 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr addrspace(1) [[P]], align 1
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr addrspace(1) [[P]], align 1
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @address_space(
+; LE-SAME: ptr addrspace(1) [[P:%.*]], i32 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 16
+; LE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; LE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr addrspace(1) [[P]], i64 2
+; LE-NEXT:    store i8 [[TMP2]], ptr addrspace(1) [[TMP3]], align 1
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @address_space(
+; BE-SAME: ptr addrspace(1) [[P:%.*]], i32 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 16
+; BE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; BE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr addrspace(1) [[P]], i64 1
+; BE-NEXT:    store i8 [[TMP2]], ptr addrspace(1) [[TMP3]], align 1
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr addrspace(1) %p, align 1
   %insert = and i32 %x, 16711680
@@ -627,14 +672,21 @@ define void @address_space(ptr addrspace(1) %p, i32 %x) {
 ; Select the tbaa.struct field at the new byte address, preserve alias scopes,
 ; and discard the old whole-word tbaa.struct description.
 define void @aa_metadata(ptr %p, i32 %x) {
-; CHECK-LABEL: define void @aa_metadata(
-; CHECK-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 16711680
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -16711681
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4, !tbaa.struct 
[[TBAA_STRUCT0:![0-9]+]], !alias.scope [[META10:![0-9]+]], !noalias 
[[META13:![0-9]+]], !llvm.access.group [[ACC_GRP15:![0-9]+]]
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @aa_metadata(
+; LE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; LE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 16
+; LE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; LE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 2
+; LE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 2, !tbaa 
[[BYTE2_TBAA0:![0-9]+]], !alias.scope [[META3:![0-9]+]], !noalias 
[[META6:![0-9]+]], !llvm.access.group [[ACC_GRP8:![0-9]+]]
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @aa_metadata(
+; BE-SAME: ptr [[P:%.*]], i32 [[X:%.*]]) {
+; BE-NEXT:    [[TMP1:%.*]] = lshr i32 [[X]], 16
+; BE-NEXT:    [[TMP2:%.*]] = trunc i32 [[TMP1]] to i8
+; BE-NEXT:    [[TMP3:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; BE-NEXT:    store i8 [[TMP2]], ptr [[TMP3]], align 1, !tbaa 
[[BYTE1_TBAA0:![0-9]+]], !alias.scope [[META3:![0-9]+]], !noalias 
[[META6:![0-9]+]], !llvm.access.group [[ACC_GRP8:![0-9]+]]
+; BE-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 4
   %insert = and i32 %x, 16711680
@@ -646,20 +698,34 @@ define void @aa_metadata(ptr %p, i32 %x) {
 
 ; The old word is also used by the branch, as in glslang.
 define void @cross_block_live_load(ptr %p, i16 %x) {
-; CHECK-LABEL: define void @cross_block_live_load(
-; CHECK-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
-; CHECK-NEXT:  [[ENTRY:.*:]]
-; CHECK-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 2
-; CHECK-NEXT:    [[NEEDS_UPDATE:%.*]] = icmp uge i16 [[OLD]], -256
-; CHECK-NEXT:    br i1 [[NEEDS_UPDATE]], label %[[UPDATE:.*]], label 
%[[EXIT:.*]]
-; CHECK:       [[UPDATE]]:
-; CHECK-NEXT:    [[INSERT:%.*]] = and i16 [[X]], -256
-; CHECK-NEXT:    [[KEEP:%.*]] = and i16 [[OLD]], 255
-; CHECK-NEXT:    [[MERGED:%.*]] = or disjoint i16 [[INSERT]], [[KEEP]]
-; CHECK-NEXT:    store i16 [[MERGED]], ptr [[P]], align 2
-; CHECK-NEXT:    br label %[[EXIT]]
-; CHECK:       [[EXIT]]:
-; CHECK-NEXT:    ret void
+; LE-LABEL: define void @cross_block_live_load(
+; LE-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; LE-NEXT:  [[ENTRY:.*:]]
+; LE-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 2
+; LE-NEXT:    [[NEEDS_UPDATE:%.*]] = icmp uge i16 [[OLD]], -256
+; LE-NEXT:    br i1 [[NEEDS_UPDATE]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
+; LE:       [[UPDATE]]:
+; LE-NEXT:    [[TMP0:%.*]] = lshr i16 [[X]], 8
+; LE-NEXT:    [[TMP1:%.*]] = trunc i16 [[TMP0]] to i8
+; LE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 1
+; LE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; LE-NEXT:    br label %[[EXIT]]
+; LE:       [[EXIT]]:
+; LE-NEXT:    ret void
+;
+; BE-LABEL: define void @cross_block_live_load(
+; BE-SAME: ptr [[P:%.*]], i16 [[X:%.*]]) {
+; BE-NEXT:  [[ENTRY:.*:]]
+; BE-NEXT:    [[OLD:%.*]] = load i16, ptr [[P]], align 2
+; BE-NEXT:    [[NEEDS_UPDATE:%.*]] = icmp uge i16 [[OLD]], -256
+; BE-NEXT:    br i1 [[NEEDS_UPDATE]], label %[[UPDATE:.*]], label %[[EXIT:.*]]
+; BE:       [[UPDATE]]:
+; BE-NEXT:    [[TMP0:%.*]] = lshr i16 [[X]], 8
+; BE-NEXT:    [[TMP1:%.*]] = trunc i16 [[TMP0]] to i8
+; BE-NEXT:    store i8 [[TMP1]], ptr [[P]], align 2
+; BE-NEXT:    br label %[[EXIT]]
+; BE:       [[EXIT]]:
+; BE-NEXT:    ret void
 ;
 entry:
   %old = load i16, ptr %p, align 2
@@ -809,22 +875,27 @@ define i32 @shared_keep_mask(ptr %p, i32 %x) {
 !14 = distinct !{!14, !12, !"other"}
 !15 = distinct !{}
 ;.
-; CHECK: attributes #[[ATTR0:[0-9]+]] = { memory(read) }
+; LE: attributes #[[ATTR0:[0-9]+]] = { memory(read) }
+;.
+; BE: attributes #[[ATTR0:[0-9]+]] = { memory(read) }
+;.
+; LE: [[BYTE2_TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
+; LE: [[META1]] = !{!"byte2", [[META2:![0-9]+]], i64 0}
+; LE: [[META2]] = !{!"root"}
+; LE: [[META3]] = !{[[META4:![0-9]+]]}
+; LE: [[META4]] = distinct !{[[META4]], [[META5:![0-9]+]], !"scope"}
+; LE: [[META5]] = distinct !{[[META5]], i1 false, !"domain"}
+; LE: [[META6]] = !{[[META7:![0-9]+]]}
+; LE: [[META7]] = distinct !{[[META7]], [[META5]], !"other"}
+; LE: [[ACC_GRP8]] = distinct !{}
 ;.
-; CHECK: [[TBAA_STRUCT0]] = !{i64 0, i64 1, [[META1:![0-9]+]], i64 1, i64 1, 
[[META4:![0-9]+]], i64 2, i64 1, [[META6:![0-9]+]], i64 3, i64 1, 
[[META8:![0-9]+]]}
-; CHECK: [[META1]] = !{[[META2:![0-9]+]], [[META2]], i64 0}
-; CHECK: [[META2]] = !{!"byte0", [[META3:![0-9]+]], i64 0}
-; CHECK: [[META3]] = !{!"root"}
-; CHECK: [[META4]] = !{[[META5:![0-9]+]], [[META5]], i64 0}
-; CHECK: [[META5]] = !{!"byte1", [[META3]], i64 0}
-; CHECK: [[META6]] = !{[[META7:![0-9]+]], [[META7]], i64 0}
-; CHECK: [[META7]] = !{!"byte2", [[META3]], i64 0}
-; CHECK: [[META8]] = !{[[META9:![0-9]+]], [[META9]], i64 0}
-; CHECK: [[META9]] = !{!"byte3", [[META3]], i64 0}
-; CHECK: [[META10]] = !{[[META11:![0-9]+]]}
-; CHECK: [[META11]] = distinct !{[[META11]], [[META12:![0-9]+]], !"scope"}
-; CHECK: [[META12]] = distinct !{[[META12]], i1 false, !"domain"}
-; CHECK: [[META13]] = !{[[META14:![0-9]+]]}
-; CHECK: [[META14]] = distinct !{[[META14]], [[META12]], !"other"}
-; CHECK: [[ACC_GRP15]] = distinct !{}
+; BE: [[BYTE1_TBAA0]] = !{[[META1:![0-9]+]], [[META1]], i64 0}
+; BE: [[META1]] = !{!"byte1", [[META2:![0-9]+]], i64 0}
+; BE: [[META2]] = !{!"root"}
+; BE: [[META3]] = !{[[META4:![0-9]+]]}
+; BE: [[META4]] = distinct !{[[META4]], [[META5:![0-9]+]], !"scope"}
+; BE: [[META5]] = distinct !{[[META5]], i1 false, !"domain"}
+; BE: [[META6]] = !{[[META7:![0-9]+]]}
+; BE: [[META7]] = distinct !{[[META7]], [[META5]], !"other"}
+; BE: [[ACC_GRP8]] = distinct !{}
 ;.
diff --git 
a/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll 
b/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll
index 3b9f5a8a286dd4..d53608facfcc6b 100644
--- a/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll
+++ b/llvm/test/Transforms/PhaseOrdering/narrow-masked-store-after-early-cse.ll
@@ -7,12 +7,9 @@ target datalayout = "e-p:64:64"
 ; sees the masked store.
 define void @restored_word(ptr %p, i32 %x, i32 %clobber) {
 ; CHECK-LABEL: define void @restored_word(
-; CHECK-SAME: ptr nofree captures(none) [[P:%.*]], i32 [[X:%.*]], i32 
[[CLOBBER:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
-; CHECK-NEXT:    [[OLD:%.*]] = load i32, ptr [[P]], align 4
-; CHECK-NEXT:    [[INSERT:%.*]] = and i32 [[X]], 255
-; CHECK-NEXT:    [[CLEAR:%.*]] = and i32 [[OLD]], -256
-; CHECK-NEXT:    [[NEW:%.*]] = or disjoint i32 [[CLEAR]], [[INSERT]]
-; CHECK-NEXT:    store i32 [[NEW]], ptr [[P]], align 4
+; CHECK-SAME: ptr nofree writeonly captures(none) initializes((0, 1)) 
[[P:%.*]], i32 [[X:%.*]], i32 [[CLOBBER:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] {
+; CHECK-NEXT:    [[TMP1:%.*]] = trunc i32 [[X]] to i8
+; CHECK-NEXT:    store i8 [[TMP1]], ptr [[P]], align 4
 ; CHECK-NEXT:    ret void
 ;
   %old = load i32, ptr %p, align 4

>From f68361e1a291c552b32bb350edae7cab2f257e3a Mon Sep 17 00:00:00 2001
From: hanbeom <[email protected]>
Date: Fri, 13 Nov 2026 15:47:27 +0900
Subject: [PATCH 3/5] update missed testcase

---
 clang/test/CodeGenCXX/bitfield-ir.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/test/CodeGenCXX/bitfield-ir.cpp 
b/clang/test/CodeGenCXX/bitfield-ir.cpp
index a393001fc336d0..f3237ce147cbe8 100644
--- a/clang/test/CodeGenCXX/bitfield-ir.cpp
+++ b/clang/test/CodeGenCXX/bitfield-ir.cpp
@@ -90,10 +90,10 @@ void A (Int *p) {
 // CHECK-NEXT:  entry:
 // CHECK-NEXT:    [[BF_LOAD:%.*]] = load i32, ptr [[P]], align 4
 // CHECK-NEXT:    [[INC:%.*]] = add i32 [[BF_LOAD]], 65536
-// CHECK-NEXT:    [[BF_VALUE:%.*]] = and i32 [[INC]], 16711680
-// CHECK-NEXT:    [[BF_CLEAR:%.*]] = and i32 [[BF_LOAD]], -16711681
-// CHECK-NEXT:    [[BF_SET:%.*]] = or disjoint i32 [[BF_VALUE]], [[BF_CLEAR]]
-// CHECK-NEXT:    store i32 [[BF_SET]], ptr [[P]], align 4
+// CHECK-NEXT:    [[TMP0:%.*]] = lshr i32 [[INC]], 16
+// CHECK-NEXT:    [[TMP1:%.*]] = trunc i32 [[TMP0]] to i8
+// CHECK-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[P]], i64 2
+// CHECK-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 2
 // CHECK-NEXT:    ret void
 //
 void B (Int *p) {

>From 0c5bebba7b6504d2351bcac1d07d732f825ac260 Mon Sep 17 00:00:00 2001
From: hanbeom <[email protected]>
Date: Sun, 15 Nov 2026 06:53:44 +0900
Subject: [PATCH 4/5] [AggressiveInstCombine][NFC] Find chained stores with
 MemorySSA

Extract the clobber query used to check masked store narrowing. Add a
finder that starts from a store and identifies a same-block predecessor
whose entire byte range it overwrites. Use alias analysis to validate
the range and record the earlier store's offset.
---
 .../AggressiveInstCombine.cpp                 | 64 +++++++++++++++++--
 1 file changed, 59 insertions(+), 5 deletions(-)

diff --git 
a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp 
b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
index 286fbaf6052380..cae3da430817c7 100644
--- a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
+++ b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
@@ -1798,6 +1798,16 @@ static bool foldConsecutiveStores(BasicBlock &BB, const 
DataLayout &DL,
   return MadeChange;
 }
 
+static MemoryAccess *getClobberBefore(const Instruction &I,
+                                      const MemoryLocation &Loc,
+                                      MemorySSA &MSSA) {
+  auto *Access = MSSA.getMemoryAccess(&I);
+  if (!Access)
+    return nullptr;
+  return MSSA.getWalker()->getClobberingMemoryAccess(
+      Access->getDefiningAccess(), Loc);
+}
+
 struct MaskedStore {
   StoreInst *Store;
   Value *Insert;
@@ -1843,17 +1853,15 @@ matchMaskedStore(StoreInst &SI, AliasAnalysis &AA, 
DominatorTree &DT,
   if (!MSSA)
     MSSA = std::make_unique<MemorySSA>(*SI.getFunction(), &AA, &DT);
   auto *LoadAccess = MSSA->getMemoryAccess(LI);
-  auto *StoreAccess = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(&SI));
-  if (!LoadAccess || !StoreAccess)
+  if (!LoadAccess)
     return std::nullopt;
 
   // The wide store writes back the preserved bytes from LI. Conservatively
   // prove that the entire word is unchanged by checking that the clobber
   // immediately before SI dominates LI. Start before SI's own MemoryDef.
   MemoryLocation Loc = MemoryLocation::get(LI).getWithoutAATags();
-  MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
-      StoreAccess->getDefiningAccess(), Loc);
-  if (!MSSA->dominates(Clobber, LoadAccess))
+  MemoryAccess *Clobber = getClobberBefore(SI, Loc, *MSSA);
+  if (!Clobber || !MSSA->dominates(Clobber, LoadAccess))
     return std::nullopt;
 
   const DataLayout &DL = SI.getDataLayout();
@@ -1887,6 +1895,52 @@ static bool narrowMatchedStores(ArrayRef<MaskedStore> 
Stores) {
   return true;
 }
 
+static StoreInst *getClobberingStore(MemoryAccess *Clobber) {
+  auto *Def = dyn_cast_if_present<MemoryDef>(Clobber);
+  return Def ? dyn_cast_or_null<StoreInst>(Def->getMemoryInst()) : nullptr;
+}
+
+struct ChainedStore {
+  StoreInst *Store;
+  uint64_t Offset;
+};
+
+/// Find the preceding simple store whose entire byte range is written by SI.
+/// The chain is local to this block, with no intervening clobber of SI's 
range.
+/// A consumer must separately check whether either store can be changed.
+[[maybe_unused]] static std::optional<ChainedStore>
+findChainedStore(StoreInst &SI,
+                                                    MemorySSA &MSSA) {
+  MemoryLocation Loc = MemoryLocation::get(&SI).getWithoutAATags();
+  if (!Loc.Size.isPrecise() || Loc.Size.isScalable())
+    return std::nullopt;
+
+  auto *First = getClobberingStore(getClobberBefore(SI, Loc, MSSA));
+  if (!First || !First->isSimple() || First->getParent() != SI.getParent() ||
+      !First->comesBefore(&SI) ||
+      First->getPointerAddressSpace() != SI.getPointerAddressSpace())
+    return std::nullopt;
+
+  MemoryLocation FirstLoc = MemoryLocation::get(First).getWithoutAATags();
+  LocationSize FirstSize = FirstLoc.Size;
+  if (!FirstSize.isPrecise() || FirstSize.isScalable() || FirstSize.isZero())
+    return std::nullopt;
+
+  AliasResult Alias = MSSA.getAA().alias(Loc, FirstLoc);
+  int64_t Offset = 0;
+  if (Alias != AliasResult::MustAlias) {
+    if (Alias != AliasResult::PartialAlias || !Alias.hasOffset())
+      return std::nullopt;
+    Offset = Alias.getOffset();
+  }
+  uint64_t FirstBytes = FirstSize.getValue().getFixedValue();
+  uint64_t LastBytes = Loc.Size.getValue().getFixedValue();
+  if (Offset < 0 || FirstBytes > LastBytes ||
+      uint64_t(Offset) > LastBytes - FirstBytes)
+    return std::nullopt;
+  return ChainedStore{First, uint64_t(Offset)};
+}
+
 static bool narrowMaskedStores(BasicBlock &BB, DominatorTree &DT,
                                AliasAnalysis &AA) {
   SmallVector<MaskedStore, 4> Stores;

>From c3913dfe52a6757b003b9bad894ed5586fda10cc Mon Sep 17 00:00:00 2001
From: hanbeom <[email protected]>
Date: Sun, 15 Nov 2026 06:53:45 +0900
Subject: [PATCH 5/5] [AggressiveInstCombine] Forward reloads between chained
 masked updates

A low-byte store followed by a bit-8 update of the same i16 word can
survive inlining in JsonCpp. Find each chain from its later store, and
reconstruct the word read by the masked update from the reaching byte
and the original high byte.

For the reciprocal swap, forward only the uses feeding the two updates
so both stores retain their dependencies on both original words. A
constant byte may use a reaching initializer on a non-escaping alloca.
Freeze that initializer when needed and retain the ordering checks.

Leave mask folding and removal of unobserved byte stores to the
existing InstCombine and DSE passes.
---
 .../AggressiveInstCombine.cpp                 | 210 +++++++++++++++++-
 .../merge-masked-byte-stores-constant.ll      |  96 ++++++++
 .../merge-masked-byte-stores.ll               | 123 ++++++++++
 3 files changed, 419 insertions(+), 10 deletions(-)
 create mode 100644 
llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores-constant.ll
 create mode 100644 
llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores.ll

diff --git 
a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp 
b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
index cae3da430817c7..6ffbd4806480bf 100644
--- a/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
+++ b/llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
@@ -14,10 +14,12 @@
 
 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
 #include "AggressiveInstCombineInternal.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/AssumptionCache.h"
 #include "llvm/Analysis/BasicAliasAnalysis.h"
+#include "llvm/Analysis/CaptureTracking.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/GlobalsModRef.h"
@@ -38,9 +40,11 @@
 #include "llvm/ProfileData/InstrProf.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/KnownBits.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/BuildLibCalls.h"
 #include "llvm/Transforms/Utils/Local.h"
+#include <iterator>
 #include <memory>
 
 using namespace llvm;
@@ -1908,8 +1912,7 @@ struct ChainedStore {
 /// Find the preceding simple store whose entire byte range is written by SI.
 /// The chain is local to this block, with no intervening clobber of SI's 
range.
 /// A consumer must separately check whether either store can be changed.
-[[maybe_unused]] static std::optional<ChainedStore>
-findChainedStore(StoreInst &SI,
+static std::optional<ChainedStore> findChainedStore(StoreInst &SI,
                                                     MemorySSA &MSSA) {
   MemoryLocation Loc = MemoryLocation::get(&SI).getWithoutAATags();
   if (!Loc.Size.isPrecise() || Loc.Size.isScalable())
@@ -1941,9 +1944,189 @@ findChainedStore(StoreInst &SI,
   return ChainedStore{First, uint64_t(Offset)};
 }
 
-static bool narrowMaskedStores(BasicBlock &BB, DominatorTree &DT,
-                               AliasAnalysis &AA) {
+struct MaskedStoreChain {
+  StoreInst *First;
+  LoadInst *Reload;
+  LoadInst *Insert;
+  Use *Keep;
+  Use *Bits;
+};
+
+/// Match a bit-8 update that reads the word written by the first store in
+/// this chain. The first store supplies the low byte of the reload.
+static std::optional<MaskedStoreChain>
+matchMaskedStoreChain(StoreInst &Last, AliasAnalysis &AA, DominatorTree &DT,
+                      std::unique_ptr<MemorySSA> &MSSA) {
+  assert(Last.getValueOperand()->getType()->isIntegerTy(16));
+
+  Instruction *Keep, *Bits, *Reload, *Insert;
+  Value *Ptr = Last.getPointerOperand();
+  auto KeepMask = m_Instruction(
+      Keep,
+      m_OneUse(m_c_And(m_Instruction(Reload, m_LoadSimple(m_Specific(Ptr))),
+                       m_SpecificInt(0xfeff))));
+  auto InsertMask = m_Instruction(
+      Bits, m_OneUse(m_c_And(m_Instruction(Insert, m_LoadSimple(m_Value())),
+                             m_SpecificInt(0x100))));
+  if (!match(Last.getValueOperand(),
+             m_OneUse(m_c_DisjointOr(KeepMask, InsertMask))))
+    return std::nullopt;
+
+  auto *Load = cast<LoadInst>(Reload);
+  auto *BitLoad = cast<LoadInst>(Insert);
+  if (Load->getParent() != Last.getParent() ||
+      Load->hasMetadata(LLVMContext::MD_invariant_group) ||
+      Load->hasMetadata(LLVMContext::MD_invariant_load) ||
+      BitLoad->getParent() != Last.getParent() ||
+      BitLoad->getPointerOperand() == Ptr ||
+      BitLoad->hasMetadata(LLVMContext::MD_invariant_group))
+    return std::nullopt;
+
+  if (!MSSA)
+    MSSA = std::make_unique<MemorySSA>(*Last.getFunction(), &AA, &DT);
+  auto First = findChainedStore(Last, *MSSA);
+  if (!First || !First->Store->getValueOperand()->getType()->isIntegerTy(8) ||
+      First->Offset != (Last.getDataLayout().isLittleEndian() ? 0u : 1u) ||
+      First->Store->hasMetadata(LLVMContext::MD_invariant_group) ||
+      !First->Store->comesBefore(Load))
+    return std::nullopt;
+
+  // First is also the clobber before Last. Both stores and the reload are
+  // in the same block and Reload reads the same range that Last writes.
+  return MaskedStoreChain{First->Store, Load, BitLoad,
+                          &Keep->getOperandUse(Keep->getOperand(0) != Load),
+                          &Bits->getOperandUse(Bits->getOperand(0) != 
BitLoad)};
+}
+
+/// Find the word containing the byte that the other chain stores. Its high
+/// byte must still be available when this chain writes its low byte.
+static Instruction *findOriginalWord(const MaskedStoreChain &Chain,
+                                     const MaskedStoreChain &Other,
+                                     MemorySSA &MSSA, const SimplifyQuery &SQ) 
{
+  MemoryLocation Loc = MemoryLocation::get(Chain.Reload).getWithoutAATags();
+  MemoryAccess *BeforeByte = getClobberBefore(*Chain.First, Loc, MSSA);
+  if (!BeforeByte)
+    return nullptr;
+  Value *Written = Other.First->getValueOperand();
+  Instruction *Start;
+  if (auto *Byte = dyn_cast<ConstantInt>(Written)) {
+    auto *Initial = getClobberingStore(BeforeByte);
+    if (!Initial || !Initial->isSimple() ||
+        !Initial->getValueOperand()->getType()->isIntegerTy(16) ||
+        Initial->getPointerOperand() != Loc.Ptr)
+      return nullptr;
+
+    // This initializer can be in a different block. Require private memory
+    // so synchronization cannot change the word before the byte store.
+    auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Loc.Ptr));
+    if (!Alloca || PointerMayBeCaptured(Alloca, /*ReturnCaptures=*/true))
+      return nullptr;
+
+    KnownBits LowByte = computeKnownBits(Initial->getValueOperand(),
+                                         SQ.getWithInstruction(Initial))
+                            .trunc(8);
+    if (!LowByte.isConstant() || LowByte.getConstant() != Byte->getValue())
+      return nullptr;
+    Start = Initial;
+  } else {
+    Instruction *Old;
+    if (!match(Written, m_Trunc(m_Instruction(
+                            Old, m_LoadSimple(m_Specific(Loc.Ptr))))) ||
+        !Old->getType()->isIntegerTy(16) ||
+        Old->getParent() != Chain.Reload->getParent() ||
+        !Old->comesBefore(Chain.First) ||
+        Old->hasMetadata(LLVMContext::MD_invariant_group) ||
+        getClobberBefore(*Old, Loc, MSSA) != BeforeByte)
+      return nullptr;
+    Start = Old;
+  }
+
+  auto Begin = isa<LoadInst>(Start) ? std::next(Start->getIterator())
+                                    : Chain.First->getIterator();
+  // A synchronization operation can affect what the reload sees even when
+  // the clobber for its memory location stays the same.
+  unsigned Remaining = MaxInstrsToScan;
+  for (Instruction &I : make_range(Begin, Chain.Reload->getIterator()))
+    if (Remaining-- == 0 || I.isAtomic() || I.isVolatile() ||
+        I.maySynchronize())
+      return nullptr;
+  return Start;
+}
+
+/// Forward the value of the two reloads used by a reciprocal byte and bit
+/// update. Both reloads still contribute to both stores, so an original load
+/// that is poison because of its overwritten low byte also reaches both
+/// stores through the byte written to the other address.
+static bool foldMaskedStoreChains(ArrayRef<MaskedStoreChain> Chains,
+                                  MemorySSA &MSSA, const SimplifyQuery &SQ) {
+  if (Chains.size() < 2)
+    return false;
+
+  SmallDenseMap<LoadInst *, const MaskedStoreChain *, 4> ByReload;
+  for (const MaskedStoreChain &Chain : Chains) {
+    // A later chain for the same reload would have an intervening clobber.
+    [[maybe_unused]] bool Inserted =
+        ByReload.try_emplace(Chain.Reload, &Chain).second;
+    assert(Inserted && "Expected at most one chain per reload");
+  }
+
+  struct Forwarding {
+    const MaskedStoreChain *A;
+    const MaskedStoreChain *B;
+    Instruction *OldA;
+    Instruction *OldB;
+  };
+  SmallVector<Forwarding, 1> Candidates;
+  for (const MaskedStoreChain &A : Chains) {
+    const auto *B = ByReload.lookup(A.Insert);
+    if (!B || B->Insert != A.Reload || !A.Reload->comesBefore(B->Reload))
+      continue;
+    if (Instruction *OldA = findOriginalWord(A, *B, MSSA, SQ))
+      if (Instruction *OldB = findOriginalWord(*B, A, MSSA, SQ))
+        Candidates.push_back({&A, B, OldA, OldB});
+  }
+
+  auto GetOriginalValue = [&](Instruction *Word) -> Value * {
+    auto *Initial = dyn_cast<StoreInst>(Word);
+    if (!Initial)
+      return Word;
+    Value *V = Initial->getValueOperand();
+    if (!isGuaranteedNotToBeUndefOrPoison(V, SQ.AC, Initial, SQ.DT)) {
+      IRBuilder<> Builder(Initial);
+      // Freeze the stored initializer so the forwarded value also agrees
+      // with any other loads from this initialization.
+      V = Builder.CreateFreeze(V);
+      Initial->setOperand(0, V);
+    }
+    return V;
+  };
+  auto ForwardReload = [](const MaskedStoreChain &Chain, Use &OtherBits,
+                          Value *Old) {
+    IRBuilder<> Builder(Chain.Reload);
+    // Replace the two uses feeding the paired stores. Other uses need their
+    // own poison proof, since an earlier byte store can overwrite poison.
+    Value *Low = Builder.CreateZExt(Chain.First->getValueOperand(),
+                                    Chain.Reload->getType());
+    Value *High = Builder.CreateAnd(Old, 0xff00);
+    Value *Word = Builder.CreateOr(High, Low, "", /*IsDisjoint=*/true);
+    Chain.Keep->set(Word);
+    OtherBits.set(Word);
+  };
+  // Finish the MemorySSA queries before forwarding. InstCombine simplifies
+  // the recomposed words and DSE can remove the now unobserved byte stores.
+  for (const auto &[A, B, OldA, OldB] : Candidates) {
+    ForwardReload(*A, *B->Bits, GetOriginalValue(OldA));
+    ForwardReload(*B, *A->Bits, GetOriginalValue(OldB));
+  }
+  return !Candidates.empty();
+}
+
+static bool foldChainedStores(BasicBlock &BB, DominatorTree &DT,
+                              AliasAnalysis &AA, const SimplifyQuery &SQ) {
   SmallVector<MaskedStore, 4> Stores;
+  SmallVector<MaskedStoreChain, 2> MaskedChains;
+  bool SawByteStore = false;
+  bool MadeChange = false;
   // Finish all MemorySSA queries before replacing any stores in the block.
   {
     std::unique_ptr<MemorySSA> MSSA;
@@ -1951,13 +2134,20 @@ static bool narrowMaskedStores(BasicBlock &BB, 
DominatorTree &DT,
       auto *SI = dyn_cast<StoreInst>(&I);
       if (!SI || !SI->isSimple())
         continue;
-      if (std::optional<MaskedStore> Candidate =
-              matchMaskedStore(*SI, AA, DT, MSSA))
+      Type *Ty = SI->getValueOperand()->getType();
+      if (SawByteStore && Ty->isIntegerTy(16))
+        if (auto Chain = matchMaskedStoreChain(*SI, AA, DT, MSSA))
+          MaskedChains.push_back(*Chain);
+      SawByteStore |= Ty->isIntegerTy(8);
+      if (auto Candidate = matchMaskedStore(*SI, AA, DT, MSSA))
         Stores.push_back(*Candidate);
     }
+    if (MSSA)
+      MadeChange = foldMaskedStoreChains(MaskedChains, *MSSA, SQ);
   }
 
-  return narrowMatchedStores(Stores);
+  MadeChange |= narrowMatchedStores(Stores);
+  return MadeChange;
 }
 
 /// Combine away instructions providing they are still equivalent when compared
@@ -2855,9 +3045,9 @@ static bool foldUnusualPatterns(Function &F, 
DominatorTree &DT,
     // Do this separately to avoid redundantly scanning stores multiple times.
     MadeChange |= foldConsecutiveStores(BB, DL, TTI, AA);
 
-    // Merge this block's original stores first. Narrow before final
-    // simplification can remove the insertion mask required for matching.
-    MadeChange |= narrowMaskedStores(BB, DT, AA);
+    // Use the original byte stores to find chains before applying narrowing.
+    // Match the masks before final simplification can remove them.
+    MadeChange |= foldChainedStores(BB, DT, AA, SimplifyQuery(DL, &TLI, &DT, 
&AC));
   }
 
   // We're done with transforms, so remove dead instructions.
diff --git 
a/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores-constant.ll
 
b/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores-constant.ll
new file mode 100644
index 00000000000000..66b7f8f93c5acd
--- /dev/null
+++ 
b/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores-constant.ll
@@ -0,0 +1,96 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 6
+; RUN: opt -passes='aggressive-instcombine,gvn,instcombine,dse' -S < %s | 
FileCheck %s
+
+target datalayout = "e-p:64:64"
+
+@left = global i16 0, align 2
+@right = global i16 0, align 2
+@go = external global i32
+@done = external global i32
+
+declare void @handoff(ptr, ptr) memory(argmem: readwrite) nounwind willreturn
+
+; The temporary object's initializer makes its low byte constant before the
+; bit swap is inlined. Its uninitialized high bits can be poison.
+define void @swap_with_constant_byte(ptr noalias %a, ptr noalias %out, i16 
%old) {
+; CHECK-LABEL: define void @swap_with_constant_byte(
+; CHECK-SAME: ptr noalias [[A:%.*]], ptr noalias [[OUT:%.*]], i16 [[OLD:%.*]]) 
{
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:    [[OLD_FR:%.*]] = freeze i16 [[OLD]]
+; CHECK-NEXT:    [[A_OLD:%.*]] = load i16, ptr [[A]], align 2
+; CHECK-NEXT:    [[TMP0:%.*]] = and i16 [[A_OLD]], -512
+; CHECK-NEXT:    [[KEEP:%.*]] = and i16 [[OLD_FR]], -512
+; CHECK-NEXT:    [[TMP1:%.*]] = or disjoint i16 [[TMP0]], 260
+; CHECK-NEXT:    [[TMP2:%.*]] = and i16 [[A_OLD]], 511
+; CHECK-NEXT:    [[TMP3:%.*]] = or disjoint i16 [[KEEP]], [[TMP2]]
+; CHECK-NEXT:    store i16 [[TMP1]], ptr [[A]], align 2
+; CHECK-NEXT:    store i16 [[TMP3]], ptr [[OUT]], align 2
+; CHECK-NEXT:    ret void
+;
+entry:
+  %b = alloca i16, align 2
+  %keep = and i16 %old, -512
+  %initial = or disjoint i16 %keep, 260
+  store i16 %initial, ptr %b, align 2
+  br label %swap
+
+swap:
+  %a.old = load i16, ptr %a, align 2
+  %byte = trunc i16 %a.old to i8
+  store i8 4, ptr %a, align 2
+  store i8 %byte, ptr %b, align 2
+  %a.reload = load i16, ptr %a, align 2
+  %b.reload = load i16, ptr %b, align 2
+  %a.bit = and i16 %a.reload, 256
+  %b.bit = and i16 %b.reload, 256
+  %a.keep = and i16 %a.reload, -257
+  %b.keep = and i16 %b.reload, -257
+  %a.new = or disjoint i16 %a.keep, %b.bit
+  %b.new = or disjoint i16 %b.keep, %a.bit
+  store i16 %a.new, ptr %a, align 2
+  store i16 %b.new, ptr %b, align 2
+  %result = load i16, ptr %b, align 2
+  store i16 %result, ptr %out, align 2
+  ret void
+}
+
+; The call can synchronize with a thread that modifies @right. Its memory
+; effects alone do not prove that @right retains the initializer.
+define void @swap_with_shared_initializer() {
+; CHECK-LABEL: define void @swap_with_shared_initializer() {
+; CHECK-NEXT:    store i16 260, ptr @right, align 2
+; CHECK-NEXT:    call void @handoff(ptr nonnull @go, ptr nonnull @done)
+; CHECK-NEXT:    [[LEFT_ORIGINAL:%.*]] = load i16, ptr @left, align 2
+; CHECK-NEXT:    [[LEFT_BYTE:%.*]] = trunc i16 [[LEFT_ORIGINAL]] to i8
+; CHECK-NEXT:    store i8 4, ptr @left, align 2
+; CHECK-NEXT:    store i8 [[LEFT_BYTE]], ptr @right, align 2
+; CHECK-NEXT:    [[LEFT_NEW:%.*]] = load i16, ptr @left, align 2
+; CHECK-NEXT:    [[RIGHT_NEW:%.*]] = load i16, ptr @right, align 2
+; CHECK-NEXT:    [[LEFT_BIT:%.*]] = and i16 [[LEFT_NEW]], 256
+; CHECK-NEXT:    [[RIGHT_BIT:%.*]] = and i16 [[RIGHT_NEW]], 256
+; CHECK-NEXT:    [[LEFT_KEEP:%.*]] = and i16 [[LEFT_NEW]], -257
+; CHECK-NEXT:    [[RIGHT_KEEP:%.*]] = and i16 [[RIGHT_NEW]], -257
+; CHECK-NEXT:    [[LEFT_UPDATED:%.*]] = or disjoint i16 [[LEFT_KEEP]], 
[[RIGHT_BIT]]
+; CHECK-NEXT:    [[RIGHT_UPDATED:%.*]] = or disjoint i16 [[RIGHT_KEEP]], 
[[LEFT_BIT]]
+; CHECK-NEXT:    store i16 [[LEFT_UPDATED]], ptr @left, align 2
+; CHECK-NEXT:    store i16 [[RIGHT_UPDATED]], ptr @right, align 2
+; CHECK-NEXT:    ret void
+;
+  store i16 260, ptr @right, align 2
+  call void @handoff(ptr @go, ptr @done)
+  %left.original = load i16, ptr @left, align 2
+  %left.byte = trunc i16 %left.original to i8
+  store i8 4, ptr @left, align 2
+  store i8 %left.byte, ptr @right, align 2
+  %left.new = load i16, ptr @left, align 2
+  %right.new = load i16, ptr @right, align 2
+  %left.bit = and i16 %left.new, 256
+  %right.bit = and i16 %right.new, 256
+  %left.keep = and i16 %left.new, -257
+  %right.keep = and i16 %right.new, -257
+  %left.updated = or disjoint i16 %left.keep, %right.bit
+  %right.updated = or disjoint i16 %right.keep, %left.bit
+  store i16 %left.updated, ptr @left, align 2
+  store i16 %right.updated, ptr @right, align 2
+  ret void
+}
diff --git 
a/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores.ll 
b/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores.ll
new file mode 100644
index 00000000000000..2335949d2d0b17
--- /dev/null
+++ b/llvm/test/Transforms/AggressiveInstCombine/merge-masked-byte-stores.ll
@@ -0,0 +1,123 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 6
+; RUN: opt 
-passes='aggressive-instcombine,aggressive-instcombine,gvn,instcombine,dse' 
-data-layout=e-p:64:64 -S < %s | FileCheck %s --check-prefixes=CHECK,LE
+; RUN: opt 
-passes='aggressive-instcombine,aggressive-instcombine,gvn,instcombine,dse' 
-data-layout=E-p:64:64 -S < %s | FileCheck %s --check-prefixes=CHECK,BE
+; RUN: opt -passes='aggressive-instcombine,aggressive-instcombine' 
-data-layout=e-p:64:64 -S < %s | FileCheck %s --check-prefix=FORWARD
+
+; The first AGC run narrows the byte updates. The second sees the pattern
+; exposed in JsonCpp after inlining, with the two objects known to be disjoint.
+; FORWARD-LABEL: define void @swap_low_nine_bits(
+; FORWARD: [[OLD_A:%.*]] = load i16, ptr
+; FORWARD-NEXT: [[OLD_B:%.*]] = load i16, ptr
+; FORWARD-NEXT: [[BYTE_A:%.*]] = trunc i16 [[OLD_B]] to i8
+; FORWARD-NEXT: store i8 [[BYTE_A]], ptr
+; FORWARD-NEXT: [[BYTE_B:%.*]] = trunc i16 [[OLD_A]] to i8
+; FORWARD-NEXT: store i8 [[BYTE_B]], ptr
+; FORWARD: [[LOW_A:%.*]] = zext i8 [[BYTE_A]] to i16
+; FORWARD-NEXT: [[HIGH_A:%.*]] = and i16 [[OLD_A]], -256
+; FORWARD-NEXT: [[WORD_A:%.*]] = or disjoint i16 [[HIGH_A]], [[LOW_A]]
+; FORWARD: and i16 [[WORD_A]], 256
+; FORWARD: and i16 [[WORD_A]], -257
+define void @swap_low_nine_bits(ptr noalias %a, ptr noalias %b) {
+;
+; CHECK-LABEL: define void @swap_low_nine_bits(
+; CHECK-SAME: ptr noalias [[A:%.*]], ptr noalias [[B:%.*]]) {
+; CHECK-NEXT:    [[P:%.*]] = getelementptr inbounds nuw i8, ptr [[A]], i64 8
+; CHECK-NEXT:    [[Q:%.*]] = getelementptr inbounds nuw i8, ptr [[B]], i64 8
+; CHECK-NEXT:    [[A_OLD:%.*]] = load i16, ptr [[P]], align 8
+; CHECK-NEXT:    [[B_OLD:%.*]] = load i16, ptr [[Q]], align 8
+; CHECK-NEXT:    [[A_PAYLOAD:%.*]] = load i64, ptr [[A]], align 8
+; CHECK-NEXT:    [[B_PAYLOAD:%.*]] = load i64, ptr [[B]], align 8
+; CHECK-NEXT:    store i64 [[B_PAYLOAD]], ptr [[A]], align 8
+; CHECK-NEXT:    store i64 [[A_PAYLOAD]], ptr [[B]], align 8
+; CHECK-NEXT:    [[TMP1:%.*]] = and i16 [[A_OLD]], -512
+; CHECK-NEXT:    [[TMP4:%.*]] = and i16 [[B_OLD]], -512
+; CHECK-NEXT:    [[TMP2:%.*]] = and i16 [[B_OLD]], 511
+; CHECK-NEXT:    [[TMP3:%.*]] = or disjoint i16 [[TMP1]], [[TMP2]]
+; CHECK-NEXT:    [[TMP5:%.*]] = and i16 [[A_OLD]], 511
+; CHECK-NEXT:    [[TMP6:%.*]] = or disjoint i16 [[TMP4]], [[TMP5]]
+; CHECK-NEXT:    store i16 [[TMP3]], ptr [[P]], align 8
+; CHECK-NEXT:    store i16 [[TMP6]], ptr [[Q]], align 8
+; CHECK-NEXT:    ret void
+;
+  %p = getelementptr inbounds i8, ptr %a, i64 8
+  %q = getelementptr inbounds i8, ptr %b, i64 8
+  %a.old = load i16, ptr %p, align 8
+  %b.old = load i16, ptr %q, align 8
+  %a.low = and i16 %a.old, 255
+  %b.low = and i16 %b.old, 255
+  %a.high = and i16 %a.old, -256
+  %b.high = and i16 %b.old, -256
+  %a.with.byte = or disjoint i16 %a.high, %b.low
+  %b.with.byte = or disjoint i16 %b.high, %a.low
+  store i16 %a.with.byte, ptr %p, align 8
+  store i16 %b.with.byte, ptr %q, align 8
+  %a.payload = load i64, ptr %a, align 8
+  %b.payload = load i64, ptr %b, align 8
+  store i64 %b.payload, ptr %a, align 8
+  store i64 %a.payload, ptr %b, align 8
+  %a.reload = load i16, ptr %p, align 8
+  %b.reload = load i16, ptr %q, align 8
+  %a.bit = and i16 %a.reload, 256
+  %b.bit = and i16 %b.reload, 256
+  %a.keep = and i16 %a.reload, -257
+  %b.keep = and i16 %b.reload, -257
+  %a.new = or disjoint i16 %a.keep, %b.bit
+  %b.new = or disjoint i16 %b.keep, %a.bit
+  store i16 %a.new, ptr %p, align 8
+  store i16 %b.new, ptr %q, align 8
+  ret void
+}
+
+; A one-way byte update can make the reload defined even when %old was
+; poison. The final store must keep using the reload in that case.
+define i16 @poison_in_overwritten_byte(ptr noalias %a, ptr noalias %b) {
+;
+;
+; LE-LABEL: define i16 @poison_in_overwritten_byte(
+; LE-SAME: ptr noalias [[A:%.*]], ptr noalias [[B:%.*]]) {
+; LE-NEXT:    [[OLD:%.*]] = load i16, ptr [[A]], align 2
+; LE-NEXT:    [[OTHER:%.*]] = load i16, ptr [[B]], align 2, !noundef 
[[META0:![0-9]+]]
+; LE-NEXT:    [[TMP1:%.*]] = trunc i16 [[OTHER]] to i8
+; LE-NEXT:    store i8 [[TMP1]], ptr [[A]], align 2
+; LE-NEXT:    [[A_RELOAD:%.*]] = load i16, ptr [[A]], align 2
+; LE-NEXT:    [[BIT:%.*]] = and i16 [[OTHER]], 256
+; LE-NEXT:    [[KEEP:%.*]] = and i16 [[A_RELOAD]], -257
+; LE-NEXT:    [[WITH_BIT:%.*]] = or disjoint i16 [[KEEP]], [[BIT]]
+; LE-NEXT:    store i16 [[WITH_BIT]], ptr [[A]], align 2
+; LE-NEXT:    ret i16 [[OLD]]
+;
+; BE-LABEL: define i16 @poison_in_overwritten_byte(
+; BE-SAME: ptr noalias [[A:%.*]], ptr noalias [[B:%.*]]) {
+; BE-NEXT:    [[OLD:%.*]] = load i16, ptr [[A]], align 2
+; BE-NEXT:    [[OTHER:%.*]] = load i16, ptr [[B]], align 2, !noundef 
[[META0:![0-9]+]]
+; BE-NEXT:    [[TMP1:%.*]] = trunc i16 [[OTHER]] to i8
+; BE-NEXT:    [[TMP2:%.*]] = getelementptr i8, ptr [[A]], i64 1
+; BE-NEXT:    store i8 [[TMP1]], ptr [[TMP2]], align 1
+; BE-NEXT:    [[A_RELOAD:%.*]] = load i16, ptr [[A]], align 2
+; BE-NEXT:    [[BIT:%.*]] = and i16 [[OTHER]], 256
+; BE-NEXT:    [[KEEP:%.*]] = and i16 [[A_RELOAD]], -257
+; BE-NEXT:    [[WITH_BIT:%.*]] = or disjoint i16 [[KEEP]], [[BIT]]
+; BE-NEXT:    store i16 [[WITH_BIT]], ptr [[A]], align 2
+; BE-NEXT:    ret i16 [[OLD]]
+;
+  %old = load i16, ptr %a, align 2
+  %other = load i16, ptr %b, align 2, !noundef !0
+  %insert = and i16 %other, 255
+  %high = and i16 %old, -256
+  %with.byte = or disjoint i16 %high, %insert
+  store i16 %with.byte, ptr %a, align 2
+  %a.reload = load i16, ptr %a, align 2
+  %b.reload = load i16, ptr %b, align 2
+  %bit = and i16 %b.reload, 256
+  %keep = and i16 %a.reload, -257
+  %with.bit = or disjoint i16 %keep, %bit
+  store i16 %with.bit, ptr %a, align 2
+  ret i16 %old
+}
+
+!0 = !{}
+;.
+; LE: [[META0]] = !{}
+;.
+; BE: [[META0]] = !{}
+;.

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to