diff --git a/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h b/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h --- a/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h +++ b/llvm/include/llvm/Transforms/Scalar/MemCpyOptimizer.h @@ -30,6 +30,8 @@ class MemCpyInst; class MemMoveInst; class MemoryDependenceResults; +class MemorySSA; +class MemorySSAUpdater; class MemSetInst; class StoreInst; class TargetLibraryInfo; @@ -38,6 +40,7 @@ class MemCpyOptPass : public PassInfoMixin { MemoryDependenceResults *MD = nullptr; TargetLibraryInfo *TLI = nullptr; + MemorySSAUpdater *MSSAU = nullptr; std::function LookupAliasAnalysis; std::function LookupAssumptionCache; std::function LookupDomTree; @@ -49,7 +52,7 @@ // Glue for the old PM. bool runImpl(Function &F, MemoryDependenceResults *MD_, - TargetLibraryInfo *TLI_, + TargetLibraryInfo *TLI_, MemorySSA *MSSA_, std::function LookupAliasAnalysis_, std::function LookupAssumptionCache_, std::function LookupDomTree_); diff --git a/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp b/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp --- a/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp +++ b/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp @@ -23,6 +23,8 @@ #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/MemoryDependenceAnalysis.h" #include "llvm/Analysis/MemoryLocation.h" +#include "llvm/Analysis/MemorySSA.h" +#include "llvm/Analysis/MemorySSAUpdater.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/Argument.h" @@ -276,6 +278,7 @@ AU.addRequired(); AU.addPreserved(); AU.addPreserved(); + AU.addPreserved(); } }; @@ -313,6 +316,11 @@ MemsetRanges Ranges(DL); BasicBlock::iterator BI(StartInst); + + // Keep track of the last seen MemoryDef and MemoryAccess to use for creating + // new accesses. + MemoryAccess *LastAcc = nullptr; + MemoryAccess *LastDef = nullptr; for (++BI; !BI->isTerminator(); ++BI) { if (!isa(BI) && !isa(BI)) { // If the instruction is readnone, ignore it, otherwise bail out. We @@ -320,6 +328,12 @@ // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) break; + if (MSSAU) { + auto *CurrentAcc = MSSAU->getMemorySSA()->getMemoryAccess(&*BI); + if (CurrentAcc) + LastAcc = CurrentAcc; + } + continue; } @@ -340,6 +354,8 @@ if (!Offset) break; + if (MSSAU) + LastDef = MSSAU->getMemorySSA()->getMemoryAccess(&*BI); Ranges.addStore(*Offset, NextStore); } else { MemSetInst *MSI = cast(BI); @@ -353,6 +369,8 @@ if (!Offset) break; + if (MSSAU) + LastDef = MSSAU->getMemorySSA()->getMemoryAccess(&*BI); Ranges.addMemSet(*Offset, MSI); } } @@ -375,6 +393,7 @@ // Now that we have full information about ranges, loop over the ranges and // emit memset's for anything big enough to be worthwhile. Instruction *AMemSet = nullptr; + for (const MemsetRange &Range : Ranges) { if (Range.TheStores.size() == 1) continue; @@ -392,15 +411,28 @@ : Range.TheStores) dbgs() << *SI << '\n'; dbgs() << "With: " << *AMemSet << '\n'); - if (!Range.TheStores.empty()) AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc()); + if (MSSAU) { + if (!LastAcc) + LastAcc = LastDef; + auto *NewAccess = + MSSAU->createMemoryAccessAfter(AMemSet, LastDef, LastAcc); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + LastAcc = NewAccess; + LastDef = NewAccess; + } + // Zap all the stores. for (Instruction *SI : Range.TheStores) { + if (MSSAU) { + MSSAU->removeMemoryAccess(SI); + } MD->removeInstruction(SI); SI->eraseFromParent(); } + ++NumMemSetInfer; } @@ -572,6 +604,17 @@ LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => " << *M << "\n"); + if (MSSAU) { + assert(isa(MSSAU->getMemorySSA()->getMemoryAccess(P))); + auto *LastDef = + cast(MSSAU->getMemorySSA()->getMemoryAccess(P)); + auto *NewAccess = + MSSAU->createMemoryAccessAfter(M, LastDef, LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + MSSAU->removeMemoryAccess(SI); + MSSAU->removeMemoryAccess(LI); + } + MD->removeInstruction(SI); SI->eraseFromParent(); MD->removeInstruction(LI); @@ -621,6 +664,11 @@ DL.getTypeStoreSize(SI->getOperand(0)->getType()), commonAlignment(SI->getAlign(), LI->getAlign()), C); if (changed) { + if (MSSAU) { + MSSAU->removeMemoryAccess(SI); + MSSAU->removeMemoryAccess(LI); + } + MD->removeInstruction(SI); SI->eraseFromParent(); MD->removeInstruction(LI); @@ -658,6 +706,15 @@ LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n"); + if (MSSAU) { + assert(isa(MSSAU->getMemorySSA()->getMemoryAccess(SI))); + auto *LastDef = + cast(MSSAU->getMemorySSA()->getMemoryAccess(SI)); + auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + MSSAU->removeMemoryAccess(SI); + } + MD->removeInstruction(SI); SI->eraseFromParent(); NumMemSetInfer++; @@ -943,14 +1000,23 @@ // TODO: Is this worth it if we're creating a less aligned memcpy? For // example we could be moving from movaps -> movq on x86. IRBuilder<> Builder(M); + Instruction *NewM; if (UseMemMove) - Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(), - MDep->getRawSource(), MDep->getSourceAlign(), - M->getLength(), M->isVolatile()); + NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(), + MDep->getRawSource(), MDep->getSourceAlign(), + M->getLength(), M->isVolatile()); else - Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(), - MDep->getRawSource(), MDep->getSourceAlign(), - M->getLength(), M->isVolatile()); + NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(), + MDep->getRawSource(), MDep->getSourceAlign(), + M->getLength(), M->isVolatile()); + + if (MSSAU) { + assert(isa(MSSAU->getMemorySSA()->getMemoryAccess(M))); + auto *LastDef = cast(MSSAU->getMemorySSA()->getMemoryAccess(M)); + auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + MSSAU->removeMemoryAccess(M); + } // Remove the instruction we're replacing. MD->removeInstruction(M); @@ -1016,11 +1082,21 @@ Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize); Value *MemsetLen = Builder.CreateSelect( Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff); - Builder.CreateMemSet( + Instruction *NewM = Builder.CreateMemSet( Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest, SrcSize), MemSet->getOperand(1), MemsetLen, MaybeAlign(Align)); + if (MSSAU) { + assert(isa(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy))); + auto *LastDef = + cast(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)); + auto *NewAccess = MSSAU->createMemoryAccessBefore( + NewM, LastDef->getDefiningAccess(), LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + MSSAU->removeMemoryAccess(MemSet); + } + MD->removeInstruction(MemSet); MemSet->eraseFromParent(); return true; @@ -1087,8 +1163,16 @@ } IRBuilder<> Builder(MemCpy); - Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), CopySize, - MaybeAlign(MemCpy->getDestAlignment())); + Instruction *NewM = + Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), + CopySize, MaybeAlign(MemCpy->getDestAlignment())); + if (MSSAU) { + auto *LastDef = + cast(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)); + auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + } + return true; } @@ -1104,6 +1188,9 @@ // If the source and destination of the memcpy are the same, then zap it. if (M->getSource() == M->getDest()) { ++BBI; + if (MSSAU) + MSSAU->removeMemoryAccess(M); + MD->removeInstruction(M); M->eraseFromParent(); return true; @@ -1115,8 +1202,18 @@ if (Value *ByteVal = isBytewiseValue(GV->getInitializer(), M->getModule()->getDataLayout())) { IRBuilder<> Builder(M); - Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), - MaybeAlign(M->getDestAlignment()), false); + Instruction *NewM = + Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), + MaybeAlign(M->getDestAlignment()), false); + if (MSSAU) { + auto *LastDef = + cast(MSSAU->getMemorySSA()->getMemoryAccess(M)); + auto *NewAccess = + MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef); + MSSAU->insertDef(cast(NewAccess), /*RenameUses=*/true); + MSSAU->removeMemoryAccess(M); + } + MD->removeInstruction(M); M->eraseFromParent(); ++NumCpyToSet; @@ -1151,6 +1248,9 @@ M->getSourceAlign().valueOrOne()); if (performCallSlotOptzn(M, M->getDest(), M->getSource(), CopySize->getZExtValue(), Alignment, C)) { + if (MSSAU) + MSSAU->removeMemoryAccess(M); + MD->removeInstruction(M); M->eraseFromParent(); return true; @@ -1167,6 +1267,9 @@ return processMemCpyMemCpyDependence(M, MDep); } else if (SrcDepInfo.isDef()) { if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) { + if (MSSAU) + MSSAU->removeMemoryAccess(M); + MD->removeInstruction(M); M->eraseFromParent(); ++NumMemCpyInstr; @@ -1177,6 +1280,8 @@ if (SrcDepInfo.isClobber()) if (MemSetInst *MDep = dyn_cast(SrcDepInfo.getInst())) if (performMemCpyToMemSetOptzn(M, MDep)) { + if (MSSAU) + MSSAU->removeMemoryAccess(M); MD->removeInstruction(M); M->eraseFromParent(); ++NumCpyToSet; @@ -1209,6 +1314,9 @@ M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(), Intrinsic::memcpy, ArgTys)); + // For MemorySSA nothing really changes (except that memcpy may imply stricter + // aliasing guarantees). + // MemDep may have over conservative information about this instruction, just // conservatively flush it from the cache. MD->removeInstruction(M); @@ -1358,8 +1466,11 @@ return AM.getResult(F); }; - bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis, - LookupAssumptionCache, LookupDomTree); + auto *MSSA = AM.getCachedResult(F); + + bool MadeChange = + runImpl(F, &MD, &TLI, MSSA ? &MSSA->getMSSA() : nullptr, + LookupAliasAnalysis, LookupAssumptionCache, LookupDomTree); if (!MadeChange) return PreservedAnalyses::all(); @@ -1372,12 +1483,14 @@ bool MemCpyOptPass::runImpl( Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_, - std::function LookupAliasAnalysis_, + MemorySSA *MSSA_, std::function LookupAliasAnalysis_, std::function LookupAssumptionCache_, std::function LookupDomTree_) { bool MadeChange = false; MD = MD_; TLI = TLI_; + MemorySSAUpdater MSSAU_(MSSA_); + MSSAU = MSSA_ ? &MSSAU_ : nullptr; LookupAliasAnalysis = std::move(LookupAliasAnalysis_); LookupAssumptionCache = std::move(LookupAssumptionCache_); LookupDomTree = std::move(LookupDomTree_); @@ -1394,6 +1507,9 @@ MadeChange = true; } + if (MSSA_ && VerifyMemorySSA) + MSSA_->verifyMemorySSA(); + MD = nullptr; return MadeChange; } @@ -1416,6 +1532,9 @@ return getAnalysis().getDomTree(); }; - return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache, + auto *MSSAWP = getAnalysisIfAvailable(); + + return Impl.runImpl(F, MD, TLI, MSSAWP ? &MSSAWP->getMSSA() : nullptr, + LookupAliasAnalysis, LookupAssumptionCache, LookupDomTree); } diff --git a/llvm/test/Transforms/MemCpyOpt/perserve-memssa.ll b/llvm/test/Transforms/MemCpyOpt/perserve-memssa.ll new file mode 100644 --- /dev/null +++ b/llvm/test/Transforms/MemCpyOpt/perserve-memssa.ll @@ -0,0 +1,137 @@ +; NOTE: Assertions have been autogenerated by utils/update_test_checks.py +; RUN: opt -aa-pipeline=basic-aa -passes='require,memcpyopt' -verify-memoryssa -S %s | FileCheck %s + +target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" +target triple = "x86_64-apple-macosx10.15.0" + +%t = type <{ i8*, [4 x i8], i8*, i8*, i32, [8192 x i8] }> + + +define i32 @test1(%t* %ptr) { +; CHECK-LABEL: @test1( +; CHECK-NEXT: invoke.cont6: +; CHECK-NEXT: [[P_1:%.*]] = getelementptr inbounds [[T:%.*]], %t* [[PTR:%.*]], i64 0, i32 0 +; CHECK-NEXT: [[P_1_C:%.*]] = bitcast i8** [[P_1]] to i8* +; CHECK-NEXT: [[P_2:%.*]] = getelementptr inbounds [[T]], %t* [[PTR]], i64 0, i32 4 +; CHECK-NEXT: [[P_3:%.*]] = getelementptr inbounds [[T]], %t* [[PTR]], i64 0, i32 5, i64 0 +; CHECK-NEXT: [[TMP0:%.*]] = bitcast i8** [[P_1]] to i8* +; CHECK-NEXT: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP0]], i8 0, i64 20, i1 false) +; CHECK-NEXT: [[TMP1:%.*]] = bitcast i32* [[P_2]] to i8* +; CHECK-NEXT: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP1]], i8 0, i64 8195, i1 false) +; CHECK-NEXT: ret i32 0 +; +invoke.cont6: + %p.1 = getelementptr inbounds %t, %t* %ptr, i64 0, i32 0 + %p.1.c = bitcast i8** %p.1 to i8* + call void @llvm.memset.p0i8.i64(i8* %p.1.c, i8 0, i64 20, i1 false) + store i8* null, i8** %p.1, align 8 + %p.2 = getelementptr inbounds %t, %t* %ptr, i64 0, i32 4 + store i32 0, i32* %p.2, align 8 + %p.3 = getelementptr inbounds %t, %t* %ptr, i64 0, i32 5, i64 0 + call void @llvm.memset.p0i8.i64(i8* %p.3, i8 0, i64 8191, i1 false) + ret i32 0 +} + +declare i8* @get_ptr() + +define void @test2(i8 *%in) { +; CHECK-LABEL: @test2( +; CHECK-NEXT: entry: +; CHECK-NEXT: [[CALL_I1_I:%.*]] = tail call i8* @get_ptr() +; CHECK-NEXT: [[TMP0:%.*]] = getelementptr i8, i8* [[CALL_I1_I]], i64 10 +; CHECK-NEXT: call void @llvm.memset.p0i8.i64(i8* align 1 [[TMP0]], i8 0, i64 0, i1 false) +; CHECK-NEXT: tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[CALL_I1_I]], i8* [[IN:%.*]], i64 10, i1 false) +; CHECK-NEXT: ret void +; +entry: + %call.i1.i = tail call i8* @get_ptr() + tail call void @llvm.memset.p0i8.i64(i8* %call.i1.i, i8 0, i64 10, i1 false) + tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* %call.i1.i, i8* %in, i64 10, i1 false) + ret void +} + +declare i8* @malloc(i64) + +define i32 @test3(i8* noalias %in) { +; CHECK-LABEL: @test3( +; CHECK-NEXT: [[CALL_I_I_I:%.*]] = tail call i8* @malloc(i64 20) +; CHECK-NEXT: tail call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[CALL_I_I_I]], i8* [[IN:%.*]], i64 20, i1 false) +; CHECK-NEXT: ret i32 10 +; + %call.i.i.i = tail call i8* @malloc(i64 20) + tail call void @llvm.memmove.p0i8.p0i8.i64(i8* %call.i.i.i, i8* %in, i64 20, i1 false) + ret i32 10 +} + +define void @test4(i32 %n, i8* noalias %ptr.0, i8* noalias %ptr.1, i32* %ptr.2) unnamed_addr { +; CHECK-LABEL: @test4( +; CHECK-NEXT: [[ELEM_I:%.*]] = getelementptr i8, i8* [[PTR_0:%.*]], i64 8 +; CHECK-NEXT: store i32 [[N:%.*]], i32* [[PTR_2:%.*]], align 8 +; CHECK-NEXT: [[TMP1:%.*]] = getelementptr i8, i8* [[ELEM_I]], i64 10 +; CHECK-NEXT: call void @llvm.memset.p0i8.i64(i8* align 1 [[TMP1]], i8 0, i64 0, i1 false) +; CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[ELEM_I]], i8* [[PTR_1:%.*]], i64 10, i1 false) +; CHECK-NEXT: ret void +; + %elem.i = getelementptr i8, i8* %ptr.0, i64 8 + call void @llvm.memset.p0i8.i64(i8* %elem.i, i8 0, i64 10, i1 false) + store i32 %n, i32* %ptr.2, align 8 + call void @llvm.memcpy.p0i8.p0i8.i64(i8* %elem.i, i8* %ptr.1, i64 10, i1 false) + ret void +} + +declare void @decompose(%t* nocapture) + +define void @test5(i32* %ptr) { +; CHECK-LABEL: @test5( +; CHECK-NEXT: entry: +; CHECK-NEXT: [[EARLY_DATA:%.*]] = alloca [128 x i8], align 8 +; CHECK-NEXT: [[TMP:%.*]] = alloca [[T:%.*]], align 8 +; CHECK-NEXT: [[TMP0:%.*]] = bitcast [128 x i8]* [[EARLY_DATA]] to i8* +; CHECK-NEXT: [[TMP1:%.*]] = bitcast %t* [[TMP]] to i8* +; CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 32, i8* [[TMP0]]) +; CHECK-NEXT: [[TMP2:%.*]] = load i32, i32* [[PTR:%.*]], align 8 +; CHECK-NEXT: call fastcc void @decompose(%t* [[TMP]]) +; CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[TMP0]], i8* [[TMP1]], i64 32, i1 false) +; CHECK-NEXT: ret void +; +entry: + %early_data = alloca [128 x i8], align 8 + %tmp = alloca %t, align 8 + %0 = bitcast [128 x i8]* %early_data to i8* + %1 = bitcast %t* %tmp to i8* + call void @llvm.lifetime.start.p0i8(i64 32, i8* %0) + %2 = load i32, i32* %ptr, align 8 + call fastcc void @decompose(%t* %tmp) + call void @llvm.memcpy.p0i8.p0i8.i64(i8* %0, i8* %1, i64 32, i1 false) + ret void +} + +define i8 @test6(i8* %ptr, i8* noalias %ptr.1) { +; CHECK-LABEL: @test6( +; CHECK-NEXT: entry: +; CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 24, i8* [[PTR:%.*]]) +; CHECK-NEXT: [[TMP0:%.*]] = load i8, i8* [[PTR]], align 8 +; CHECK-NEXT: call void @llvm.memcpy.p0i8.p0i8.i64(i8* [[PTR]], i8* [[PTR_1:%.*]], i64 24, i1 false) +; CHECK-NEXT: ret i8 [[TMP0]] +; +entry: + call void @llvm.lifetime.start.p0i8(i64 24, i8* %ptr) + %0 = load i8, i8* %ptr, align 8 + call void @llvm.memmove.p0i8.p0i8.i64(i8* %ptr, i8* %ptr.1, i64 24, i1 false) + ret i8 %0 +} + +; Function Attrs: argmemonly nounwind willreturn +declare void @llvm.lifetime.start.p0i8(i64 immarg, i8* nocapture) #0 + +; Function Attrs: argmemonly nounwind willreturn +declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg) #0 + +; Function Attrs: argmemonly nounwind willreturn writeonly +declare void @llvm.memset.p0i8.i64(i8* nocapture writeonly, i8, i64, i1 immarg) #1 + +; Function Attrs: argmemonly nounwind willreturn +declare void @llvm.memmove.p0i8.p0i8.i64(i8* nocapture, i8* nocapture readonly, i64, i1 immarg) #0 + +attributes #0 = { argmemonly nounwind willreturn } +attributes #1 = { argmemonly nounwind willreturn writeonly }