[llvm] [MemCpyOpt] Drop dead `memmove` calls on `memset`'d source data (PR #101930)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Sat Aug 31 19:16:48 PDT 2024
================
@@ -1854,12 +1855,53 @@ bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
return false;
}
+/// Memmove calls with overlapping src/dest buffers that come after a memset may
+/// be removed.
+bool MemCpyOptPass::isMemMoveMemSetDependency(MemMoveInst *M) {
+ MemoryUseOrDef *MemMoveAccess = MSSA->getMemoryAccess(M);
+ if (!MemMoveAccess)
+ return false;
+
+ BatchAAResults BAA(*AA);
+ MemoryAccess *FirstDef = MemMoveAccess->getDefiningAccess();
+ MemoryLocation SourceLoc = MemoryLocation::getForSource(M);
+ MemoryAccess *SourceClobber =
+ MSSA->getWalker()->getClobberingMemoryAccess(FirstDef, SourceLoc, BAA);
+
+ MemSetInst *MS = nullptr;
+ if (auto *Def = dyn_cast<MemoryDef>(SourceClobber))
+ MS = dyn_cast_or_null<MemSetInst>(Def->getMemoryInst());
+
+ if (!MS || MS->getParent() != M->getParent())
+ return false;
+
+ // The destination buffer must have been memset'd.
+ if (!BAA.isMustAlias(MS->getDest(), M->getDest()))
+ return false;
+
+ // No clobbering writes in between.
+ if (writtenBetween(MSSA, BAA, SourceLoc, MSSA->getMemoryAccess(MS),
+ MemMoveAccess))
+ return false;
+ return true;
+}
+
/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
/// not to alias.
-bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
+bool MemCpyOptPass::processMemMove(MemMoveInst *M, BasicBlock::iterator &BBI) {
// See if the source could be modified by this memmove potentially.
- if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M))))
+ if (isModSet(AA->getModRefInfo(M, MemoryLocation::getForSource(M)))) {
+ // On the off-chance the memmove clobbers src with previously memset'd
+ // bytes, the memmove may be redundant.
+ if (isMemMoveMemSetDependency(M)) {
----------------
dtcxzyw wrote:
```suggestion
if (!M->isVolatile() && isMemMoveMemSetDependency(M)) {
```
Should bail out volatile memmoves.
https://github.com/llvm/llvm-project/pull/101930
More information about the llvm-commits
mailing list