#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.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/DependenceAnalysis.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopIterator.h"
#include "llvm/Analysis/MustExecute.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.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/IntrinsicInst.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/IR/ValueMap.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GenericDomTree.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/UnrollLoop.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <assert.h>
#include <memory>
#include <type_traits>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "loop-unroll-and-jam"
STATISTIC(NumUnrolledAndJammed, "Number of loops unroll and jammed");
STATISTIC(NumCompletelyUnrolledAndJammed, "Number of loops unroll and jammed");
typedef SmallPtrSet<BasicBlock *, 4> BasicBlockSet;
static bool partitionLoopBlocks(Loop &L, BasicBlockSet &ForeBlocks,
BasicBlockSet &AftBlocks, DominatorTree &DT) {
Loop *SubLoop = L.getSubLoops()[0];
BasicBlock *SubLoopLatch = SubLoop->getLoopLatch();
for (BasicBlock *BB : L.blocks()) {
if (!SubLoop->contains(BB)) {
if (DT.dominates(SubLoopLatch, BB))
AftBlocks.insert(BB);
else
ForeBlocks.insert(BB);
}
}
BasicBlock *SubLoopPreHeader = SubLoop->getLoopPreheader();
for (BasicBlock *BB : ForeBlocks) {
if (BB == SubLoopPreHeader)
continue;
Instruction *TI = BB->getTerminator();
for (BasicBlock *Succ : successors(TI))
if (!ForeBlocks.count(Succ))
return false;
}
return true;
}
static bool partitionOuterLoopBlocks(
Loop &Root, Loop &JamLoop, BasicBlockSet &JamLoopBlocks,
DenseMap<Loop *, BasicBlockSet> &ForeBlocksMap,
DenseMap<Loop *, BasicBlockSet> &AftBlocksMap, DominatorTree &DT) {
JamLoopBlocks.insert(JamLoop.block_begin(), JamLoop.block_end());
for (Loop *L : Root.getLoopsInPreorder()) {
if (L == &JamLoop)
break;
if (!partitionLoopBlocks(*L, ForeBlocksMap[L], AftBlocksMap[L], DT))
return false;
}
return true;
}
static bool partitionOuterLoopBlocks(Loop *L, Loop *SubLoop,
BasicBlockSet &ForeBlocks,
BasicBlockSet &SubLoopBlocks,
BasicBlockSet &AftBlocks,
DominatorTree *DT) {
SubLoopBlocks.insert(SubLoop->block_begin(), SubLoop->block_end());
return partitionLoopBlocks(*L, ForeBlocks, AftBlocks, *DT);
}
template <typename T>
static bool processHeaderPhiOperands(BasicBlock *Header, BasicBlock *Latch,
BasicBlockSet &AftBlocks, T Visit) {
SmallVector<Instruction *, 8> Worklist;
SmallPtrSet<Instruction *, 8> VisitedInstr;
for (auto &Phi : Header->phis()) {
Value *V = Phi.getIncomingValueForBlock(Latch);
if (Instruction *I = dyn_cast<Instruction>(V))
Worklist.push_back(I);
}
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
if (!Visit(I))
return false;
VisitedInstr.insert(I);
if (AftBlocks.count(I->getParent()))
for (auto &U : I->operands())
if (Instruction *II = dyn_cast<Instruction>(U))
if (!VisitedInstr.count(II))
Worklist.push_back(II);
}
return true;
}
static void moveHeaderPhiOperandsToForeBlocks(BasicBlock *Header,
BasicBlock *Latch,
Instruction *InsertLoc,
BasicBlockSet &AftBlocks) {
std::vector<Instruction *> Visited;
processHeaderPhiOperands(Header, Latch, AftBlocks,
[&Visited, &AftBlocks](Instruction *I) {
if (AftBlocks.count(I->getParent()))
Visited.push_back(I);
return true;
});
BasicBlock *InsertLocBB = InsertLoc->getParent();
for (Instruction *I : reverse(Visited)) {
if (I->getParent() != InsertLocBB)
I->moveBefore(InsertLoc);
}
}
LoopUnrollResult
llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount,
unsigned TripMultiple, bool UnrollRemainder,
LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
AssumptionCache *AC, const TargetTransformInfo *TTI,
OptimizationRemarkEmitter *ORE, Loop **EpilogueLoop) {
BasicBlock *Header = L->getHeader();
assert(Header && "No header.");
assert(L->getSubLoops().size() == 1);
Loop *SubLoop = *L->begin();
if (TripCount == 0 && Count < 2) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; almost nothing to do\n");
return LoopUnrollResult::Unmodified;
}
assert(Count > 0);
assert(TripMultiple > 0);
assert(TripCount == 0 || TripCount % TripMultiple == 0);
bool CompletelyUnroll = (Count == TripCount);
if (TripMultiple % Count != 0) {
if (!UnrollRuntimeLoopRemainder(L, Count, false,
true,
UnrollRemainder, false,
LI, SE, DT, AC, TTI, true, EpilogueLoop)) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; remainder loop could not be "
"generated when assuming runtime trip count\n");
return LoopUnrollResult::Unmodified;
}
}
if (SE) {
SE->forgetLoop(L);
SE->forgetLoop(SubLoop);
}
using namespace ore;
if (CompletelyUnroll) {
LLVM_DEBUG(dbgs() << "COMPLETELY UNROLL AND JAMMING loop %"
<< Header->getName() << " with trip count " << TripCount
<< "!\n");
ORE->emit(OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
L->getHeader())
<< "completely unroll and jammed loop with "
<< NV("UnrollCount", TripCount) << " iterations");
} else {
auto DiagBuilder = [&]() {
OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
L->getHeader());
return Diag << "unroll and jammed loop by a factor of "
<< NV("UnrollCount", Count);
};
LLVM_DEBUG(dbgs() << "UNROLL AND JAMMING loop %" << Header->getName()
<< " by " << Count);
if (TripMultiple != 1) {
LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
ORE->emit([&]() {
return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple)
<< " trips per branch";
});
} else {
LLVM_DEBUG(dbgs() << " with run-time trip count");
ORE->emit([&]() { return DiagBuilder() << " with run-time trip count"; });
}
LLVM_DEBUG(dbgs() << "!\n");
}
BasicBlock *Preheader = L->getLoopPreheader();
BasicBlock *LatchBlock = L->getLoopLatch();
assert(Preheader && "No preheader");
assert(LatchBlock && "No latch block");
BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
assert(BI && !BI->isUnconditional());
bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
bool SubLoopContinueOnTrue = SubLoop->contains(
SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0));
BasicBlockSet SubLoopBlocks;
BasicBlockSet ForeBlocks;
BasicBlockSet AftBlocks;
partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks, AftBlocks,
DT);
std::vector<BasicBlock *> ForeBlocksFirst;
std::vector<BasicBlock *> ForeBlocksLast;
std::vector<BasicBlock *> SubLoopBlocksFirst;
std::vector<BasicBlock *> SubLoopBlocksLast;
std::vector<BasicBlock *> AftBlocksFirst;
std::vector<BasicBlock *> AftBlocksLast;
ForeBlocksFirst.push_back(Header);
ForeBlocksLast.push_back(SubLoop->getLoopPreheader());
SubLoopBlocksFirst.push_back(SubLoop->getHeader());
SubLoopBlocksLast.push_back(SubLoop->getExitingBlock());
AftBlocksFirst.push_back(SubLoop->getExitBlock());
AftBlocksLast.push_back(L->getExitingBlock());
ValueToValueMapTy LastValueMap;
moveHeaderPhiOperandsToForeBlocks(
Header, LatchBlock, ForeBlocksLast[0]->getTerminator(), AftBlocks);
LoopBlocksDFS DFS(L);
DFS.perform(LI);
LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
if (Header->getParent()->isDebugInfoForProfiling() && !EnableFSDiscriminator)
for (BasicBlock *BB : L->getBlocks())
for (Instruction &I : *BB)
if (!isa<DbgInfoIntrinsic>(&I))
if (const DILocation *DIL = I.getDebugLoc()) {
auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(Count);
if (NewDIL)
I.setDebugLoc(*NewDIL);
else
LLVM_DEBUG(dbgs()
<< "Failed to create new discriminator: "
<< DIL->getFilename() << " Line: " << DIL->getLine());
}
for (unsigned It = 1; It != Count; ++It) {
SmallVector<BasicBlock *, 8> NewBlocks;
DenseMap<Value *, Value *> PrevItValueMap;
SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
NewLoops[L] = L;
NewLoops[SubLoop] = SubLoop;
for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
ValueToValueMapTy VMap;
BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
Header->getParent()->getBasicBlockList().push_back(New);
addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
if (ForeBlocks.count(*BB)) {
if (*BB == ForeBlocksFirst[0])
ForeBlocksFirst.push_back(New);
if (*BB == ForeBlocksLast[0])
ForeBlocksLast.push_back(New);
} else if (SubLoopBlocks.count(*BB)) {
if (*BB == SubLoopBlocksFirst[0])
SubLoopBlocksFirst.push_back(New);
if (*BB == SubLoopBlocksLast[0])
SubLoopBlocksLast.push_back(New);
} else if (AftBlocks.count(*BB)) {
if (*BB == AftBlocksFirst[0])
AftBlocksFirst.push_back(New);
if (*BB == AftBlocksLast[0])
AftBlocksLast.push_back(New);
} else {
llvm_unreachable("BB being cloned should be in Fore/Sub/Aft");
}
PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]);
LastValueMap[*BB] = New;
for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
VI != VE; ++VI) {
PrevItValueMap[VI->second] =
const_cast<Value *>(It == 1 ? VI->first : LastValueMap[VI->first]);
LastValueMap[VI->first] = VI->second;
}
NewBlocks.push_back(New);
if (*BB == ForeBlocksFirst[0])
DT->addNewBlock(New, ForeBlocksLast[It - 1]);
else if (*BB == SubLoopBlocksFirst[0])
DT->addNewBlock(New, SubLoopBlocksLast[It - 1]);
else if (*BB == AftBlocksFirst[0])
DT->addNewBlock(New, AftBlocksLast[It - 1]);
else {
auto BBDomNode = DT->getNode(*BB);
auto BBIDom = BBDomNode->getIDom();
BasicBlock *OriginalBBIDom = BBIDom->getBlock();
assert(OriginalBBIDom);
assert(LastValueMap[cast<Value>(OriginalBBIDom)]);
DT->addNewBlock(
New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
}
}
remapInstructionsInBlocks(NewBlocks, LastValueMap);
for (BasicBlock *NewBlock : NewBlocks) {
for (Instruction &I : *NewBlock) {
if (auto *II = dyn_cast<AssumeInst>(&I))
AC->registerAssumption(II);
}
}
for (PHINode &Phi : ForeBlocksFirst[It]->phis()) {
Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]);
assert(OldValue && "should have incoming edge from Aft[It]");
Value *NewValue = OldValue;
if (Value *PrevValue = PrevItValueMap[OldValue])
NewValue = PrevValue;
assert(Phi.getNumOperands() == 2);
Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]);
Phi.setIncomingValue(0, NewValue);
Phi.removeIncomingValue(1);
}
}
auto updatePHIBlocksAndValues = [](BasicBlock *BB, BasicBlock *OldBB,
BasicBlock *NewBB,
ValueToValueMapTy &LastValueMap) {
for (PHINode &Phi : BB->phis()) {
for (unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) {
if (Phi.getIncomingBlock(b) == OldBB) {
Value *OldValue = Phi.getIncomingValue(b);
if (Value *LastValue = LastValueMap[OldValue])
Phi.setIncomingValue(b, LastValue);
Phi.setIncomingBlock(b, NewBB);
break;
}
}
}
};
auto movePHIs = [](BasicBlock *Src, BasicBlock *Dest) {
Instruction *insertPoint = Dest->getFirstNonPHI();
while (PHINode *Phi = dyn_cast<PHINode>(Src->begin()))
Phi->moveBefore(insertPoint);
};
updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.back(),
LastValueMap);
BranchInst *ForeTerm =
cast<BranchInst>(ForeBlocksLast.back()->getTerminator());
assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
ForeTerm->setSuccessor(0, SubLoopBlocksFirst[0]);
if (CompletelyUnroll) {
while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) {
Phi->replaceAllUsesWith(Phi->getIncomingValueForBlock(Preheader));
Phi->getParent()->getInstList().erase(Phi);
}
} else {
updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0],
AftBlocksLast.back(), LastValueMap);
}
for (unsigned It = 1; It != Count; It++) {
BranchInst *ForeTerm =
cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator());
assert(ForeTerm->getNumSuccessors() == 1 && "Expecting one successor");
ForeTerm->setSuccessor(0, ForeBlocksFirst[It]);
}
BranchInst *SubTerm =
cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator());
SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]);
SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]);
SubLoopBlocksFirst[0]->replacePhiUsesWith(ForeBlocksLast[0],
ForeBlocksLast.back());
SubLoopBlocksFirst[0]->replacePhiUsesWith(SubLoopBlocksLast[0],
SubLoopBlocksLast.back());
for (unsigned It = 1; It != Count; It++) {
BranchInst *SubTerm =
cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator());
BranchInst::Create(SubLoopBlocksFirst[It], SubTerm);
SubTerm->eraseFromParent();
SubLoopBlocksFirst[It]->replacePhiUsesWith(ForeBlocksLast[It],
ForeBlocksLast.back());
SubLoopBlocksFirst[It]->replacePhiUsesWith(SubLoopBlocksLast[It],
SubLoopBlocksLast.back());
movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]);
}
BranchInst *AftTerm = cast<BranchInst>(AftBlocksLast.back()->getTerminator());
if (CompletelyUnroll) {
BranchInst::Create(LoopExit, AftTerm);
AftTerm->eraseFromParent();
} else {
AftTerm->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]);
assert(AftTerm->getSuccessor(ContinueOnTrue) == LoopExit &&
"Expecting the ContinueOnTrue successor of AftTerm to be LoopExit");
}
AftBlocksFirst[0]->replacePhiUsesWith(SubLoopBlocksLast[0],
SubLoopBlocksLast.back());
for (unsigned It = 1; It != Count; It++) {
BranchInst *AftTerm =
cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator());
BranchInst::Create(AftBlocksFirst[It], AftTerm);
AftTerm->eraseFromParent();
AftBlocksFirst[It]->replacePhiUsesWith(SubLoopBlocksLast[It],
SubLoopBlocksLast.back());
movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]);
}
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
if (Count != 1) {
SmallVector<DominatorTree::UpdateType, 4> DTUpdates;
DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, ForeBlocksLast[0],
SubLoopBlocksFirst[0]);
DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete,
SubLoopBlocksLast[0], AftBlocksFirst[0]);
DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
ForeBlocksLast.back(), SubLoopBlocksFirst[0]);
DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert,
SubLoopBlocksLast.back(), AftBlocksFirst[0]);
DTU.applyUpdatesPermissive(DTUpdates);
}
SmallPtrSet<BasicBlock *, 16> MergeBlocks;
MergeBlocks.insert(ForeBlocksLast.begin(), ForeBlocksLast.end());
MergeBlocks.insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end());
MergeBlocks.insert(AftBlocksLast.begin(), AftBlocksLast.end());
MergeBlockSuccessorsIntoGivenBlocks(MergeBlocks, L, &DTU, LI);
DT = &DTU.getDomTree();
simplifyLoopAfterUnroll(SubLoop, true, LI, SE, DT, AC, TTI);
simplifyLoopAfterUnroll(L, !CompletelyUnroll && Count > 1, LI, SE, DT, AC,
TTI);
NumCompletelyUnrolledAndJammed += CompletelyUnroll;
++NumUnrolledAndJammed;
if (CompletelyUnroll)
LI->erase(L);
#ifndef NDEBUG
Loop *OutestLoop = SubLoop->getParentLoop()
? SubLoop->getParentLoop()->getParentLoop()
? SubLoop->getParentLoop()->getParentLoop()
: SubLoop->getParentLoop()
: SubLoop;
assert(DT->verify());
LI->verify(*DT);
assert(OutestLoop->isRecursivelyLCSSAForm(*DT, *LI));
if (!CompletelyUnroll)
assert(L->isLoopSimplifyForm());
assert(SubLoop->isLoopSimplifyForm());
SE->verify();
#endif
return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
: LoopUnrollResult::PartiallyUnrolled;
}
static bool getLoadsAndStores(BasicBlockSet &Blocks,
SmallVector<Instruction *, 4> &MemInstr) {
for (BasicBlock *BB : Blocks) {
for (Instruction &I : *BB) {
if (auto *Ld = dyn_cast<LoadInst>(&I)) {
if (!Ld->isSimple())
return false;
MemInstr.push_back(&I);
} else if (auto *St = dyn_cast<StoreInst>(&I)) {
if (!St->isSimple())
return false;
MemInstr.push_back(&I);
} else if (I.mayReadOrWriteMemory()) {
return false;
}
}
}
return true;
}
static bool preservesForwardDependence(Instruction *Src, Instruction *Dst,
unsigned UnrollLevel, unsigned JamLevel,
bool Sequentialized, Dependence *D) {
for (unsigned CurLoopDepth = UnrollLevel + 1; CurLoopDepth <= JamLevel;
++CurLoopDepth) {
auto JammedDir = D->getDirection(CurLoopDepth);
if (JammedDir == Dependence::DVEntry::LT)
return true;
if (JammedDir & Dependence::DVEntry::GT)
return false;
}
return true;
}
static bool preservesBackwardDependence(Instruction *Src, Instruction *Dst,
unsigned UnrollLevel, unsigned JamLevel,
bool Sequentialized, Dependence *D) {
for (unsigned CurLoopDepth = UnrollLevel + 1; CurLoopDepth <= JamLevel;
++CurLoopDepth) {
auto JammedDir = D->getDirection(CurLoopDepth);
if (JammedDir == Dependence::DVEntry::GT)
return true;
if (JammedDir & Dependence::DVEntry::LT)
return false;
}
return Sequentialized;
}
static bool checkDependency(Instruction *Src, Instruction *Dst,
unsigned UnrollLevel, unsigned JamLevel,
bool Sequentialized, DependenceInfo &DI) {
assert(UnrollLevel <= JamLevel &&
"Expecting JamLevel to be at least UnrollLevel");
if (Src == Dst)
return true;
if (isa<LoadInst>(Src) && isa<LoadInst>(Dst))
return true;
std::unique_ptr<Dependence> D = DI.depends(Src, Dst, true);
if (!D)
return true;
assert(D->isOrdered() && "Expected an output, flow or anti dep.");
if (D->isConfused()) {
LLVM_DEBUG(dbgs() << " Confused dependency between:\n"
<< " " << *Src << "\n"
<< " " << *Dst << "\n");
return false;
}
for (unsigned CurLoopDepth = 1; CurLoopDepth < UnrollLevel; ++CurLoopDepth)
if (!(D->getDirection(CurLoopDepth) & Dependence::DVEntry::EQ))
return true;
auto UnrollDirection = D->getDirection(UnrollLevel);
if (UnrollDirection == Dependence::DVEntry::EQ)
return true;
if (UnrollDirection & Dependence::DVEntry::LT &&
!preservesForwardDependence(Src, Dst, UnrollLevel, JamLevel,
Sequentialized, D.get()))
return false;
if (UnrollDirection & Dependence::DVEntry::GT &&
!preservesBackwardDependence(Src, Dst, UnrollLevel, JamLevel,
Sequentialized, D.get()))
return false;
return true;
}
static bool
checkDependencies(Loop &Root, const BasicBlockSet &SubLoopBlocks,
const DenseMap<Loop *, BasicBlockSet> &ForeBlocksMap,
const DenseMap<Loop *, BasicBlockSet> &AftBlocksMap,
DependenceInfo &DI, LoopInfo &LI) {
SmallVector<BasicBlockSet, 8> AllBlocks;
for (Loop *L : Root.getLoopsInPreorder())
if (ForeBlocksMap.find(L) != ForeBlocksMap.end())
AllBlocks.push_back(ForeBlocksMap.lookup(L));
AllBlocks.push_back(SubLoopBlocks);
for (Loop *L : Root.getLoopsInPreorder())
if (AftBlocksMap.find(L) != AftBlocksMap.end())
AllBlocks.push_back(AftBlocksMap.lookup(L));
unsigned LoopDepth = Root.getLoopDepth();
SmallVector<Instruction *, 4> EarlierLoadsAndStores;
SmallVector<Instruction *, 4> CurrentLoadsAndStores;
for (BasicBlockSet &Blocks : AllBlocks) {
CurrentLoadsAndStores.clear();
if (!getLoadsAndStores(Blocks, CurrentLoadsAndStores))
return false;
Loop *CurLoop = LI.getLoopFor((*Blocks.begin())->front().getParent());
unsigned CurLoopDepth = CurLoop->getLoopDepth();
for (auto *Earlier : EarlierLoadsAndStores) {
Loop *EarlierLoop = LI.getLoopFor(Earlier->getParent());
unsigned EarlierDepth = EarlierLoop->getLoopDepth();
unsigned CommonLoopDepth = std::min(EarlierDepth, CurLoopDepth);
for (auto *Later : CurrentLoadsAndStores) {
if (!checkDependency(Earlier, Later, LoopDepth, CommonLoopDepth, false,
DI))
return false;
}
}
size_t NumInsts = CurrentLoadsAndStores.size();
for (size_t I = 0; I < NumInsts; ++I) {
for (size_t J = I; J < NumInsts; ++J) {
if (!checkDependency(CurrentLoadsAndStores[I], CurrentLoadsAndStores[J],
LoopDepth, CurLoopDepth, true, DI))
return false;
}
}
EarlierLoadsAndStores.append(CurrentLoadsAndStores.begin(),
CurrentLoadsAndStores.end());
}
return true;
}
static bool isEligibleLoopForm(const Loop &Root) {
if (Root.getSubLoops().size() != 1)
return false;
const Loop *L = &Root;
do {
if (!L->isLoopSimplifyForm())
return false;
if (!L->isRotatedForm())
return false;
if (L->getHeader()->hasAddressTaken()) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Address taken\n");
return false;
}
unsigned SubLoopsSize = L->getSubLoops().size();
if (SubLoopsSize == 0)
return true;
if (SubLoopsSize != 1)
return false;
if (!L->getExitBlock()) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; only loops with single exit "
"blocks can be unrolled and jammed.\n");
return false;
}
if (!L->getExitingBlock()) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; only loops with single "
"exiting blocks can be unrolled and jammed.\n");
return false;
}
L = L->getSubLoops()[0];
} while (L);
return true;
}
static Loop *getInnerMostLoop(Loop *L) {
while (!L->getSubLoops().empty())
L = L->getSubLoops()[0];
return L;
}
bool llvm::isSafeToUnrollAndJam(Loop *L, ScalarEvolution &SE, DominatorTree &DT,
DependenceInfo &DI, LoopInfo &LI) {
if (!isEligibleLoopForm(*L)) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Ineligible loop form\n");
return false;
}
Loop *JamLoop = getInnerMostLoop(L);
BasicBlockSet SubLoopBlocks;
DenseMap<Loop *, BasicBlockSet> ForeBlocksMap;
DenseMap<Loop *, BasicBlockSet> AftBlocksMap;
if (!partitionOuterLoopBlocks(*L, *JamLoop, SubLoopBlocks, ForeBlocksMap,
AftBlocksMap, DT)) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Incompatible loop layout\n");
return false;
}
if (AftBlocksMap[L].size() != 1) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Can't currently handle "
"multiple blocks after the loop\n");
return false;
}
if (any_of(L->getLoopsInPreorder(), [&SE](Loop *SubLoop) {
return !hasIterationCountInvariantInParent(SubLoop, SE);
})) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Inner loop iteration count is "
"not consistent on each iteration\n");
return false;
}
SimpleLoopSafetyInfo LSI;
LSI.computeLoopSafetyInfo(L);
if (LSI.anyBlockMayThrow()) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; Something may throw\n");
return false;
}
BasicBlock *Header = L->getHeader();
BasicBlock *Latch = L->getLoopLatch();
BasicBlockSet AftBlocks = AftBlocksMap[L];
Loop *SubLoop = L->getSubLoops()[0];
if (!processHeaderPhiOperands(
Header, Latch, AftBlocks, [&AftBlocks, &SubLoop](Instruction *I) {
if (SubLoop->contains(I->getParent()))
return false;
if (AftBlocks.count(I->getParent())) {
if (isa<PHINode>(I))
return false;
if (I->mayHaveSideEffects() || I->mayReadOrWriteMemory())
return false;
}
return true;
})) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; can't move required "
"instructions after subloop to before it\n");
return false;
}
if (!checkDependencies(*L, SubLoopBlocks, ForeBlocksMap, AftBlocksMap, DI,
LI)) {
LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; failed dependency check\n");
return false;
}
return true;
}