NaryReassociate.cpp [plain text]
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "nary-reassociate"
namespace {
class NaryReassociate : public FunctionPass {
public:
static char ID;
NaryReassociate(): FunctionPass(ID) {
initializeNaryReassociatePass(*PassRegistry::getPassRegistry());
}
bool doInitialization(Module &M) override {
DL = &M.getDataLayout();
return false;
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<ScalarEvolutionWrapperPass>();
AU.addPreserved<TargetLibraryInfoWrapperPass>();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.setPreservesCFG();
}
private:
bool doOneIteration(Function &F);
Instruction *tryReassociate(Instruction *I);
Instruction *tryReassociateGEP(GetElementPtrInst *GEP);
GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
unsigned I, Type *IndexedType);
GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
unsigned I, Value *LHS,
Value *RHS, Type *IndexedType);
Instruction *tryReassociateBinaryOp(BinaryOperator *I);
Instruction *tryReassociateBinaryOp(Value *LHS, Value *RHS,
BinaryOperator *I);
Instruction *tryReassociatedBinaryOp(const SCEV *LHS, Value *RHS,
BinaryOperator *I);
bool matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1, Value *&Op2);
const SCEV *getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
const SCEV *RHS);
Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr,
Instruction *Dominatee);
bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP);
AssumptionCache *AC;
const DataLayout *DL;
DominatorTree *DT;
ScalarEvolution *SE;
TargetLibraryInfo *TLI;
TargetTransformInfo *TTI;
DenseMap<const SCEV *, SmallVector<WeakVH, 2>> SeenExprs;
};
}
char NaryReassociate::ID = 0;
INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation",
false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation",
false, false)
FunctionPass *llvm::createNaryReassociatePass() {
return new NaryReassociate();
}
bool NaryReassociate::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
bool Changed = false, ChangedInThisIteration;
do {
ChangedInThisIteration = doOneIteration(F);
Changed |= ChangedInThisIteration;
} while (ChangedInThisIteration);
return Changed;
}
static bool isPotentiallyNaryReassociable(Instruction *I) {
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::GetElementPtr:
case Instruction::Mul:
return true;
default:
return false;
}
}
bool NaryReassociate::doOneIteration(Function &F) {
bool Changed = false;
SeenExprs.clear();
for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
BasicBlock *BB = Node->getBlock();
for (auto I = BB->begin(); I != BB->end(); ++I) {
if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(&*I)) {
const SCEV *OldSCEV = SE->getSCEV(&*I);
if (Instruction *NewI = tryReassociate(&*I)) {
Changed = true;
SE->forgetValue(&*I);
I->replaceAllUsesWith(NewI);
RecursivelyDeleteTriviallyDeadInstructions(&*I, TLI);
I = NewI->getIterator();
}
const SCEV *NewSCEV = SE->getSCEV(&*I);
SeenExprs[NewSCEV].push_back(WeakVH(&*I));
if (NewSCEV != OldSCEV)
SeenExprs[OldSCEV].push_back(WeakVH(&*I));
}
}
}
return Changed;
}
Instruction *NaryReassociate::tryReassociate(Instruction *I) {
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Mul:
return tryReassociateBinaryOp(cast<BinaryOperator>(I));
case Instruction::GetElementPtr:
return tryReassociateGEP(cast<GetElementPtrInst>(I));
default:
llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable");
}
}
static bool isGEPFoldable(GetElementPtrInst *GEP,
const TargetTransformInfo *TTI,
const DataLayout *DL) {
GlobalVariable *BaseGV = nullptr;
int64_t BaseOffset = 0;
bool HasBaseReg = false;
int64_t Scale = 0;
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand()))
BaseGV = GV;
else
HasBaseReg = true;
gep_type_iterator GTI = gep_type_begin(GEP);
for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) {
if (isa<SequentialType>(*GTI)) {
int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) {
BaseOffset += ConstIdx->getSExtValue() * ElementSize;
} else {
if (Scale != 0) {
return false;
}
Scale = ElementSize;
}
} else {
StructType *STy = cast<StructType>(*GTI);
uint64_t Field = cast<ConstantInt>(*I)->getZExtValue();
BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field);
}
}
unsigned AddrSpace = GEP->getPointerAddressSpace();
return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV,
BaseOffset, HasBaseReg, Scale, AddrSpace);
}
Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) {
if (isGEPFoldable(GEP, TTI, DL))
return nullptr;
gep_type_iterator GTI = gep_type_begin(*GEP);
for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) {
if (isa<SequentialType>(*GTI++)) {
if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) {
return NewGEP;
}
}
}
return nullptr;
}
bool NaryReassociate::requiresSignExtension(Value *Index,
GetElementPtrInst *GEP) {
unsigned PointerSizeInBits =
DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace());
return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits;
}
GetElementPtrInst *
NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I,
Type *IndexedType) {
Value *IndexToSplit = GEP->getOperand(I + 1);
if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) {
IndexToSplit = SExt->getOperand(0);
} else if (ZExtInst *ZExt = dyn_cast<ZExtInst>(IndexToSplit)) {
if (isKnownNonNegative(ZExt->getOperand(0), *DL, 0, AC, GEP, DT))
IndexToSplit = ZExt->getOperand(0);
}
if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) {
if (requiresSignExtension(IndexToSplit, GEP) &&
computeOverflowForSignedAdd(AO, *DL, AC, GEP, DT) !=
OverflowResult::NeverOverflows)
return nullptr;
Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1);
if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType))
return NewGEP;
if (LHS != RHS) {
if (auto *NewGEP =
tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType))
return NewGEP;
}
}
return nullptr;
}
GetElementPtrInst *NaryReassociate::tryReassociateGEPAtIndex(
GetElementPtrInst *GEP, unsigned I, Value *LHS, Value *RHS,
Type *IndexedType) {
SmallVector<const SCEV *, 4> IndexExprs;
for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
IndexExprs.push_back(SE->getSCEV(*Index));
IndexExprs[I] = SE->getSCEV(LHS);
if (isKnownNonNegative(LHS, *DL, 0, AC, GEP, DT) &&
DL->getTypeSizeInBits(LHS->getType()) <
DL->getTypeSizeInBits(GEP->getOperand(I)->getType())) {
IndexExprs[I] =
SE->getZeroExtendExpr(IndexExprs[I], GEP->getOperand(I)->getType());
}
const SCEV *CandidateExpr = SE->getGEPExpr(
GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()),
IndexExprs, GEP->isInBounds());
auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP);
if (Candidate == nullptr)
return nullptr;
PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType());
if (TypeOfCandidate == nullptr)
return nullptr;
uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType);
Type *ElementType = TypeOfCandidate->getElementType();
uint64_t ElementSize = DL->getTypeAllocSize(ElementType);
if (IndexedSize % ElementSize != 0)
return nullptr;
IRBuilder<> Builder(GEP);
Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate);
if (RHS->getType() != IntPtrTy)
RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy);
if (IndexedSize != ElementSize) {
RHS = Builder.CreateMul(
RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize));
}
GetElementPtrInst *NewGEP =
cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS));
NewGEP->setIsInBounds(GEP->isInBounds());
NewGEP->takeName(GEP);
return NewGEP;
}
Instruction *NaryReassociate::tryReassociateBinaryOp(BinaryOperator *I) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
if (auto *NewI = tryReassociateBinaryOp(LHS, RHS, I))
return NewI;
if (auto *NewI = tryReassociateBinaryOp(RHS, LHS, I))
return NewI;
return nullptr;
}
Instruction *NaryReassociate::tryReassociateBinaryOp(Value *LHS, Value *RHS,
BinaryOperator *I) {
Value *A = nullptr, *B = nullptr;
if (LHS->hasOneUse() && matchTernaryOp(I, LHS, A, B)) {
const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B);
const SCEV *RHSExpr = SE->getSCEV(RHS);
if (BExpr != RHSExpr) {
if (auto *NewI =
tryReassociatedBinaryOp(getBinarySCEV(I, AExpr, RHSExpr), B, I))
return NewI;
}
if (AExpr != RHSExpr) {
if (auto *NewI =
tryReassociatedBinaryOp(getBinarySCEV(I, BExpr, RHSExpr), A, I))
return NewI;
}
}
return nullptr;
}
Instruction *NaryReassociate::tryReassociatedBinaryOp(const SCEV *LHSExpr,
Value *RHS,
BinaryOperator *I) {
auto *LHS = findClosestMatchingDominator(LHSExpr, I);
if (LHS == nullptr)
return nullptr;
Instruction *NewI = nullptr;
switch (I->getOpcode()) {
case Instruction::Add:
NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I);
break;
case Instruction::Mul:
NewI = BinaryOperator::CreateMul(LHS, RHS, "", I);
break;
default:
llvm_unreachable("Unexpected instruction.");
}
NewI->takeName(I);
return NewI;
}
bool NaryReassociate::matchTernaryOp(BinaryOperator *I, Value *V, Value *&Op1,
Value *&Op2) {
switch (I->getOpcode()) {
case Instruction::Add:
return match(V, m_Add(m_Value(Op1), m_Value(Op2)));
case Instruction::Mul:
return match(V, m_Mul(m_Value(Op1), m_Value(Op2)));
default:
llvm_unreachable("Unexpected instruction.");
}
return false;
}
const SCEV *NaryReassociate::getBinarySCEV(BinaryOperator *I, const SCEV *LHS,
const SCEV *RHS) {
switch (I->getOpcode()) {
case Instruction::Add:
return SE->getAddExpr(LHS, RHS);
case Instruction::Mul:
return SE->getMulExpr(LHS, RHS);
default:
llvm_unreachable("Unexpected instruction.");
}
return nullptr;
}
Instruction *
NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr,
Instruction *Dominatee) {
auto Pos = SeenExprs.find(CandidateExpr);
if (Pos == SeenExprs.end())
return nullptr;
auto &Candidates = Pos->second;
while (!Candidates.empty()) {
if (Value *Candidate = Candidates.back()) {
Instruction *CandidateInstruction = cast<Instruction>(Candidate);
if (DT->dominates(CandidateInstruction, Dominatee))
return CandidateInstruction;
}
Candidates.pop_back();
}
return nullptr;
}