47 #define DEBUG_TYPE "amdgpu-codegenprepare" 54 "amdgpu-codegenprepare-widen-constant-loads",
55 cl::desc(
"Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
60 "amdgpu-codegenprepare-mul24",
61 cl::desc(
"Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
72 bool HasUnsafeFPMath =
false;
73 bool HasFP32Denormals =
false;
80 unsigned getBaseElementBitWidth(
const Type *
T)
const;
97 bool needsPromotionToI32(
const Type *T)
const;
119 bool promoteUniformOpToI32(
ICmpInst &I)
const;
130 bool promoteUniformOpToI32(
SelectInst &I)
const;
146 unsigned numBitsUnsigned(
Value *
Op,
unsigned ScalarSize)
const;
147 unsigned numBitsSigned(
Value *Op,
unsigned ScalarSize)
const;
148 bool isI24(
Value *V,
unsigned ScalarSize)
const;
149 bool isU24(
Value *V,
unsigned ScalarSize)
const;
158 bool IsDiv,
bool IsSigned)
const;
172 bool canWidenScalarExtLoad(
LoadInst &I)
const;
181 bool visitInstruction(
Instruction &I) {
return false; }
190 bool doInitialization(
Module &M)
override;
193 StringRef getPassName()
const override {
return "AMDGPU IR optimizations"; }
204 unsigned AMDGPUCodeGenPrepare::getBaseElementBitWidth(
const Type *
T)
const {
205 assert(needsPromotionToI32(T) &&
"T does not need promotion to i32");
209 return cast<VectorType>(
T)->getElementType()->getIntegerBitWidth();
213 assert(needsPromotionToI32(T) &&
"T does not need promotion to i32");
221 return I.
getOpcode() == Instruction::AShr ||
225 bool AMDGPUCodeGenPrepare::isSigned(
const SelectInst &I)
const {
227 cast<ICmpInst>(I.
getOperand(0))->isSigned() :
false;
230 bool AMDGPUCodeGenPrepare::needsPromotionToI32(
const Type *T)
const {
235 if (
const VectorType *VT = dyn_cast<VectorType>(T)) {
238 if (
ST->hasVOP3PInsts())
241 return needsPromotionToI32(VT->getElementType());
250 case Instruction::Shl:
252 case Instruction::Sub:
254 case Instruction::Mul:
264 case Instruction::Shl:
266 case Instruction::Mul:
268 case Instruction::Sub:
275 bool AMDGPUCodeGenPrepare::canWidenScalarExtLoad(
LoadInst &I)
const {
282 return I.
isSimple() && TySize < 32 && Align >= 4 && DA->isUniform(&I);
285 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(
BinaryOperator &I)
const {
287 "I does not need promotion to i32");
289 if (I.
getOpcode() == Instruction::SDiv ||
299 Value *ExtOp0 =
nullptr;
300 Value *ExtOp1 =
nullptr;
301 Value *ExtRes =
nullptr;
302 Value *TruncRes =
nullptr;
313 if (
Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
315 Inst->setHasNoSignedWrap();
318 Inst->setHasNoUnsignedWrap();
320 if (
const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
321 Inst->setIsExact(ExactOp->isExact());
332 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(
ICmpInst &I)
const {
334 "I does not need promotion to i32");
340 Value *ExtOp0 =
nullptr;
341 Value *ExtOp1 =
nullptr;
342 Value *NewICmp =
nullptr;
359 bool AMDGPUCodeGenPrepare::promoteUniformOpToI32(
SelectInst &I)
const {
361 "I does not need promotion to i32");
367 Value *ExtOp1 =
nullptr;
368 Value *ExtOp2 =
nullptr;
369 Value *ExtRes =
nullptr;
370 Value *TruncRes =
nullptr;
388 bool AMDGPUCodeGenPrepare::promoteUniformBitreverseToI32(
391 "I must be bitreverse intrinsic");
393 "I does not need promotion to i32");
414 unsigned AMDGPUCodeGenPrepare::numBitsUnsigned(
Value *
Op,
415 unsigned ScalarSize)
const {
420 unsigned AMDGPUCodeGenPrepare::numBitsSigned(
Value *Op,
421 unsigned ScalarSize)
const {
428 return ScalarSize >= 24 &&
430 numBitsSigned(V, ScalarSize) < 24;
434 return numBitsUnsigned(V, ScalarSize) <= 24;
452 if (Values.
size() == 1)
456 for (
int I = 0,
E = Values.
size(); I !=
E; ++
I)
462 bool AMDGPUCodeGenPrepare::replaceMulWithMul24(
BinaryOperator &I)
const {
468 if (Size <= 16 && ST->has16BitInsts())
472 if (DA->isUniform(&I))
483 if (
ST->hasMulU24() &&
isU24(LHS, Size) &&
isU24(RHS, Size)) {
484 IntrID = Intrinsic::amdgcn_mul_u24;
485 }
else if (
ST->hasMulI24() &&
isI24(LHS, Size) &&
isI24(RHS, Size)) {
486 IntrID = Intrinsic::amdgcn_mul_i24;
499 for (
int I = 0,
E = LHSVals.
size(); I !=
E; ++
I) {
501 if (IntrID == Intrinsic::amdgcn_mul_u24) {
511 if (IntrID == Intrinsic::amdgcn_mul_u24) {
513 LHSVals[I]->getType()));
516 LHSVals[I]->getType()));
539 return HasDenormals ^ IsOne;
561 bool UnsafeDiv = HasUnsafeFPMath || FMF.
isFast() ||
577 Value *NewFDiv =
nullptr;
579 if (
VectorType *VT = dyn_cast<VectorType>(Ty)) {
584 for (
unsigned I = 0,
E = VT->getNumElements(); I !=
E; ++
I) {
590 NewElt = Builder.
CreateFDiv(NumEltI, DenEltI);
592 NewElt = Builder.
CreateCall(Decl, { NumEltI, DenEltI });
599 NewFDiv = Builder.
CreateCall(Decl, { Num, Den });
627 return std::make_pair(Lo, Hi);
631 return getMul64(Builder, LHS, RHS).second;
639 bool IsDiv,
bool IsSigned)
const {
652 unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
653 unsigned DivBits = 32 - SignBits;
700 {FQNeg->
getType()}, {FQNeg, FB, FA}, FQ);
744 assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
745 Opc == Instruction::SRem || Opc == Instruction::SDiv);
751 if (isa<Constant>(Den))
754 bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
755 bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
771 if (
Value *Res = expandDivRem24(Builder, I, Num, Den, IsDiv, IsSigned)) {
780 Value *Sign =
nullptr;
786 Sign = IsDiv ? Builder.
CreateXor(LHSign, RHSign) : LHSign;
804 Value *RCP_LO, *RCP_HI;
805 std::tie(RCP_LO, RCP_HI) =
getMul64(Builder, RCP, Den);
846 Value *Tmp1 = Builder.
CreateAnd(Remainder_GE_Den, Remainder_GE_Zero);
861 Res = Builder.
CreateSelect(Num_GE_Num_S_Rem_CC, Div, Quotient_S_One);
873 Res = Builder.
CreateSelect(Num_GE_Num_S_Rem_CC, Rem, Remainder_A_Den);
886 bool AMDGPUCodeGenPrepare::visitBinaryOperator(
BinaryOperator &I) {
887 if (
ST->has16BitInsts() && needsPromotionToI32(I.
getType()) &&
888 DA->isUniform(&I) && promoteUniformOpToI32(I))
891 if (UseMul24Intrin && replaceMulWithMul24(I))
894 bool Changed =
false;
897 Value *NewDiv =
nullptr;
898 if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
899 Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
906 if (
VectorType *VT = dyn_cast<VectorType>(Ty)) {
909 for (
unsigned N = 0,
E = VT->getNumElements();
N !=
E; ++
N) {
912 Value *NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
914 NewElt = Builder.
CreateBinOp(Opc, NumEltN, DenEltN);
918 NewDiv = expandDivRem32(Builder, I, Num, Den);
931 bool AMDGPUCodeGenPrepare::visitLoadInst(
LoadInst &I) {
937 canWidenScalarExtLoad(I)) {
949 if (
auto *Range = WidenLoad->
getMetadata(LLVMContext::MD_range)) {
951 mdconst::extract<ConstantInt>(Range->getOperand(0));
954 WidenLoad->
setMetadata(LLVMContext::MD_range,
nullptr);
967 int TySize =
Mod->getDataLayout().getTypeSizeInBits(I.
getType());
979 bool AMDGPUCodeGenPrepare::visitICmpInst(
ICmpInst &I) {
980 bool Changed =
false;
984 Changed |= promoteUniformOpToI32(I);
989 bool AMDGPUCodeGenPrepare::visitSelectInst(
SelectInst &I) {
990 bool Changed =
false;
992 if (
ST->has16BitInsts() && needsPromotionToI32(I.
getType()) &&
994 Changed |= promoteUniformOpToI32(I);
999 bool AMDGPUCodeGenPrepare::visitIntrinsicInst(
IntrinsicInst &I) {
1001 case Intrinsic::bitreverse:
1002 return visitBitreverseIntrinsicInst(I);
1008 bool AMDGPUCodeGenPrepare::visitBitreverseIntrinsicInst(
IntrinsicInst &I) {
1009 bool Changed =
false;
1011 if (
ST->has16BitInsts() && needsPromotionToI32(I.
getType()) &&
1013 Changed |= promoteUniformBitreverseToI32(I);
1018 bool AMDGPUCodeGenPrepare::doInitialization(
Module &M) {
1020 DL = &
Mod->getDataLayout();
1025 if (skipFunction(F))
1028 auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
1034 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1035 DA = &getAnalysis<LegacyDivergenceAnalysis>();
1037 HasFP32Denormals = ST->hasFP32Denormals(F);
1039 bool MadeChange =
false;
1044 Next = std::next(I);
1045 MadeChange |= visit(*I);
1053 "AMDGPU IR optimizations",
false,
false)
1059 char AMDGPUCodeGenPrepare::
ID = 0;
1062 return new AMDGPUCodeGenPrepare();
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction, which must be an operator which supports these flags.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
FastMathFlags getFastMathFlags() const
Get the flags to be applied to created floating point ops.
Base class for instruction visitors.
AMDGPU specific subclass of TargetSubtarget.
void setFast(bool B=true)
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
This class represents lattice values for constants.
BinaryOps getOpcode() const
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
A Module instance is used to store all the information related to an LLVM module. ...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
APInt zext(unsigned width) const
Zero extend to a new width.
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
float BitsToFloat(uint32_t Bits)
This function takes a 32-bit integer and returns the bit equivalent float.
A cache of @llvm.assume calls within a function.
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
FunctionPass * createAMDGPUCodeGenPreparePass()
An instruction for reading from memory.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
static Value * insertValues(IRBuilder<> &Builder, Type *Ty, SmallVectorImpl< Value *> &Values)
static bool promotedOpIsNUW(const Instruction &I)
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
This class represents the LLVM 'select' instruction.
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This file contains the simple types necessary to represent the attributes associated with functions a...
static bool isI24(SDValue Op, SelectionDAG &DAG)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Address space for 32-bit constant memory.
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Type * getType() const
All values are typed, get the type of this value.
Value * CreateSExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a SExt or Trunc from the integer value V to DestTy.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateSIToFP(Value *V, Type *DestTy, const Twine &Name="")
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * getOperand(unsigned i) const
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static bool promotedOpIsNSW(const Instruction &I)
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
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...
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Value * CreateFMul(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
ConstantFP - Floating Point Values [float, double].
Value * CreateFPToUI(Value *V, Type *DestTy, const Twine &Name="")
bool isFast() const
'Fast' means all bits are set.
Represent the analysis usage information of a pass.
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
bool allowReciprocal() const
self_iterator getIterator()
Class to represent integer types.
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
The AMDGPU TargetMachine interface definition for hw codgen targets.
static bool shouldKeepFDivF32(Value *Num, bool UnsafeDiv, bool HasDenormals)
static Value * getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
This struct is a compact representation of a valid (non-zero power of two) alignment.
Value * CreateUIToFP(Value *V, Type *DestTy, const Twine &Name="")
Value * CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static bool isU24(SDValue Op, SelectionDAG &DAG)
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Value * CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name="")
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Utility class for floating point operations which can have information about relaxed accuracy require...
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type *> Types, ArrayRef< Value *> Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with args, mangled using Types.
Value * CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx, const Twine &Name="")
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
static bool hasUnsafeFPMath(const Function &F)
The access may modify the value stored in memory.
static std::pair< Value *, Value * > getMul64(IRBuilder<> &Builder, Value *LHS, Value *RHS)
Class to represent vector types.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Predicate getPredicate() const
Return the predicate for this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
unsigned getIntegerBitWidth() const
StringRef getValueAsString() const
Return the attribute's value as a string.
float getFPAccuracy() const
Get the maximum error permitted by this operation in ULPs.
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Value * CreateFPToSI(Value *V, Type *DestTy, const Twine &Name="")
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Type * getFloatTy()
Fetch the type representing a 32-bit floating point value.
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateFDiv(Value *L, Value *R, const Twine &Name="", MDNode *FPMD=nullptr)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
bool isExactlyValue(const APFloat &V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations", false, false) INITIALIZE_PASS_END(AMDGPUCodeGenPrepare
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
static void extractValues(IRBuilder<> &Builder, SmallVectorImpl< Value *> &Values, Value *V)
Statically lint checks LLVM IR
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Address space for constant memory (VTX2).
bool isNullValue() const
Determine if all bits are clear.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const