[llvm] [MemCpyOpt] Drop dead `memmove` calls on `memset`'d source data (PR #101930)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 6 06:46:53 PDT 2024


================
@@ -1853,12 +1854,54 @@ 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());
+
+  // Limit the memset to be within the same basic block.
+  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))
----------------
nikic wrote:

This check doesn't make sense to me. You have already checked above that SourceLoc is not clobbered using getClobberingMemoryAccess. What you need to verify now is that the destination location is not clobbered either. In your tests that would be `store i32 1, ptr %array` instead of `store i32 1, ptr %array.idx`.

It would probably be cleanest if you a) first checked that the memmove is of the form memmove(x, x+A, B) and then checked the location x with LocationSize A+B to cover both at the same time. Then you don't need writtenBefore and can handle the cross-BB case for free.

https://github.com/llvm/llvm-project/pull/101930


More information about the llvm-commits mailing list