Index: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp =================================================================== --- llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp +++ llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp @@ -8110,6 +8110,19 @@ Store->isIndexed()) return SDValue(); Stores.push_back(Store); + + // If this store is used as a chain operand in a store that is not included + // in the set of stores to be merged, then the transform may not be safe. + // We must preserve the order of that other store relative to the indivdual + // stores in this set. + for (SDNode *Use : Store->uses()) { + auto *StoreUse = dyn_cast(Use); + if (StoreUse && StoreUse->getChain().getNode() == Store && + !is_contained(Stores, StoreUse)) + return SDValue(); + } + + // Get the next link in the chain and try to collect another store. Chain = Store->getChain(); } // There is no reason to continue if we do not have at least a pair of stores. Index: llvm/test/CodeGen/SystemZ/merge-stores.ll =================================================================== --- llvm/test/CodeGen/SystemZ/merge-stores.ll +++ llvm/test/CodeGen/SystemZ/merge-stores.ll @@ -16,8 +16,8 @@ ; CHECK-NEXT: srlg %r0, %r2, 32 ; CHECK-NEXT: st %r0, 0(%r1) ; CHECK-NEXT: lhi %r0, 0 -; CHECK-NEXT: stg %r2, 0(%r1) ; CHECK-NEXT: sthrl %r0, e +; CHECK-NEXT: st %r2, 4(%r1) ; CHECK-NEXT: strl %r2, d ; CHECK-NEXT: br %r14 %xsh = lshr i64 %x, 32