44 #define DEBUG_TYPE "ppc-loop-instr-form-prep" 87 cl::desc(
"Potential common base number threshold per function for PPC loop " 92 cl::desc(
"prefer update form when ds form is also a update form"));
100 cl::desc(
"Potential PHI threshold per loop for PPC loop prep of update " 105 cl::desc(
"Potential PHI threshold per loop for PPC loop prep of DS form"));
109 cl::desc(
"Potential PHI threshold per loop for PPC loop prep of DQ form"));
118 cl::desc(
"Minimal common base load/store instructions triggering DS/DQ form " 121 STATISTIC(PHINodeAlreadyExistsUpdate,
"PHI node already in pre-increment form");
122 STATISTIC(PHINodeAlreadyExistsDS,
"PHI node already in DS form");
123 STATISTIC(PHINodeAlreadyExistsDQ,
"PHI node already in DQ form");
124 STATISTIC(DSFormChainRewritten,
"Num of DS form chain rewritten");
125 STATISTIC(DQFormChainRewritten,
"Num of DQ form chain rewritten");
126 STATISTIC(UpdFormChainRewritten,
"Num of update form chain rewritten");
129 struct BucketElement {
139 Elements(1, BucketElement(I)) {}
141 const SCEV *BaseSCEV;
149 enum InstrForm { UpdateForm = 1, DSForm = 4, DQForm = 16 };
184 unsigned SuccPrepCount;
186 bool runOnLoop(
Loop *L);
190 const SCEV *BasePtrStartSCEV,
197 collectCandidates(
Loop *L,
200 unsigned MaxCandidateNum);
205 unsigned MaxCandidateNum);
221 bool prepareBaseForDispFormChain(Bucket &BucketChain,
229 bool prepareBaseForUpdateFormChain(Bucket &BucketChain);
233 bool rewriteLoadStores(
Loop *L, Bucket &BucketChain,
241 static const char *
name =
"Prepare loop for ppc preferred instruction forms";
253 return new PPCLoopInstrFormPrep(TM);
257 Value *StrippedBasePtr = BasePtr;
258 while (
BitCastInst *BC = dyn_cast<BitCastInst>(StrippedBasePtr))
259 StrippedBasePtr = BC->getOperand(0);
261 return GEP->isInBounds();
267 assert(I &&
"Invalid paramater!");
269 return (I->
getName() + Suffix).str();
275 if (
LoadInst *LMemI = dyn_cast<LoadInst>(MemI)) {
276 return LMemI->getPointerOperand();
277 }
else if (
StoreInst *SMemI = dyn_cast<StoreInst>(MemI)) {
278 return SMemI->getPointerOperand();
279 }
else if (
IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(MemI)) {
281 return IMemI->getArgOperand(0);
291 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
292 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
293 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
294 DT = DTWP ? &DTWP->getDomTree() :
nullptr;
295 PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
296 ST =
TM ?
TM->getSubtargetImpl(F) :
nullptr;
299 bool MadeChange =
false;
301 for (
auto I = LI->begin(),
IE = LI->end();
I !=
IE; ++
I)
303 MadeChange |= runOnLoop(*L);
308 void PPCLoopInstrFormPrep::addOneCandidate(
Instruction *MemI,
const SCEV *LSCEV,
310 unsigned MaxCandidateNum) {
312 "Candidate should be a memory instruction.");
313 assert(LSCEV &&
"Invalid SCEV for Ptr value.");
314 bool FoundBucket =
false;
315 for (
auto &
B : Buckets) {
316 const SCEV *Diff = SE->getMinusSCEV(LSCEV,
B.BaseSCEV);
317 if (
const auto *CDiff = dyn_cast<SCEVConstant>(Diff)) {
318 B.Elements.push_back(BucketElement(CDiff, MemI));
325 if (Buckets.size() == MaxCandidateNum)
327 Buckets.push_back(Bucket(LSCEV, MemI));
334 unsigned MaxCandidateNum) {
336 for (
const auto &BB : L->
blocks())
337 for (
auto &J : *BB) {
341 if (
LoadInst *LMemI = dyn_cast<LoadInst>(&J)) {
343 PtrValue = LMemI->getPointerOperand();
344 }
else if (
StoreInst *SMemI = dyn_cast<StoreInst>(&J)) {
346 PtrValue = SMemI->getPointerOperand();
347 }
else if (
IntrinsicInst *IMemI = dyn_cast<IntrinsicInst>(&J)) {
350 PtrValue = IMemI->getArgOperand(0);
361 const SCEV *LSCEV = SE->getSCEVAtScope(PtrValue, L);
363 if (!LARSCEV || LARSCEV->
getLoop() != L)
366 if (isValidCandidate(&J, PtrValue))
367 addOneCandidate(MemI, LSCEV, Buckets, MaxCandidateNum);
372 bool PPCLoopInstrFormPrep::prepareBaseForDispFormChain(Bucket &BucketChain,
382 for (
unsigned j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
383 if (!BucketChain.Elements[j].Offset)
384 RemainderOffsetInfo[0] = std::make_pair(0, 1);
387 BucketChain.Elements[j].Offset->getAPInt().urem(Form);
388 if (RemainderOffsetInfo.
find(Remainder) == RemainderOffsetInfo.
end())
389 RemainderOffsetInfo[Remainder] = std::make_pair(j, 1);
391 RemainderOffsetInfo[Remainder].second++;
409 unsigned MaxCountRemainder = 0;
410 for (
unsigned j = 0; j < (
unsigned)Form; j++)
411 if ((RemainderOffsetInfo.
find(j) != RemainderOffsetInfo.
end()) &&
412 RemainderOffsetInfo[j].
second >
413 RemainderOffsetInfo[MaxCountRemainder].
second)
414 MaxCountRemainder = j;
422 if (MaxCountRemainder == 0)
427 BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first].Offset;
428 BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
429 for (
auto &
E : BucketChain.Elements) {
431 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(
E.Offset, Offset));
433 E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
436 std::swap(BucketChain.Elements[RemainderOffsetInfo[MaxCountRemainder].first],
437 BucketChain.Elements[0]);
447 bool PPCLoopInstrFormPrep::prepareBaseForUpdateFormChain(Bucket &BucketChain) {
457 for (
int j = 0, je = BucketChain.Elements.size(); j != je; ++j) {
458 if (
auto *II = dyn_cast<IntrinsicInst>(BucketChain.Elements[j].Instr))
468 if (!BucketChain.Elements[j].Offset ||
469 BucketChain.Elements[j].Offset->isZero())
472 const SCEV *
Offset = BucketChain.Elements[j].Offset;
473 BucketChain.BaseSCEV = SE->getAddExpr(BucketChain.BaseSCEV, Offset);
474 for (
auto &
E : BucketChain.Elements) {
476 E.Offset = cast<SCEVConstant>(SE->getMinusSCEV(
E.Offset, Offset));
478 E.Offset = cast<SCEVConstant>(SE->getNegativeSCEV(Offset));
481 std::swap(BucketChain.Elements[j], BucketChain.Elements[0]);
487 bool PPCLoopInstrFormPrep::rewriteLoadStores(
Loop *L, Bucket &BucketChain,
490 bool MadeChange =
false;
492 cast<SCEVAddRecExpr>(BucketChain.BaseSCEV);
496 LLVM_DEBUG(
dbgs() <<
"PIP: Transforming: " << *BasePtrSCEV <<
"\n");
498 assert(BasePtrSCEV->
getLoop() == L &&
"AddRec for the wrong loop?");
502 Instruction *MemI = BucketChain.Elements.begin()->Instr;
504 assert(BasePtr &&
"No pointer operand");
510 if (!SE->isLoopInvariant(BasePtrSCEV->
getStart(), L))
520 bool CanPreInc = (Form == UpdateForm ||
521 ((Form == DSForm) && !BasePtrIncSCEV->
getAPInt().
urem(4) &&
523 const SCEV *BasePtrStartSCEV =
nullptr;
526 SE->getMinusSCEV(BasePtrSCEV->
getStart(), BasePtrIncSCEV);
528 BasePtrStartSCEV = BasePtrSCEV->
getStart();
533 if (alreadyPrepared(L, MemI, BasePtrStartSCEV, BasePtrIncSCEV, Form))
536 LLVM_DEBUG(
dbgs() <<
"PIP: New start is: " << *BasePtrStartSCEV <<
"\n");
539 unsigned HeaderLoopPredCount =
pred_size(Header);
548 Value *BasePtrStart = SCEVE.expandCodeFor(BasePtrStartSCEV, I8PtrTy,
554 if (PI != LoopPredecessor)
557 NewPHI->
addIncoming(BasePtrStart, LoopPredecessor);
565 I8Ty, NewPHI, BasePtrIncSCEV->
getValue(),
567 cast<GetElementPtrInst>(PtrInc)->setIsInBounds(
IsPtrInBounds(BasePtr));
569 if (PI == LoopPredecessor)
584 if (PI == LoopPredecessor)
592 I8Ty, NewPHI, BasePtrIncSCEV->
getValue(),
595 cast<GetElementPtrInst>(PtrInc)->setIsInBounds(
IsPtrInBounds(BasePtr));
609 if (
Instruction *IDel = dyn_cast<Instruction>(BasePtr))
610 BBChanged.
insert(IDel->getParent());
617 NewPtrs.
insert(NewBasePtr);
619 for (
auto I = std::next(BucketChain.Elements.begin()),
620 IE = BucketChain.Elements.end();
I !=
IE; ++
I) {
622 assert(Ptr &&
"No pointer operand");
623 if (NewPtrs.
count(Ptr))
627 if (!
I->Offset ||
I->Offset->getValue()->isZero()) {
628 RealNewPtr = NewBasePtr;
631 if (PtrIP && isa<Instruction>(NewBasePtr) &&
634 else if (PtrIP && isa<PHINode>(PtrIP))
640 I8Ty, PtrInc,
I->Offset->getValue(),
648 if (
Instruction *IDel = dyn_cast<Instruction>(Ptr))
649 BBChanged.
insert(IDel->getParent());
657 ReplNewPtr = RealNewPtr;
662 NewPtrs.
insert(RealNewPtr);
669 if (Form == DSForm && !CanPreInc)
670 DSFormChainRewritten++;
671 else if (Form == DQForm)
672 DQFormChainRewritten++;
673 else if (Form == UpdateForm || (Form == DSForm && CanPreInc))
674 UpdFormChainRewritten++;
679 bool PPCLoopInstrFormPrep::updateFormPrep(
Loop *L,
681 bool MadeChange =
false;
685 for (
auto &Bucket : Buckets)
688 if (prepareBaseForUpdateFormChain(Bucket))
689 MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, UpdateForm);
692 for (
auto &BB : L->
blocks())
693 if (BBChanged.
count(BB))
700 bool MadeChange =
false;
706 for (
auto &Bucket : Buckets) {
709 if (prepareBaseForDispFormChain(Bucket, Form))
710 MadeChange |= rewriteLoadStores(L, Bucket, BBChanged, Form);
714 for (
auto &BB : L->
blocks())
715 if (BBChanged.
count(BB))
725 const SCEV *BasePtrStartSCEV,
735 if (!PredBB || !LatchBB)
740 for (
auto & CurrentPHI : PHIIter) {
745 if (!SE->isSCEVable(CurrentPHINode->
getType()))
748 const SCEV *PHISCEV = SE->getSCEVAtScope(CurrentPHINode, L);
756 if (!PHIBasePtrIncSCEV)
764 if (PHIBasePtrIncSCEV == BasePtrIncSCEV) {
767 if (Form == UpdateForm &&
768 PHIBasePtrSCEV->
getStart() == BasePtrStartSCEV) {
769 ++PHINodeAlreadyExistsUpdate;
772 if (Form == DSForm || Form == DQForm) {
774 SE->getMinusSCEV(PHIBasePtrSCEV->
getStart(), BasePtrStartSCEV));
777 ++PHINodeAlreadyExistsDS;
779 ++PHINodeAlreadyExistsDQ;
790 bool PPCLoopInstrFormPrep::runOnLoop(
Loop *L) {
791 bool MadeChange =
false;
807 if (!LoopPredecessor ||
813 if (!LoopPredecessor) {
814 LLVM_DEBUG(
dbgs() <<
"PIP fails since no predecessor for current loop.\n");
820 const Value *PtrValue) {
821 assert((PtrValue && I) &&
"Invalid parameter!");
823 if (
ST &&
ST->hasAltivec() &&
824 PtrValue->getType()->getPointerElementType()->isVectorTy())
831 if (PtrValue->getType()->getPointerElementType()->isIntegerTy(64)) {
832 const SCEV *LSCEV = SE->getSCEVAtScope(const_cast<Value *>(PtrValue), L);
834 if (!LARSCEV || LARSCEV->
getLoop() != L)
838 const APInt &ConstInt = StepConst->getValue()->getValue();
848 assert((PtrValue && I) &&
"Invalid parameter!");
849 if (isa<IntrinsicInst>(I))
857 [](
const User *U) {
return isa<SExtInst>(U); }));
862 assert((PtrValue && I) &&
"Invalid parameter!");
863 return !isa<IntrinsicInst>(
I) &&
ST &&
ST->hasP9Vector() &&
864 (PtrValue->getType()->getPointerElementType()->isVectorTy());
872 if (!UpdateFormBuckets.
empty())
873 MadeChange |= updateFormPrep(L, UpdateFormBuckets);
881 if (!DSFormBuckets.
empty())
882 MadeChange |= dispFormPrep(L, DSFormBuckets, DSForm);
890 if (!DQFormBuckets.
empty())
891 MadeChange |= dispFormPrep(L, DQFormBuckets, DQForm);
void initializePPCLoopInstrFormPrepPass(PassRegistry &)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
The main scalar evolution driver.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
STATISTIC(NumFunctions, "Total number of functions")
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Type * getPointerElementType() const
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void setIsInBounds(bool b=true)
Set or clear the inbounds flag on this GEP instruction.
bool isIntegerTy() const
True if this is an instance of IntegerType.
const APInt & getAPInt() const
BlockT * getHeader() const
ConstantInt * getValue() const
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
This class represents a no-op cast from one type to another.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type cast(const Y &Val)
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
APInt urem(const APInt &RHS) const
Unsigned remainder operation.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
df_iterator< T > df_end(const T &G)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
FunctionPass class - This class is used to implement most global optimizations.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const SCEV * getStart() const
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Common code between 32-bit and 64-bit PowerPC targets.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
df_iterator< T > df_begin(const T &G)
A range adaptor for a pair of iterators.
FunctionPass * createPPCLoopInstrFormPrepPass(PPCTargetMachine &TM)
Class for arbitrary precision integers.
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
static const Function * getParent(const Value *V)
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
The legacy pass manager's analysis pass to compute loop information.
print Print MemDeps of function
Legacy analysis pass which computes a DominatorTree.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
iterator_range< block_iterator > blocks() const
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
static IntegerType * getInt8Ty(LLVMContext &C)
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This class represents a constant integer value.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.