#include "PPC.h"
#include "PPCSubtarget.h"
#include "PPCTargetMachine.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IntrinsicsPowerPC.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.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/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
#include <cassert>
#include <iterator>
#include <utility>
#define DEBUG_TYPE "ppc-loop-instr-form-prep"
using namespace llvm;
static cl::opt<unsigned>
MaxVarsPrep("ppc-formprep-max-vars", cl::Hidden, cl::init(24),
cl::desc("Potential common base number threshold per function "
"for PPC loop prep"));
static cl::opt<bool> PreferUpdateForm("ppc-formprep-prefer-update",
cl::init(true), cl::Hidden,
cl::desc("prefer update form when ds form is also a update form"));
static cl::opt<bool> EnableUpdateFormForNonConstInc(
"ppc-formprep-update-nonconst-inc", cl::init(false), cl::Hidden,
cl::desc("prepare update form when the load/store increment is a loop "
"invariant non-const value."));
static cl::opt<bool> EnableChainCommoning(
"ppc-formprep-chain-commoning", cl::init(false), cl::Hidden,
cl::desc("Enable chain commoning in PPC loop prepare pass."));
static cl::opt<unsigned> MaxVarsUpdateForm("ppc-preinc-prep-max-vars",
cl::Hidden, cl::init(3),
cl::desc("Potential PHI threshold per loop for PPC loop prep of update "
"form"));
static cl::opt<unsigned> MaxVarsDSForm("ppc-dsprep-max-vars",
cl::Hidden, cl::init(3),
cl::desc("Potential PHI threshold per loop for PPC loop prep of DS form"));
static cl::opt<unsigned> MaxVarsDQForm("ppc-dqprep-max-vars",
cl::Hidden, cl::init(8),
cl::desc("Potential PHI threshold per loop for PPC loop prep of DQ form"));
static cl::opt<unsigned> MaxVarsChainCommon(
"ppc-chaincommon-max-vars", cl::Hidden, cl::init(4),
cl::desc("Bucket number per loop for PPC loop chain common"));
static cl::opt<unsigned> DispFormPrepMinThreshold("ppc-dispprep-min-threshold",
cl::Hidden, cl::init(2),
cl::desc("Minimal common base load/store instructions triggering DS/DQ form "
"preparation"));
static cl::opt<unsigned> ChainCommonPrepMinThreshold(
"ppc-chaincommon-min-threshold", cl::Hidden, cl::init(4),
cl::desc("Minimal common base load/store instructions triggering chain "
"commoning preparation. Must be not smaller than 4"));
STATISTIC(PHINodeAlreadyExistsUpdate, "PHI node already in pre-increment form");
STATISTIC(PHINodeAlreadyExistsDS, "PHI node already in DS form");
STATISTIC(PHINodeAlreadyExistsDQ, "PHI node already in DQ form");
STATISTIC(DSFormChainRewritten, "Num of DS form chain rewritten");
STATISTIC(DQFormChainRewritten, "Num of DQ form chain rewritten");
STATISTIC(UpdFormChainRewritten, "Num of update form chain rewritten");
STATISTIC(ChainCommoningRewritten, "Num of commoning chains");
namespace {
struct BucketElement {
BucketElement(const SCEV *O, Instruction *I) : Offset(O), Instr(I) {}
BucketElement(Instruction *I) : Offset(nullptr), Instr(I) {}
const SCEV *Offset;
Instruction *Instr;
};
struct Bucket {
Bucket(const SCEV *B, Instruction *I)
: BaseSCEV(B), Elements(1, BucketElement(I)) {
ChainSize = 0;
}
const SCEV *BaseSCEV;
SmallVector<BucketElement, 16> Elements;
unsigned ChainSize;
SmallVector<BucketElement, 16> ChainBases;
};
enum PrepForm { UpdateForm = 1, DSForm = 4, DQForm = 16, ChainCommoning };
class PPCLoopInstrFormPrep : public FunctionPass {
public:
static char ID;
PPCLoopInstrFormPrep() : FunctionPass(ID) {
initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
}
PPCLoopInstrFormPrep(PPCTargetMachine &TM) : FunctionPass(ID), TM(&TM) {
initializePPCLoopInstrFormPrepPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<ScalarEvolutionWrapperPass>();
}
bool runOnFunction(Function &F) override;
private:
PPCTargetMachine *TM = nullptr;
const PPCSubtarget *ST;
DominatorTree *DT;
LoopInfo *LI;
ScalarEvolution *SE;
bool PreserveLCSSA;
bool HasCandidateForPrepare;
unsigned SuccPrepCount;
bool runOnLoop(Loop *L);
bool alreadyPrepared(Loop *L, Instruction *MemI,
const SCEV *BasePtrStartSCEV,
const SCEV *BasePtrIncSCEV, PrepForm Form);
Value *getNodeForInc(Loop *L, Instruction *MemI,
const SCEV *BasePtrIncSCEV);
bool chainCommoning(Loop *L, SmallVector<Bucket, 16> &Buckets);
bool prepareBasesForCommoningChains(Bucket &BucketChain);
bool
rewriteLoadStoresForCommoningChains(Loop *L, Bucket &Bucket,
SmallSet<BasicBlock *, 16> &BBChanged);
SmallVector<Bucket, 16> collectCandidates(
Loop *L,
std::function<bool(const Instruction *, Value *, const Type *)>
isValidCandidate,
std::function<bool(const SCEV *)> isValidDiff,
unsigned MaxCandidateNum);
void addOneCandidate(Instruction *MemI, const SCEV *LSCEV,
SmallVector<Bucket, 16> &Buckets,
std::function<bool(const SCEV *)> isValidDiff,
unsigned MaxCandidateNum);
bool updateFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets);
bool dispFormPrep(Loop *L, SmallVector<Bucket, 16> &Buckets, PrepForm Form);
bool prepareBaseForDispFormChain(Bucket &BucketChain, PrepForm Form);
bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
bool rewriteLoadStores(Loop *L, Bucket &BucketChain,
SmallSet<BasicBlock *, 16> &BBChanged,
PrepForm Form);
std::pair<Instruction *, Instruction *>
rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
Instruction *BaseMemI, bool CanPreInc, PrepForm Form,
SCEVExpander &SCEVE, SmallPtrSet<Value *, 16> &DeletedPtrs);
Instruction *
rewriteForBucketElement(std::pair<Instruction *, Instruction *> Base,
const BucketElement &Element, Value *OffToBase,
SmallPtrSet<Value *, 16> &DeletedPtrs);
};
}
char PPCLoopInstrFormPrep::ID = 0;
static const char *name = "Prepare loop for ppc preferred instruction forms";
INITIALIZE_PASS_BEGIN(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_END(PPCLoopInstrFormPrep, DEBUG_TYPE, name, false, false)
static constexpr StringRef PHINodeNameSuffix = ".phi";
static constexpr StringRef CastNodeNameSuffix = ".cast";
static constexpr StringRef GEPNodeIncNameSuffix = ".inc";
static constexpr StringRef GEPNodeOffNameSuffix = ".off";
FunctionPass *llvm::createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM) {
return new PPCLoopInstrFormPrep(TM);
}
static bool IsPtrInBounds(Value *BasePtr) {
Value *StrippedBasePtr = BasePtr;
while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
StrippedBasePtr = BC->getOperand(0);
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(StrippedBasePtr))
return GEP->isInBounds();
return false;
}
static std::string getInstrName(const Value *I, StringRef Suffix) {
assert(I && "Invalid paramater!");
if (I->hasName())
return (I->getName() + Suffix).str();
else
return "";
}
static Value *getPointerOperandAndType(Value *MemI,
Type **PtrElementType = nullptr) {
Value *PtrValue = nullptr;
Type *PointerElementType = nullptr;
if (LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
PtrValue = LMemI->getPointerOperand();
PointerElementType = LMemI->getType();
} else if (StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
PtrValue = SMemI->getPointerOperand();
PointerElementType = SMemI->getValueOperand()->getType();
} else if (IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
PointerElementType = Type::getInt8Ty(MemI->getContext());
if (IMemI->getIntrinsicID() == Intrinsic::prefetch ||
IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) {
PtrValue = IMemI->getArgOperand(0);
} else if (IMemI->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp) {
PtrValue = IMemI->getArgOperand(1);
}
}
if (PtrElementType)
*PtrElementType = PointerElementType;
return PtrValue;
}
bool PPCLoopInstrFormPrep::runOnFunction(Function &F) {
if (skipFunction(F))
return false;
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : nullptr;
PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
ST = TM ? TM->getSubtargetImpl(F) : nullptr;
SuccPrepCount = 0;
bool MadeChange = false;
for (Loop *I : *LI)
for (Loop *L : depth_first(I))
MadeChange |= runOnLoop(L);
return MadeChange;
}
bool PPCLoopInstrFormPrep::prepareBasesForCommoningChains(Bucket &CBucket) {
assert(ChainCommonPrepMinThreshold >= 4 &&
"Thredhold can not be smaller than 4!\n");
if (CBucket.Elements.size() < ChainCommonPrepMinThreshold)
return false;
const SCEV *FirstOffset = CBucket.Elements[1].Offset;
unsigned FirstOffsetReusedCount = 1;
unsigned FirstOffsetReusedCountInFirstChain = 1;
unsigned EleNum = CBucket.Elements.size();
bool SawChainSeparater = false;
for (unsigned j = 2; j != EleNum; ++j) {
if (SE->getMinusSCEV(CBucket.Elements[j].Offset,
CBucket.Elements[j - 1].Offset) == FirstOffset) {
if (!SawChainSeparater)
FirstOffsetReusedCountInFirstChain++;
FirstOffsetReusedCount++;
} else
SawChainSeparater = true;
}
if (FirstOffsetReusedCount == 1)
return false;
unsigned ChainNum =
FirstOffsetReusedCount / FirstOffsetReusedCountInFirstChain;
if (!SawChainSeparater)
ChainNum = (unsigned)sqrt((double)EleNum);
CBucket.ChainSize = (unsigned)(EleNum / ChainNum);
if (CBucket.ChainSize * ChainNum != EleNum)
return false;
if (SawChainSeparater) {
for (unsigned i = 1; i < CBucket.ChainSize; i++)
for (unsigned j = 1; j < ChainNum; j++)
if (CBucket.Elements[i].Offset !=
SE->getMinusSCEV(CBucket.Elements[i + j * CBucket.ChainSize].Offset,
CBucket.Elements[j * CBucket.ChainSize].Offset))
return false;
}
for (unsigned i = 0; i < ChainNum; i++)
CBucket.ChainBases.push_back(CBucket.Elements[i * CBucket.ChainSize]);
LLVM_DEBUG(dbgs() << "Bucket has " << ChainNum << " chains.\n");
return true;
}
bool PPCLoopInstrFormPrep::chainCommoning(Loop *L,
SmallVector<Bucket, 16> &Buckets) {
bool MadeChange = false;
if (Buckets.empty())
return MadeChange;
SmallSet<BasicBlock *, 16> BBChanged;
for (auto &Bucket : Buckets) {
if (prepareBasesForCommoningChains(Bucket))
MadeChange |= rewriteLoadStoresForCommoningChains(L, Bucket, BBChanged);
}
if (MadeChange)
for (auto *BB : BBChanged)
DeleteDeadPHIs(BB);
return MadeChange;
}
bool PPCLoopInstrFormPrep::rewriteLoadStoresForCommoningChains(
Loop *L, Bucket &Bucket, SmallSet<BasicBlock *, 16> &BBChanged) {
bool MadeChange = false;
assert(Bucket.Elements.size() ==
Bucket.ChainBases.size() * Bucket.ChainSize &&
"invalid bucket for chain commoning!\n");
SmallPtrSet<Value *, 16> DeletedPtrs;
BasicBlock *Header = L->getHeader();
BasicBlock *LoopPredecessor = L->getLoopPredecessor();
SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
"loopprepare-chaincommon");
for (unsigned ChainIdx = 0; ChainIdx < Bucket.ChainBases.size(); ++ChainIdx) {
unsigned BaseElemIdx = Bucket.ChainSize * ChainIdx;
const SCEV *BaseSCEV =
ChainIdx ? SE->getAddExpr(Bucket.BaseSCEV,
Bucket.Elements[BaseElemIdx].Offset)
: Bucket.BaseSCEV;
const SCEVAddRecExpr *BasePtrSCEV = cast<SCEVAddRecExpr>(BaseSCEV);
if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
return MadeChange;
assert(BasePtrSCEV->isAffine() &&
"Invalid SCEV type for the base ptr for a candidate chain!\n");
std::pair<Instruction *, Instruction *> Base = rewriteForBase(
L, BasePtrSCEV, Bucket.Elements[BaseElemIdx].Instr,
false , ChainCommoning, SCEVE, DeletedPtrs);
if (!Base.first || !Base.second)
return MadeChange;
SmallPtrSet<Value *, 16> NewPtrs;
NewPtrs.insert(Base.first);
for (unsigned Idx = BaseElemIdx + 1; Idx < BaseElemIdx + Bucket.ChainSize;
++Idx) {
BucketElement &I = Bucket.Elements[Idx];
Value *Ptr = getPointerOperandAndType(I.Instr);
assert(Ptr && "No pointer operand");
if (NewPtrs.count(Ptr))
continue;
const SCEV *OffsetSCEV =
BaseElemIdx ? SE->getMinusSCEV(Bucket.Elements[Idx].Offset,
Bucket.Elements[BaseElemIdx].Offset)
: Bucket.Elements[Idx].Offset;
if (!BaseElemIdx)
if (!SCEVE.isSafeToExpand(OffsetSCEV))
return false;
Value *OffsetValue = SCEVE.expandCodeFor(
OffsetSCEV, OffsetSCEV->getType(), LoopPredecessor->getTerminator());
Instruction *NewPtr = rewriteForBucketElement(Base, Bucket.Elements[Idx],
OffsetValue, DeletedPtrs);
assert(NewPtr && "Wrong rewrite!\n");
NewPtrs.insert(NewPtr);
}
++ChainCommoningRewritten;
}
SCEVE.clear();
for (auto *Ptr : DeletedPtrs) {
if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
BBChanged.insert(IDel->getParent());
RecursivelyDeleteTriviallyDeadInstructions(Ptr);
}
MadeChange = true;
return MadeChange;
}
std::pair<Instruction *, Instruction *>
PPCLoopInstrFormPrep::rewriteForBase(Loop *L, const SCEVAddRecExpr *BasePtrSCEV,
Instruction *BaseMemI, bool CanPreInc,
PrepForm Form, SCEVExpander &SCEVE,
SmallPtrSet<Value *, 16> &DeletedPtrs) {
LLVM_DEBUG(dbgs() << "PIP: Transforming: " << *BasePtrSCEV << "\n");
assert(BasePtrSCEV->getLoop() == L && "AddRec for the wrong loop?");
Value *BasePtr = getPointerOperandAndType(BaseMemI);
assert(BasePtr && "No pointer operand");
Type *I8Ty = Type::getInt8Ty(BaseMemI->getParent()->getContext());
Type *I8PtrTy =
Type::getInt8PtrTy(BaseMemI->getParent()->getContext(),
BasePtr->getType()->getPointerAddressSpace());
bool IsConstantInc = false;
const SCEV *BasePtrIncSCEV = BasePtrSCEV->getStepRecurrence(*SE);
Value *IncNode = getNodeForInc(L, BaseMemI, BasePtrIncSCEV);
const SCEVConstant *BasePtrIncConstantSCEV =
dyn_cast<SCEVConstant>(BasePtrIncSCEV);
if (BasePtrIncConstantSCEV)
IsConstantInc = true;
if (!IncNode) {
LLVM_DEBUG(dbgs() << "Loop Increasement can not be represented!\n");
return std::make_pair(nullptr, nullptr);
}
if (Form == UpdateForm && !IsConstantInc && !EnableUpdateFormForNonConstInc) {
LLVM_DEBUG(
dbgs()
<< "Update form prepare for non-const increment is not enabled!\n");
return std::make_pair(nullptr, nullptr);
}
const SCEV *BasePtrStartSCEV = nullptr;
if (CanPreInc) {
assert(SE->isLoopInvariant(BasePtrIncSCEV, L) &&
"Increment is not loop invariant!\n");
BasePtrStartSCEV = SE->getMinusSCEV(BasePtrSCEV->getStart(),
IsConstantInc ? BasePtrIncConstantSCEV
: BasePtrIncSCEV);
} else
BasePtrStartSCEV = BasePtrSCEV->getStart();
if (alreadyPrepared(L, BaseMemI, BasePtrStartSCEV, BasePtrIncSCEV, Form)) {
LLVM_DEBUG(dbgs() << "Instruction form is already prepared!\n");
return std::make_pair(nullptr, nullptr);
}
LLVM_DEBUG(dbgs() << "PIP: New start is: " << *BasePtrStartSCEV << "\n");
BasicBlock *Header = L->getHeader();
unsigned HeaderLoopPredCount = pred_size(Header);
BasicBlock *LoopPredecessor = L->getLoopPredecessor();
PHINode *NewPHI = PHINode::Create(I8PtrTy, HeaderLoopPredCount,
getInstrName(BaseMemI, PHINodeNameSuffix),
Header->getFirstNonPHI());
Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
LoopPredecessor->getTerminator());
for (auto PI : predecessors(Header)) {
if (PI != LoopPredecessor)
continue;
NewPHI->addIncoming(BasePtrStart, LoopPredecessor);
}
Instruction *PtrInc = nullptr;
Instruction *NewBasePtr = nullptr;
if (CanPreInc) {
Instruction *InsPoint = &*Header->getFirstInsertionPt();
PtrInc = GetElementPtrInst::Create(
I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
InsPoint);
cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
for (auto PI : predecessors(Header)) {
if (PI == LoopPredecessor)
continue;
NewPHI->addIncoming(PtrInc, PI);
}
if (PtrInc->getType() != BasePtr->getType())
NewBasePtr =
new BitCastInst(PtrInc, BasePtr->getType(),
getInstrName(PtrInc, CastNodeNameSuffix), InsPoint);
else
NewBasePtr = PtrInc;
} else {
for (auto PI : predecessors(Header)) {
if (PI == LoopPredecessor)
continue;
BasicBlock *BB = PI;
Instruction *InsPoint = BB->getTerminator();
PtrInc = GetElementPtrInst::Create(
I8Ty, NewPHI, IncNode, getInstrName(BaseMemI, GEPNodeIncNameSuffix),
InsPoint);
cast<GetElementPtrInst>(PtrInc)->setIsInBounds(IsPtrInBounds(BasePtr));
NewPHI->addIncoming(PtrInc, PI);
}
PtrInc = NewPHI;
if (NewPHI->getType() != BasePtr->getType())
NewBasePtr = new BitCastInst(NewPHI, BasePtr->getType(),
getInstrName(NewPHI, CastNodeNameSuffix),
&*Header->getFirstInsertionPt());
else
NewBasePtr = NewPHI;
}
BasePtr->replaceAllUsesWith(NewBasePtr);
DeletedPtrs.insert(BasePtr);
return std::make_pair(NewBasePtr, PtrInc);
}
Instruction *PPCLoopInstrFormPrep::rewriteForBucketElement(
std::pair<Instruction *, Instruction *> Base, const BucketElement &Element,
Value *OffToBase, SmallPtrSet<Value *, 16> &DeletedPtrs) {
Instruction *NewBasePtr = Base.first;
Instruction *PtrInc = Base.second;
assert((NewBasePtr && PtrInc) && "base does not exist!\n");
Type *I8Ty = Type::getInt8Ty(PtrInc->getParent()->getContext());
Value *Ptr = getPointerOperandAndType(Element.Instr);
assert(Ptr && "No pointer operand");
Instruction *RealNewPtr;
if (!Element.Offset ||
(isa<SCEVConstant>(Element.Offset) &&
cast<SCEVConstant>(Element.Offset)->getValue()->isZero())) {
RealNewPtr = NewBasePtr;
} else {
Instruction *PtrIP = dyn_cast<Instruction>(Ptr);
if (PtrIP && isa<Instruction>(NewBasePtr) &&
cast<Instruction>(NewBasePtr)->getParent() == PtrIP->getParent())
PtrIP = nullptr;
else if (PtrIP && isa<PHINode>(PtrIP))
PtrIP = &*PtrIP->getParent()->getFirstInsertionPt();
else if (!PtrIP)
PtrIP = Element.Instr;
assert(OffToBase && "There should be an offset for non base element!\n");
GetElementPtrInst *NewPtr = GetElementPtrInst::Create(
I8Ty, PtrInc, OffToBase,
getInstrName(Element.Instr, GEPNodeOffNameSuffix), PtrIP);
if (!PtrIP)
NewPtr->insertAfter(cast<Instruction>(PtrInc));
NewPtr->setIsInBounds(IsPtrInBounds(Ptr));
RealNewPtr = NewPtr;
}
Instruction *ReplNewPtr;
if (Ptr->getType() != RealNewPtr->getType()) {
ReplNewPtr = new BitCastInst(RealNewPtr, Ptr->getType(),
getInstrName(Ptr, CastNodeNameSuffix));
ReplNewPtr->insertAfter(RealNewPtr);
} else
ReplNewPtr = RealNewPtr;
Ptr->replaceAllUsesWith(ReplNewPtr);
DeletedPtrs.insert(Ptr);
return ReplNewPtr;
}
void PPCLoopInstrFormPrep::addOneCandidate(
Instruction *MemI, const SCEV *LSCEV, SmallVector<Bucket, 16> &Buckets,
std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
assert((MemI && getPointerOperandAndType(MemI)) &&
"Candidate should be a memory instruction.");
assert(LSCEV && "Invalid SCEV for Ptr value.");
bool FoundBucket = false;
for (auto &B : Buckets) {
if (cast<SCEVAddRecExpr>(B.BaseSCEV)->getStepRecurrence(*SE) !=
cast<SCEVAddRecExpr>(LSCEV)->getStepRecurrence(*SE))
continue;
const SCEV *Diff = SE->getMinusSCEV(LSCEV, B.BaseSCEV);
if (isValidDiff(Diff)) {
B.Elements.push_back(BucketElement(Diff, MemI));
FoundBucket = true;
break;
}
}
if (!FoundBucket) {
if (Buckets.size() == MaxCandidateNum) {
LLVM_DEBUG(dbgs() << "Can not prepare more chains, reach maximum limit "
<< MaxCandidateNum << "\n");
return;
}
Buckets.push_back(Bucket(LSCEV, MemI));
}
}
SmallVector<Bucket, 16> PPCLoopInstrFormPrep::collectCandidates(
Loop *L,
std::function<bool(const Instruction *, Value *, const Type *)>
isValidCandidate,
std::function<bool(const SCEV *)> isValidDiff, unsigned MaxCandidateNum) {
SmallVector<Bucket, 16> Buckets;
for (const auto &BB : L->blocks())
for (auto &J : *BB) {
Value *PtrValue = nullptr;
Type *PointerElementType = nullptr;
PtrValue = getPointerOperandAndType(&J, &PointerElementType);
if (!PtrValue)
continue;
if (PtrValue->getType()->getPointerAddressSpace())
continue;
if (L->isLoopInvariant(PtrValue))
continue;
const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
if (!LARSCEV || LARSCEV->getLoop() != L)
continue;
HasCandidateForPrepare = true;
if (isValidCandidate(&J, PtrValue, PointerElementType))
addOneCandidate(&J, LSCEV, Buckets, isValidDiff, MaxCandidateNum);
}
return Buckets;
}
bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
PrepForm Form) {
DenseMap<unsigned, std::pair<unsigned, unsigned>> RemainderOffsetInfo;
for (unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
if (!BucketChain.Elements[j].Offset)
RemainderOffsetInfo[0] = std::make_pair(0, 1);
else {
unsigned Remainder = cast<SCEVConstant>(BucketChain.Elements[j].Offset)
->getAPInt()
.urem(Form);
if (RemainderOffsetInfo.find(Remainder) == RemainderOffsetInfo.end())
RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
else
RemainderOffsetInfo[Remainder].second++;
}
}
unsigned MaxCountRemainder = 0;
for (unsigned j = 0; j < (unsigned)Form; j++)
if ((RemainderOffsetInfo.find(j) != RemainderOffsetInfo.end()) &&
RemainderOffsetInfo[j].second >
RemainderOffsetInfo[MaxCountRemainder].second)
MaxCountRemainder = j;
if (RemainderOffsetInfo[MaxCountRemainder].second < DispFormPrepMinThreshold)
return false;
if (MaxCountRemainder == 0)
return true;
const SCEV *Offset =
BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
for (auto &E : BucketChain.Elements) {
if (E.Offset)
E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
else
E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
}
std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
BucketChain.Elements[0]);
return true;
}
bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
for (int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
if (auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
if (II->getIntrinsicID() == Intrinsic::prefetch)
continue;
if (j == 0)
break;
if (!BucketChain.Elements[j].Offset ||
cast<SCEVConstant>(BucketChain.Elements[j].Offset)->isZero())
break;
const SCEV *Offset = BucketChain.Elements[j].Offset;
BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
for (auto &E : BucketChain.Elements) {
if (E.Offset)
E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(E.Offset, Offset));
else
E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
}
std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
break;
}
return true;
}
bool PPCLoopInstrFormPrep::rewriteLoadStores(
Loop *L, Bucket &BucketChain, SmallSet<BasicBlock *, 16> &BBChanged,
PrepForm Form) {
bool MadeChange = false;
const SCEVAddRecExpr *BasePtrSCEV =
cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
if (!BasePtrSCEV->isAffine())
return MadeChange;
BasicBlock *Header = L->getHeader();
SCEVExpander SCEVE(*SE, Header->getModule()->getDataLayout(),
"loopprepare-formrewrite");
if (!SCEVE.isSafeToExpand(BasePtrSCEV->getStart()))
return MadeChange;
SmallPtrSet<Value *, 16> DeletedPtrs;
bool CanPreInc = (Form == UpdateForm ||
((Form == DSForm) &&
isa<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE)) &&
!cast<SCEVConstant>(BasePtrSCEV->getStepRecurrence(*SE))
->getAPInt()
.urem(4) &&
PreferUpdateForm));
std::pair<Instruction *, Instruction *> Base =
rewriteForBase(L, BasePtrSCEV, BucketChain.Elements.begin()->Instr,
CanPreInc, Form, SCEVE, DeletedPtrs);
if (!Base.first || !Base.second)
return MadeChange;
SmallPtrSet<Value *, 16> NewPtrs;
NewPtrs.insert(Base.first);
for (auto I = std::next(BucketChain.Elements.begin()),
IE = BucketChain.Elements.end(); I != IE; ++I) {
Value *Ptr = getPointerOperandAndType(I->Instr);
assert(Ptr && "No pointer operand");
if (NewPtrs.count(Ptr))
continue;
Instruction *NewPtr = rewriteForBucketElement(
Base, *I,
I->Offset ? cast<SCEVConstant>(I->Offset)->getValue() : nullptr,
DeletedPtrs);
assert(NewPtr && "wrong rewrite!\n");
NewPtrs.insert(NewPtr);
}
SCEVE.clear();
for (auto *Ptr : DeletedPtrs) {
if (Instruction *IDel = dyn_cast<Instruction>(Ptr))
BBChanged.insert(IDel->getParent());
RecursivelyDeleteTriviallyDeadInstructions(Ptr);
}
MadeChange = true;
SuccPrepCount++;
if (Form == DSForm && !CanPreInc)
DSFormChainRewritten++;
else if (Form == DQForm)
DQFormChainRewritten++;
else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
UpdFormChainRewritten++;
return MadeChange;
}
bool PPCLoopInstrFormPrep::updateFormPrep(Loop *L,
SmallVector<Bucket, 16> &Buckets) {
bool MadeChange = false;
if (Buckets.empty())
return MadeChange;
SmallSet<BasicBlock *, 16> BBChanged;
for (auto &Bucket : Buckets)
if (prepareBaseForUpdateFormChain(Bucket))
MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
if (MadeChange)
for (auto *BB : BBChanged)
DeleteDeadPHIs(BB);
return MadeChange;
}
bool PPCLoopInstrFormPrep::dispFormPrep(Loop *L,
SmallVector<Bucket, 16> &Buckets,
PrepForm Form) {
bool MadeChange = false;
if (Buckets.empty())
return MadeChange;
SmallSet<BasicBlock *, 16> BBChanged;
for (auto &Bucket : Buckets) {
if (Bucket.Elements.size() < DispFormPrepMinThreshold)
continue;
if (prepareBaseForDispFormChain(Bucket, Form))
MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
}
if (MadeChange)
for (auto *BB : BBChanged)
DeleteDeadPHIs(BB);
return MadeChange;
}
Value *PPCLoopInstrFormPrep::getNodeForInc(Loop *L, Instruction *MemI,
const SCEV *BasePtrIncSCEV) {
if (isa<SCEVConstant>(BasePtrIncSCEV))
return cast<SCEVConstant>(BasePtrIncSCEV)->getValue();
if (!SE->isLoopInvariant(BasePtrIncSCEV, L))
return nullptr;
BasicBlock *BB = MemI->getParent();
if (!BB)
return nullptr;
BasicBlock *LatchBB = L->getLoopLatch();
if (!LatchBB)
return nullptr;
iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
for (auto &CurrentPHI : PHIIter) {
PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
if (!CurrentPHINode)
continue;
if (!SE->isSCEVable(CurrentPHINode->getType()))
continue;
const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
if (!PHIBasePtrSCEV)
continue;
const SCEV *PHIBasePtrIncSCEV = PHIBasePtrSCEV->getStepRecurrence(*SE);
if (!PHIBasePtrIncSCEV || (PHIBasePtrIncSCEV != BasePtrIncSCEV))
continue;
if (Instruction *I = dyn_cast<Instruction>(
CurrentPHINode->getIncomingValueForBlock(LatchBB))) {
Value *StrippedBaseI = I;
while (BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBaseI))
StrippedBaseI = BC->getOperand(0);
Instruction *StrippedI = dyn_cast<Instruction>(StrippedBaseI);
if (!StrippedI)
continue;
if (StrippedI->getOpcode() == Instruction::Add ||
(StrippedI->getOpcode() == Instruction::GetElementPtr &&
StrippedI->getNumOperands() == 2)) {
if (SE->getSCEVAtScope(StrippedI->getOperand(0), L) == BasePtrIncSCEV)
return StrippedI->getOperand(0);
if (SE->getSCEVAtScope(StrippedI->getOperand(1), L) == BasePtrIncSCEV)
return StrippedI->getOperand(1);
}
}
}
return nullptr;
}
bool PPCLoopInstrFormPrep::alreadyPrepared(Loop *L, Instruction *MemI,
const SCEV *BasePtrStartSCEV,
const SCEV *BasePtrIncSCEV,
PrepForm Form) {
BasicBlock *BB = MemI->getParent();
if (!BB)
return false;
BasicBlock *PredBB = L->getLoopPredecessor();
BasicBlock *LatchBB = L->getLoopLatch();
if (!PredBB || !LatchBB)
return false;
iterator_range<BasicBlock::phi_iterator> PHIIter = BB->phis();
for (auto & CurrentPHI : PHIIter) {
PHINode *CurrentPHINode = dyn_cast<PHINode>(&CurrentPHI);
if (!CurrentPHINode)
continue;
if (!SE->isSCEVable(CurrentPHINode->getType()))
continue;
const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
const SCEVAddRecExpr *PHIBasePtrSCEV = dyn_cast<SCEVAddRecExpr>(PHISCEV);
if (!PHIBasePtrSCEV)
continue;
const SCEVConstant *PHIBasePtrIncSCEV =
dyn_cast<SCEVConstant>(PHIBasePtrSCEV->getStepRecurrence(*SE));
if (!PHIBasePtrIncSCEV)
continue;
if (CurrentPHINode->getNumIncomingValues() == 2) {
if ((CurrentPHINode->getIncomingBlock(0) == LatchBB &&
CurrentPHINode->getIncomingBlock(1) == PredBB) ||
(CurrentPHINode->getIncomingBlock(1) == LatchBB &&
CurrentPHINode->getIncomingBlock(0) == PredBB)) {
if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
if ((Form == UpdateForm || Form == ChainCommoning ) &&
PHIBasePtrSCEV->getStart() == BasePtrStartSCEV) {
++PHINodeAlreadyExistsUpdate;
return true;
}
if (Form == DSForm || Form == DQForm) {
const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
SE->getMinusSCEV(PHIBasePtrSCEV->getStart(), BasePtrStartSCEV));
if (Diff && !Diff->getAPInt().urem(Form)) {
if (Form == DSForm)
++PHINodeAlreadyExistsDS;
else
++PHINodeAlreadyExistsDQ;
return true;
}
}
}
}
}
}
return false;
}
bool PPCLoopInstrFormPrep::runOnLoop(Loop *L) {
bool MadeChange = false;
if (!L->isInnermost())
return MadeChange;
if (SuccPrepCount >= MaxVarsPrep)
return MadeChange;
LLVM_DEBUG(dbgs() << "PIP: Examining: " << *L << "\n");
BasicBlock *LoopPredecessor = L->getLoopPredecessor();
if (!LoopPredecessor ||
!LoopPredecessor->getTerminator()->getType()->isVoidTy()) {
LoopPredecessor = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
if (LoopPredecessor)
MadeChange = true;
}
if (!LoopPredecessor) {
LLVM_DEBUG(dbgs() << "PIP fails since no predecessor for current loop.\n");
return MadeChange;
}
auto isUpdateFormCandidate = [&](const Instruction *I, Value *PtrValue,
const Type *PointerElementType) {
assert((PtrValue && I) && "Invalid parameter!");
if (ST && ST->hasAltivec() && PointerElementType->isVectorTy())
return false;
auto *II = dyn_cast<IntrinsicInst>(I);
if (II && ((II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp) ||
II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp))
return false;
if (PointerElementType->isIntegerTy(64)) {
const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
const SCEVAddRecExpr *LARSCEV = dyn_cast<SCEVAddRecExpr>(LSCEV);
if (!LARSCEV || LARSCEV->getLoop() != L)
return false;
if (const SCEVConstant *StepConst =
dyn_cast<SCEVConstant>(LARSCEV->getStepRecurrence(*SE))) {
const APInt &ConstInt = StepConst->getValue()->getValue();
if (ConstInt.isSignedIntN(16) && ConstInt.srem(4) != 0)
return false;
}
}
return true;
};
auto isDSFormCandidate = [](const Instruction *I, Value *PtrValue,
const Type *PointerElementType) {
assert((PtrValue && I) && "Invalid parameter!");
if (isa<IntrinsicInst>(I))
return false;
return (PointerElementType->isIntegerTy(64)) ||
(PointerElementType->isFloatTy()) ||
(PointerElementType->isDoubleTy()) ||
(PointerElementType->isIntegerTy(32) &&
llvm::any_of(I->users(),
[](const User *U) { return isa<SExtInst>(U); }));
};
auto isDQFormCandidate = [&](const Instruction *I, Value *PtrValue,
const Type *PointerElementType) {
assert((PtrValue && I) && "Invalid parameter!");
auto *II = dyn_cast<IntrinsicInst>(I);
if (II)
return II->getIntrinsicID() == Intrinsic::ppc_vsx_lxvp ||
II->getIntrinsicID() == Intrinsic::ppc_vsx_stxvp;
return ST && ST->hasP9Vector() && (PointerElementType->isVectorTy());
};
auto isChainCommoningCandidate = [&](const Instruction *I, Value *PtrValue,
const Type *PointerElementType) {
const SCEVAddRecExpr *ARSCEV =
cast<SCEVAddRecExpr>(SE->getSCEVAtScope(PtrValue, L));
if (!ARSCEV)
return false;
if (!ARSCEV->isAffine())
return false;
const SCEV *Start = ARSCEV->getStart();
if (isa<SCEVUnknown>(Start) && Start->getType()->isPointerTy())
return true;
const SCEVAddExpr *ASCEV = dyn_cast<SCEVAddExpr>(Start);
if (!ASCEV)
return false;
bool SawPointer = false;
for (const SCEV *Op : ASCEV->operands()) {
if (Op->getType()->isPointerTy()) {
if (SawPointer)
return false;
SawPointer = true;
} else if (!Op->getType()->isIntegerTy())
return false;
}
return SawPointer;
};
auto isValidConstantDiff = [](const SCEV *Diff) {
return dyn_cast<SCEVConstant>(Diff) != nullptr;
};
auto isValidChainCommoningDiff = [](const SCEV *Diff) {
assert(Diff && "Invalid Diff!\n");
if (isa<SCEVConstant>(Diff))
return false;
if (isa<SCEVUnknown>(Diff) && Diff->getType()->isIntegerTy())
return true;
const SCEVNAryExpr *ADiff = dyn_cast<SCEVNAryExpr>(Diff);
if (!ADiff)
return false;
for (const SCEV *Op : ADiff->operands())
if (!Op->getType()->isIntegerTy())
return false;
return true;
};
HasCandidateForPrepare = false;
LLVM_DEBUG(dbgs() << "Start to prepare for update form.\n");
SmallVector<Bucket, 16> UpdateFormBuckets = collectCandidates(
L, isUpdateFormCandidate, isValidConstantDiff, MaxVarsUpdateForm);
if (!UpdateFormBuckets.empty())
MadeChange |= updateFormPrep(L, UpdateFormBuckets);
else if (!HasCandidateForPrepare) {
LLVM_DEBUG(
dbgs()
<< "No prepare candidates found, stop praparation for current loop!\n");
return MadeChange;
}
LLVM_DEBUG(dbgs() << "Start to prepare for DS form.\n");
SmallVector<Bucket, 16> DSFormBuckets = collectCandidates(
L, isDSFormCandidate, isValidConstantDiff, MaxVarsDSForm);
if (!DSFormBuckets.empty())
MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
LLVM_DEBUG(dbgs() << "Start to prepare for DQ form.\n");
SmallVector<Bucket, 16> DQFormBuckets = collectCandidates(
L, isDQFormCandidate, isValidConstantDiff, MaxVarsDQForm);
if (!DQFormBuckets.empty())
MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
if (!EnableChainCommoning) {
LLVM_DEBUG(dbgs() << "Chain commoning is not enabled.\n");
return MadeChange;
}
LLVM_DEBUG(dbgs() << "Start to prepare for chain commoning.\n");
SmallVector<Bucket, 16> Buckets =
collectCandidates(L, isChainCommoningCandidate, isValidChainCommoningDiff,
MaxVarsChainCommon);
if (!Buckets.empty())
MadeChange |= chainCommoning(L, Buckets);
return MadeChange;
}