22#include "llvm/IR/IntrinsicsX86.h"
29#define DEBUG_TYPE "x86-partial-reduction"
49 return "X86 Partial Reduction";
59 return new X86PartialReduction();
62char X86PartialReduction::ID = 0;
65 "X86 Partial Reduction",
false,
false)
70 if (!ST->hasVNNI() && !ST->hasAVXVNNI())
76 if (isa<SExtInst>(
LHS))
80 if (
auto *Cast = dyn_cast<CastInst>(
Op)) {
82 (Cast->getOpcode() == Instruction::SExt ||
83 Cast->getOpcode() == Instruction::ZExt) &&
84 Cast->getOperand(0)->getType()->getScalarSizeInBits() <= 8)
88 return isa<Constant>(
Op);
103 bool ReduceInOneBB) {
108 if (cast<FixedVectorType>(
Op->getType())->getNumElements() < 8)
112 if (!cast<VectorType>(
Op->getType())->getElementType()->isIntegerTy(32))
115 auto *
Mul = dyn_cast<BinaryOperator>(
Op);
126 if (ReduceInOneBB && matchVPDPBUSDPattern(
ST,
Mul,
DL))
133 if (
ST->hasSSE41()) {
145 auto CanShrinkOp = [&](
Value *
Op) {
147 if (
auto *Cast = dyn_cast<CastInst>(
Op)) {
149 (Cast->getOpcode() == Instruction::SExt ||
150 Cast->getOpcode() == Instruction::ZExt) &&
151 Cast->getOperand(0)->getType()->getScalarSizeInBits() <= 16)
155 return isa<Constant>(
Op);
166 if (
auto *BO = dyn_cast<BinaryOperator>(
Op)) {
178 if (!CanShrinkOp(
LHS) && !CanShrinkOp(
RHS))
183 auto *MulTy = cast<FixedVectorType>(
Op->getType());
184 unsigned NumElts = MulTy->getNumElements();
191 for (
int i = 0, e = NumElts / 2; i !=
e; ++i) {
193 OddMask[i] = i * 2 + 1;
198 Value *EvenElts = Builder.CreateShuffleVector(NewMul, NewMul, EvenMask);
199 Value *OddElts = Builder.CreateShuffleVector(NewMul, NewMul, OddMask);
200 Value *
MAdd = Builder.CreateAdd(EvenElts, OddElts);
204 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
206 Value *
Concat = Builder.CreateShuffleVector(MAdd, Zero, ConcatMask);
214bool X86PartialReduction::trySADReplacement(
Instruction *
Op) {
220 if (!cast<VectorType>(
Op->getType())->getElementType()->isIntegerTy(32))
224 if (
match(
Op, PatternMatch::m_Intrinsic<Intrinsic::abs>())) {
225 LHS =
Op->getOperand(0);
228 auto *
SI = dyn_cast<SelectInst>(
Op);
240 auto *Sub = dyn_cast<BinaryOperator>(
LHS);
241 if (!Sub || Sub->getOpcode() != Instruction::Sub)
246 if (
auto *ZExt = dyn_cast<ZExtInst>(
Op))
247 if (cast<VectorType>(ZExt->getOperand(0)->getType())
250 return ZExt->getOperand(0);
256 Value *Op0 = getZeroExtendedVal(Sub->getOperand(0));
257 Value *Op1 = getZeroExtendedVal(Sub->getOperand(1));
263 auto *OpTy = cast<FixedVectorType>(
Op->getType());
264 unsigned NumElts = OpTy->getNumElements();
266 unsigned IntrinsicNumElts;
268 if (
ST->hasBWI() && NumElts >= 64) {
269 IID = Intrinsic::x86_avx512_psad_bw_512;
270 IntrinsicNumElts = 64;
271 }
else if (
ST->hasAVX2() && NumElts >= 32) {
272 IID = Intrinsic::x86_avx2_psad_bw;
273 IntrinsicNumElts = 32;
275 IID = Intrinsic::x86_sse2_psad_bw;
276 IntrinsicNumElts = 16;
284 for (
unsigned i = 0; i != NumElts; ++i)
286 for (
unsigned i = NumElts; i != 16; ++i)
287 ConcatMask[i] = (i % NumElts) + NumElts;
290 Op0 = Builder.CreateShuffleVector(Op0, Zero, ConcatMask);
291 Op1 = Builder.CreateShuffleVector(Op1, Zero, ConcatMask);
299 assert(NumElts % IntrinsicNumElts == 0 &&
"Unexpected number of elements!");
300 unsigned NumSplits = NumElts / IntrinsicNumElts;
304 for (
unsigned i = 0; i != NumSplits; ++i) {
306 std::iota(ExtractMask.begin(), ExtractMask.end(), i * IntrinsicNumElts);
307 Value *ExtractOp0 = Builder.CreateShuffleVector(Op0, Op0, ExtractMask);
308 Value *ExtractOp1 = Builder.CreateShuffleVector(Op1, Op0, ExtractMask);
309 Ops[i] = Builder.CreateCall(PSADBWFn, {ExtractOp0, ExtractOp1});
310 Ops[i] = Builder.CreateBitCast(Ops[i], I32Ty);
314 unsigned Stages =
Log2_32(NumSplits);
315 for (
unsigned s = Stages; s > 0; --s) {
316 unsigned NumConcatElts =
317 cast<FixedVectorType>(Ops[0]->
getType())->getNumElements() * 2;
318 for (
unsigned i = 0; i != 1U << (s - 1); ++i) {
320 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
321 Ops[i] = Builder.CreateShuffleVector(Ops[i*2], Ops[i*2+1], ConcatMask);
327 NumElts = cast<FixedVectorType>(OpTy)->getNumElements();
330 Ops[0] = Builder.CreateShuffleVector(Ops[0], Ops[0],
ArrayRef<int>{0, 1});
331 }
else if (NumElts >= 8) {
334 cast<FixedVectorType>(Ops[0]->
getType())->getNumElements();
335 for (
unsigned i = 0; i != SubElts; ++i)
337 for (
unsigned i = SubElts; i != NumElts; ++i)
338 ConcatMask[i] = (i % SubElts) + SubElts;
341 Ops[0] = Builder.CreateShuffleVector(Ops[0], Zero, ConcatMask);
344 Op->replaceAllUsesWith(Ops[0]);
345 Op->eraseFromParent();
353 bool &ReduceInOneBB) {
354 ReduceInOneBB =
true;
357 if (!Index || !Index->isNullValue())
361 if (!BO || BO->getOpcode() != Instruction::Add || !BO->hasOneUse())
364 ReduceInOneBB =
false;
366 unsigned NumElems = cast<FixedVectorType>(BO->getType())->getNumElements();
372 unsigned Stages =
Log2_32(NumElems);
373 for (
unsigned i = 0; i != Stages; ++i) {
374 const auto *BO = dyn_cast<BinaryOperator>(
Op);
375 if (!BO || BO->getOpcode() != Instruction::Add)
378 ReduceInOneBB =
false;
382 if (i != 0 && !BO->hasNUses(2))
388 auto *Shuffle = dyn_cast<ShuffleVectorInst>(
LHS);
392 Shuffle = dyn_cast<ShuffleVectorInst>(
RHS);
398 if (!Shuffle || Shuffle->getOperand(0) !=
Op)
402 unsigned MaskEnd = 1 << i;
403 for (
unsigned Index = 0; Index < MaskEnd; ++Index)
404 if (Shuffle->getMaskValue(Index) != (
int)(MaskEnd + Index))
408 return const_cast<Value *
>(
Op);
416 if (!Phi->hasOneUse())
419 Instruction *U = cast<Instruction>(*Phi->user_begin());
423 while (U->hasOneUse() && U->getOpcode() == BO->
getOpcode())
424 U = cast<Instruction>(*U->user_begin());
438 while (!Worklist.
empty()) {
440 if (!Visited.
insert(V).second)
443 if (
auto *PN = dyn_cast<PHINode>(V)) {
446 if (!PN->hasNUses(PN == Root ? 2 : 1))
455 if (
auto *BO = dyn_cast<BinaryOperator>(V)) {
456 if (BO->getOpcode() == Instruction::Add) {
458 if (BO->hasNUses(BO == Root ? 2 : 1)) {
465 if (BO->hasNUses(BO == Root ? 3 : 2)) {
467 for (
auto *U : BO->users())
468 if (
auto *
P = dyn_cast<PHINode>(U))
488 if (
auto *
I = dyn_cast<Instruction>(V)) {
489 if (!V->hasNUses(
I == Root ? 2 : 1))
498bool X86PartialReduction::runOnFunction(
Function &
F) {
502 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
507 ST =
TM.getSubtargetImpl(
F);
509 DL = &
F.getDataLayout();
511 bool MadeChange =
false;
514 auto *EE = dyn_cast<ExtractElementInst>(&
I);
529 if (tryMAddReplacement(
I, ReduceInOneBB)) {
536 if (
I != Root && trySADReplacement(
I))
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static SymbolRef::Type getType(const Symbol *Sym)
Target-Independent Code Generator Pass Configuration Options pass.
static constexpr int Concat[]
static bool isReachableFromPHI(PHINode *Phi, BinaryOperator *BO)
BinaryOperator const DataLayout * DL
if(isa< SExtInst >(LHS)) std auto IsFreeTruncation
static Value * matchAddReduction(const ExtractElementInst &EE, bool &ReduceInOneBB)
static void collectLeaves(Value *Root, SmallVectorImpl< Instruction * > &Leaves)
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
BinaryOps getOpcode() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
FunctionPass class - This class is used to implement most global optimizations.
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Value * getOperand(unsigned i) const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
const ParentTy * getParent() const
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
This is an optimization pass for GlobalISel generic memory operations.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
@ SPF_ABS
Floating point maxnum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
FunctionPass * createX86PartialReductionPass()
This pass optimizes arithmetic based on knowledge that is only used by a reduction sequence and is th...
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
DWARFExpression::Operation Op
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits.
unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Get the upper bound on bit size for this Value Op as a signed integer.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.