#include "llvm/Transforms/Scalar/LoopDistribute.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/LoopVersioning.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <cassert>
#include <functional>
#include <list>
#include <tuple>
#include <utility>
using namespace llvm;
#define LDIST_NAME "loop-distribute"
#define DEBUG_TYPE LDIST_NAME
static const char *const LLVMLoopDistributeFollowupAll =
"llvm.loop.distribute.followup_all";
static const char *const LLVMLoopDistributeFollowupCoincident =
"llvm.loop.distribute.followup_coincident";
static const char *const LLVMLoopDistributeFollowupSequential =
"llvm.loop.distribute.followup_sequential";
static const char *const LLVMLoopDistributeFollowupFallback =
"llvm.loop.distribute.followup_fallback";
static cl::opt<bool>
LDistVerify("loop-distribute-verify", cl::Hidden,
cl::desc("Turn on DominatorTree and LoopInfo verification "
"after Loop Distribution"),
cl::init(false));
static cl::opt<bool> DistributeNonIfConvertible(
"loop-distribute-non-if-convertible", cl::Hidden,
cl::desc("Whether to distribute into a loop that may not be "
"if-convertible by the loop vectorizer"),
cl::init(false));
static cl::opt<unsigned> DistributeSCEVCheckThreshold(
"loop-distribute-scev-check-threshold", cl::init(8), cl::Hidden,
cl::desc("The maximum number of SCEV checks allowed for Loop "
"Distribution"));
static cl::opt<unsigned> PragmaDistributeSCEVCheckThreshold(
"loop-distribute-scev-check-threshold-with-pragma", cl::init(128),
cl::Hidden,
cl::desc(
"The maximum number of SCEV checks allowed for Loop "
"Distribution for loop marked with #pragma loop distribute(enable)"));
static cl::opt<bool> EnableLoopDistribute(
"enable-loop-distribute", cl::Hidden,
cl::desc("Enable the new, experimental LoopDistribution Pass"),
cl::init(false));
STATISTIC(NumLoopsDistributed, "Number of loops distributed");
namespace {
class InstPartition {
using InstructionSet = SmallPtrSet<Instruction *, 8>;
public:
InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
: DepCycle(DepCycle), OrigLoop(L) {
Set.insert(I);
}
bool hasDepCycle() const { return DepCycle; }
void add(Instruction *I) { Set.insert(I); }
InstructionSet::iterator begin() { return Set.begin(); }
InstructionSet::iterator end() { return Set.end(); }
InstructionSet::const_iterator begin() const { return Set.begin(); }
InstructionSet::const_iterator end() const { return Set.end(); }
bool empty() const { return Set.empty(); }
void moveTo(InstPartition &Other) {
Other.Set.insert(Set.begin(), Set.end());
Set.clear();
Other.DepCycle |= DepCycle;
}
void populateUsedSet() {
for (auto *B : OrigLoop->getBlocks())
Set.insert(B->getTerminator());
SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
for (Value *V : I->operand_values()) {
auto *I = dyn_cast<Instruction>(V);
if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
Worklist.push_back(I);
}
}
}
Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
unsigned Index, LoopInfo *LI,
DominatorTree *DT) {
ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
VMap, Twine(".ldist") + Twine(Index),
LI, DT, ClonedLoopBlocks);
return ClonedLoop;
}
const Loop *getClonedLoop() const { return ClonedLoop; }
Loop *getDistributedLoop() const {
return ClonedLoop ? ClonedLoop : OrigLoop;
}
ValueToValueMapTy &getVMap() { return VMap; }
void remapInstructions() {
remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
}
void removeUnusedInsts() {
SmallVector<Instruction *, 8> Unused;
for (auto *Block : OrigLoop->getBlocks())
for (auto &Inst : *Block)
if (!Set.count(&Inst)) {
Instruction *NewInst = &Inst;
if (!VMap.empty())
NewInst = cast<Instruction>(VMap[NewInst]);
assert(!isa<BranchInst>(NewInst) &&
"Branches are marked used early on");
Unused.push_back(NewInst);
}
for (auto *Inst : reverse(Unused)) {
if (!Inst->use_empty())
Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
Inst->eraseFromParent();
}
}
void print() const {
if (DepCycle)
dbgs() << " (cycle)\n";
for (auto *I : Set)
dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
}
void printBlocks() const {
for (auto *BB : getDistributedLoop()->getBlocks())
dbgs() << *BB;
}
private:
InstructionSet Set;
bool DepCycle;
Loop *OrigLoop;
Loop *ClonedLoop = nullptr;
SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
ValueToValueMapTy VMap;
};
class InstPartitionContainer {
using InstToPartitionIdT = DenseMap<Instruction *, int>;
public:
InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
: L(L), LI(LI), DT(DT) {}
unsigned getSize() const { return PartitionContainer.size(); }
void addToCyclicPartition(Instruction *Inst) {
if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
PartitionContainer.emplace_back(Inst, L, true);
else
PartitionContainer.back().add(Inst);
}
void addToNewNonCyclicPartition(Instruction *Inst) {
PartitionContainer.emplace_back(Inst, L);
}
void mergeAdjacentNonCyclic() {
mergeAdjacentPartitionsIf(
[](const InstPartition *P) { return !P->hasDepCycle(); });
}
void mergeNonIfConvertible() {
mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
if (Partition->hasDepCycle())
return true;
bool seenStore = false;
for (auto *Inst : *Partition)
if (isa<StoreInst>(Inst)) {
seenStore = true;
if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
return false;
}
return seenStore;
});
}
void mergeBeforePopulating() {
mergeAdjacentNonCyclic();
if (!DistributeNonIfConvertible)
mergeNonIfConvertible();
}
bool mergeToAvoidDuplicatedLoads() {
using LoadToPartitionT = DenseMap<Instruction *, InstPartition *>;
using ToBeMergedT = EquivalenceClasses<InstPartition *>;
LoadToPartitionT LoadToPartition;
ToBeMergedT ToBeMerged;
for (PartitionContainerT::iterator I = PartitionContainer.begin(),
E = PartitionContainer.end();
I != E; ++I) {
auto *PartI = &*I;
for (Instruction *Inst : *PartI)
if (isa<LoadInst>(Inst)) {
bool NewElt;
LoadToPartitionT::iterator LoadToPart;
std::tie(LoadToPart, NewElt) =
LoadToPartition.insert(std::make_pair(Inst, PartI));
if (!NewElt) {
LLVM_DEBUG(dbgs()
<< "Merging partitions due to this load in multiple "
<< "partitions: " << PartI << ", " << LoadToPart->second
<< "\n"
<< *Inst << "\n");
auto PartJ = I;
do {
--PartJ;
ToBeMerged.unionSets(PartI, &*PartJ);
} while (&*PartJ != LoadToPart->second);
}
}
}
if (ToBeMerged.empty())
return false;
for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
I != E; ++I) {
if (!I->isLeader())
continue;
auto PartI = I->getData();
for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
ToBeMerged.member_end())) {
PartJ->moveTo(*PartI);
}
}
PartitionContainer.remove_if(
[](const InstPartition &P) { return P.empty(); });
return true;
}
void setupPartitionIdOnInstructions() {
int PartitionID = 0;
for (const auto &Partition : PartitionContainer) {
for (Instruction *Inst : Partition) {
bool NewElt;
InstToPartitionIdT::iterator Iter;
std::tie(Iter, NewElt) =
InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
if (!NewElt)
Iter->second = -1;
}
++PartitionID;
}
}
void populateUsedSet() {
for (auto &P : PartitionContainer)
P.populateUsedSet();
}
void cloneLoops() {
BasicBlock *OrigPH = L->getLoopPreheader();
BasicBlock *Pred = OrigPH->getSinglePredecessor();
assert(Pred && "Preheader does not have a single predecessor");
BasicBlock *ExitBlock = L->getExitBlock();
assert(ExitBlock && "No single exit block");
Loop *NewLoop;
assert(!PartitionContainer.empty() && "at least two partitions expected");
assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
"preheader not empty");
MDNode *OrigLoopID = L->getLoopID();
BasicBlock *TopPH = OrigPH;
unsigned Index = getSize() - 1;
for (auto I = std::next(PartitionContainer.rbegin()),
E = PartitionContainer.rend();
I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
auto *Part = &*I;
NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
Part->getVMap()[ExitBlock] = TopPH;
Part->remapInstructions();
setNewLoopID(OrigLoopID, Part);
}
Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
setNewLoopID(OrigLoopID, &PartitionContainer.back());
for (auto Curr = PartitionContainer.cbegin(),
Next = std::next(PartitionContainer.cbegin()),
E = PartitionContainer.cend();
Next != E; ++Curr, ++Next)
DT->changeImmediateDominator(
Next->getDistributedLoop()->getLoopPreheader(),
Curr->getDistributedLoop()->getExitingBlock());
}
void removeUnusedInsts() {
for (auto &Partition : PartitionContainer)
Partition.removeUnusedInsts();
}
SmallVector<int, 8>
computePartitionSetForPointers(const LoopAccessInfo &LAI) {
const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
unsigned N = RtPtrCheck->Pointers.size();
SmallVector<int, 8> PtrToPartitions(N);
for (unsigned I = 0; I < N; ++I) {
Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;
auto Instructions =
LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);
int &Partition = PtrToPartitions[I];
Partition = -2;
for (Instruction *Inst : Instructions) {
int ThisPartition = this->InstToPartitionId[Inst];
if (Partition == -2)
Partition = ThisPartition;
else if (Partition == -1)
break;
else if (Partition != (int)ThisPartition)
Partition = -1;
}
assert(Partition != -2 && "Pointer not belonging to any partition");
}
return PtrToPartitions;
}
void print(raw_ostream &OS) const {
unsigned Index = 0;
for (const auto &P : PartitionContainer) {
OS << "Partition " << Index++ << " (" << &P << "):\n";
P.print();
}
}
void dump() const { print(dbgs()); }
#ifndef NDEBUG
friend raw_ostream &operator<<(raw_ostream &OS,
const InstPartitionContainer &Partitions) {
Partitions.print(OS);
return OS;
}
#endif
void printBlocks() const {
unsigned Index = 0;
for (const auto &P : PartitionContainer) {
dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
P.printBlocks();
}
}
private:
using PartitionContainerT = std::list<InstPartition>;
PartitionContainerT PartitionContainer;
InstToPartitionIdT InstToPartitionId;
Loop *L;
LoopInfo *LI;
DominatorTree *DT;
template <class UnaryPredicate>
void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
InstPartition *PrevMatch = nullptr;
for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
auto DoesMatch = Predicate(&*I);
if (PrevMatch == nullptr && DoesMatch) {
PrevMatch = &*I;
++I;
} else if (PrevMatch != nullptr && DoesMatch) {
I->moveTo(*PrevMatch);
I = PartitionContainer.erase(I);
} else {
PrevMatch = nullptr;
++I;
}
}
}
void setNewLoopID(MDNode *OrigLoopID, InstPartition *Part) {
Optional<MDNode *> PartitionID = makeFollowupLoopID(
OrigLoopID,
{LLVMLoopDistributeFollowupAll,
Part->hasDepCycle() ? LLVMLoopDistributeFollowupSequential
: LLVMLoopDistributeFollowupCoincident});
if (PartitionID) {
Loop *NewLoop = Part->getDistributedLoop();
NewLoop->setLoopID(PartitionID.value());
}
}
};
class MemoryInstructionDependences {
using Dependence = MemoryDepChecker::Dependence;
public:
struct Entry {
Instruction *Inst;
unsigned NumUnsafeDependencesStartOrEnd = 0;
Entry(Instruction *Inst) : Inst(Inst) {}
};
using AccessesType = SmallVector<Entry, 8>;
AccessesType::const_iterator begin() const { return Accesses.begin(); }
AccessesType::const_iterator end() const { return Accesses.end(); }
MemoryInstructionDependences(
const SmallVectorImpl<Instruction *> &Instructions,
const SmallVectorImpl<Dependence> &Dependences) {
Accesses.append(Instructions.begin(), Instructions.end());
LLVM_DEBUG(dbgs() << "Backward dependences:\n");
for (auto &Dep : Dependences)
if (Dep.isPossiblyBackward()) {
++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
--Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
LLVM_DEBUG(Dep.print(dbgs(), 2, Instructions));
}
}
private:
AccessesType Accesses;
};
class LoopDistributeForLoop {
public:
LoopDistributeForLoop(Loop *L, Function *F, LoopInfo *LI, DominatorTree *DT,
ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
: L(L), F(F), LI(LI), DT(DT), SE(SE), ORE(ORE) {
setForced();
}
bool processLoop(std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
assert(L->isInnermost() && "Only process inner loops.");
LLVM_DEBUG(dbgs() << "\nLDist: In \""
<< L->getHeader()->getParent()->getName()
<< "\" checking " << *L << "\n");
if (!L->getExitBlock())
return fail("MultipleExitBlocks", "multiple exit blocks");
if (!L->isLoopSimplifyForm())
return fail("NotLoopSimplifyForm",
"loop is not in loop-simplify form");
if (!L->isRotatedForm())
return fail("NotBottomTested", "loop is not bottom tested");
BasicBlock *PH = L->getLoopPreheader();
LAI = &GetLAA(*L);
if (LAI->canVectorizeMemory())
return fail("MemOpsCanBeVectorized",
"memory operations are safe for vectorization");
auto *Dependences = LAI->getDepChecker().getDependences();
if (!Dependences || Dependences->empty())
return fail("NoUnsafeDeps", "no unsafe dependences to isolate");
InstPartitionContainer Partitions(L, LI, DT);
const MemoryDepChecker &DepChecker = LAI->getDepChecker();
MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
*Dependences);
int NumUnsafeDependencesActive = 0;
for (auto &InstDep : MID) {
Instruction *I = InstDep.Inst;
if (NumUnsafeDependencesActive ||
InstDep.NumUnsafeDependencesStartOrEnd > 0)
Partitions.addToCyclicPartition(I);
else
Partitions.addToNewNonCyclicPartition(I);
NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
assert(NumUnsafeDependencesActive >= 0 &&
"Negative number of dependences active");
}
auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
for (auto *Inst : DefsUsedOutside)
Partitions.addToNewNonCyclicPartition(Inst);
LLVM_DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
Partitions.mergeBeforePopulating();
LLVM_DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
Partitions.populateUsedSet();
LLVM_DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
if (Partitions.mergeToAvoidDuplicatedLoads()) {
LLVM_DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
<< Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
}
const SCEVPredicate &Pred = LAI->getPSE().getPredicate();
if (LAI->hasConvergentOp() && !Pred.isAlwaysTrue()) {
return fail("RuntimeCheckWithConvergent",
"may not insert runtime check with convergent operation");
}
if (Pred.getComplexity() > (IsForced.value_or(false)
? PragmaDistributeSCEVCheckThreshold
: DistributeSCEVCheckThreshold))
return fail("TooManySCEVRuntimeChecks",
"too many SCEV run-time checks needed.\n");
if (!IsForced.value_or(false) && hasDisableAllTransformsHint(L))
return fail("HeuristicDisabled", "distribution heuristic disabled");
LLVM_DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
Partitions.setupPartitionIdOnInstructions();
auto PtrToPartition = Partitions.computePartitionSetForPointers(*LAI);
const auto *RtPtrChecking = LAI->getRuntimePointerChecking();
const auto &AllChecks = RtPtrChecking->getChecks();
auto Checks = includeOnlyCrossPartitionChecks(AllChecks, PtrToPartition,
RtPtrChecking);
if (LAI->hasConvergentOp() && !Checks.empty()) {
return fail("RuntimeCheckWithConvergent",
"may not insert runtime check with convergent operation");
}
if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
SplitBlock(PH, PH->getTerminator(), DT, LI);
if (!Pred.isAlwaysTrue() || !Checks.empty()) {
assert(!LAI->hasConvergentOp() && "inserting illegal loop versioning");
MDNode *OrigLoopID = L->getLoopID();
LLVM_DEBUG(dbgs() << "\nPointers:\n");
LLVM_DEBUG(LAI->getRuntimePointerChecking()->printChecks(dbgs(), Checks));
LoopVersioning LVer(*LAI, Checks, L, LI, DT, SE);
LVer.versionLoop(DefsUsedOutside);
LVer.annotateLoopWithNoAlias();
MDNode *UnversionedLoopID =
makeFollowupLoopID(OrigLoopID,
{LLVMLoopDistributeFollowupAll,
LLVMLoopDistributeFollowupFallback},
"llvm.loop.distribute.", true)
.value();
LVer.getNonVersionedLoop()->setLoopID(UnversionedLoopID);
}
Partitions.cloneLoops();
Partitions.removeUnusedInsts();
LLVM_DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
LLVM_DEBUG(Partitions.printBlocks());
if (LDistVerify) {
LI->verify(*DT);
assert(DT->verify(DominatorTree::VerificationLevel::Fast));
}
++NumLoopsDistributed;
ORE->emit([&]() {
return OptimizationRemark(LDIST_NAME, "Distribute", L->getStartLoc(),
L->getHeader())
<< "distributed loop";
});
return true;
}
bool fail(StringRef RemarkName, StringRef Message) {
LLVMContext &Ctx = F->getContext();
bool Forced = isForced().value_or(false);
LLVM_DEBUG(dbgs() << "Skipping; " << Message << "\n");
ORE->emit([&]() {
return OptimizationRemarkMissed(LDIST_NAME, "NotDistributed",
L->getStartLoc(), L->getHeader())
<< "loop not distributed: use -Rpass-analysis=loop-distribute for "
"more "
"info";
});
ORE->emit(OptimizationRemarkAnalysis(
Forced ? OptimizationRemarkAnalysis::AlwaysPrint : LDIST_NAME,
RemarkName, L->getStartLoc(), L->getHeader())
<< "loop not distributed: " << Message);
if (Forced)
Ctx.diagnose(DiagnosticInfoOptimizationFailure(
*F, L->getStartLoc(), "loop not distributed: failed "
"explicitly specified loop distribution"));
return false;
}
const Optional<bool> &isForced() const { return IsForced; }
private:
SmallVector<RuntimePointerCheck, 4> includeOnlyCrossPartitionChecks(
const SmallVectorImpl<RuntimePointerCheck> &AllChecks,
const SmallVectorImpl<int> &PtrToPartition,
const RuntimePointerChecking *RtPtrChecking) {
SmallVector<RuntimePointerCheck, 4> Checks;
copy_if(AllChecks, std::back_inserter(Checks),
[&](const RuntimePointerCheck &Check) {
for (unsigned PtrIdx1 : Check.first->Members)
for (unsigned PtrIdx2 : Check.second->Members)
if (RtPtrChecking->needsChecking(PtrIdx1, PtrIdx2) &&
!RuntimePointerChecking::arePointersInSamePartition(
PtrToPartition, PtrIdx1, PtrIdx2))
return true;
return false;
});
return Checks;
}
void setForced() {
Optional<const MDOperand *> Value =
findStringMetadataForLoop(L, "llvm.loop.distribute.enable");
if (!Value)
return;
const MDOperand *Op = *Value;
assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
IsForced = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
}
Loop *L;
Function *F;
LoopInfo *LI;
const LoopAccessInfo *LAI = nullptr;
DominatorTree *DT;
ScalarEvolution *SE;
OptimizationRemarkEmitter *ORE;
Optional<bool> IsForced;
};
}
static bool runImpl(Function &F, LoopInfo *LI, DominatorTree *DT,
ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,
std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
SmallVector<Loop *, 8> Worklist;
for (Loop *TopLevelLoop : *LI)
for (Loop *L : depth_first(TopLevelLoop))
if (L->isInnermost())
Worklist.push_back(L);
bool Changed = false;
for (Loop *L : Worklist) {
LoopDistributeForLoop LDL(L, &F, LI, DT, SE, ORE);
if (LDL.isForced().value_or(EnableLoopDistribute))
Changed |= LDL.processLoop(GetLAA);
}
return Changed;
}
namespace {
class LoopDistributeLegacy : public FunctionPass {
public:
static char ID;
LoopDistributeLegacy() : FunctionPass(ID) {
initializeLoopDistributeLegacyPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
std::function<const LoopAccessInfo &(Loop &)> GetLAA =
[&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
return runImpl(F, LI, DT, SE, ORE, GetLAA);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<LoopAccessLegacyAnalysis>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
};
}
PreservedAnalyses LoopDistributePass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
auto &AA = AM.getResult<AAManager>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
std::function<const LoopAccessInfo &(Loop &)> GetLAA =
[&](Loop &L) -> const LoopAccessInfo & {
LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
TLI, TTI, nullptr, nullptr, nullptr};
return LAM.getResult<LoopAccessAnalysis>(L, AR);
};
bool Changed = runImpl(F, &LI, &DT, &SE, &ORE, GetLAA);
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<LoopAnalysis>();
PA.preserve<DominatorTreeAnalysis>();
return PA;
}
char LoopDistributeLegacy::ID;
static const char ldist_name[] = "Loop Distribution";
INITIALIZE_PASS_BEGIN(LoopDistributeLegacy, LDIST_NAME, ldist_name, false,
false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
INITIALIZE_PASS_END(LoopDistributeLegacy, LDIST_NAME, ldist_name, false, false)
FunctionPass *llvm::createLoopDistributePass() { return new LoopDistributeLegacy(); }