[Codegen] Forward temporary DPS output copies (#24727)

Destination-passing-style (DPS) operations update explicit init
operands. After tensor-to-memref bufferization preserves tensor value
semantics, an update of a dispatch output may be represented by a
private temporary:

  %temp = memref.alloc()
  memref.copy %source, %temp
  linalg.generic ... outs(%temp)
  memref.copy %temp, %target

Forward the final target through this chain:

  memref.copy %source, %target
  linalg.generic ... outs(%target)

This removes the private allocation and copy-out. The copy-in is
redirected to %target rather than removed because the DPS operation may
still read its init operand.

Reject the rewrite when the copy source or another DPS operand may alias
the final target, or when an intervening operation may access that
target. These checks prevent moving target writes ahead of reads that
observed its previous contents.

MLIR alias analysis handles ordinary local values but does not
distinguish all IREE storage roots. Refine it with dispatch ABI facts:
different HAL interface binding ordinals and different memref global
symbols are disjoint; subspans of the same binding may overlap because
their byte offsets can be dynamic; and local allocations are disjoint
from bindings and globals. Unknown roots remain conservative.

Run the pass after bufferization has made the allocation and copies
explicit and before Linalg/LinalgExt lowering removes the DPS init
operands needed to retarget the operation.

---------

Signed-off-by: Yuwei Sun <yuweis2@illinois.edu>
Signed-off-by: Hao Ren <rhao8608@gmail.com>
Co-authored-by: Yuwei Sun <yuweis2@illinois.edu>
diff --git a/compiler/src/iree/compiler/Codegen/Common/BUILD.bazel b/compiler/src/iree/compiler/Codegen/Common/BUILD.bazel
index b28be7a..c07b5f8 100644
--- a/compiler/src/iree/compiler/Codegen/Common/BUILD.bazel
+++ b/compiler/src/iree/compiler/Codegen/Common/BUILD.bazel
@@ -110,6 +110,7 @@
         "FlattenMemRefs.cpp",
         "FlattenSwizzleHintAllocs.cpp",
         "FoldAffineMinInDistributedLoops.cpp",
+        "FoldMemRefCopyIntoDPSOps.cpp",
         "FoldSplitReductionAndWorkgroupMappingLoops.cpp",
         "FoldTensorExtractOp.cpp",
         "FoldTensorSubsetIntoVectorTransferOps.cpp",
diff --git a/compiler/src/iree/compiler/Codegen/Common/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/Common/CMakeLists.txt
index 1e52247..694401a 100644
--- a/compiler/src/iree/compiler/Codegen/Common/CMakeLists.txt
+++ b/compiler/src/iree/compiler/Codegen/Common/CMakeLists.txt
@@ -104,6 +104,7 @@
     "FlattenMemRefs.cpp"
     "FlattenSwizzleHintAllocs.cpp"
     "FoldAffineMinInDistributedLoops.cpp"
+    "FoldMemRefCopyIntoDPSOps.cpp"
     "FoldSplitReductionAndWorkgroupMappingLoops.cpp"
     "FoldTensorExtractOp.cpp"
     "FoldTensorSubsetIntoVectorTransferOps.cpp"
diff --git a/compiler/src/iree/compiler/Codegen/Common/FoldMemRefCopyIntoDPSOps.cpp b/compiler/src/iree/compiler/Codegen/Common/FoldMemRefCopyIntoDPSOps.cpp
new file mode 100644
index 0000000..93f1bb7
--- /dev/null
+++ b/compiler/src/iree/compiler/Codegen/Common/FoldMemRefCopyIntoDPSOps.cpp
@@ -0,0 +1,338 @@
+// Copyright 2026 The IREE Authors
+//
+// Licensed under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+#include "iree/compiler/Codegen/Common/Passes.h"
+#include "iree/compiler/Codegen/Utils/Utils.h"
+#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
+#include "mlir/Analysis/AliasAnalysis.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/MemRef/Utils/MemRefUtils.h"
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/Dominance.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Interfaces/DestinationStyleOpInterface.h"
+#include "mlir/Interfaces/SideEffectInterfaces.h"
+#include "mlir/Pass/Pass.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+namespace mlir::iree_compiler {
+
+#define GEN_PASS_DEF_FOLDMEMREFCOPYINTODPSOPSPASS
+#include "iree/compiler/Codegen/Common/Passes.h.inc"
+
+namespace {
+
+// Finds the storage root of a memref view. For example, both %alloc and
+// `memref.subview %alloc` have %alloc as their root.
+static Value getMemRefViewRoot(Value value) {
+  auto memrefValue = dyn_cast<MemrefValue>(value);
+  if (!memrefValue) {
+    return value;
+  }
+  return memref::skipViewLikeOps(memrefValue);
+}
+
+static bool isDerivedFromLocalAlloc(Value value) {
+  Operation *root = getMemRefViewRoot(value).getDefiningOp();
+  return isa_and_nonnull<memref::AllocOp, memref::AllocaOp>(root);
+}
+
+static std::optional<FlatSymbolRefAttr> getMemRefGlobalRoot(Value value) {
+  auto getGlobalOp =
+      getMemRefViewRoot(value).getDefiningOp<memref::GetGlobalOp>();
+  if (!getGlobalOp) {
+    return std::nullopt;
+  }
+  return getGlobalOp.getNameAttr();
+}
+
+// A HAL binding may be hidden by bufferization casts and views. Walk through
+// those producers so that, for example, a subview of binding(0) is still
+// classified as binding(0).
+static std::optional<IREE::HAL::InterfaceBindingSubspanOp>
+getInterfaceBindingRoot(Value value) {
+  auto typedValue = dyn_cast<TypedValue<MemRefType>>(value);
+  if (!typedValue) {
+    return std::nullopt;
+  }
+  return getSourceSubspanMemref(typedValue);
+}
+
+// Answers whether two memrefs may address the same storage. MLIR's local alias
+// analysis does not model IREE executable bindings and does not distinguish
+// all memref globals, so refine those roots before falling back to it:
+//
+//   lhs root       rhs root       result
+//   binding(0)     binding(1)     no alias, when both name the same layout
+//   binding(0)     binding(0)     may alias (subspan offsets may overlap)
+//   binding(*)     binding(*)     may alias, when the layouts differ
+//   @global_a      @global_b      no alias
+//   binding/global local alloc    no alias
+//   unknown        unknown        MLIR AliasAnalysis
+//
+// A binding ordinal is an index into one pipeline layout, so ordinals are only
+// comparable within a layout.
+//
+// A "local alloc" includes its view-like derivatives. An unknown root is
+// conservatively assumed to may-alias, because it may be a function argument or
+// an unrecognized alias.
+static bool mayAlias(Value lhs, Value rhs, AliasAnalysis &aliasAnalysis) {
+  std::optional<IREE::HAL::InterfaceBindingSubspanOp> lhsSubspan =
+      getInterfaceBindingRoot(lhs);
+  std::optional<IREE::HAL::InterfaceBindingSubspanOp> rhsSubspan =
+      getInterfaceBindingRoot(rhs);
+  if (lhsSubspan && rhsSubspan) {
+    if (lhsSubspan->getLayout() != rhsSubspan->getLayout()) {
+      return true;
+    }
+    return lhsSubspan->getBinding() == rhsSubspan->getBinding();
+  }
+
+  if (lhsSubspan || rhsSubspan) {
+    Value other = lhsSubspan ? rhs : lhs;
+    return !isDerivedFromLocalAlloc(other) && !getMemRefGlobalRoot(other);
+  }
+
+  std::optional<FlatSymbolRefAttr> lhsGlobal = getMemRefGlobalRoot(lhs);
+  std::optional<FlatSymbolRefAttr> rhsGlobal = getMemRefGlobalRoot(rhs);
+  if (lhsGlobal && rhsGlobal) {
+    return *lhsGlobal == *rhsGlobal;
+  }
+  if (lhsGlobal || rhsGlobal) {
+    Value other = lhsGlobal ? rhs : lhs;
+    return !isDerivedFromLocalAlloc(other);
+  }
+
+  return !aliasAnalysis.alias(lhs, rhs).isNo();
+}
+
+static bool opMayAccessTarget(Operation *op, Value target,
+                              AliasAnalysis &aliasAnalysis) {
+  // MLIR mod/ref can recognize that this operation cannot access the target.
+  if (aliasAnalysis.getModRef(op, target).isNoModRef()) {
+    return false;
+  }
+
+  // Otherwise inspect memref operands with mayAlias, because generic mod/ref
+  // cannot use the HAL binding and global distinctions above.
+  for (Value operand : op->getOperands()) {
+    if (isa<MemRefType>(operand.getType()) &&
+        mayAlias(operand, target, aliasAnalysis)) {
+      return true;
+    }
+  }
+
+  // An operation with recursive or unbound addressable effects is
+  // conservatively assumed to access the target.
+  auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op);
+  if (!effectInterface || op->hasTrait<OpTrait::HasRecursiveMemoryEffects>()) {
+    return true;
+  }
+
+  SmallVector<MemoryEffects::EffectInstance> effects;
+  effectInterface.getEffects(effects);
+  for (const MemoryEffects::EffectInstance &effect : effects) {
+    if (!isa<MemoryEffects::Read, MemoryEffects::Write>(effect.getEffect())) {
+      continue;
+    }
+    if (!effect.getValue() && effect.getResource()->isAddressable()) {
+      return true;
+    }
+  }
+  return false;
+}
+
+// The effects an operation declares for itself describe only its operands. A
+// payload region may additionally access values captured from the enclosing
+// scope, which never appear in those effects.
+static bool opRegionsMayAccessTarget(Operation *op, Value target,
+                                     AliasAnalysis &aliasAnalysis) {
+  for (Region &region : op->getRegions()) {
+    for (Block &block : region) {
+      for (Operation &nestedOp : block) {
+        if (opMayAccessTarget(&nestedOp, target, aliasAnalysis)) {
+          return true;
+        }
+      }
+    }
+  }
+  return false;
+}
+
+// Nothing between the copy-in and the copy-out may access %target, because the
+// rewrite moves the update of %target above all of it.
+static bool hasInterveningTargetAccess(Operation *first, Operation *last,
+                                       Operation *dpsOp, Value target,
+                                       AliasAnalysis &aliasAnalysis) {
+  for (Operation *op = first->getNextNode(); op && op != last;
+       op = op->getNextNode()) {
+    // Recurse into the DPS op's region to check whether the payload accesses
+    // %target, but skip the DPS op itself: its write is supposed to access the
+    // target (that write is what the rewrite moves).
+    if (op == dpsOp) {
+      if (opRegionsMayAccessTarget(op, target, aliasAnalysis)) {
+        return true;
+      }
+      continue;
+    }
+    if (opMayAccessTarget(op, target, aliasAnalysis)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+// The rewrite turns
+//
+//   memref.copy %source, %temp          memref.copy %source, %target
+//   dps_op ins(%in) outs(%temp)   -->   dps_op ins(%in) outs(%target)
+//   memref.copy %temp, %target
+//
+// so %target, rather than a private temporary, holds the copied-in data while
+// the operation runs and receives its writes in place. The two values read
+// alongside that write must therefore not alias %target:
+//
+//   %source  copying it into %target must not overwrite %source itself, and
+//            must not become a copy between overlapping ranges.
+//   %in      the operation would otherwise read a buffer it is concurrently
+//            writing and observe its own partial results, where before it read
+//            %in and wrote the disjoint %temp.
+static bool targetMayAliasDpsReads(DestinationStyleOpInterface dpsOp,
+                                   OpOperand *forwardedInitOperand,
+                                   Value copySource, Value target,
+                                   AliasAnalysis &aliasAnalysis) {
+  if (mayAlias(copySource, target, aliasAnalysis)) {
+    return true;
+  }
+
+  for (OpOperand &operand : dpsOp->getOpOperands()) {
+    if (&operand == forwardedInitOperand) {
+      continue;
+    }
+    if (isa<MemRefType>(operand.get().getType()) &&
+        mayAlias(operand.get(), target, aliasAnalysis)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+struct FoldTemporaryCopyIntoDpsOp final : OpRewritePattern<memref::CopyOp> {
+  FoldTemporaryCopyIntoDpsOp(MLIRContext *context, AliasAnalysis &aliasAnalysis,
+                             DominanceInfo &dominanceInfo)
+      : OpRewritePattern(context), aliasAnalysis(aliasAnalysis),
+        dominanceInfo(dominanceInfo) {}
+
+  LogicalResult matchAndRewrite(memref::CopyOp copyOut,
+                                PatternRewriter &rewriter) const override {
+    // Forward the temporary destination produced by bufferization:
+    //
+    //   copy %source, %temp             copy %source, %target
+    //   dps_op outs(%temp)       -->    dps_op outs(%target)
+    //   copy %temp, %target
+    //
+    // The checks below require one init copy, one DPS writer, and one output
+    // copy in program order. They also prove that moving the target write to
+    // the input-copy position cannot change any intervening memory access.
+    auto allocOp = copyOut.getSource().getDefiningOp<memref::AllocOp>();
+    if (!allocOp) {
+      return failure();
+    }
+
+    memref::CopyOp copyIn;
+    DestinationStyleOpInterface dpsOp;
+    OpOperand *forwardedInitOperand = nullptr;
+    for (Operation *user : allocOp->getUsers()) {
+      if (user == copyOut.getOperation()) {
+        continue;
+      }
+      if (auto copy = dyn_cast<memref::CopyOp>(user)) {
+        if (copy.getTarget() == allocOp.getResult() && !copyIn) {
+          copyIn = copy;
+          continue;
+        }
+        return failure();
+      }
+      if (auto candidate = dyn_cast<DestinationStyleOpInterface>(user)) {
+        if (candidate.getNumDpsInits() != 1 || dpsOp) {
+          return failure();
+        }
+        OpOperand *initOperand = candidate.getDpsInitOperand(0);
+        if (initOperand->get() != allocOp.getResult()) {
+          return failure();
+        }
+        dpsOp = candidate;
+        forwardedInitOperand = initOperand;
+        continue;
+      }
+      return failure();
+    }
+
+    if (!copyIn || !dpsOp) {
+      return failure();
+    }
+    if (copyIn->getBlock() != dpsOp->getBlock() ||
+        dpsOp->getBlock() != copyOut->getBlock()) {
+      return failure();
+    }
+    if (!copyIn->isBeforeInBlock(dpsOp) || !dpsOp->isBeforeInBlock(copyOut)) {
+      return failure();
+    }
+
+    Value finalTarget = copyOut.getTarget();
+    // The rewrite moves the write of the target up to the copy-in. A target
+    // defined after that point would not dominate its new use.
+    if (!dominanceInfo.dominates(finalTarget, copyIn)) {
+      return failure();
+    }
+    // Nothing read while %target is being written may alias it.
+    if (targetMayAliasDpsReads(dpsOp, forwardedInitOperand, copyIn.getSource(),
+                               finalTarget, aliasAnalysis)) {
+      return failure();
+    }
+    // Nothing the update is moved across may access %target.
+    if (hasInterveningTargetAccess(copyIn, copyOut, dpsOp, finalTarget,
+                                   aliasAnalysis)) {
+      return failure();
+    }
+
+    rewriter.setInsertionPoint(copyIn);
+    memref::CopyOp::create(rewriter, copyIn.getLoc(), copyIn.getSource(),
+                           finalTarget);
+    forwardedInitOperand->set(finalTarget);
+
+    rewriter.eraseOp(copyOut);
+    rewriter.eraseOp(copyIn);
+    if (allocOp->use_empty()) {
+      rewriter.eraseOp(allocOp);
+    }
+    return success();
+  }
+
+private:
+  AliasAnalysis &aliasAnalysis;
+  DominanceInfo &dominanceInfo;
+};
+
+struct FoldMemRefCopyIntoDPSOpsPass final
+    : impl::FoldMemRefCopyIntoDPSOpsPassBase<FoldMemRefCopyIntoDPSOpsPass> {
+  using FoldMemRefCopyIntoDPSOpsPassBase::FoldMemRefCopyIntoDPSOpsPassBase;
+
+  void runOnOperation() override {
+    RewritePatternSet patterns(&getContext());
+    AliasAnalysis &aliasAnalysis = getAnalysis<AliasAnalysis>();
+    DominanceInfo &dominanceInfo = getAnalysis<DominanceInfo>();
+    patterns.add<FoldTemporaryCopyIntoDpsOp>(&getContext(), aliasAnalysis,
+                                             dominanceInfo);
+    if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) {
+      signalPassFailure();
+    }
+  }
+};
+
+} // namespace
+
+} // namespace mlir::iree_compiler
diff --git a/compiler/src/iree/compiler/Codegen/Common/Passes.td b/compiler/src/iree/compiler/Codegen/Common/Passes.td
index 65c21c4..ca0da66 100644
--- a/compiler/src/iree/compiler/Codegen/Common/Passes.td
+++ b/compiler/src/iree/compiler/Codegen/Common/Passes.td
@@ -589,6 +589,31 @@
   let summary = "Fold `affine.min` ops in distributed loops";
 }
 
+def FoldMemRefCopyIntoDPSOpsPass :
+    InterfacePass<"iree-codegen-fold-memref-copy-into-dps-ops", "mlir::FunctionOpInterface"> {
+  let summary = "Fold temporary output copies into destination-style memref ops";
+  let description = [{
+    Retargets destination-style operations from private temporaries to their
+    final output buffers. For example:
+
+      memref.copy %source, %temporary
+      linalg.generic outs(%temporary)
+      memref.copy %temporary, %target
+
+    becomes:
+
+      memref.copy %source, %target
+      linalg.generic outs(%target)
+
+    The rewrite requires a single copy-in, destination-style writer, and
+    copy-out, and rejects potentially aliasing inputs or intervening accesses
+    to the final target.
+  }];
+  let dependentDialects = [
+    "memref::MemRefDialect"
+  ];
+}
+
 def FoldReshapeIntoInterfaceTensorPass :
     Pass<"iree-codegen-fold-reshape-into-interface-tensor", ""> {
   let summary = "Folds reshape operations into the interface bindings.";
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel b/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel
index 4f7818a..a49caa6 100644
--- a/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel
+++ b/compiler/src/iree/compiler/Codegen/Common/test/BUILD.bazel
@@ -57,6 +57,7 @@
             "fold_affine_min_of_block_id.mlir",
             "fold_bitcast_into_interface_tensor.mlir",
             "fold_bitcast_into_load_from_buffer.mlir",
+            "fold_memref_copy_into_dps_ops.mlir",
             "fold_reshape_into_interface_tensor.mlir",
             "fold_split_reduction_workgroup_mapping_loops.mlir",
             "fold_tensor_extract_op.mlir",
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt
index 05d1bc0..9e293b4 100644
--- a/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt
+++ b/compiler/src/iree/compiler/Codegen/Common/test/CMakeLists.txt
@@ -52,6 +52,7 @@
     "fold_affine_min_of_block_id.mlir"
     "fold_bitcast_into_interface_tensor.mlir"
     "fold_bitcast_into_load_from_buffer.mlir"
+    "fold_memref_copy_into_dps_ops.mlir"
     "fold_reshape_into_interface_tensor.mlir"
     "fold_split_reduction_workgroup_mapping_loops.mlir"
     "fold_tensor_extract_op.mlir"
diff --git a/compiler/src/iree/compiler/Codegen/Common/test/fold_memref_copy_into_dps_ops.mlir b/compiler/src/iree/compiler/Codegen/Common/test/fold_memref_copy_into_dps_ops.mlir
new file mode 100644
index 0000000..173b1aa
--- /dev/null
+++ b/compiler/src/iree/compiler/Codegen/Common/test/fold_memref_copy_into_dps_ops.mlir
@@ -0,0 +1,304 @@
+// RUN: iree-opt --split-input-file --pass-pipeline="builtin.module(func.func(iree-codegen-fold-memref-copy-into-dps-ops))" %s | FileCheck %s
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @fold_linalg_generic_temp() {
+  %source = memref.alloc() : memref<4xf32>
+  %target = memref.alloc() : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @fold_linalg_generic_temp(
+// CHECK-DAG: %[[SOURCE:.+]] = memref.alloc
+// CHECK-DAG: %[[TARGET:.+]] = memref.alloc
+// CHECK: memref.copy %[[SOURCE]], %[[TARGET]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TARGET]] : memref<4xf32>)
+// CHECK-NOT: memref.copy
+
+// -----
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_copy_source_aliases_target(%target: memref<4xf32>) {
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %target, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_copy_source_aliases_target(
+// CHECK-SAME:    %[[TARGET:.+]]: memref<4xf32>
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy %[[TARGET]], %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+memref.global "private" @source_global : memref<4xf32> = dense<0.0>
+memref.global "private" @target_global : memref<4xf32> = dense<0.0>
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @fold_distinct_globals() {
+  %source = memref.get_global @source_global : memref<4xf32>
+  %target = memref.get_global @target_global : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @fold_distinct_globals(
+// CHECK-DAG: %[[SOURCE:.+]] = memref.get_global @source_global
+// CHECK-DAG: %[[TARGET:.+]] = memref.get_global @target_global
+// CHECK: memref.copy %[[SOURCE]], %[[TARGET]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TARGET]] : memref<4xf32>)
+// CHECK-NOT: memref.copy
+
+// -----
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_dps_input_aliases_target(%source: memref<4xf32>,
+                                            %target: memref<4xf32>) {
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map, #map],
+    iterator_types = ["parallel"]
+  } ins(%target : memref<4xf32>) outs(%temp : memref<4xf32>) {
+  ^bb0(%in: f32, %out: f32):
+    linalg.yield %in : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_dps_input_aliases_target(
+// CHECK-SAME:    %[[SOURCE:.+]]: memref<4xf32>, %[[TARGET:.+]]: memref<4xf32>
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy %[[SOURCE]], %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: ins(%[[TARGET]] : memref<4xf32>)
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_intervening_target_access(%source: memref<4xf32>,
+                                             %target: memref<4xf32>) -> f32 {
+  %c0 = arith.constant 0 : index
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  %read = memref.load %target[%c0] : memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return %read : f32
+}
+
+// CHECK-LABEL: func.func @no_fold_intervening_target_access(
+// CHECK-SAME:    %[[SOURCE:.+]]: memref<4xf32>, %[[TARGET:.+]]: memref<4xf32>
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy %[[SOURCE]], %[[TEMP]]
+// CHECK: memref.load %[[TARGET]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+#pipeline_layout = #hal.pipeline.layout<bindings = [
+  #hal.pipeline.binding<storage_buffer>,
+  #hal.pipeline.binding<storage_buffer>
+]>
+#map = affine_map<(d0) -> (d0)>
+
+func.func @fold_distinct_hal_bindings() {
+  %source = hal.interface.binding.subspan layout(#pipeline_layout) binding(0) : memref<4xf32>
+  %target = hal.interface.binding.subspan layout(#pipeline_layout) binding(1) : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @fold_distinct_hal_bindings(
+// CHECK-DAG: %[[SOURCE:.+]] = hal.interface.binding.subspan {{.+}} binding(0)
+// CHECK-DAG: %[[TARGET:.+]] = hal.interface.binding.subspan {{.+}} binding(1)
+// CHECK: memref.copy %[[SOURCE]], %[[TARGET]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TARGET]] : memref<4xf32>)
+// CHECK-NOT: memref.copy
+
+// -----
+
+#pipeline_layout = #hal.pipeline.layout<bindings = [
+  #hal.pipeline.binding<storage_buffer>
+]>
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_same_hal_binding() {
+  %c0 = arith.constant 0 : index
+  %c64 = arith.constant 64 : index
+  %source = hal.interface.binding.subspan layout(#pipeline_layout) binding(0) offset(%c0) : memref<4xf32>
+  %target = hal.interface.binding.subspan layout(#pipeline_layout) binding(0) offset(%c64) : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_same_hal_binding(
+// CHECK-DAG: %[[SOURCE:.+]] = hal.interface.binding.subspan {{.+}} binding(0)
+// CHECK-DAG: %[[TARGET:.+]] = hal.interface.binding.subspan {{.+}} binding(0)
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy %[[SOURCE]], %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_dps_payload_reads_target() {
+  %c0 = arith.constant 0 : index
+  %source = memref.alloc() : memref<4xf32>
+  %target = memref.alloc() : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    %value = memref.load %target[%c0] : memref<4xf32>
+    linalg.yield %value : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_dps_payload_reads_target(
+// CHECK-DAG: %[[SOURCE:.+]] = memref.alloc
+// CHECK-DAG: %[[TARGET:.+]] = memref.alloc
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy %[[SOURCE]], %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.load %[[TARGET]]
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_target_does_not_dominate_copy_in() {
+  %source = memref.alloc() : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  %target = memref.alloc() : memref<4xf32>
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_target_does_not_dominate_copy_in(
+// CHECK-DAG: %[[SOURCE:.+]] = memref.alloc
+// CHECK-DAG: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy {{.+}}, %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: %[[TARGET:.+]] = memref.alloc
+// CHECK: memref.copy %[[TEMP]], %[[TARGET]]
+
+// -----
+
+#pipeline_layout_a = #hal.pipeline.layout<bindings = [
+  #hal.pipeline.binding<storage_buffer>,
+  #hal.pipeline.binding<storage_buffer>
+]>
+#pipeline_layout_b = #hal.pipeline.layout<bindings = [
+  #hal.pipeline.binding<uniform_buffer>,
+  #hal.pipeline.binding<storage_buffer>
+]>
+#map = affine_map<(d0) -> (d0)>
+
+func.func @no_fold_bindings_from_different_layouts() {
+  %source = hal.interface.binding.subspan layout(#pipeline_layout_a) binding(0) : memref<4xf32>
+  %target = hal.interface.binding.subspan layout(#pipeline_layout_b) binding(1) : memref<4xf32>
+  %temp = memref.alloc() : memref<4xf32>
+  memref.copy %source, %temp : memref<4xf32> to memref<4xf32>
+  linalg.generic {
+    indexing_maps = [#map],
+    iterator_types = ["parallel"]
+  } outs(%temp : memref<4xf32>) {
+  ^bb0(%out: f32):
+    linalg.yield %out : f32
+  }
+  memref.copy %temp, %target : memref<4xf32> to memref<4xf32>
+  return
+}
+
+// CHECK-LABEL: func.func @no_fold_bindings_from_different_layouts(
+// CHECK: %[[TEMP:.+]] = memref.alloc
+// CHECK: memref.copy {{.+}}, %[[TEMP]]
+// CHECK: linalg.generic
+// CHECK-SAME: outs(%[[TEMP]] : memref<4xf32>)
+// CHECK: memref.copy %[[TEMP]],
diff --git a/compiler/src/iree/compiler/Codegen/LLVMGPU/Passes.cpp b/compiler/src/iree/compiler/Codegen/LLVMGPU/Passes.cpp
index 107b446..61a02a1 100644
--- a/compiler/src/iree/compiler/Codegen/LLVMGPU/Passes.cpp
+++ b/compiler/src/iree/compiler/Codegen/LLVMGPU/Passes.cpp
@@ -911,6 +911,9 @@
   funcPassManager.addPass(createCanonicalizerPass());
   funcPassManager.addPass(createCSEPass());
 
+  // Retarget copy-in/DPS-op/copy-out chains while DPS inits are explicit.
+  funcPassManager.addPass(createFoldMemRefCopyIntoDPSOpsPass());
+
   funcPassManager.addPass(IREE::LinalgExt::createLinalgExtToLoopsPass());
   funcPassManager.addPass(createMemrefCopyToLinalgPass());
   funcPassManager.addPass(createConvertLinalgToLoopsPass());
@@ -977,6 +980,9 @@
   modulePassManager.addPass(createLowerUKernelOpsToCallsPass());
 
   FunctionLikeNest(modulePassManager)
+      // Retarget copy-in/DPS-op/copy-out chains while DPS inits are explicit.
+      .addPass(createFoldMemRefCopyIntoDPSOpsPass)
+
       // LinalgExt -> SCF
       .addPass(IREE::LinalgExt::createLinalgExtToLoopsPass)