#include "llvm/Transforms/Vectorize/VectorCombine.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/BasicAliasAnalysis.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Vectorize.h"
#define DEBUG_TYPE "vector-combine"
#include "llvm/Transforms/Utils/InstructionWorklist.h"
using namespace llvm;
using namespace llvm::PatternMatch;
STATISTIC(NumVecLoad, "Number of vector loads formed");
STATISTIC(NumVecCmp, "Number of vector compares formed");
STATISTIC(NumVecBO, "Number of vector binops formed");
STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
STATISTIC(NumScalarBO, "Number of scalar binops formed");
STATISTIC(NumScalarCmp, "Number of scalar compares formed");
static cl::opt<bool> DisableVectorCombine(
"disable-vector-combine", cl::init(false), cl::Hidden,
cl::desc("Disable all vector combine transforms"));
static cl::opt<bool> DisableBinopExtractShuffle(
"disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
cl::desc("Disable binop extract to shuffle transforms"));
static cl::opt<unsigned> MaxInstrsToScan(
"vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
cl::desc("Max number of instructions to scan for vector combining."));
static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
namespace {
class VectorCombine {
public:
VectorCombine(Function &F, const TargetTransformInfo &TTI,
const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
bool ScalarizationOnly)
: F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC),
ScalarizationOnly(ScalarizationOnly) {}
bool run();
private:
Function &F;
IRBuilder<> Builder;
const TargetTransformInfo &TTI;
const DominatorTree &DT;
AAResults &AA;
AssumptionCache &AC;
bool ScalarizationOnly;
InstructionWorklist Worklist;
bool vectorizeLoadInsert(Instruction &I);
ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
ExtractElementInst *Ext1,
unsigned PreferredExtractIndex) const;
bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
const Instruction &I,
ExtractElementInst *&ConvertToShuffle,
unsigned PreferredExtractIndex);
void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
Instruction &I);
void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
Instruction &I);
bool foldExtractExtract(Instruction &I);
bool foldBitcastShuf(Instruction &I);
bool scalarizeBinopOrCmp(Instruction &I);
bool foldExtractedCmps(Instruction &I);
bool foldSingleElementStore(Instruction &I);
bool scalarizeLoadExtract(Instruction &I);
bool foldShuffleOfBinops(Instruction &I);
bool foldShuffleFromReductions(Instruction &I);
bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
void replaceValue(Value &Old, Value &New) {
Old.replaceAllUsesWith(&New);
if (auto *NewI = dyn_cast<Instruction>(&New)) {
New.takeName(&Old);
Worklist.pushUsersToWorkList(*NewI);
Worklist.pushValue(NewI);
}
Worklist.pushValue(&Old);
}
void eraseInstruction(Instruction &I) {
for (Value *Op : I.operands())
Worklist.pushValue(Op);
Worklist.remove(&I);
I.eraseFromParent();
}
};
}
bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
auto *Ty = dyn_cast<FixedVectorType>(I.getType());
Value *Scalar;
if (!Ty || !match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
!Scalar->hasOneUse())
return false;
Value *X;
bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
if (!HasExtract)
X = Scalar;
auto *Load = dyn_cast<LoadInst>(X);
if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
mustSuppressSpeculation(*Load))
return false;
const DataLayout &DL = I.getModule()->getDataLayout();
Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
unsigned AS = Load->getPointerAddressSpace();
Type *ScalarTy = Scalar->getType();
uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
ScalarSize % 8 != 0)
return false;
unsigned MinVecNumElts = MinVectorSize / ScalarSize;
auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
unsigned OffsetEltIndex = 0;
Align Alignment = Load->getAlign();
if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT)) {
unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
APInt Offset(OffsetBitWidth, 0);
SrcPtr = SrcPtr->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
if (Offset.isNegative())
return false;
uint64_t ScalarSizeInBytes = ScalarSize / 8;
if (Offset.urem(ScalarSizeInBytes) != 0)
return false;
OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
if (OffsetEltIndex >= MinVecNumElts)
return false;
if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &DT))
return false;
Alignment = commonAlignment(Alignment, Offset.getZExtValue());
}
Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
Type *LoadTy = Load->getType();
InstructionCost OldCost =
TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
true, HasExtract);
InstructionCost NewCost =
TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
unsigned OutputNumElts = Ty->getNumElements();
SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem);
assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
Mask[0] = OffsetEltIndex;
if (OffsetEltIndex)
NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
if (OldCost < NewCost || !NewCost.isValid())
return false;
IRBuilder<> Builder(Load);
Value *CastedPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
SrcPtr, MinVecTy->getPointerTo(AS));
Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
VecLd = Builder.CreateShuffleVector(VecLd, Mask);
replaceValue(I, *VecLd);
++NumVecLoad;
return true;
}
ExtractElementInst *VectorCombine::getShuffleExtract(
ExtractElementInst *Ext0, ExtractElementInst *Ext1,
unsigned PreferredExtractIndex = InvalidIndex) const {
auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
assert(Index0C && Index1C && "Expected constant extract indexes");
unsigned Index0 = Index0C->getZExtValue();
unsigned Index1 = Index1C->getZExtValue();
if (Index0 == Index1)
return nullptr;
Type *VecTy = Ext0->getVectorOperand()->getType();
assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
InstructionCost Cost0 =
TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
InstructionCost Cost1 =
TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
if (!Cost0.isValid() && !Cost1.isValid())
return nullptr;
if (Cost0 > Cost1)
return Ext0;
if (Cost1 > Cost0)
return Ext1;
if (PreferredExtractIndex == Index0)
return Ext1;
if (PreferredExtractIndex == Index1)
return Ext0;
return Index0 > Index1 ? Ext0 : Ext1;
}
bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
ExtractElementInst *Ext1,
const Instruction &I,
ExtractElementInst *&ConvertToShuffle,
unsigned PreferredExtractIndex) {
auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
unsigned Opcode = I.getOpcode();
Type *ScalarTy = Ext0->getType();
auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
InstructionCost ScalarOpCost, VectorOpCost;
bool IsBinOp = Instruction::isBinaryOp(Opcode);
if (IsBinOp) {
ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
} else {
assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
"Expected a compare");
CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
ScalarOpCost = TTI.getCmpSelInstrCost(
Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
VectorOpCost = TTI.getCmpSelInstrCost(
Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
}
unsigned Ext0Index = Ext0IndexC->getZExtValue();
unsigned Ext1Index = Ext1IndexC->getZExtValue();
InstructionCost Extract0Cost =
TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index);
InstructionCost Extract1Cost =
TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index);
InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
InstructionCost OldCost, NewCost;
if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
: !Ext0->hasOneUse() || !Ext1->hasOneUse();
OldCost = CheapExtractCost + ScalarOpCost;
NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
} else {
OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
NewCost = VectorOpCost + CheapExtractCost +
!Ext0->hasOneUse() * Extract0Cost +
!Ext1->hasOneUse() * Extract1Cost;
}
ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
if (ConvertToShuffle) {
if (IsBinOp && DisableBinopExtractShuffle)
return true;
NewCost +=
TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
}
return OldCost < NewCost;
}
static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
unsigned NewIndex, IRBuilder<> &Builder) {
auto *VecTy = cast<FixedVectorType>(Vec->getType());
SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
ShufMask[NewIndex] = OldIndex;
return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
}
static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt,
unsigned NewIndex,
IRBuilder<> &Builder) {
if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
return nullptr;
Value *X = ExtElt->getVectorOperand();
Value *C = ExtElt->getIndexOperand();
assert(isa<ConstantInt>(C) && "Expected a constant index operand");
if (isa<Constant>(X))
return nullptr;
Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
NewIndex, Builder);
return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
}
void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
ExtractElementInst *Ext1, Instruction &I) {
assert(isa<CmpInst>(&I) && "Expected a compare");
assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
"Expected matching constant extract indexes");
++NumVecCmp;
CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
replaceValue(I, *NewExt);
}
void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
ExtractElementInst *Ext1, Instruction &I) {
assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
"Expected matching constant extract indexes");
++NumVecBO;
Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
Value *VecBO =
Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
VecBOInst->copyIRFlags(&I);
Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
replaceValue(I, *NewExt);
}
bool VectorCombine::foldExtractExtract(Instruction &I) {
if (!isSafeToSpeculativelyExecute(&I))
return false;
Instruction *I0, *I1;
CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
!match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1))))
return false;
Value *V0, *V1;
uint64_t C0, C1;
if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
!match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
V0->getType() != V1->getType())
return false;
auto *Ext0 = cast<ExtractElementInst>(I0);
auto *Ext1 = cast<ExtractElementInst>(I1);
uint64_t InsertIndex = InvalidIndex;
if (I.hasOneUse())
match(I.user_back(),
m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
ExtractElementInst *ExtractToChange;
if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
return false;
if (ExtractToChange) {
unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
ExtractElementInst *NewExtract =
translateExtract(ExtractToChange, CheapExtractIdx, Builder);
if (!NewExtract)
return false;
if (ExtractToChange == Ext0)
Ext0 = NewExtract;
else
Ext1 = NewExtract;
}
if (Pred != CmpInst::BAD_ICMP_PREDICATE)
foldExtExtCmp(Ext0, Ext1, I);
else
foldExtExtBinop(Ext0, Ext1, I);
Worklist.push(Ext0);
Worklist.push(Ext1);
return true;
}
bool VectorCombine::foldBitcastShuf(Instruction &I) {
Value *V;
ArrayRef<int> Mask;
if (!match(&I, m_BitCast(
m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
return false;
auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy)
return false;
unsigned DestNumElts = DestTy->getNumElements();
unsigned SrcNumElts = SrcTy->getNumElements();
SmallVector<int, 16> NewMask;
if (SrcNumElts <= DestNumElts) {
assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
unsigned ScaleFactor = DestNumElts / SrcNumElts;
narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
} else {
assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
unsigned ScaleFactor = SrcNumElts / DestNumElts;
if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
return false;
}
InstructionCost DestCost = TTI.getShuffleCost(
TargetTransformInfo::SK_PermuteSingleSrc, DestTy, NewMask);
InstructionCost SrcCost =
TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy, Mask);
if (DestCost > SrcCost || !DestCost.isValid())
return false;
++NumShufOfBitcast;
Value *CastV = Builder.CreateBitCast(V, DestTy);
Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
replaceValue(I, *Shuf);
return true;
}
bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Value *Ins0, *Ins1;
if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
!match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
return false;
bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
if (IsCmp)
for (User *U : I.users())
if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
return false;
Constant *VecC0 = nullptr, *VecC1 = nullptr;
Value *V0 = nullptr, *V1 = nullptr;
uint64_t Index0 = 0, Index1 = 0;
if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
m_ConstantInt(Index0))) &&
!match(Ins0, m_Constant(VecC0)))
return false;
if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
m_ConstantInt(Index1))) &&
!match(Ins1, m_Constant(VecC1)))
return false;
bool IsConst0 = !V0;
bool IsConst1 = !V1;
if (IsConst0 && IsConst1)
return false;
if (!IsConst0 && !IsConst1 && Index0 != Index1)
return false;
auto *I0 = dyn_cast_or_null<Instruction>(V0);
auto *I1 = dyn_cast_or_null<Instruction>(V1);
if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
(IsConst1 && I0 && I0->mayReadFromMemory()))
return false;
uint64_t Index = IsConst0 ? Index1 : Index0;
Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
Type *VecTy = I.getType();
assert(VecTy->isVectorTy() &&
(IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
(ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
ScalarTy->isPointerTy()) &&
"Unexpected types for insert element into binop or cmp");
unsigned Opcode = I.getOpcode();
InstructionCost ScalarOpCost, VectorOpCost;
if (IsCmp) {
CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
ScalarOpCost = TTI.getCmpSelInstrCost(
Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
VectorOpCost = TTI.getCmpSelInstrCost(
Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
} else {
ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
}
InstructionCost InsertCost =
TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index);
InstructionCost OldCost =
(IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
InstructionCost NewCost = ScalarOpCost + InsertCost +
(IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
(IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
if (OldCost < NewCost || !NewCost.isValid())
return false;
if (IsCmp)
++NumScalarCmp;
else
++NumScalarBO;
if (IsConst0)
V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
if (IsConst1)
V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
Value *Scalar =
IsCmp ? Builder.CreateCmp(Pred, V0, V1)
: Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
Scalar->setName(I.getName() + ".scalar");
if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
ScalarInst->copyIRFlags(&I);
Value *NewVecC =
IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
: Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
replaceValue(I, *Insert);
return true;
}
bool VectorCombine::foldExtractedCmps(Instruction &I) {
if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
return false;
Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
Instruction *I0, *I1;
Constant *C0, *C1;
CmpInst::Predicate P0, P1;
if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
!match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
P0 != P1)
return false;
Value *X;
uint64_t Index0, Index1;
if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
!match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1)))))
return false;
auto *Ext0 = cast<ExtractElementInst>(I0);
auto *Ext1 = cast<ExtractElementInst>(I1);
ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
if (!ConvertToShuf)
return false;
CmpInst::Predicate Pred = P0;
unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
: Instruction::ICmp;
auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
if (!VecTy)
return false;
InstructionCost OldCost =
TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0);
OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1);
OldCost +=
TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
CmpInst::makeCmpResultType(I0->getType()), Pred) *
2;
OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
InstructionCost NewCost = TTI.getCmpSelInstrCost(
CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem);
ShufMask[CheapIndex] = ExpensiveIndex;
NewCost += TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy,
ShufMask);
NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex);
if (OldCost < NewCost || !NewCost.isValid())
return false;
SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
UndefValue::get(VecTy->getElementType()));
CmpC[Index0] = C0;
CmpC[Index1] = C1;
Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
VCmp, Shuf);
Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
replaceValue(I, *NewExt);
++NumVecCmpBO;
return true;
}
static bool isMemModifiedBetween(BasicBlock::iterator Begin,
BasicBlock::iterator End,
const MemoryLocation &Loc, AAResults &AA) {
unsigned NumScanned = 0;
return std::any_of(Begin, End, [&](const Instruction &Instr) {
return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
++NumScanned > MaxInstrsToScan;
});
}
class ScalarizationResult {
enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
StatusTy Status;
Value *ToFreeze;
ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
: Status(Status), ToFreeze(ToFreeze) {}
public:
ScalarizationResult(const ScalarizationResult &Other) = default;
~ScalarizationResult() {
assert(!ToFreeze && "freeze() not called with ToFreeze being set");
}
static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
static ScalarizationResult safe() { return {StatusTy::Safe}; }
static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
return {StatusTy::SafeWithFreeze, ToFreeze};
}
bool isSafe() const { return Status == StatusTy::Safe; }
bool isUnsafe() const { return Status == StatusTy::Unsafe; }
bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
void discard() {
ToFreeze = nullptr;
Status = StatusTy::Unsafe;
}
void freeze(IRBuilder<> &Builder, Instruction &UserI) {
assert(isSafeWithFreeze() &&
"should only be used when freezing is required");
assert(is_contained(ToFreeze->users(), &UserI) &&
"UserI must be a user of ToFreeze");
IRBuilder<>::InsertPointGuard Guard(Builder);
Builder.SetInsertPoint(cast<Instruction>(&UserI));
Value *Frozen =
Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
for (Use &U : make_early_inc_range((UserI.operands())))
if (U.get() == ToFreeze)
U.set(Frozen);
ToFreeze = nullptr;
}
};
static ScalarizationResult canScalarizeAccess(FixedVectorType *VecTy,
Value *Idx, Instruction *CtxI,
AssumptionCache &AC,
const DominatorTree &DT) {
if (auto *C = dyn_cast<ConstantInt>(Idx)) {
if (C->getValue().ult(VecTy->getNumElements()))
return ScalarizationResult::safe();
return ScalarizationResult::unsafe();
}
unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
APInt Zero(IntWidth, 0);
APInt MaxElts(IntWidth, VecTy->getNumElements());
ConstantRange ValidIndices(Zero, MaxElts);
ConstantRange IdxRange(IntWidth, true);
if (isGuaranteedNotToBePoison(Idx, &AC)) {
if (ValidIndices.contains(computeConstantRange(Idx, false,
true, &AC, CtxI, &DT)))
return ScalarizationResult::safe();
return ScalarizationResult::unsafe();
}
Value *IdxBase;
ConstantInt *CI;
if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
IdxRange = IdxRange.binaryAnd(CI->getValue());
} else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
IdxRange = IdxRange.urem(CI->getValue());
}
if (ValidIndices.contains(IdxRange))
return ScalarizationResult::safeWithFreeze(IdxBase);
return ScalarizationResult::unsafe();
}
static Align computeAlignmentAfterScalarization(Align VectorAlignment,
Type *ScalarType, Value *Idx,
const DataLayout &DL) {
if (auto *C = dyn_cast<ConstantInt>(Idx))
return commonAlignment(VectorAlignment,
C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
}
bool VectorCombine::foldSingleElementStore(Instruction &I) {
StoreInst *SI = dyn_cast<StoreInst>(&I);
if (!SI || !SI->isSimple() ||
!isa<FixedVectorType>(SI->getValueOperand()->getType()))
return false;
Instruction *Source;
Value *NewElement;
Value *Idx;
if (!match(SI->getValueOperand(),
m_InsertElt(m_Instruction(Source), m_Value(NewElement),
m_Value(Idx))))
return false;
if (auto *Load = dyn_cast<LoadInst>(Source)) {
auto VecTy = cast<FixedVectorType>(SI->getValueOperand()->getType());
const DataLayout &DL = I.getModule()->getDataLayout();
Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
!DL.typeSizeEqualsStoreSize(Load->getType()) ||
SrcAddr != SI->getPointerOperand()->stripPointerCasts())
return false;
auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
if (ScalarizableIdx.isUnsafe() ||
isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
MemoryLocation::get(SI), AA))
return false;
if (ScalarizableIdx.isSafeWithFreeze())
ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
Value *GEP = Builder.CreateInBoundsGEP(
SI->getValueOperand()->getType(), SI->getPointerOperand(),
{ConstantInt::get(Idx->getType(), 0), Idx});
StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
NSI->copyMetadata(*SI);
Align ScalarOpAlignment = computeAlignmentAfterScalarization(
std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
DL);
NSI->setAlignment(ScalarOpAlignment);
replaceValue(I, *NSI);
eraseInstruction(I);
return true;
}
return false;
}
bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
Value *Ptr;
if (!match(&I, m_Load(m_Value(Ptr))))
return false;
auto *LI = cast<LoadInst>(&I);
const DataLayout &DL = I.getModule()->getDataLayout();
if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(LI->getType()))
return false;
auto *FixedVT = dyn_cast<FixedVectorType>(LI->getType());
if (!FixedVT)
return false;
InstructionCost OriginalCost =
TTI.getMemoryOpCost(Instruction::Load, LI->getType(), LI->getAlign(),
LI->getPointerAddressSpace());
InstructionCost ScalarizedCost = 0;
Instruction *LastCheckedInst = LI;
unsigned NumInstChecked = 0;
for (User *U : LI->users()) {
auto *UI = dyn_cast<ExtractElementInst>(U);
if (!UI || UI->getParent() != LI->getParent())
return false;
if (!isGuaranteedNotToBePoison(UI->getOperand(1), &AC, LI, &DT))
return false;
if (LastCheckedInst->comesBefore(UI)) {
for (Instruction &I :
make_range(std::next(LI->getIterator()), UI->getIterator())) {
if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
return false;
NumInstChecked++;
}
LastCheckedInst = UI;
}
auto ScalarIdx = canScalarizeAccess(FixedVT, UI->getOperand(1), &I, AC, DT);
if (!ScalarIdx.isSafe()) {
ScalarIdx.discard();
return false;
}
auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
OriginalCost +=
TTI.getVectorInstrCost(Instruction::ExtractElement, LI->getType(),
Index ? Index->getZExtValue() : -1);
ScalarizedCost +=
TTI.getMemoryOpCost(Instruction::Load, FixedVT->getElementType(),
Align(1), LI->getPointerAddressSpace());
ScalarizedCost += TTI.getAddressComputationCost(FixedVT->getElementType());
}
if (ScalarizedCost >= OriginalCost)
return false;
for (User *U : LI->users()) {
auto *EI = cast<ExtractElementInst>(U);
Builder.SetInsertPoint(EI);
Value *Idx = EI->getOperand(1);
Value *GEP =
Builder.CreateInBoundsGEP(FixedVT, Ptr, {Builder.getInt32(0), Idx});
auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
FixedVT->getElementType(), GEP, EI->getName() + ".scalar"));
Align ScalarOpAlignment = computeAlignmentAfterScalarization(
LI->getAlign(), FixedVT->getElementType(), Idx, DL);
NewLoad->setAlignment(ScalarOpAlignment);
replaceValue(*EI, *NewLoad);
}
return true;
}
bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
if (!VecTy)
return false;
BinaryOperator *B0, *B1;
ArrayRef<int> Mask;
if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
m_Mask(Mask))) ||
B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
return false;
SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
Instruction::BinaryOps Opcode = B0->getOpcode();
InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
InstructionCost ShufCost = TTI.getShuffleCost(
TargetTransformInfo::SK_PermuteSingleSrc, VecTy, UnaryMask);
if (ShufCost > BinopCost)
return false;
Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
std::swap(X, Y);
Value *Shuf0, *Shuf1;
if (X == Z) {
Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
} else if (Y == W) {
Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
} else {
return false;
}
Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
NewInst->copyIRFlags(B0);
NewInst->andIRFlags(B1);
}
replaceValue(I, *NewBO);
return true;
}
bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
auto *II = dyn_cast<IntrinsicInst>(&I);
if (!II)
return false;
switch (II->getIntrinsicID()) {
case Intrinsic::vector_reduce_add:
case Intrinsic::vector_reduce_mul:
case Intrinsic::vector_reduce_and:
case Intrinsic::vector_reduce_or:
case Intrinsic::vector_reduce_xor:
case Intrinsic::vector_reduce_smin:
case Intrinsic::vector_reduce_smax:
case Intrinsic::vector_reduce_umin:
case Intrinsic::vector_reduce_umax:
break;
default:
return false;
}
std::queue<Value *> Worklist;
SmallPtrSet<Value *, 4> Visited;
ShuffleVectorInst *Shuffle = nullptr;
if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
Worklist.push(Op);
while (!Worklist.empty()) {
Value *CV = Worklist.front();
Worklist.pop();
if (Visited.contains(CV))
continue;
if (isSplatValue(CV))
continue;
Visited.insert(CV);
if (auto *CI = dyn_cast<Instruction>(CV)) {
if (CI->isBinaryOp()) {
for (auto *Op : CI->operand_values())
Worklist.push(Op);
continue;
} else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
if (Shuffle && Shuffle != SV)
return false;
Shuffle = SV;
continue;
}
}
return false;
}
if (!Shuffle)
return false;
for (auto *V : Visited)
for (auto *U : V->users())
if (!Visited.contains(U) && U != &I)
return false;
FixedVectorType *VecType =
dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
if (!VecType)
return false;
FixedVectorType *ShuffleInputType =
dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
if (!ShuffleInputType)
return false;
int NumInputElts = ShuffleInputType->getNumElements();
SmallVector<int> ConcatMask;
Shuffle->getShuffleMask(ConcatMask);
sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
bool UsesSecondVec =
any_of(ConcatMask, [&](int M) { return M >= NumInputElts; });
InstructionCost OldCost = TTI.getShuffleCost(
UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
Shuffle->getShuffleMask());
InstructionCost NewCost = TTI.getShuffleCost(
UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
ConcatMask);
LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
<< "\n");
LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
<< "\n");
if (NewCost < OldCost) {
Builder.SetInsertPoint(Shuffle);
Value *NewShuffle = Builder.CreateShuffleVector(
Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
replaceValue(*Shuffle, *NewShuffle);
}
return foldSelectShuffle(*Shuffle, true);
}
bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
auto *SVI = dyn_cast<ShuffleVectorInst>(&I);
auto *VT = dyn_cast<FixedVectorType>(I.getType());
if (!SVI || !VT)
return false;
auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
VT != Op0->getType())
return false;
auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
auto checkSVNonOpUses = [&](Instruction *I) {
if (!I || I->getOperand(0)->getType() != VT)
return true;
return any_of(I->users(), [&](User *U) {
return U != Op0 && U != Op1 &&
!(isa<ShuffleVectorInst>(U) &&
(InputShuffles.contains(cast<Instruction>(U)) ||
isInstructionTriviallyDead(cast<Instruction>(U))));
});
};
if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
return false;
SmallVector<ShuffleVectorInst *> Shuffles;
auto collectShuffles = [&](Instruction *I) {
for (auto *U : I->users()) {
auto *SV = dyn_cast<ShuffleVectorInst>(U);
if (!SV || SV->getType() != VT)
return false;
if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
(SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
return false;
if (!llvm::is_contained(Shuffles, SV))
Shuffles.push_back(SV);
}
return true;
};
if (!collectShuffles(Op0) || !collectShuffles(Op1))
return false;
if (FromReduction && Shuffles.size() > 1)
return false;
if (!FromReduction) {
for (ShuffleVectorInst *SV : Shuffles) {
for (auto U : SV->users()) {
ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
Shuffles.push_back(SSV);
}
}
}
SmallVector<std::pair<int, int>> V1, V2;
SmallVector<SmallVector<int>> OrigReconstructMasks;
int MaxV1Elt = 0, MaxV2Elt = 0;
unsigned NumElts = VT->getNumElements();
for (ShuffleVectorInst *SVN : Shuffles) {
SmallVector<int> Mask;
SVN->getShuffleMask(Mask);
Value *SVOp0 = SVN->getOperand(0);
Value *SVOp1 = SVN->getOperand(1);
if (isa<UndefValue>(SVOp1)) {
auto *SSV = cast<ShuffleVectorInst>(SVOp0);
SVOp0 = SSV->getOperand(0);
SVOp1 = SSV->getOperand(1);
for (unsigned I = 0, E = Mask.size(); I != E; I++) {
if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
return false;
Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
}
}
if (SVOp0 == Op1 && SVOp1 == Op0) {
std::swap(SVOp0, SVOp1);
ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
}
if (SVOp0 != Op0 || SVOp1 != Op1)
return false;
SmallVector<int> ReconstructMask;
for (unsigned I = 0; I < Mask.size(); I++) {
if (Mask[I] < 0) {
ReconstructMask.push_back(-1);
} else if (Mask[I] < static_cast<int>(NumElts)) {
MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
auto It = find_if(V1, [&](const std::pair<int, int> &A) {
return Mask[I] == A.first;
});
if (It != V1.end())
ReconstructMask.push_back(It - V1.begin());
else {
ReconstructMask.push_back(V1.size());
V1.emplace_back(Mask[I], V1.size());
}
} else {
MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
auto It = find_if(V2, [&](const std::pair<int, int> &A) {
return Mask[I] - static_cast<int>(NumElts) == A.first;
});
if (It != V2.end())
ReconstructMask.push_back(NumElts + It - V2.begin());
else {
ReconstructMask.push_back(NumElts + V2.size());
V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
}
}
}
if (FromReduction)
sort(ReconstructMask);
OrigReconstructMasks.push_back(std::move(ReconstructMask));
}
if (V1.empty() || V2.empty() ||
(MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
MaxV2Elt == static_cast<int>(V2.size()) - 1))
return false;
auto GetBaseMaskValue = [&](Instruction *I, int M) {
auto *SV = dyn_cast<ShuffleVectorInst>(I);
if (!SV)
return M;
if (isa<UndefValue>(SV->getOperand(1)))
if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
if (InputShuffles.contains(SSV))
return SSV->getMaskValue(SV->getMaskValue(M));
return SV->getMaskValue(M);
};
auto SortBase = [&](Instruction *A, std::pair<int, int> X,
std::pair<int, int> Y) {
int MXA = GetBaseMaskValue(A, X.first);
int MYA = GetBaseMaskValue(A, Y.first);
return MXA < MYA;
};
stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
return SortBase(SVI0A, A, B);
});
stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
return SortBase(SVI1A, A, B);
});
SmallVector<SmallVector<int>> ReconstructMasks;
for (auto Mask : OrigReconstructMasks) {
SmallVector<int> ReconstructMask;
for (int M : Mask) {
auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
auto It = find_if(V, [M](auto A) { return A.second == M; });
assert(It != V.end() && "Expected all entries in Mask");
return std::distance(V.begin(), It);
};
if (M < 0)
ReconstructMask.push_back(-1);
else if (M < static_cast<int>(NumElts)) {
ReconstructMask.push_back(FindIndex(V1, M));
} else {
ReconstructMask.push_back(NumElts + FindIndex(V2, M));
}
}
ReconstructMasks.push_back(std::move(ReconstructMask));
}
SmallVector<int> V1A, V1B, V2A, V2B;
for (unsigned I = 0; I < V1.size(); I++) {
V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
}
for (unsigned I = 0; I < V2.size(); I++) {
V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
}
while (V1A.size() < NumElts) {
V1A.push_back(UndefMaskElem);
V1B.push_back(UndefMaskElem);
}
while (V2A.size() < NumElts) {
V2A.push_back(UndefMaskElem);
V2B.push_back(UndefMaskElem);
}
auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
auto *SV = dyn_cast<ShuffleVectorInst>(I);
if (!SV)
return C;
return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
? TTI::SK_PermuteSingleSrc
: TTI::SK_PermuteTwoSrc,
VT, SV->getShuffleMask());
};
auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
};
InstructionCost CostBefore =
TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
InstructionCost(0), AddShuffleCost);
CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
InstructionCost(0), AddShuffleCost);
FixedVectorType *Op0SmallVT =
FixedVectorType::get(VT->getScalarType(), V1.size());
FixedVectorType *Op1SmallVT =
FixedVectorType::get(VT->getScalarType(), V2.size());
InstructionCost CostAfter =
TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
InstructionCost(0), AddShuffleMaskCost);
std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
CostAfter +=
std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
InstructionCost(0), AddShuffleMaskCost);
LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
<< " vs CostAfter: " << CostAfter << "\n");
if (CostBefore <= CostAfter)
return false;
auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
auto *SV = dyn_cast<ShuffleVectorInst>(I);
if (!SV)
return I;
if (isa<UndefValue>(SV->getOperand(1)))
if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
if (InputShuffles.contains(SSV))
return SSV->getOperand(Op);
return SV->getOperand(Op);
};
Builder.SetInsertPoint(SVI0A->getNextNode());
Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
GetShuffleOperand(SVI0A, 1), V1A);
Builder.SetInsertPoint(SVI0B->getNextNode());
Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
GetShuffleOperand(SVI0B, 1), V1B);
Builder.SetInsertPoint(SVI1A->getNextNode());
Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
GetShuffleOperand(SVI1A, 1), V2A);
Builder.SetInsertPoint(SVI1B->getNextNode());
Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
GetShuffleOperand(SVI1B, 1), V2B);
Builder.SetInsertPoint(Op0);
Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
NSV0A, NSV0B);
if (auto *I = dyn_cast<Instruction>(NOp0))
I->copyIRFlags(Op0, true);
Builder.SetInsertPoint(Op1);
Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
NSV1A, NSV1B);
if (auto *I = dyn_cast<Instruction>(NOp1))
I->copyIRFlags(Op1, true);
for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
Builder.SetInsertPoint(Shuffles[S]);
Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
replaceValue(*Shuffles[S], *NSV);
}
Worklist.pushValue(NSV0A);
Worklist.pushValue(NSV0B);
Worklist.pushValue(NSV1A);
Worklist.pushValue(NSV1B);
for (auto *S : Shuffles)
Worklist.add(S);
return true;
}
bool VectorCombine::run() {
if (DisableVectorCombine)
return false;
if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType( true)))
return false;
bool MadeChange = false;
auto FoldInst = [this, &MadeChange](Instruction &I) {
Builder.SetInsertPoint(&I);
if (!ScalarizationOnly) {
MadeChange |= vectorizeLoadInsert(I);
MadeChange |= foldExtractExtract(I);
MadeChange |= foldBitcastShuf(I);
MadeChange |= foldExtractedCmps(I);
MadeChange |= foldShuffleOfBinops(I);
MadeChange |= foldShuffleFromReductions(I);
MadeChange |= foldSelectShuffle(I);
}
MadeChange |= scalarizeBinopOrCmp(I);
MadeChange |= scalarizeLoadExtract(I);
MadeChange |= foldSingleElementStore(I);
};
for (BasicBlock &BB : F) {
if (!DT.isReachableFromEntry(&BB))
continue;
for (Instruction &I : make_early_inc_range(BB)) {
if (I.isDebugOrPseudoInst())
continue;
FoldInst(I);
}
}
while (!Worklist.isEmpty()) {
Instruction *I = Worklist.removeOne();
if (!I)
continue;
if (isInstructionTriviallyDead(I)) {
eraseInstruction(*I);
continue;
}
FoldInst(*I);
}
return MadeChange;
}
namespace {
class VectorCombineLegacyPass : public FunctionPass {
public:
static char ID;
VectorCombineLegacyPass() : FunctionPass(ID) {
initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.addRequired<AAResultsWrapperPass>();
AU.setPreservesCFG();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
AU.addPreserved<AAResultsWrapperPass>();
AU.addPreserved<BasicAAWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
VectorCombine Combiner(F, TTI, DT, AA, AC, false);
return Combiner.run();
}
};
}
char VectorCombineLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine",
"Optimize scalar/vector ops", false,
false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine",
"Optimize scalar/vector ops", false, false)
Pass *llvm::createVectorCombinePass() {
return new VectorCombineLegacyPass();
}
PreservedAnalyses VectorCombinePass::run(Function &F,
FunctionAnalysisManager &FAM) {
auto &AC = FAM.getResult<AssumptionAnalysis>(F);
TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
AAResults &AA = FAM.getResult<AAManager>(F);
VectorCombine Combiner(F, TTI, DT, AA, AC, ScalarizationOnly);
if (!Combiner.run())
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
return PA;
}