10b57cec5SDimitry Andric //===-- AMDGPUCodeGenPrepare.cpp ------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This pass does misc. AMDGPU optimizations on IR before instruction
110b57cec5SDimitry Andric /// selection.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric
150b57cec5SDimitry Andric #include "AMDGPU.h"
160b57cec5SDimitry Andric #include "AMDGPUTargetMachine.h"
17fe013be4SDimitry Andric #include "SIModeRegisterDefaults.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
195ffd83dbSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
20fe013be4SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
21fe013be4SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
245ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h"
25fe013be4SDimitry Andric #include "llvm/IR/IRBuilder.h"
260b57cec5SDimitry Andric #include "llvm/IR/InstVisitor.h"
27e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsAMDGPU.h"
28fe013be4SDimitry Andric #include "llvm/IR/PatternMatch.h"
29480093f4SDimitry Andric #include "llvm/InitializePasses.h"
300b57cec5SDimitry Andric #include "llvm/Pass.h"
31e8d8bef9SDimitry Andric #include "llvm/Support/KnownBits.h"
325ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/IntegerDivision.h"
33fe013be4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
340b57cec5SDimitry Andric
350b57cec5SDimitry Andric #define DEBUG_TYPE "amdgpu-codegenprepare"
360b57cec5SDimitry Andric
370b57cec5SDimitry Andric using namespace llvm;
38fe013be4SDimitry Andric using namespace llvm::PatternMatch;
390b57cec5SDimitry Andric
400b57cec5SDimitry Andric namespace {
410b57cec5SDimitry Andric
420b57cec5SDimitry Andric static cl::opt<bool> WidenLoads(
430b57cec5SDimitry Andric "amdgpu-codegenprepare-widen-constant-loads",
440b57cec5SDimitry Andric cl::desc("Widen sub-dword constant address space loads in AMDGPUCodeGenPrepare"),
450b57cec5SDimitry Andric cl::ReallyHidden,
465ffd83dbSDimitry Andric cl::init(false));
470b57cec5SDimitry Andric
48e8d8bef9SDimitry Andric static cl::opt<bool> Widen16BitOps(
49e8d8bef9SDimitry Andric "amdgpu-codegenprepare-widen-16-bit-ops",
50e8d8bef9SDimitry Andric cl::desc("Widen uniform 16-bit instructions to 32-bit in AMDGPUCodeGenPrepare"),
51e8d8bef9SDimitry Andric cl::ReallyHidden,
52e8d8bef9SDimitry Andric cl::init(true));
53e8d8bef9SDimitry Andric
54fe013be4SDimitry Andric static cl::opt<bool>
55*c9157d92SDimitry Andric BreakLargePHIs("amdgpu-codegenprepare-break-large-phis",
56fe013be4SDimitry Andric cl::desc("Break large PHI nodes for DAGISel"),
57fe013be4SDimitry Andric cl::ReallyHidden, cl::init(true));
58fe013be4SDimitry Andric
59fe013be4SDimitry Andric static cl::opt<bool>
60*c9157d92SDimitry Andric ForceBreakLargePHIs("amdgpu-codegenprepare-force-break-large-phis",
61fe013be4SDimitry Andric cl::desc("For testing purposes, always break large "
62fe013be4SDimitry Andric "PHIs even if it isn't profitable."),
63fe013be4SDimitry Andric cl::ReallyHidden, cl::init(false));
64fe013be4SDimitry Andric
65*c9157d92SDimitry Andric static cl::opt<unsigned> BreakLargePHIsThreshold(
66fe013be4SDimitry Andric "amdgpu-codegenprepare-break-large-phis-threshold",
67fe013be4SDimitry Andric cl::desc("Minimum type size in bits for breaking large PHI nodes"),
68fe013be4SDimitry Andric cl::ReallyHidden, cl::init(32));
69fe013be4SDimitry Andric
708bcb0991SDimitry Andric static cl::opt<bool> UseMul24Intrin(
718bcb0991SDimitry Andric "amdgpu-codegenprepare-mul24",
728bcb0991SDimitry Andric cl::desc("Introduce mul24 intrinsics in AMDGPUCodeGenPrepare"),
738bcb0991SDimitry Andric cl::ReallyHidden,
748bcb0991SDimitry Andric cl::init(true));
758bcb0991SDimitry Andric
765ffd83dbSDimitry Andric // Legalize 64-bit division by using the generic IR expansion.
775ffd83dbSDimitry Andric static cl::opt<bool> ExpandDiv64InIR(
785ffd83dbSDimitry Andric "amdgpu-codegenprepare-expand-div64",
795ffd83dbSDimitry Andric cl::desc("Expand 64-bit division in AMDGPUCodeGenPrepare"),
805ffd83dbSDimitry Andric cl::ReallyHidden,
815ffd83dbSDimitry Andric cl::init(false));
825ffd83dbSDimitry Andric
835ffd83dbSDimitry Andric // Leave all division operations as they are. This supersedes ExpandDiv64InIR
845ffd83dbSDimitry Andric // and is used for testing the legalizer.
855ffd83dbSDimitry Andric static cl::opt<bool> DisableIDivExpand(
865ffd83dbSDimitry Andric "amdgpu-codegenprepare-disable-idiv-expansion",
875ffd83dbSDimitry Andric cl::desc("Prevent expanding integer division in AMDGPUCodeGenPrepare"),
885ffd83dbSDimitry Andric cl::ReallyHidden,
895ffd83dbSDimitry Andric cl::init(false));
905ffd83dbSDimitry Andric
91fe013be4SDimitry Andric // Disable processing of fdiv so we can better test the backend implementations.
92fe013be4SDimitry Andric static cl::opt<bool> DisableFDivExpand(
93fe013be4SDimitry Andric "amdgpu-codegenprepare-disable-fdiv-expansion",
94fe013be4SDimitry Andric cl::desc("Prevent expanding floating point division in AMDGPUCodeGenPrepare"),
95fe013be4SDimitry Andric cl::ReallyHidden,
96fe013be4SDimitry Andric cl::init(false));
97fe013be4SDimitry Andric
98fe013be4SDimitry Andric class AMDGPUCodeGenPrepareImpl
99fe013be4SDimitry Andric : public InstVisitor<AMDGPUCodeGenPrepareImpl, bool> {
100fe013be4SDimitry Andric public:
1010b57cec5SDimitry Andric const GCNSubtarget *ST = nullptr;
102fe013be4SDimitry Andric const TargetLibraryInfo *TLInfo = nullptr;
1030b57cec5SDimitry Andric AssumptionCache *AC = nullptr;
1045ffd83dbSDimitry Andric DominatorTree *DT = nullptr;
105fe013be4SDimitry Andric UniformityInfo *UA = nullptr;
1060b57cec5SDimitry Andric Module *Mod = nullptr;
1070b57cec5SDimitry Andric const DataLayout *DL = nullptr;
1080b57cec5SDimitry Andric bool HasUnsafeFPMath = false;
109fe013be4SDimitry Andric bool HasFP32DenormalFlush = false;
110fe013be4SDimitry Andric bool FlowChanged = false;
111*c9157d92SDimitry Andric mutable Function *SqrtF32 = nullptr;
112*c9157d92SDimitry Andric mutable Function *LdexpF32 = nullptr;
113fe013be4SDimitry Andric
114fe013be4SDimitry Andric DenseMap<const PHINode *, bool> BreakPhiNodesCache;
115fe013be4SDimitry Andric
getSqrtF32() const116*c9157d92SDimitry Andric Function *getSqrtF32() const {
117*c9157d92SDimitry Andric if (SqrtF32)
118*c9157d92SDimitry Andric return SqrtF32;
119*c9157d92SDimitry Andric
120*c9157d92SDimitry Andric LLVMContext &Ctx = Mod->getContext();
121*c9157d92SDimitry Andric SqrtF32 = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_sqrt,
122*c9157d92SDimitry Andric {Type::getFloatTy(Ctx)});
123*c9157d92SDimitry Andric return SqrtF32;
124*c9157d92SDimitry Andric }
125*c9157d92SDimitry Andric
getLdexpF32() const126*c9157d92SDimitry Andric Function *getLdexpF32() const {
127*c9157d92SDimitry Andric if (LdexpF32)
128*c9157d92SDimitry Andric return LdexpF32;
129*c9157d92SDimitry Andric
130*c9157d92SDimitry Andric LLVMContext &Ctx = Mod->getContext();
131*c9157d92SDimitry Andric LdexpF32 = Intrinsic::getDeclaration(
132*c9157d92SDimitry Andric Mod, Intrinsic::ldexp, {Type::getFloatTy(Ctx), Type::getInt32Ty(Ctx)});
133*c9157d92SDimitry Andric return LdexpF32;
134*c9157d92SDimitry Andric }
135*c9157d92SDimitry Andric
136fe013be4SDimitry Andric bool canBreakPHINode(const PHINode &I);
1370b57cec5SDimitry Andric
1380b57cec5SDimitry Andric /// Copies exact/nsw/nuw flags (if any) from binary operation \p I to
1390b57cec5SDimitry Andric /// binary operation \p V.
1400b57cec5SDimitry Andric ///
1410b57cec5SDimitry Andric /// \returns Binary operation \p V.
1420b57cec5SDimitry Andric /// \returns \p T's base element bit width.
1430b57cec5SDimitry Andric unsigned getBaseElementBitWidth(const Type *T) const;
1440b57cec5SDimitry Andric
1450b57cec5SDimitry Andric /// \returns Equivalent 32 bit integer type for given type \p T. For example,
1460b57cec5SDimitry Andric /// if \p T is i7, then i32 is returned; if \p T is <3 x i12>, then <3 x i32>
1470b57cec5SDimitry Andric /// is returned.
1480b57cec5SDimitry Andric Type *getI32Ty(IRBuilder<> &B, const Type *T) const;
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric /// \returns True if binary operation \p I is a signed binary operation, false
1510b57cec5SDimitry Andric /// otherwise.
1520b57cec5SDimitry Andric bool isSigned(const BinaryOperator &I) const;
1530b57cec5SDimitry Andric
1540b57cec5SDimitry Andric /// \returns True if the condition of 'select' operation \p I comes from a
1550b57cec5SDimitry Andric /// signed 'icmp' operation, false otherwise.
1560b57cec5SDimitry Andric bool isSigned(const SelectInst &I) const;
1570b57cec5SDimitry Andric
1580b57cec5SDimitry Andric /// \returns True if type \p T needs to be promoted to 32 bit integer type,
1590b57cec5SDimitry Andric /// false otherwise.
1600b57cec5SDimitry Andric bool needsPromotionToI32(const Type *T) const;
1610b57cec5SDimitry Andric
162fe013be4SDimitry Andric /// Return true if \p T is a legal scalar floating point type.
163fe013be4SDimitry Andric bool isLegalFloatingTy(const Type *T) const;
164fe013be4SDimitry Andric
165fe013be4SDimitry Andric /// Wrapper to pass all the arguments to computeKnownFPClass
computeKnownFPClass(const Value * V,FPClassTest Interested,const Instruction * CtxI) const166fe013be4SDimitry Andric KnownFPClass computeKnownFPClass(const Value *V, FPClassTest Interested,
167fe013be4SDimitry Andric const Instruction *CtxI) const {
168fe013be4SDimitry Andric return llvm::computeKnownFPClass(V, *DL, Interested, 0, TLInfo, AC, CtxI,
169fe013be4SDimitry Andric DT);
170fe013be4SDimitry Andric }
171fe013be4SDimitry Andric
canIgnoreDenormalInput(const Value * V,const Instruction * CtxI) const172fe013be4SDimitry Andric bool canIgnoreDenormalInput(const Value *V, const Instruction *CtxI) const {
173fe013be4SDimitry Andric return HasFP32DenormalFlush ||
174fe013be4SDimitry Andric computeKnownFPClass(V, fcSubnormal, CtxI).isKnownNeverSubnormal();
175fe013be4SDimitry Andric }
176fe013be4SDimitry Andric
1770b57cec5SDimitry Andric /// Promotes uniform binary operation \p I to equivalent 32 bit binary
1780b57cec5SDimitry Andric /// operation.
1790b57cec5SDimitry Andric ///
1800b57cec5SDimitry Andric /// \details \p I's base element bit width must be greater than 1 and less
1810b57cec5SDimitry Andric /// than or equal 16. Promotion is done by sign or zero extending operands to
1820b57cec5SDimitry Andric /// 32 bits, replacing \p I with equivalent 32 bit binary operation, and
1830b57cec5SDimitry Andric /// truncating the result of 32 bit binary operation back to \p I's original
1840b57cec5SDimitry Andric /// type. Division operation is not promoted.
1850b57cec5SDimitry Andric ///
1860b57cec5SDimitry Andric /// \returns True if \p I is promoted to equivalent 32 bit binary operation,
1870b57cec5SDimitry Andric /// false otherwise.
1880b57cec5SDimitry Andric bool promoteUniformOpToI32(BinaryOperator &I) const;
1890b57cec5SDimitry Andric
1900b57cec5SDimitry Andric /// Promotes uniform 'icmp' operation \p I to 32 bit 'icmp' operation.
1910b57cec5SDimitry Andric ///
1920b57cec5SDimitry Andric /// \details \p I's base element bit width must be greater than 1 and less
1930b57cec5SDimitry Andric /// than or equal 16. Promotion is done by sign or zero extending operands to
1940b57cec5SDimitry Andric /// 32 bits, and replacing \p I with 32 bit 'icmp' operation.
1950b57cec5SDimitry Andric ///
1960b57cec5SDimitry Andric /// \returns True.
1970b57cec5SDimitry Andric bool promoteUniformOpToI32(ICmpInst &I) const;
1980b57cec5SDimitry Andric
1990b57cec5SDimitry Andric /// Promotes uniform 'select' operation \p I to 32 bit 'select'
2000b57cec5SDimitry Andric /// operation.
2010b57cec5SDimitry Andric ///
2020b57cec5SDimitry Andric /// \details \p I's base element bit width must be greater than 1 and less
2030b57cec5SDimitry Andric /// than or equal 16. Promotion is done by sign or zero extending operands to
2040b57cec5SDimitry Andric /// 32 bits, replacing \p I with 32 bit 'select' operation, and truncating the
2050b57cec5SDimitry Andric /// result of 32 bit 'select' operation back to \p I's original type.
2060b57cec5SDimitry Andric ///
2070b57cec5SDimitry Andric /// \returns True.
2080b57cec5SDimitry Andric bool promoteUniformOpToI32(SelectInst &I) const;
2090b57cec5SDimitry Andric
2100b57cec5SDimitry Andric /// Promotes uniform 'bitreverse' intrinsic \p I to 32 bit 'bitreverse'
2110b57cec5SDimitry Andric /// intrinsic.
2120b57cec5SDimitry Andric ///
2130b57cec5SDimitry Andric /// \details \p I's base element bit width must be greater than 1 and less
2140b57cec5SDimitry Andric /// than or equal 16. Promotion is done by zero extending the operand to 32
2150b57cec5SDimitry Andric /// bits, replacing \p I with 32 bit 'bitreverse' intrinsic, shifting the
2160b57cec5SDimitry Andric /// result of 32 bit 'bitreverse' intrinsic to the right with zero fill (the
2170b57cec5SDimitry Andric /// shift amount is 32 minus \p I's base element bit width), and truncating
2180b57cec5SDimitry Andric /// the result of the shift operation back to \p I's original type.
2190b57cec5SDimitry Andric ///
2200b57cec5SDimitry Andric /// \returns True.
2210b57cec5SDimitry Andric bool promoteUniformBitreverseToI32(IntrinsicInst &I) const;
2220b57cec5SDimitry Andric
223349cc55cSDimitry Andric /// \returns The minimum number of bits needed to store the value of \Op as an
224349cc55cSDimitry Andric /// unsigned integer. Truncating to this size and then zero-extending to
22504eeddc0SDimitry Andric /// the original will not change the value.
22604eeddc0SDimitry Andric unsigned numBitsUnsigned(Value *Op) const;
227349cc55cSDimitry Andric
228349cc55cSDimitry Andric /// \returns The minimum number of bits needed to store the value of \Op as a
229349cc55cSDimitry Andric /// signed integer. Truncating to this size and then sign-extending to
23004eeddc0SDimitry Andric /// the original size will not change the value.
23104eeddc0SDimitry Andric unsigned numBitsSigned(Value *Op) const;
2320b57cec5SDimitry Andric
2330b57cec5SDimitry Andric /// Replace mul instructions with llvm.amdgcn.mul.u24 or llvm.amdgcn.mul.s24.
2340b57cec5SDimitry Andric /// SelectionDAG has an issue where an and asserting the bits are known
2350b57cec5SDimitry Andric bool replaceMulWithMul24(BinaryOperator &I) const;
2360b57cec5SDimitry Andric
2375ffd83dbSDimitry Andric /// Perform same function as equivalently named function in DAGCombiner. Since
2385ffd83dbSDimitry Andric /// we expand some divisions here, we need to perform this before obscuring.
2395ffd83dbSDimitry Andric bool foldBinOpIntoSelect(BinaryOperator &I) const;
2405ffd83dbSDimitry Andric
2415ffd83dbSDimitry Andric bool divHasSpecialOptimization(BinaryOperator &I,
2425ffd83dbSDimitry Andric Value *Num, Value *Den) const;
2435ffd83dbSDimitry Andric int getDivNumBits(BinaryOperator &I,
2445ffd83dbSDimitry Andric Value *Num, Value *Den,
2455ffd83dbSDimitry Andric unsigned AtLeast, bool Signed) const;
2465ffd83dbSDimitry Andric
2470b57cec5SDimitry Andric /// Expands 24 bit div or rem.
2480b57cec5SDimitry Andric Value* expandDivRem24(IRBuilder<> &Builder, BinaryOperator &I,
2490b57cec5SDimitry Andric Value *Num, Value *Den,
2500b57cec5SDimitry Andric bool IsDiv, bool IsSigned) const;
2510b57cec5SDimitry Andric
2525ffd83dbSDimitry Andric Value *expandDivRem24Impl(IRBuilder<> &Builder, BinaryOperator &I,
2535ffd83dbSDimitry Andric Value *Num, Value *Den, unsigned NumBits,
2545ffd83dbSDimitry Andric bool IsDiv, bool IsSigned) const;
2555ffd83dbSDimitry Andric
2560b57cec5SDimitry Andric /// Expands 32 bit div or rem.
2570b57cec5SDimitry Andric Value* expandDivRem32(IRBuilder<> &Builder, BinaryOperator &I,
2580b57cec5SDimitry Andric Value *Num, Value *Den) const;
2590b57cec5SDimitry Andric
2605ffd83dbSDimitry Andric Value *shrinkDivRem64(IRBuilder<> &Builder, BinaryOperator &I,
2615ffd83dbSDimitry Andric Value *Num, Value *Den) const;
2625ffd83dbSDimitry Andric void expandDivRem64(BinaryOperator &I) const;
2635ffd83dbSDimitry Andric
2640b57cec5SDimitry Andric /// Widen a scalar load.
2650b57cec5SDimitry Andric ///
2660b57cec5SDimitry Andric /// \details \p Widen scalar load for uniform, small type loads from constant
2670b57cec5SDimitry Andric // memory / to a full 32-bits and then truncate the input to allow a scalar
2680b57cec5SDimitry Andric // load instead of a vector load.
2690b57cec5SDimitry Andric //
2700b57cec5SDimitry Andric /// \returns True.
2710b57cec5SDimitry Andric
2720b57cec5SDimitry Andric bool canWidenScalarExtLoad(LoadInst &I) const;
2730b57cec5SDimitry Andric
274fe013be4SDimitry Andric Value *matchFractPat(IntrinsicInst &I);
275fe013be4SDimitry Andric Value *applyFractPat(IRBuilder<> &Builder, Value *FractArg);
276fe013be4SDimitry Andric
277fe013be4SDimitry Andric bool canOptimizeWithRsq(const FPMathOperator *SqrtOp, FastMathFlags DivFMF,
278fe013be4SDimitry Andric FastMathFlags SqrtFMF) const;
279fe013be4SDimitry Andric
280fe013be4SDimitry Andric Value *optimizeWithRsq(IRBuilder<> &Builder, Value *Num, Value *Den,
281fe013be4SDimitry Andric FastMathFlags DivFMF, FastMathFlags SqrtFMF,
282fe013be4SDimitry Andric const Instruction *CtxI) const;
283fe013be4SDimitry Andric
284fe013be4SDimitry Andric Value *optimizeWithRcp(IRBuilder<> &Builder, Value *Num, Value *Den,
285fe013be4SDimitry Andric FastMathFlags FMF, const Instruction *CtxI) const;
286fe013be4SDimitry Andric Value *optimizeWithFDivFast(IRBuilder<> &Builder, Value *Num, Value *Den,
287fe013be4SDimitry Andric float ReqdAccuracy) const;
288fe013be4SDimitry Andric
289fe013be4SDimitry Andric Value *visitFDivElement(IRBuilder<> &Builder, Value *Num, Value *Den,
290fe013be4SDimitry Andric FastMathFlags DivFMF, FastMathFlags SqrtFMF,
291fe013be4SDimitry Andric Value *RsqOp, const Instruction *FDiv,
292fe013be4SDimitry Andric float ReqdAccuracy) const;
293fe013be4SDimitry Andric
294fe013be4SDimitry Andric std::pair<Value *, Value *> getFrexpResults(IRBuilder<> &Builder,
295fe013be4SDimitry Andric Value *Src) const;
296fe013be4SDimitry Andric
297fe013be4SDimitry Andric Value *emitRcpIEEE1ULP(IRBuilder<> &Builder, Value *Src,
298fe013be4SDimitry Andric bool IsNegative) const;
299fe013be4SDimitry Andric Value *emitFrexpDiv(IRBuilder<> &Builder, Value *LHS, Value *RHS,
300fe013be4SDimitry Andric FastMathFlags FMF) const;
301*c9157d92SDimitry Andric Value *emitSqrtIEEE2ULP(IRBuilder<> &Builder, Value *Src,
302*c9157d92SDimitry Andric FastMathFlags FMF) const;
303fe013be4SDimitry Andric
3040b57cec5SDimitry Andric public:
3050b57cec5SDimitry Andric bool visitFDiv(BinaryOperator &I);
3060b57cec5SDimitry Andric
visitInstruction(Instruction & I)3070b57cec5SDimitry Andric bool visitInstruction(Instruction &I) { return false; }
3080b57cec5SDimitry Andric bool visitBinaryOperator(BinaryOperator &I);
3090b57cec5SDimitry Andric bool visitLoadInst(LoadInst &I);
3100b57cec5SDimitry Andric bool visitICmpInst(ICmpInst &I);
3110b57cec5SDimitry Andric bool visitSelectInst(SelectInst &I);
312fe013be4SDimitry Andric bool visitPHINode(PHINode &I);
3130b57cec5SDimitry Andric
3140b57cec5SDimitry Andric bool visitIntrinsicInst(IntrinsicInst &I);
3150b57cec5SDimitry Andric bool visitBitreverseIntrinsicInst(IntrinsicInst &I);
316fe013be4SDimitry Andric bool visitMinNum(IntrinsicInst &I);
317*c9157d92SDimitry Andric bool visitSqrt(IntrinsicInst &I);
318fe013be4SDimitry Andric bool run(Function &F);
319fe013be4SDimitry Andric };
3200b57cec5SDimitry Andric
321fe013be4SDimitry Andric class AMDGPUCodeGenPrepare : public FunctionPass {
322fe013be4SDimitry Andric private:
323fe013be4SDimitry Andric AMDGPUCodeGenPrepareImpl Impl;
3240b57cec5SDimitry Andric
325fe013be4SDimitry Andric public:
326fe013be4SDimitry Andric static char ID;
AMDGPUCodeGenPrepare()327fe013be4SDimitry Andric AMDGPUCodeGenPrepare() : FunctionPass(ID) {
328fe013be4SDimitry Andric initializeAMDGPUCodeGenPreparePass(*PassRegistry::getPassRegistry());
329fe013be4SDimitry Andric }
getAnalysisUsage(AnalysisUsage & AU) const3300b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
3310b57cec5SDimitry Andric AU.addRequired<AssumptionCacheTracker>();
332fe013be4SDimitry Andric AU.addRequired<UniformityInfoWrapperPass>();
333fe013be4SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>();
3345ffd83dbSDimitry Andric
3355ffd83dbSDimitry Andric // FIXME: Division expansion needs to preserve the dominator tree.
3365ffd83dbSDimitry Andric if (!ExpandDiv64InIR)
3370b57cec5SDimitry Andric AU.setPreservesAll();
3380b57cec5SDimitry Andric }
339fe013be4SDimitry Andric bool runOnFunction(Function &F) override;
340fe013be4SDimitry Andric bool doInitialization(Module &M) override;
getPassName() const341fe013be4SDimitry Andric StringRef getPassName() const override { return "AMDGPU IR optimizations"; }
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric } // end anonymous namespace
3450b57cec5SDimitry Andric
run(Function & F)346fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::run(Function &F) {
347*c9157d92SDimitry Andric BreakPhiNodesCache.clear();
348fe013be4SDimitry Andric bool MadeChange = false;
349fe013be4SDimitry Andric
350fe013be4SDimitry Andric Function::iterator NextBB;
351fe013be4SDimitry Andric for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; FI = NextBB) {
352fe013be4SDimitry Andric BasicBlock *BB = &*FI;
353fe013be4SDimitry Andric NextBB = std::next(FI);
354fe013be4SDimitry Andric
355fe013be4SDimitry Andric BasicBlock::iterator Next;
356fe013be4SDimitry Andric for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;
357fe013be4SDimitry Andric I = Next) {
358fe013be4SDimitry Andric Next = std::next(I);
359fe013be4SDimitry Andric
360fe013be4SDimitry Andric MadeChange |= visit(*I);
361fe013be4SDimitry Andric
362fe013be4SDimitry Andric if (Next != E) { // Control flow changed
363fe013be4SDimitry Andric BasicBlock *NextInstBB = Next->getParent();
364fe013be4SDimitry Andric if (NextInstBB != BB) {
365fe013be4SDimitry Andric BB = NextInstBB;
366fe013be4SDimitry Andric E = BB->end();
367fe013be4SDimitry Andric FE = F.end();
368fe013be4SDimitry Andric }
369fe013be4SDimitry Andric }
370fe013be4SDimitry Andric }
371fe013be4SDimitry Andric }
372fe013be4SDimitry Andric return MadeChange;
373fe013be4SDimitry Andric }
374fe013be4SDimitry Andric
getBaseElementBitWidth(const Type * T) const375fe013be4SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::getBaseElementBitWidth(const Type *T) const {
3760b57cec5SDimitry Andric assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3770b57cec5SDimitry Andric
3780b57cec5SDimitry Andric if (T->isIntegerTy())
3790b57cec5SDimitry Andric return T->getIntegerBitWidth();
3800b57cec5SDimitry Andric return cast<VectorType>(T)->getElementType()->getIntegerBitWidth();
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric
getI32Ty(IRBuilder<> & B,const Type * T) const383fe013be4SDimitry Andric Type *AMDGPUCodeGenPrepareImpl::getI32Ty(IRBuilder<> &B, const Type *T) const {
3840b57cec5SDimitry Andric assert(needsPromotionToI32(T) && "T does not need promotion to i32");
3850b57cec5SDimitry Andric
3860b57cec5SDimitry Andric if (T->isIntegerTy())
3870b57cec5SDimitry Andric return B.getInt32Ty();
3885ffd83dbSDimitry Andric return FixedVectorType::get(B.getInt32Ty(), cast<FixedVectorType>(T));
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric
isSigned(const BinaryOperator & I) const391fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const BinaryOperator &I) const {
3920b57cec5SDimitry Andric return I.getOpcode() == Instruction::AShr ||
3930b57cec5SDimitry Andric I.getOpcode() == Instruction::SDiv || I.getOpcode() == Instruction::SRem;
3940b57cec5SDimitry Andric }
3950b57cec5SDimitry Andric
isSigned(const SelectInst & I) const396fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isSigned(const SelectInst &I) const {
3970b57cec5SDimitry Andric return isa<ICmpInst>(I.getOperand(0)) ?
3980b57cec5SDimitry Andric cast<ICmpInst>(I.getOperand(0))->isSigned() : false;
3990b57cec5SDimitry Andric }
4000b57cec5SDimitry Andric
needsPromotionToI32(const Type * T) const401fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::needsPromotionToI32(const Type *T) const {
402e8d8bef9SDimitry Andric if (!Widen16BitOps)
403e8d8bef9SDimitry Andric return false;
404e8d8bef9SDimitry Andric
4050b57cec5SDimitry Andric const IntegerType *IntTy = dyn_cast<IntegerType>(T);
4060b57cec5SDimitry Andric if (IntTy && IntTy->getBitWidth() > 1 && IntTy->getBitWidth() <= 16)
4070b57cec5SDimitry Andric return true;
4080b57cec5SDimitry Andric
4090b57cec5SDimitry Andric if (const VectorType *VT = dyn_cast<VectorType>(T)) {
4100b57cec5SDimitry Andric // TODO: The set of packed operations is more limited, so may want to
4110b57cec5SDimitry Andric // promote some anyway.
4120b57cec5SDimitry Andric if (ST->hasVOP3PInsts())
4130b57cec5SDimitry Andric return false;
4140b57cec5SDimitry Andric
4150b57cec5SDimitry Andric return needsPromotionToI32(VT->getElementType());
4160b57cec5SDimitry Andric }
4170b57cec5SDimitry Andric
4180b57cec5SDimitry Andric return false;
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric
isLegalFloatingTy(const Type * Ty) const421fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::isLegalFloatingTy(const Type *Ty) const {
422fe013be4SDimitry Andric return Ty->isFloatTy() || Ty->isDoubleTy() ||
423fe013be4SDimitry Andric (Ty->isHalfTy() && ST->has16BitInsts());
424fe013be4SDimitry Andric }
425fe013be4SDimitry Andric
4260b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nsw set.
promotedOpIsNSW(const Instruction & I)4270b57cec5SDimitry Andric static bool promotedOpIsNSW(const Instruction &I) {
4280b57cec5SDimitry Andric switch (I.getOpcode()) {
4290b57cec5SDimitry Andric case Instruction::Shl:
4300b57cec5SDimitry Andric case Instruction::Add:
4310b57cec5SDimitry Andric case Instruction::Sub:
4320b57cec5SDimitry Andric return true;
4330b57cec5SDimitry Andric case Instruction::Mul:
4340b57cec5SDimitry Andric return I.hasNoUnsignedWrap();
4350b57cec5SDimitry Andric default:
4360b57cec5SDimitry Andric return false;
4370b57cec5SDimitry Andric }
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric
4400b57cec5SDimitry Andric // Return true if the op promoted to i32 should have nuw set.
promotedOpIsNUW(const Instruction & I)4410b57cec5SDimitry Andric static bool promotedOpIsNUW(const Instruction &I) {
4420b57cec5SDimitry Andric switch (I.getOpcode()) {
4430b57cec5SDimitry Andric case Instruction::Shl:
4440b57cec5SDimitry Andric case Instruction::Add:
4450b57cec5SDimitry Andric case Instruction::Mul:
4460b57cec5SDimitry Andric return true;
4470b57cec5SDimitry Andric case Instruction::Sub:
4480b57cec5SDimitry Andric return I.hasNoUnsignedWrap();
4490b57cec5SDimitry Andric default:
4500b57cec5SDimitry Andric return false;
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric
canWidenScalarExtLoad(LoadInst & I) const454fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canWidenScalarExtLoad(LoadInst &I) const {
4550b57cec5SDimitry Andric Type *Ty = I.getType();
4560b57cec5SDimitry Andric const DataLayout &DL = Mod->getDataLayout();
4570b57cec5SDimitry Andric int TySize = DL.getTypeSizeInBits(Ty);
4585ffd83dbSDimitry Andric Align Alignment = DL.getValueOrABITypeAlignment(I.getAlign(), Ty);
4590b57cec5SDimitry Andric
460fe013be4SDimitry Andric return I.isSimple() && TySize < 32 && Alignment >= 4 && UA->isUniform(&I);
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric
promoteUniformOpToI32(BinaryOperator & I) const463fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(BinaryOperator &I) const {
4640b57cec5SDimitry Andric assert(needsPromotionToI32(I.getType()) &&
4650b57cec5SDimitry Andric "I does not need promotion to i32");
4660b57cec5SDimitry Andric
4670b57cec5SDimitry Andric if (I.getOpcode() == Instruction::SDiv ||
4680b57cec5SDimitry Andric I.getOpcode() == Instruction::UDiv ||
4690b57cec5SDimitry Andric I.getOpcode() == Instruction::SRem ||
4700b57cec5SDimitry Andric I.getOpcode() == Instruction::URem)
4710b57cec5SDimitry Andric return false;
4720b57cec5SDimitry Andric
4730b57cec5SDimitry Andric IRBuilder<> Builder(&I);
4740b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
4750b57cec5SDimitry Andric
4760b57cec5SDimitry Andric Type *I32Ty = getI32Ty(Builder, I.getType());
4770b57cec5SDimitry Andric Value *ExtOp0 = nullptr;
4780b57cec5SDimitry Andric Value *ExtOp1 = nullptr;
4790b57cec5SDimitry Andric Value *ExtRes = nullptr;
4800b57cec5SDimitry Andric Value *TruncRes = nullptr;
4810b57cec5SDimitry Andric
4820b57cec5SDimitry Andric if (isSigned(I)) {
4830b57cec5SDimitry Andric ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
4840b57cec5SDimitry Andric ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
4850b57cec5SDimitry Andric } else {
4860b57cec5SDimitry Andric ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
4870b57cec5SDimitry Andric ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric
4900b57cec5SDimitry Andric ExtRes = Builder.CreateBinOp(I.getOpcode(), ExtOp0, ExtOp1);
4910b57cec5SDimitry Andric if (Instruction *Inst = dyn_cast<Instruction>(ExtRes)) {
4920b57cec5SDimitry Andric if (promotedOpIsNSW(cast<Instruction>(I)))
4930b57cec5SDimitry Andric Inst->setHasNoSignedWrap();
4940b57cec5SDimitry Andric
4950b57cec5SDimitry Andric if (promotedOpIsNUW(cast<Instruction>(I)))
4960b57cec5SDimitry Andric Inst->setHasNoUnsignedWrap();
4970b57cec5SDimitry Andric
4980b57cec5SDimitry Andric if (const auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
4990b57cec5SDimitry Andric Inst->setIsExact(ExactOp->isExact());
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5030b57cec5SDimitry Andric
5040b57cec5SDimitry Andric I.replaceAllUsesWith(TruncRes);
5050b57cec5SDimitry Andric I.eraseFromParent();
5060b57cec5SDimitry Andric
5070b57cec5SDimitry Andric return true;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric
promoteUniformOpToI32(ICmpInst & I) const510fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(ICmpInst &I) const {
5110b57cec5SDimitry Andric assert(needsPromotionToI32(I.getOperand(0)->getType()) &&
5120b57cec5SDimitry Andric "I does not need promotion to i32");
5130b57cec5SDimitry Andric
5140b57cec5SDimitry Andric IRBuilder<> Builder(&I);
5150b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
5160b57cec5SDimitry Andric
5170b57cec5SDimitry Andric Type *I32Ty = getI32Ty(Builder, I.getOperand(0)->getType());
5180b57cec5SDimitry Andric Value *ExtOp0 = nullptr;
5190b57cec5SDimitry Andric Value *ExtOp1 = nullptr;
5200b57cec5SDimitry Andric Value *NewICmp = nullptr;
5210b57cec5SDimitry Andric
5220b57cec5SDimitry Andric if (I.isSigned()) {
5230b57cec5SDimitry Andric ExtOp0 = Builder.CreateSExt(I.getOperand(0), I32Ty);
5240b57cec5SDimitry Andric ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5250b57cec5SDimitry Andric } else {
5260b57cec5SDimitry Andric ExtOp0 = Builder.CreateZExt(I.getOperand(0), I32Ty);
5270b57cec5SDimitry Andric ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5280b57cec5SDimitry Andric }
5290b57cec5SDimitry Andric NewICmp = Builder.CreateICmp(I.getPredicate(), ExtOp0, ExtOp1);
5300b57cec5SDimitry Andric
5310b57cec5SDimitry Andric I.replaceAllUsesWith(NewICmp);
5320b57cec5SDimitry Andric I.eraseFromParent();
5330b57cec5SDimitry Andric
5340b57cec5SDimitry Andric return true;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric
promoteUniformOpToI32(SelectInst & I) const537fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformOpToI32(SelectInst &I) const {
5380b57cec5SDimitry Andric assert(needsPromotionToI32(I.getType()) &&
5390b57cec5SDimitry Andric "I does not need promotion to i32");
5400b57cec5SDimitry Andric
5410b57cec5SDimitry Andric IRBuilder<> Builder(&I);
5420b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
5430b57cec5SDimitry Andric
5440b57cec5SDimitry Andric Type *I32Ty = getI32Ty(Builder, I.getType());
5450b57cec5SDimitry Andric Value *ExtOp1 = nullptr;
5460b57cec5SDimitry Andric Value *ExtOp2 = nullptr;
5470b57cec5SDimitry Andric Value *ExtRes = nullptr;
5480b57cec5SDimitry Andric Value *TruncRes = nullptr;
5490b57cec5SDimitry Andric
5500b57cec5SDimitry Andric if (isSigned(I)) {
5510b57cec5SDimitry Andric ExtOp1 = Builder.CreateSExt(I.getOperand(1), I32Ty);
5520b57cec5SDimitry Andric ExtOp2 = Builder.CreateSExt(I.getOperand(2), I32Ty);
5530b57cec5SDimitry Andric } else {
5540b57cec5SDimitry Andric ExtOp1 = Builder.CreateZExt(I.getOperand(1), I32Ty);
5550b57cec5SDimitry Andric ExtOp2 = Builder.CreateZExt(I.getOperand(2), I32Ty);
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric ExtRes = Builder.CreateSelect(I.getOperand(0), ExtOp1, ExtOp2);
5580b57cec5SDimitry Andric TruncRes = Builder.CreateTrunc(ExtRes, I.getType());
5590b57cec5SDimitry Andric
5600b57cec5SDimitry Andric I.replaceAllUsesWith(TruncRes);
5610b57cec5SDimitry Andric I.eraseFromParent();
5620b57cec5SDimitry Andric
5630b57cec5SDimitry Andric return true;
5640b57cec5SDimitry Andric }
5650b57cec5SDimitry Andric
promoteUniformBitreverseToI32(IntrinsicInst & I) const566fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::promoteUniformBitreverseToI32(
5670b57cec5SDimitry Andric IntrinsicInst &I) const {
5680b57cec5SDimitry Andric assert(I.getIntrinsicID() == Intrinsic::bitreverse &&
5690b57cec5SDimitry Andric "I must be bitreverse intrinsic");
5700b57cec5SDimitry Andric assert(needsPromotionToI32(I.getType()) &&
5710b57cec5SDimitry Andric "I does not need promotion to i32");
5720b57cec5SDimitry Andric
5730b57cec5SDimitry Andric IRBuilder<> Builder(&I);
5740b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
5750b57cec5SDimitry Andric
5760b57cec5SDimitry Andric Type *I32Ty = getI32Ty(Builder, I.getType());
5770b57cec5SDimitry Andric Function *I32 =
5780b57cec5SDimitry Andric Intrinsic::getDeclaration(Mod, Intrinsic::bitreverse, { I32Ty });
5790b57cec5SDimitry Andric Value *ExtOp = Builder.CreateZExt(I.getOperand(0), I32Ty);
5800b57cec5SDimitry Andric Value *ExtRes = Builder.CreateCall(I32, { ExtOp });
5810b57cec5SDimitry Andric Value *LShrOp =
5820b57cec5SDimitry Andric Builder.CreateLShr(ExtRes, 32 - getBaseElementBitWidth(I.getType()));
5830b57cec5SDimitry Andric Value *TruncRes =
5840b57cec5SDimitry Andric Builder.CreateTrunc(LShrOp, I.getType());
5850b57cec5SDimitry Andric
5860b57cec5SDimitry Andric I.replaceAllUsesWith(TruncRes);
5870b57cec5SDimitry Andric I.eraseFromParent();
5880b57cec5SDimitry Andric
5890b57cec5SDimitry Andric return true;
5900b57cec5SDimitry Andric }
5910b57cec5SDimitry Andric
numBitsUnsigned(Value * Op) const592fe013be4SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsUnsigned(Value *Op) const {
59304eeddc0SDimitry Andric return computeKnownBits(Op, *DL, 0, AC).countMaxActiveBits();
5940b57cec5SDimitry Andric }
5950b57cec5SDimitry Andric
numBitsSigned(Value * Op) const596fe013be4SDimitry Andric unsigned AMDGPUCodeGenPrepareImpl::numBitsSigned(Value *Op) const {
59704eeddc0SDimitry Andric return ComputeMaxSignificantBits(Op, *DL, 0, AC);
5980b57cec5SDimitry Andric }
5990b57cec5SDimitry Andric
extractValues(IRBuilder<> & Builder,SmallVectorImpl<Value * > & Values,Value * V)6000b57cec5SDimitry Andric static void extractValues(IRBuilder<> &Builder,
6010b57cec5SDimitry Andric SmallVectorImpl<Value *> &Values, Value *V) {
6025ffd83dbSDimitry Andric auto *VT = dyn_cast<FixedVectorType>(V->getType());
6030b57cec5SDimitry Andric if (!VT) {
6040b57cec5SDimitry Andric Values.push_back(V);
6050b57cec5SDimitry Andric return;
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric
6080b57cec5SDimitry Andric for (int I = 0, E = VT->getNumElements(); I != E; ++I)
6090b57cec5SDimitry Andric Values.push_back(Builder.CreateExtractElement(V, I));
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric
insertValues(IRBuilder<> & Builder,Type * Ty,SmallVectorImpl<Value * > & Values)6120b57cec5SDimitry Andric static Value *insertValues(IRBuilder<> &Builder,
6130b57cec5SDimitry Andric Type *Ty,
6140b57cec5SDimitry Andric SmallVectorImpl<Value *> &Values) {
615bdd1243dSDimitry Andric if (!Ty->isVectorTy()) {
616bdd1243dSDimitry Andric assert(Values.size() == 1);
6170b57cec5SDimitry Andric return Values[0];
618bdd1243dSDimitry Andric }
6190b57cec5SDimitry Andric
620bdd1243dSDimitry Andric Value *NewVal = PoisonValue::get(Ty);
6210b57cec5SDimitry Andric for (int I = 0, E = Values.size(); I != E; ++I)
6220b57cec5SDimitry Andric NewVal = Builder.CreateInsertElement(NewVal, Values[I], I);
6230b57cec5SDimitry Andric
6240b57cec5SDimitry Andric return NewVal;
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric
replaceMulWithMul24(BinaryOperator & I) const627fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::replaceMulWithMul24(BinaryOperator &I) const {
6280b57cec5SDimitry Andric if (I.getOpcode() != Instruction::Mul)
6290b57cec5SDimitry Andric return false;
6300b57cec5SDimitry Andric
6310b57cec5SDimitry Andric Type *Ty = I.getType();
6320b57cec5SDimitry Andric unsigned Size = Ty->getScalarSizeInBits();
6330b57cec5SDimitry Andric if (Size <= 16 && ST->has16BitInsts())
6340b57cec5SDimitry Andric return false;
6350b57cec5SDimitry Andric
6360b57cec5SDimitry Andric // Prefer scalar if this could be s_mul_i32
637fe013be4SDimitry Andric if (UA->isUniform(&I))
6380b57cec5SDimitry Andric return false;
6390b57cec5SDimitry Andric
6400b57cec5SDimitry Andric Value *LHS = I.getOperand(0);
6410b57cec5SDimitry Andric Value *RHS = I.getOperand(1);
6420b57cec5SDimitry Andric IRBuilder<> Builder(&I);
6430b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
6440b57cec5SDimitry Andric
645349cc55cSDimitry Andric unsigned LHSBits = 0, RHSBits = 0;
646349cc55cSDimitry Andric bool IsSigned = false;
6470b57cec5SDimitry Andric
64804eeddc0SDimitry Andric if (ST->hasMulU24() && (LHSBits = numBitsUnsigned(LHS)) <= 24 &&
64904eeddc0SDimitry Andric (RHSBits = numBitsUnsigned(RHS)) <= 24) {
650349cc55cSDimitry Andric IsSigned = false;
651349cc55cSDimitry Andric
65204eeddc0SDimitry Andric } else if (ST->hasMulI24() && (LHSBits = numBitsSigned(LHS)) <= 24 &&
65304eeddc0SDimitry Andric (RHSBits = numBitsSigned(RHS)) <= 24) {
654349cc55cSDimitry Andric IsSigned = true;
655349cc55cSDimitry Andric
6560b57cec5SDimitry Andric } else
6570b57cec5SDimitry Andric return false;
6580b57cec5SDimitry Andric
6590b57cec5SDimitry Andric SmallVector<Value *, 4> LHSVals;
6600b57cec5SDimitry Andric SmallVector<Value *, 4> RHSVals;
6610b57cec5SDimitry Andric SmallVector<Value *, 4> ResultVals;
6620b57cec5SDimitry Andric extractValues(Builder, LHSVals, LHS);
6630b57cec5SDimitry Andric extractValues(Builder, RHSVals, RHS);
6640b57cec5SDimitry Andric
6650b57cec5SDimitry Andric IntegerType *I32Ty = Builder.getInt32Ty();
666*c9157d92SDimitry Andric IntegerType *IntrinTy = Size > 32 ? Builder.getInt64Ty() : I32Ty;
667*c9157d92SDimitry Andric Type *DstTy = LHSVals[0]->getType();
668*c9157d92SDimitry Andric
6690b57cec5SDimitry Andric for (int I = 0, E = LHSVals.size(); I != E; ++I) {
670*c9157d92SDimitry Andric Value *LHS = IsSigned ? Builder.CreateSExtOrTrunc(LHSVals[I], I32Ty)
671*c9157d92SDimitry Andric : Builder.CreateZExtOrTrunc(LHSVals[I], I32Ty);
672*c9157d92SDimitry Andric Value *RHS = IsSigned ? Builder.CreateSExtOrTrunc(RHSVals[I], I32Ty)
673*c9157d92SDimitry Andric : Builder.CreateZExtOrTrunc(RHSVals[I], I32Ty);
674*c9157d92SDimitry Andric Intrinsic::ID ID =
675*c9157d92SDimitry Andric IsSigned ? Intrinsic::amdgcn_mul_i24 : Intrinsic::amdgcn_mul_u24;
676*c9157d92SDimitry Andric Value *Result = Builder.CreateIntrinsic(ID, {IntrinTy}, {LHS, RHS});
677*c9157d92SDimitry Andric Result = IsSigned ? Builder.CreateSExtOrTrunc(Result, DstTy)
678*c9157d92SDimitry Andric : Builder.CreateZExtOrTrunc(Result, DstTy);
679*c9157d92SDimitry Andric ResultVals.push_back(Result);
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric
6828bcb0991SDimitry Andric Value *NewVal = insertValues(Builder, Ty, ResultVals);
6838bcb0991SDimitry Andric NewVal->takeName(&I);
6848bcb0991SDimitry Andric I.replaceAllUsesWith(NewVal);
6850b57cec5SDimitry Andric I.eraseFromParent();
6860b57cec5SDimitry Andric
6870b57cec5SDimitry Andric return true;
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric
6905ffd83dbSDimitry Andric // Find a select instruction, which may have been casted. This is mostly to deal
6915ffd83dbSDimitry Andric // with cases where i16 selects were promoted here to i32.
findSelectThroughCast(Value * V,CastInst * & Cast)6925ffd83dbSDimitry Andric static SelectInst *findSelectThroughCast(Value *V, CastInst *&Cast) {
6935ffd83dbSDimitry Andric Cast = nullptr;
6945ffd83dbSDimitry Andric if (SelectInst *Sel = dyn_cast<SelectInst>(V))
6955ffd83dbSDimitry Andric return Sel;
6960b57cec5SDimitry Andric
6975ffd83dbSDimitry Andric if ((Cast = dyn_cast<CastInst>(V))) {
6985ffd83dbSDimitry Andric if (SelectInst *Sel = dyn_cast<SelectInst>(Cast->getOperand(0)))
6995ffd83dbSDimitry Andric return Sel;
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric
7025ffd83dbSDimitry Andric return nullptr;
7035ffd83dbSDimitry Andric }
7040b57cec5SDimitry Andric
foldBinOpIntoSelect(BinaryOperator & BO) const705fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::foldBinOpIntoSelect(BinaryOperator &BO) const {
7065ffd83dbSDimitry Andric // Don't do this unless the old select is going away. We want to eliminate the
7075ffd83dbSDimitry Andric // binary operator, not replace a binop with a select.
7085ffd83dbSDimitry Andric int SelOpNo = 0;
7095ffd83dbSDimitry Andric
7105ffd83dbSDimitry Andric CastInst *CastOp;
7115ffd83dbSDimitry Andric
7125ffd83dbSDimitry Andric // TODO: Should probably try to handle some cases with multiple
7135ffd83dbSDimitry Andric // users. Duplicating the select may be profitable for division.
7145ffd83dbSDimitry Andric SelectInst *Sel = findSelectThroughCast(BO.getOperand(0), CastOp);
7155ffd83dbSDimitry Andric if (!Sel || !Sel->hasOneUse()) {
7165ffd83dbSDimitry Andric SelOpNo = 1;
7175ffd83dbSDimitry Andric Sel = findSelectThroughCast(BO.getOperand(1), CastOp);
7185ffd83dbSDimitry Andric }
7195ffd83dbSDimitry Andric
7205ffd83dbSDimitry Andric if (!Sel || !Sel->hasOneUse())
7210b57cec5SDimitry Andric return false;
7220b57cec5SDimitry Andric
7235ffd83dbSDimitry Andric Constant *CT = dyn_cast<Constant>(Sel->getTrueValue());
7245ffd83dbSDimitry Andric Constant *CF = dyn_cast<Constant>(Sel->getFalseValue());
7255ffd83dbSDimitry Andric Constant *CBO = dyn_cast<Constant>(BO.getOperand(SelOpNo ^ 1));
7265ffd83dbSDimitry Andric if (!CBO || !CT || !CF)
7275ffd83dbSDimitry Andric return false;
7285ffd83dbSDimitry Andric
7295ffd83dbSDimitry Andric if (CastOp) {
7305ffd83dbSDimitry Andric if (!CastOp->hasOneUse())
7315ffd83dbSDimitry Andric return false;
7325ffd83dbSDimitry Andric CT = ConstantFoldCastOperand(CastOp->getOpcode(), CT, BO.getType(), *DL);
7335ffd83dbSDimitry Andric CF = ConstantFoldCastOperand(CastOp->getOpcode(), CF, BO.getType(), *DL);
7345ffd83dbSDimitry Andric }
7355ffd83dbSDimitry Andric
7365ffd83dbSDimitry Andric // TODO: Handle special 0/-1 cases DAG combine does, although we only really
7375ffd83dbSDimitry Andric // need to handle divisions here.
7385ffd83dbSDimitry Andric Constant *FoldedT = SelOpNo ?
7395ffd83dbSDimitry Andric ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CT, *DL) :
7405ffd83dbSDimitry Andric ConstantFoldBinaryOpOperands(BO.getOpcode(), CT, CBO, *DL);
741753f127fSDimitry Andric if (!FoldedT || isa<ConstantExpr>(FoldedT))
7425ffd83dbSDimitry Andric return false;
7435ffd83dbSDimitry Andric
7445ffd83dbSDimitry Andric Constant *FoldedF = SelOpNo ?
7455ffd83dbSDimitry Andric ConstantFoldBinaryOpOperands(BO.getOpcode(), CBO, CF, *DL) :
7465ffd83dbSDimitry Andric ConstantFoldBinaryOpOperands(BO.getOpcode(), CF, CBO, *DL);
747753f127fSDimitry Andric if (!FoldedF || isa<ConstantExpr>(FoldedF))
7485ffd83dbSDimitry Andric return false;
7495ffd83dbSDimitry Andric
7505ffd83dbSDimitry Andric IRBuilder<> Builder(&BO);
7515ffd83dbSDimitry Andric Builder.SetCurrentDebugLocation(BO.getDebugLoc());
7525ffd83dbSDimitry Andric if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&BO))
7535ffd83dbSDimitry Andric Builder.setFastMathFlags(FPOp->getFastMathFlags());
7545ffd83dbSDimitry Andric
7555ffd83dbSDimitry Andric Value *NewSelect = Builder.CreateSelect(Sel->getCondition(),
7565ffd83dbSDimitry Andric FoldedT, FoldedF);
7575ffd83dbSDimitry Andric NewSelect->takeName(&BO);
7585ffd83dbSDimitry Andric BO.replaceAllUsesWith(NewSelect);
7595ffd83dbSDimitry Andric BO.eraseFromParent();
7605ffd83dbSDimitry Andric if (CastOp)
7615ffd83dbSDimitry Andric CastOp->eraseFromParent();
7625ffd83dbSDimitry Andric Sel->eraseFromParent();
7635ffd83dbSDimitry Andric return true;
7645ffd83dbSDimitry Andric }
7655ffd83dbSDimitry Andric
766fe013be4SDimitry Andric std::pair<Value *, Value *>
getFrexpResults(IRBuilder<> & Builder,Value * Src) const767fe013be4SDimitry Andric AMDGPUCodeGenPrepareImpl::getFrexpResults(IRBuilder<> &Builder,
768fe013be4SDimitry Andric Value *Src) const {
769fe013be4SDimitry Andric Type *Ty = Src->getType();
770fe013be4SDimitry Andric Value *Frexp = Builder.CreateIntrinsic(Intrinsic::frexp,
771fe013be4SDimitry Andric {Ty, Builder.getInt32Ty()}, Src);
772fe013be4SDimitry Andric Value *FrexpMant = Builder.CreateExtractValue(Frexp, {0});
773fe013be4SDimitry Andric
774fe013be4SDimitry Andric // Bypass the bug workaround for the exponent result since it doesn't matter.
775fe013be4SDimitry Andric // TODO: Does the bug workaround even really need to consider the exponent
776fe013be4SDimitry Andric // result? It's unspecified by the spec.
777fe013be4SDimitry Andric
778fe013be4SDimitry Andric Value *FrexpExp =
779fe013be4SDimitry Andric ST->hasFractBug()
780fe013be4SDimitry Andric ? Builder.CreateIntrinsic(Intrinsic::amdgcn_frexp_exp,
781fe013be4SDimitry Andric {Builder.getInt32Ty(), Ty}, Src)
782fe013be4SDimitry Andric : Builder.CreateExtractValue(Frexp, {1});
783fe013be4SDimitry Andric return {FrexpMant, FrexpExp};
784fe013be4SDimitry Andric }
785fe013be4SDimitry Andric
786fe013be4SDimitry Andric /// Emit an expansion of 1.0 / Src good for 1ulp that supports denormals.
emitRcpIEEE1ULP(IRBuilder<> & Builder,Value * Src,bool IsNegative) const787fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitRcpIEEE1ULP(IRBuilder<> &Builder,
788fe013be4SDimitry Andric Value *Src,
789fe013be4SDimitry Andric bool IsNegative) const {
790fe013be4SDimitry Andric // Same as for 1.0, but expand the sign out of the constant.
791fe013be4SDimitry Andric // -1.0 / x -> rcp (fneg x)
792fe013be4SDimitry Andric if (IsNegative)
793fe013be4SDimitry Andric Src = Builder.CreateFNeg(Src);
794fe013be4SDimitry Andric
795fe013be4SDimitry Andric // The rcp instruction doesn't support denormals, so scale the input
796fe013be4SDimitry Andric // out of the denormal range and convert at the end.
797fe013be4SDimitry Andric //
798fe013be4SDimitry Andric // Expand as 2^-n * (1.0 / (x * 2^n))
799fe013be4SDimitry Andric
800fe013be4SDimitry Andric // TODO: Skip scaling if input is known never denormal and the input
801fe013be4SDimitry Andric // range won't underflow to denormal. The hard part is knowing the
802fe013be4SDimitry Andric // result. We need a range check, the result could be denormal for
803fe013be4SDimitry Andric // 0x1p+126 < den <= 0x1p+127.
804fe013be4SDimitry Andric auto [FrexpMant, FrexpExp] = getFrexpResults(Builder, Src);
805fe013be4SDimitry Andric Value *ScaleFactor = Builder.CreateNeg(FrexpExp);
806fe013be4SDimitry Andric Value *Rcp = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMant);
807*c9157d92SDimitry Andric return Builder.CreateCall(getLdexpF32(), {Rcp, ScaleFactor});
808fe013be4SDimitry Andric }
809fe013be4SDimitry Andric
810fe013be4SDimitry Andric /// Emit a 2ulp expansion for fdiv by using frexp for input scaling.
emitFrexpDiv(IRBuilder<> & Builder,Value * LHS,Value * RHS,FastMathFlags FMF) const811fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitFrexpDiv(IRBuilder<> &Builder, Value *LHS,
812fe013be4SDimitry Andric Value *RHS,
813fe013be4SDimitry Andric FastMathFlags FMF) const {
814fe013be4SDimitry Andric // If we have have to work around the fract/frexp bug, we're worse off than
815fe013be4SDimitry Andric // using the fdiv.fast expansion. The full safe expansion is faster if we have
816fe013be4SDimitry Andric // fast FMA.
817fe013be4SDimitry Andric if (HasFP32DenormalFlush && ST->hasFractBug() && !ST->hasFastFMAF32() &&
818fe013be4SDimitry Andric (!FMF.noNaNs() || !FMF.noInfs()))
819fe013be4SDimitry Andric return nullptr;
820fe013be4SDimitry Andric
821fe013be4SDimitry Andric // We're scaling the LHS to avoid a denormal input, and scale the denominator
822fe013be4SDimitry Andric // to avoid large values underflowing the result.
823fe013be4SDimitry Andric auto [FrexpMantRHS, FrexpExpRHS] = getFrexpResults(Builder, RHS);
824fe013be4SDimitry Andric
825fe013be4SDimitry Andric Value *Rcp =
826fe013be4SDimitry Andric Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, FrexpMantRHS);
827fe013be4SDimitry Andric
828fe013be4SDimitry Andric auto [FrexpMantLHS, FrexpExpLHS] = getFrexpResults(Builder, LHS);
829fe013be4SDimitry Andric Value *Mul = Builder.CreateFMul(FrexpMantLHS, Rcp);
830fe013be4SDimitry Andric
831fe013be4SDimitry Andric // We multiplied by 2^N/2^M, so we need to multiply by 2^(N-M) to scale the
832fe013be4SDimitry Andric // result.
833fe013be4SDimitry Andric Value *ExpDiff = Builder.CreateSub(FrexpExpLHS, FrexpExpRHS);
834*c9157d92SDimitry Andric return Builder.CreateCall(getLdexpF32(), {Mul, ExpDiff});
835*c9157d92SDimitry Andric }
836*c9157d92SDimitry Andric
837*c9157d92SDimitry Andric /// Emit a sqrt that handles denormals and is accurate to 2ulp.
emitSqrtIEEE2ULP(IRBuilder<> & Builder,Value * Src,FastMathFlags FMF) const838*c9157d92SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::emitSqrtIEEE2ULP(IRBuilder<> &Builder,
839*c9157d92SDimitry Andric Value *Src,
840*c9157d92SDimitry Andric FastMathFlags FMF) const {
841*c9157d92SDimitry Andric Type *Ty = Src->getType();
842*c9157d92SDimitry Andric APFloat SmallestNormal =
843*c9157d92SDimitry Andric APFloat::getSmallestNormalized(Ty->getFltSemantics());
844*c9157d92SDimitry Andric Value *NeedScale =
845*c9157d92SDimitry Andric Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
846*c9157d92SDimitry Andric
847*c9157d92SDimitry Andric ConstantInt *Zero = Builder.getInt32(0);
848*c9157d92SDimitry Andric Value *InputScaleFactor =
849*c9157d92SDimitry Andric Builder.CreateSelect(NeedScale, Builder.getInt32(32), Zero);
850*c9157d92SDimitry Andric
851*c9157d92SDimitry Andric Value *Scaled = Builder.CreateCall(getLdexpF32(), {Src, InputScaleFactor});
852*c9157d92SDimitry Andric
853*c9157d92SDimitry Andric Value *Sqrt = Builder.CreateCall(getSqrtF32(), Scaled);
854*c9157d92SDimitry Andric
855*c9157d92SDimitry Andric Value *OutputScaleFactor =
856*c9157d92SDimitry Andric Builder.CreateSelect(NeedScale, Builder.getInt32(-16), Zero);
857*c9157d92SDimitry Andric return Builder.CreateCall(getLdexpF32(), {Sqrt, OutputScaleFactor});
858fe013be4SDimitry Andric }
859fe013be4SDimitry Andric
860fe013be4SDimitry Andric /// Emit an expansion of 1.0 / sqrt(Src) good for 1ulp that supports denormals.
emitRsqIEEE1ULP(IRBuilder<> & Builder,Value * Src,bool IsNegative)861fe013be4SDimitry Andric static Value *emitRsqIEEE1ULP(IRBuilder<> &Builder, Value *Src,
862fe013be4SDimitry Andric bool IsNegative) {
863fe013be4SDimitry Andric // bool need_scale = x < 0x1p-126f;
864fe013be4SDimitry Andric // float input_scale = need_scale ? 0x1.0p+24f : 1.0f;
865fe013be4SDimitry Andric // float output_scale = need_scale ? 0x1.0p+12f : 1.0f;
866fe013be4SDimitry Andric // rsq(x * input_scale) * output_scale;
867fe013be4SDimitry Andric
868fe013be4SDimitry Andric Type *Ty = Src->getType();
869fe013be4SDimitry Andric APFloat SmallestNormal =
870fe013be4SDimitry Andric APFloat::getSmallestNormalized(Ty->getFltSemantics());
871fe013be4SDimitry Andric Value *NeedScale =
872fe013be4SDimitry Andric Builder.CreateFCmpOLT(Src, ConstantFP::get(Ty, SmallestNormal));
873fe013be4SDimitry Andric Constant *One = ConstantFP::get(Ty, 1.0);
874fe013be4SDimitry Andric Constant *InputScale = ConstantFP::get(Ty, 0x1.0p+24);
875fe013be4SDimitry Andric Constant *OutputScale =
876fe013be4SDimitry Andric ConstantFP::get(Ty, IsNegative ? -0x1.0p+12 : 0x1.0p+12);
877fe013be4SDimitry Andric
878fe013be4SDimitry Andric Value *InputScaleFactor = Builder.CreateSelect(NeedScale, InputScale, One);
879fe013be4SDimitry Andric
880fe013be4SDimitry Andric Value *ScaledInput = Builder.CreateFMul(Src, InputScaleFactor);
881fe013be4SDimitry Andric Value *Rsq = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, ScaledInput);
882fe013be4SDimitry Andric Value *OutputScaleFactor = Builder.CreateSelect(
883fe013be4SDimitry Andric NeedScale, OutputScale, IsNegative ? ConstantFP::get(Ty, -1.0) : One);
884fe013be4SDimitry Andric
885fe013be4SDimitry Andric return Builder.CreateFMul(Rsq, OutputScaleFactor);
886fe013be4SDimitry Andric }
887fe013be4SDimitry Andric
canOptimizeWithRsq(const FPMathOperator * SqrtOp,FastMathFlags DivFMF,FastMathFlags SqrtFMF) const888fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canOptimizeWithRsq(const FPMathOperator *SqrtOp,
889fe013be4SDimitry Andric FastMathFlags DivFMF,
890fe013be4SDimitry Andric FastMathFlags SqrtFMF) const {
891fe013be4SDimitry Andric // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
892fe013be4SDimitry Andric if (!DivFMF.allowContract() || !SqrtFMF.allowContract())
893fe013be4SDimitry Andric return false;
894fe013be4SDimitry Andric
895fe013be4SDimitry Andric // v_rsq_f32 gives 1ulp
896fe013be4SDimitry Andric return SqrtFMF.approxFunc() || HasUnsafeFPMath ||
897fe013be4SDimitry Andric SqrtOp->getFPAccuracy() >= 1.0f;
898fe013be4SDimitry Andric }
899fe013be4SDimitry Andric
optimizeWithRsq(IRBuilder<> & Builder,Value * Num,Value * Den,const FastMathFlags DivFMF,const FastMathFlags SqrtFMF,const Instruction * CtxI) const900fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithRsq(
901*c9157d92SDimitry Andric IRBuilder<> &Builder, Value *Num, Value *Den, const FastMathFlags DivFMF,
902*c9157d92SDimitry Andric const FastMathFlags SqrtFMF, const Instruction *CtxI) const {
903fe013be4SDimitry Andric // The rsqrt contraction increases accuracy from ~2ulp to ~1ulp.
904fe013be4SDimitry Andric assert(DivFMF.allowContract() && SqrtFMF.allowContract());
905fe013be4SDimitry Andric
906fe013be4SDimitry Andric // rsq_f16 is accurate to 0.51 ulp.
907fe013be4SDimitry Andric // rsq_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
908fe013be4SDimitry Andric // rsq_f64 is never accurate.
909fe013be4SDimitry Andric const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num);
910fe013be4SDimitry Andric if (!CLHS)
911fe013be4SDimitry Andric return nullptr;
912fe013be4SDimitry Andric
913fe013be4SDimitry Andric assert(Den->getType()->isFloatTy());
914fe013be4SDimitry Andric
915fe013be4SDimitry Andric bool IsNegative = false;
916fe013be4SDimitry Andric
917fe013be4SDimitry Andric // TODO: Handle other numerator values with arcp.
918fe013be4SDimitry Andric if (CLHS->isExactlyValue(1.0) || (IsNegative = CLHS->isExactlyValue(-1.0))) {
919fe013be4SDimitry Andric // Add in the sqrt flags.
920fe013be4SDimitry Andric IRBuilder<>::FastMathFlagGuard Guard(Builder);
921*c9157d92SDimitry Andric Builder.setFastMathFlags(DivFMF | SqrtFMF);
922fe013be4SDimitry Andric
923*c9157d92SDimitry Andric if ((DivFMF.approxFunc() && SqrtFMF.approxFunc()) || HasUnsafeFPMath ||
924fe013be4SDimitry Andric canIgnoreDenormalInput(Den, CtxI)) {
925fe013be4SDimitry Andric Value *Result = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rsq, Den);
926fe013be4SDimitry Andric // -1.0 / sqrt(x) -> fneg(rsq(x))
927fe013be4SDimitry Andric return IsNegative ? Builder.CreateFNeg(Result) : Result;
928fe013be4SDimitry Andric }
929fe013be4SDimitry Andric
930fe013be4SDimitry Andric return emitRsqIEEE1ULP(Builder, Den, IsNegative);
931fe013be4SDimitry Andric }
932fe013be4SDimitry Andric
933fe013be4SDimitry Andric return nullptr;
934fe013be4SDimitry Andric }
935fe013be4SDimitry Andric
9365ffd83dbSDimitry Andric // Optimize fdiv with rcp:
9375ffd83dbSDimitry Andric //
9385ffd83dbSDimitry Andric // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
9395ffd83dbSDimitry Andric // allowed with unsafe-fp-math or afn.
9405ffd83dbSDimitry Andric //
941fe013be4SDimitry Andric // a/b -> a*rcp(b) when arcp is allowed, and we only need provide ULP 1.0
942fe013be4SDimitry Andric Value *
optimizeWithRcp(IRBuilder<> & Builder,Value * Num,Value * Den,FastMathFlags FMF,const Instruction * CtxI) const943fe013be4SDimitry Andric AMDGPUCodeGenPrepareImpl::optimizeWithRcp(IRBuilder<> &Builder, Value *Num,
944fe013be4SDimitry Andric Value *Den, FastMathFlags FMF,
945fe013be4SDimitry Andric const Instruction *CtxI) const {
946fe013be4SDimitry Andric // rcp_f16 is accurate to 0.51 ulp.
947fe013be4SDimitry Andric // rcp_f32 is accurate for !fpmath >= 1.0ulp and denormals are flushed.
948fe013be4SDimitry Andric // rcp_f64 is never accurate.
949fe013be4SDimitry Andric assert(Den->getType()->isFloatTy());
9505ffd83dbSDimitry Andric
9515ffd83dbSDimitry Andric if (const ConstantFP *CLHS = dyn_cast<ConstantFP>(Num)) {
952fe013be4SDimitry Andric bool IsNegative = false;
953fe013be4SDimitry Andric if (CLHS->isExactlyValue(1.0) ||
954fe013be4SDimitry Andric (IsNegative = CLHS->isExactlyValue(-1.0))) {
955fe013be4SDimitry Andric Value *Src = Den;
956fe013be4SDimitry Andric
957fe013be4SDimitry Andric if (HasFP32DenormalFlush || FMF.approxFunc()) {
958fe013be4SDimitry Andric // -1.0 / x -> 1.0 / fneg(x)
959fe013be4SDimitry Andric if (IsNegative)
960fe013be4SDimitry Andric Src = Builder.CreateFNeg(Src);
9615ffd83dbSDimitry Andric
9625ffd83dbSDimitry Andric // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
9635ffd83dbSDimitry Andric // the CI documentation has a worst case error of 1 ulp.
964fe013be4SDimitry Andric // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK
965fe013be4SDimitry Andric // to use it as long as we aren't trying to use denormals.
9665ffd83dbSDimitry Andric //
9675ffd83dbSDimitry Andric // v_rcp_f16 and v_rsq_f16 DO support denormals.
9685ffd83dbSDimitry Andric
9695ffd83dbSDimitry Andric // NOTE: v_sqrt and v_rcp will be combined to v_rsq later. So we don't
9705ffd83dbSDimitry Andric // insert rsq intrinsic here.
9715ffd83dbSDimitry Andric
9725ffd83dbSDimitry Andric // 1.0 / x -> rcp(x)
973fe013be4SDimitry Andric return Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Src);
9745ffd83dbSDimitry Andric }
9755ffd83dbSDimitry Andric
976fe013be4SDimitry Andric // TODO: If the input isn't denormal, and we know the input exponent isn't
977fe013be4SDimitry Andric // big enough to introduce a denormal we can avoid the scaling.
978fe013be4SDimitry Andric return emitRcpIEEE1ULP(Builder, Src, IsNegative);
9795ffd83dbSDimitry Andric }
9805ffd83dbSDimitry Andric }
9815ffd83dbSDimitry Andric
982fe013be4SDimitry Andric if (FMF.allowReciprocal()) {
9835ffd83dbSDimitry Andric // x / y -> x * (1.0 / y)
984fe013be4SDimitry Andric
985fe013be4SDimitry Andric // TODO: Could avoid denormal scaling and use raw rcp if we knew the output
986fe013be4SDimitry Andric // will never underflow.
987fe013be4SDimitry Andric if (HasFP32DenormalFlush || FMF.approxFunc()) {
988fe013be4SDimitry Andric Value *Recip = Builder.CreateUnaryIntrinsic(Intrinsic::amdgcn_rcp, Den);
9895ffd83dbSDimitry Andric return Builder.CreateFMul(Num, Recip);
9905ffd83dbSDimitry Andric }
991fe013be4SDimitry Andric
992fe013be4SDimitry Andric Value *Recip = emitRcpIEEE1ULP(Builder, Den, false);
993fe013be4SDimitry Andric return Builder.CreateFMul(Num, Recip);
994fe013be4SDimitry Andric }
995fe013be4SDimitry Andric
9965ffd83dbSDimitry Andric return nullptr;
9975ffd83dbSDimitry Andric }
9985ffd83dbSDimitry Andric
9995ffd83dbSDimitry Andric // optimize with fdiv.fast:
10005ffd83dbSDimitry Andric //
10015ffd83dbSDimitry Andric // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10025ffd83dbSDimitry Andric //
10035ffd83dbSDimitry Andric // 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp.
10045ffd83dbSDimitry Andric //
10055ffd83dbSDimitry Andric // NOTE: optimizeWithRcp should be tried first because rcp is the preference.
optimizeWithFDivFast(IRBuilder<> & Builder,Value * Num,Value * Den,float ReqdAccuracy) const1006fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::optimizeWithFDivFast(
1007fe013be4SDimitry Andric IRBuilder<> &Builder, Value *Num, Value *Den, float ReqdAccuracy) const {
10085ffd83dbSDimitry Andric // fdiv.fast can achieve 2.5 ULP accuracy.
10095ffd83dbSDimitry Andric if (ReqdAccuracy < 2.5f)
10105ffd83dbSDimitry Andric return nullptr;
10115ffd83dbSDimitry Andric
10125ffd83dbSDimitry Andric // Only have fdiv.fast for f32.
1013fe013be4SDimitry Andric assert(Den->getType()->isFloatTy());
10145ffd83dbSDimitry Andric
10155ffd83dbSDimitry Andric bool NumIsOne = false;
10165ffd83dbSDimitry Andric if (const ConstantFP *CNum = dyn_cast<ConstantFP>(Num)) {
10175ffd83dbSDimitry Andric if (CNum->isExactlyValue(+1.0) || CNum->isExactlyValue(-1.0))
10185ffd83dbSDimitry Andric NumIsOne = true;
10195ffd83dbSDimitry Andric }
10205ffd83dbSDimitry Andric
10215ffd83dbSDimitry Andric // fdiv does not support denormals. But 1.0/x is always fine to use it.
1022fe013be4SDimitry Andric //
1023fe013be4SDimitry Andric // TODO: This works for any value with a specific known exponent range, don't
1024fe013be4SDimitry Andric // just limit to constant 1.
1025fe013be4SDimitry Andric if (!HasFP32DenormalFlush && !NumIsOne)
10265ffd83dbSDimitry Andric return nullptr;
10275ffd83dbSDimitry Andric
1028fe013be4SDimitry Andric return Builder.CreateIntrinsic(Intrinsic::amdgcn_fdiv_fast, {}, {Num, Den});
1029fe013be4SDimitry Andric }
1030fe013be4SDimitry Andric
visitFDivElement(IRBuilder<> & Builder,Value * Num,Value * Den,FastMathFlags DivFMF,FastMathFlags SqrtFMF,Value * RsqOp,const Instruction * FDivInst,float ReqdDivAccuracy) const1031fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::visitFDivElement(
1032fe013be4SDimitry Andric IRBuilder<> &Builder, Value *Num, Value *Den, FastMathFlags DivFMF,
1033fe013be4SDimitry Andric FastMathFlags SqrtFMF, Value *RsqOp, const Instruction *FDivInst,
1034fe013be4SDimitry Andric float ReqdDivAccuracy) const {
1035fe013be4SDimitry Andric if (RsqOp) {
1036fe013be4SDimitry Andric Value *Rsq =
1037fe013be4SDimitry Andric optimizeWithRsq(Builder, Num, RsqOp, DivFMF, SqrtFMF, FDivInst);
1038fe013be4SDimitry Andric if (Rsq)
1039fe013be4SDimitry Andric return Rsq;
1040fe013be4SDimitry Andric }
1041fe013be4SDimitry Andric
1042fe013be4SDimitry Andric Value *Rcp = optimizeWithRcp(Builder, Num, Den, DivFMF, FDivInst);
1043fe013be4SDimitry Andric if (Rcp)
1044fe013be4SDimitry Andric return Rcp;
1045fe013be4SDimitry Andric
1046fe013be4SDimitry Andric // In the basic case fdiv_fast has the same instruction count as the frexp div
1047fe013be4SDimitry Andric // expansion. Slightly prefer fdiv_fast since it ends in an fmul that can
1048fe013be4SDimitry Andric // potentially be fused into a user. Also, materialization of the constants
1049fe013be4SDimitry Andric // can be reused for multiple instances.
1050fe013be4SDimitry Andric Value *FDivFast = optimizeWithFDivFast(Builder, Num, Den, ReqdDivAccuracy);
1051fe013be4SDimitry Andric if (FDivFast)
1052fe013be4SDimitry Andric return FDivFast;
1053fe013be4SDimitry Andric
1054fe013be4SDimitry Andric return emitFrexpDiv(Builder, Num, Den, DivFMF);
10555ffd83dbSDimitry Andric }
10565ffd83dbSDimitry Andric
10575ffd83dbSDimitry Andric // Optimizations is performed based on fpmath, fast math flags as well as
10585ffd83dbSDimitry Andric // denormals to optimize fdiv with either rcp or fdiv.fast.
10595ffd83dbSDimitry Andric //
10605ffd83dbSDimitry Andric // With rcp:
10615ffd83dbSDimitry Andric // 1/x -> rcp(x) when rcp is sufficiently accurate or inaccurate rcp is
10625ffd83dbSDimitry Andric // allowed with unsafe-fp-math or afn.
10635ffd83dbSDimitry Andric //
10645ffd83dbSDimitry Andric // a/b -> a*rcp(b) when inaccurate rcp is allowed with unsafe-fp-math or afn.
10655ffd83dbSDimitry Andric //
10665ffd83dbSDimitry Andric // With fdiv.fast:
10675ffd83dbSDimitry Andric // a/b -> fdiv.fast(a, b) when !fpmath >= 2.5ulp with denormals flushed.
10685ffd83dbSDimitry Andric //
10695ffd83dbSDimitry Andric // 1/x -> fdiv.fast(1,x) when !fpmath >= 2.5ulp.
10705ffd83dbSDimitry Andric //
10715ffd83dbSDimitry Andric // NOTE: rcp is the preference in cases that both are legal.
visitFDiv(BinaryOperator & FDiv)1072fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitFDiv(BinaryOperator &FDiv) {
1073fe013be4SDimitry Andric if (DisableFDivExpand)
1074fe013be4SDimitry Andric return false;
10755ffd83dbSDimitry Andric
10765ffd83dbSDimitry Andric Type *Ty = FDiv.getType()->getScalarType();
1077fe013be4SDimitry Andric if (!Ty->isFloatTy())
1078fe013be4SDimitry Andric return false;
10795ffd83dbSDimitry Andric
1080e8d8bef9SDimitry Andric // The f64 rcp/rsq approximations are pretty inaccurate. We can do an
1081fe013be4SDimitry Andric // expansion around them in codegen. f16 is good enough to always use.
10820b57cec5SDimitry Andric
10830b57cec5SDimitry Andric const FPMathOperator *FPOp = cast<const FPMathOperator>(&FDiv);
1084fe013be4SDimitry Andric const FastMathFlags DivFMF = FPOp->getFastMathFlags();
10855ffd83dbSDimitry Andric const float ReqdAccuracy = FPOp->getFPAccuracy();
10860b57cec5SDimitry Andric
1087fe013be4SDimitry Andric FastMathFlags SqrtFMF;
10880b57cec5SDimitry Andric
10890b57cec5SDimitry Andric Value *Num = FDiv.getOperand(0);
10900b57cec5SDimitry Andric Value *Den = FDiv.getOperand(1);
10910b57cec5SDimitry Andric
1092fe013be4SDimitry Andric Value *RsqOp = nullptr;
1093fe013be4SDimitry Andric auto *DenII = dyn_cast<IntrinsicInst>(Den);
1094fe013be4SDimitry Andric if (DenII && DenII->getIntrinsicID() == Intrinsic::sqrt &&
1095fe013be4SDimitry Andric DenII->hasOneUse()) {
1096fe013be4SDimitry Andric const auto *SqrtOp = cast<FPMathOperator>(DenII);
1097fe013be4SDimitry Andric SqrtFMF = SqrtOp->getFastMathFlags();
1098fe013be4SDimitry Andric if (canOptimizeWithRsq(SqrtOp, DivFMF, SqrtFMF))
1099fe013be4SDimitry Andric RsqOp = SqrtOp->getOperand(0);
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric
1102*c9157d92SDimitry Andric // Inaccurate rcp is allowed with unsafe-fp-math or afn.
1103*c9157d92SDimitry Andric //
1104*c9157d92SDimitry Andric // Defer to codegen to handle this.
1105*c9157d92SDimitry Andric //
1106*c9157d92SDimitry Andric // TODO: Decide on an interpretation for interactions between afn + arcp +
1107*c9157d92SDimitry Andric // !fpmath, and make it consistent between here and codegen. For now, defer
1108*c9157d92SDimitry Andric // expansion of afn to codegen. The current interpretation is so aggressive we
1109*c9157d92SDimitry Andric // don't need any pre-consideration here when we have better information. A
1110*c9157d92SDimitry Andric // more conservative interpretation could use handling here.
1111*c9157d92SDimitry Andric const bool AllowInaccurateRcp = HasUnsafeFPMath || DivFMF.approxFunc();
1112*c9157d92SDimitry Andric if (!RsqOp && AllowInaccurateRcp)
1113*c9157d92SDimitry Andric return false;
1114*c9157d92SDimitry Andric
1115*c9157d92SDimitry Andric // Defer the correct implementations to codegen.
1116*c9157d92SDimitry Andric if (ReqdAccuracy < 1.0f)
1117*c9157d92SDimitry Andric return false;
1118*c9157d92SDimitry Andric
1119fe013be4SDimitry Andric IRBuilder<> Builder(FDiv.getParent(), std::next(FDiv.getIterator()));
1120fe013be4SDimitry Andric Builder.setFastMathFlags(DivFMF);
1121fe013be4SDimitry Andric Builder.SetCurrentDebugLocation(FDiv.getDebugLoc());
1122fe013be4SDimitry Andric
1123fe013be4SDimitry Andric SmallVector<Value *, 4> NumVals;
1124fe013be4SDimitry Andric SmallVector<Value *, 4> DenVals;
1125fe013be4SDimitry Andric SmallVector<Value *, 4> RsqDenVals;
1126fe013be4SDimitry Andric extractValues(Builder, NumVals, Num);
1127fe013be4SDimitry Andric extractValues(Builder, DenVals, Den);
1128fe013be4SDimitry Andric
1129fe013be4SDimitry Andric if (RsqOp)
1130fe013be4SDimitry Andric extractValues(Builder, RsqDenVals, RsqOp);
1131fe013be4SDimitry Andric
1132fe013be4SDimitry Andric SmallVector<Value *, 4> ResultVals(NumVals.size());
1133fe013be4SDimitry Andric for (int I = 0, E = NumVals.size(); I != E; ++I) {
1134fe013be4SDimitry Andric Value *NumElt = NumVals[I];
1135fe013be4SDimitry Andric Value *DenElt = DenVals[I];
1136fe013be4SDimitry Andric Value *RsqDenElt = RsqOp ? RsqDenVals[I] : nullptr;
1137fe013be4SDimitry Andric
1138fe013be4SDimitry Andric Value *NewElt =
1139fe013be4SDimitry Andric visitFDivElement(Builder, NumElt, DenElt, DivFMF, SqrtFMF, RsqDenElt,
1140fe013be4SDimitry Andric cast<Instruction>(FPOp), ReqdAccuracy);
1141fe013be4SDimitry Andric if (!NewElt) {
1142fe013be4SDimitry Andric // Keep the original, but scalarized.
1143fe013be4SDimitry Andric
1144fe013be4SDimitry Andric // This has the unfortunate side effect of sometimes scalarizing when
1145fe013be4SDimitry Andric // we're not going to do anything.
1146fe013be4SDimitry Andric NewElt = Builder.CreateFDiv(NumElt, DenElt);
1147fe013be4SDimitry Andric if (auto *NewEltInst = dyn_cast<Instruction>(NewElt))
1148fe013be4SDimitry Andric NewEltInst->copyMetadata(FDiv);
11490b57cec5SDimitry Andric }
11500b57cec5SDimitry Andric
1151fe013be4SDimitry Andric ResultVals[I] = NewElt;
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric
1154fe013be4SDimitry Andric Value *NewVal = insertValues(Builder, FDiv.getType(), ResultVals);
1155fe6060f1SDimitry Andric
1156fe013be4SDimitry Andric if (NewVal) {
1157fe013be4SDimitry Andric FDiv.replaceAllUsesWith(NewVal);
1158fe013be4SDimitry Andric NewVal->takeName(&FDiv);
1159fe013be4SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(&FDiv, TLInfo);
1160fe013be4SDimitry Andric }
1161fe6060f1SDimitry Andric
1162fe6060f1SDimitry Andric return true;
1163fe6060f1SDimitry Andric }
1164fe6060f1SDimitry Andric
hasUnsafeFPMath(const Function & F)11650b57cec5SDimitry Andric static bool hasUnsafeFPMath(const Function &F) {
11660b57cec5SDimitry Andric Attribute Attr = F.getFnAttribute("unsafe-fp-math");
1167fe6060f1SDimitry Andric return Attr.getValueAsBool();
11680b57cec5SDimitry Andric }
11690b57cec5SDimitry Andric
getMul64(IRBuilder<> & Builder,Value * LHS,Value * RHS)11700b57cec5SDimitry Andric static std::pair<Value*, Value*> getMul64(IRBuilder<> &Builder,
11710b57cec5SDimitry Andric Value *LHS, Value *RHS) {
11720b57cec5SDimitry Andric Type *I32Ty = Builder.getInt32Ty();
11730b57cec5SDimitry Andric Type *I64Ty = Builder.getInt64Ty();
11740b57cec5SDimitry Andric
11750b57cec5SDimitry Andric Value *LHS_EXT64 = Builder.CreateZExt(LHS, I64Ty);
11760b57cec5SDimitry Andric Value *RHS_EXT64 = Builder.CreateZExt(RHS, I64Ty);
11770b57cec5SDimitry Andric Value *MUL64 = Builder.CreateMul(LHS_EXT64, RHS_EXT64);
11780b57cec5SDimitry Andric Value *Lo = Builder.CreateTrunc(MUL64, I32Ty);
11790b57cec5SDimitry Andric Value *Hi = Builder.CreateLShr(MUL64, Builder.getInt64(32));
11800b57cec5SDimitry Andric Hi = Builder.CreateTrunc(Hi, I32Ty);
1181bdd1243dSDimitry Andric return std::pair(Lo, Hi);
11820b57cec5SDimitry Andric }
11830b57cec5SDimitry Andric
getMulHu(IRBuilder<> & Builder,Value * LHS,Value * RHS)11840b57cec5SDimitry Andric static Value* getMulHu(IRBuilder<> &Builder, Value *LHS, Value *RHS) {
11850b57cec5SDimitry Andric return getMul64(Builder, LHS, RHS).second;
11860b57cec5SDimitry Andric }
11870b57cec5SDimitry Andric
118881ad6265SDimitry Andric /// Figure out how many bits are really needed for this division. \p AtLeast is
11895ffd83dbSDimitry Andric /// an optimization hint to bypass the second ComputeNumSignBits call if we the
11905ffd83dbSDimitry Andric /// first one is insufficient. Returns -1 on failure.
getDivNumBits(BinaryOperator & I,Value * Num,Value * Den,unsigned AtLeast,bool IsSigned) const1191fe013be4SDimitry Andric int AMDGPUCodeGenPrepareImpl::getDivNumBits(BinaryOperator &I, Value *Num,
1192fe013be4SDimitry Andric Value *Den, unsigned AtLeast,
1193fe013be4SDimitry Andric bool IsSigned) const {
11945ffd83dbSDimitry Andric const DataLayout &DL = Mod->getDataLayout();
11955ffd83dbSDimitry Andric unsigned LHSSignBits = ComputeNumSignBits(Num, DL, 0, AC, &I);
11965ffd83dbSDimitry Andric if (LHSSignBits < AtLeast)
11975ffd83dbSDimitry Andric return -1;
11985ffd83dbSDimitry Andric
11995ffd83dbSDimitry Andric unsigned RHSSignBits = ComputeNumSignBits(Den, DL, 0, AC, &I);
12005ffd83dbSDimitry Andric if (RHSSignBits < AtLeast)
12015ffd83dbSDimitry Andric return -1;
12025ffd83dbSDimitry Andric
12035ffd83dbSDimitry Andric unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
12045ffd83dbSDimitry Andric unsigned DivBits = Num->getType()->getScalarSizeInBits() - SignBits;
12055ffd83dbSDimitry Andric if (IsSigned)
12065ffd83dbSDimitry Andric ++DivBits;
12075ffd83dbSDimitry Andric return DivBits;
12085ffd83dbSDimitry Andric }
12095ffd83dbSDimitry Andric
12100b57cec5SDimitry Andric // The fractional part of a float is enough to accurately represent up to
12110b57cec5SDimitry Andric // a 24-bit signed integer.
expandDivRem24(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den,bool IsDiv,bool IsSigned) const1212fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24(IRBuilder<> &Builder,
1213fe013be4SDimitry Andric BinaryOperator &I, Value *Num,
1214fe013be4SDimitry Andric Value *Den, bool IsDiv,
1215fe013be4SDimitry Andric bool IsSigned) const {
12165ffd83dbSDimitry Andric int DivBits = getDivNumBits(I, Num, Den, 9, IsSigned);
12175ffd83dbSDimitry Andric if (DivBits == -1)
12180b57cec5SDimitry Andric return nullptr;
12195ffd83dbSDimitry Andric return expandDivRem24Impl(Builder, I, Num, Den, DivBits, IsDiv, IsSigned);
12205ffd83dbSDimitry Andric }
12210b57cec5SDimitry Andric
expandDivRem24Impl(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den,unsigned DivBits,bool IsDiv,bool IsSigned) const1222fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem24Impl(
1223fe013be4SDimitry Andric IRBuilder<> &Builder, BinaryOperator &I, Value *Num, Value *Den,
1224fe013be4SDimitry Andric unsigned DivBits, bool IsDiv, bool IsSigned) const {
12250b57cec5SDimitry Andric Type *I32Ty = Builder.getInt32Ty();
12265ffd83dbSDimitry Andric Num = Builder.CreateTrunc(Num, I32Ty);
12275ffd83dbSDimitry Andric Den = Builder.CreateTrunc(Den, I32Ty);
12285ffd83dbSDimitry Andric
12290b57cec5SDimitry Andric Type *F32Ty = Builder.getFloatTy();
12300b57cec5SDimitry Andric ConstantInt *One = Builder.getInt32(1);
12310b57cec5SDimitry Andric Value *JQ = One;
12320b57cec5SDimitry Andric
12330b57cec5SDimitry Andric if (IsSigned) {
12340b57cec5SDimitry Andric // char|short jq = ia ^ ib;
12350b57cec5SDimitry Andric JQ = Builder.CreateXor(Num, Den);
12360b57cec5SDimitry Andric
12370b57cec5SDimitry Andric // jq = jq >> (bitsize - 2)
12380b57cec5SDimitry Andric JQ = Builder.CreateAShr(JQ, Builder.getInt32(30));
12390b57cec5SDimitry Andric
12400b57cec5SDimitry Andric // jq = jq | 0x1
12410b57cec5SDimitry Andric JQ = Builder.CreateOr(JQ, One);
12420b57cec5SDimitry Andric }
12430b57cec5SDimitry Andric
12440b57cec5SDimitry Andric // int ia = (int)LHS;
12450b57cec5SDimitry Andric Value *IA = Num;
12460b57cec5SDimitry Andric
12470b57cec5SDimitry Andric // int ib, (int)RHS;
12480b57cec5SDimitry Andric Value *IB = Den;
12490b57cec5SDimitry Andric
12500b57cec5SDimitry Andric // float fa = (float)ia;
12510b57cec5SDimitry Andric Value *FA = IsSigned ? Builder.CreateSIToFP(IA, F32Ty)
12520b57cec5SDimitry Andric : Builder.CreateUIToFP(IA, F32Ty);
12530b57cec5SDimitry Andric
12540b57cec5SDimitry Andric // float fb = (float)ib;
12550b57cec5SDimitry Andric Value *FB = IsSigned ? Builder.CreateSIToFP(IB,F32Ty)
12560b57cec5SDimitry Andric : Builder.CreateUIToFP(IB,F32Ty);
12570b57cec5SDimitry Andric
12585ffd83dbSDimitry Andric Function *RcpDecl = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp,
12595ffd83dbSDimitry Andric Builder.getFloatTy());
12605ffd83dbSDimitry Andric Value *RCP = Builder.CreateCall(RcpDecl, { FB });
12610b57cec5SDimitry Andric Value *FQM = Builder.CreateFMul(FA, RCP);
12620b57cec5SDimitry Andric
12630b57cec5SDimitry Andric // fq = trunc(fqm);
12640b57cec5SDimitry Andric CallInst *FQ = Builder.CreateUnaryIntrinsic(Intrinsic::trunc, FQM);
12650b57cec5SDimitry Andric FQ->copyFastMathFlags(Builder.getFastMathFlags());
12660b57cec5SDimitry Andric
12670b57cec5SDimitry Andric // float fqneg = -fq;
12680b57cec5SDimitry Andric Value *FQNeg = Builder.CreateFNeg(FQ);
12690b57cec5SDimitry Andric
12700b57cec5SDimitry Andric // float fr = mad(fqneg, fb, fa);
12715ffd83dbSDimitry Andric auto FMAD = !ST->hasMadMacF32Insts()
12725ffd83dbSDimitry Andric ? Intrinsic::fma
12735ffd83dbSDimitry Andric : (Intrinsic::ID)Intrinsic::amdgcn_fmad_ftz;
12745ffd83dbSDimitry Andric Value *FR = Builder.CreateIntrinsic(FMAD,
12750b57cec5SDimitry Andric {FQNeg->getType()}, {FQNeg, FB, FA}, FQ);
12760b57cec5SDimitry Andric
12770b57cec5SDimitry Andric // int iq = (int)fq;
12780b57cec5SDimitry Andric Value *IQ = IsSigned ? Builder.CreateFPToSI(FQ, I32Ty)
12790b57cec5SDimitry Andric : Builder.CreateFPToUI(FQ, I32Ty);
12800b57cec5SDimitry Andric
12810b57cec5SDimitry Andric // fr = fabs(fr);
12820b57cec5SDimitry Andric FR = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FR, FQ);
12830b57cec5SDimitry Andric
12840b57cec5SDimitry Andric // fb = fabs(fb);
12850b57cec5SDimitry Andric FB = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FB, FQ);
12860b57cec5SDimitry Andric
12870b57cec5SDimitry Andric // int cv = fr >= fb;
12880b57cec5SDimitry Andric Value *CV = Builder.CreateFCmpOGE(FR, FB);
12890b57cec5SDimitry Andric
12900b57cec5SDimitry Andric // jq = (cv ? jq : 0);
12910b57cec5SDimitry Andric JQ = Builder.CreateSelect(CV, JQ, Builder.getInt32(0));
12920b57cec5SDimitry Andric
12930b57cec5SDimitry Andric // dst = iq + jq;
12940b57cec5SDimitry Andric Value *Div = Builder.CreateAdd(IQ, JQ);
12950b57cec5SDimitry Andric
12960b57cec5SDimitry Andric Value *Res = Div;
12970b57cec5SDimitry Andric if (!IsDiv) {
12980b57cec5SDimitry Andric // Rem needs compensation, it's easier to recompute it
12990b57cec5SDimitry Andric Value *Rem = Builder.CreateMul(Div, Den);
13000b57cec5SDimitry Andric Res = Builder.CreateSub(Num, Rem);
13010b57cec5SDimitry Andric }
13020b57cec5SDimitry Andric
13035ffd83dbSDimitry Andric if (DivBits != 0 && DivBits < 32) {
13045ffd83dbSDimitry Andric // Extend in register from the number of bits this divide really is.
13050b57cec5SDimitry Andric if (IsSigned) {
13065ffd83dbSDimitry Andric int InRegBits = 32 - DivBits;
13075ffd83dbSDimitry Andric
13085ffd83dbSDimitry Andric Res = Builder.CreateShl(Res, InRegBits);
13095ffd83dbSDimitry Andric Res = Builder.CreateAShr(Res, InRegBits);
13100b57cec5SDimitry Andric } else {
13115ffd83dbSDimitry Andric ConstantInt *TruncMask
13125ffd83dbSDimitry Andric = Builder.getInt32((UINT64_C(1) << DivBits) - 1);
13130b57cec5SDimitry Andric Res = Builder.CreateAnd(Res, TruncMask);
13140b57cec5SDimitry Andric }
13155ffd83dbSDimitry Andric }
13160b57cec5SDimitry Andric
13170b57cec5SDimitry Andric return Res;
13180b57cec5SDimitry Andric }
13190b57cec5SDimitry Andric
13205ffd83dbSDimitry Andric // Try to recognize special cases the DAG will emit special, better expansions
13215ffd83dbSDimitry Andric // than the general expansion we do here.
13225ffd83dbSDimitry Andric
13235ffd83dbSDimitry Andric // TODO: It would be better to just directly handle those optimizations here.
divHasSpecialOptimization(BinaryOperator & I,Value * Num,Value * Den) const1324fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::divHasSpecialOptimization(BinaryOperator &I,
1325fe013be4SDimitry Andric Value *Num,
1326fe013be4SDimitry Andric Value *Den) const {
13275ffd83dbSDimitry Andric if (Constant *C = dyn_cast<Constant>(Den)) {
13285ffd83dbSDimitry Andric // Arbitrary constants get a better expansion as long as a wider mulhi is
13295ffd83dbSDimitry Andric // legal.
13305ffd83dbSDimitry Andric if (C->getType()->getScalarSizeInBits() <= 32)
13315ffd83dbSDimitry Andric return true;
13325ffd83dbSDimitry Andric
13335ffd83dbSDimitry Andric // TODO: Sdiv check for not exact for some reason.
13345ffd83dbSDimitry Andric
13355ffd83dbSDimitry Andric // If there's no wider mulhi, there's only a better expansion for powers of
13365ffd83dbSDimitry Andric // two.
13375ffd83dbSDimitry Andric // TODO: Should really know for each vector element.
13385ffd83dbSDimitry Andric if (isKnownToBeAPowerOfTwo(C, *DL, true, 0, AC, &I, DT))
13395ffd83dbSDimitry Andric return true;
13405ffd83dbSDimitry Andric
13415ffd83dbSDimitry Andric return false;
13425ffd83dbSDimitry Andric }
13435ffd83dbSDimitry Andric
13445ffd83dbSDimitry Andric if (BinaryOperator *BinOpDen = dyn_cast<BinaryOperator>(Den)) {
13455ffd83dbSDimitry Andric // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
13465ffd83dbSDimitry Andric if (BinOpDen->getOpcode() == Instruction::Shl &&
13475ffd83dbSDimitry Andric isa<Constant>(BinOpDen->getOperand(0)) &&
13485ffd83dbSDimitry Andric isKnownToBeAPowerOfTwo(BinOpDen->getOperand(0), *DL, true,
13495ffd83dbSDimitry Andric 0, AC, &I, DT)) {
13505ffd83dbSDimitry Andric return true;
13515ffd83dbSDimitry Andric }
13525ffd83dbSDimitry Andric }
13535ffd83dbSDimitry Andric
13545ffd83dbSDimitry Andric return false;
13555ffd83dbSDimitry Andric }
13565ffd83dbSDimitry Andric
getSign32(Value * V,IRBuilder<> & Builder,const DataLayout * DL)13575ffd83dbSDimitry Andric static Value *getSign32(Value *V, IRBuilder<> &Builder, const DataLayout *DL) {
13585ffd83dbSDimitry Andric // Check whether the sign can be determined statically.
13595ffd83dbSDimitry Andric KnownBits Known = computeKnownBits(V, *DL);
13605ffd83dbSDimitry Andric if (Known.isNegative())
13615ffd83dbSDimitry Andric return Constant::getAllOnesValue(V->getType());
13625ffd83dbSDimitry Andric if (Known.isNonNegative())
13635ffd83dbSDimitry Andric return Constant::getNullValue(V->getType());
13645ffd83dbSDimitry Andric return Builder.CreateAShr(V, Builder.getInt32(31));
13655ffd83dbSDimitry Andric }
13665ffd83dbSDimitry Andric
expandDivRem32(IRBuilder<> & Builder,BinaryOperator & I,Value * X,Value * Y) const1367fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::expandDivRem32(IRBuilder<> &Builder,
13685ffd83dbSDimitry Andric BinaryOperator &I, Value *X,
13695ffd83dbSDimitry Andric Value *Y) const {
13700b57cec5SDimitry Andric Instruction::BinaryOps Opc = I.getOpcode();
13710b57cec5SDimitry Andric assert(Opc == Instruction::URem || Opc == Instruction::UDiv ||
13720b57cec5SDimitry Andric Opc == Instruction::SRem || Opc == Instruction::SDiv);
13730b57cec5SDimitry Andric
13740b57cec5SDimitry Andric FastMathFlags FMF;
13750b57cec5SDimitry Andric FMF.setFast();
13760b57cec5SDimitry Andric Builder.setFastMathFlags(FMF);
13770b57cec5SDimitry Andric
13785ffd83dbSDimitry Andric if (divHasSpecialOptimization(I, X, Y))
13795ffd83dbSDimitry Andric return nullptr; // Keep it for later optimization.
13800b57cec5SDimitry Andric
13810b57cec5SDimitry Andric bool IsDiv = Opc == Instruction::UDiv || Opc == Instruction::SDiv;
13820b57cec5SDimitry Andric bool IsSigned = Opc == Instruction::SRem || Opc == Instruction::SDiv;
13830b57cec5SDimitry Andric
13845ffd83dbSDimitry Andric Type *Ty = X->getType();
13850b57cec5SDimitry Andric Type *I32Ty = Builder.getInt32Ty();
13860b57cec5SDimitry Andric Type *F32Ty = Builder.getFloatTy();
13870b57cec5SDimitry Andric
13880b57cec5SDimitry Andric if (Ty->getScalarSizeInBits() < 32) {
13890b57cec5SDimitry Andric if (IsSigned) {
13905ffd83dbSDimitry Andric X = Builder.CreateSExt(X, I32Ty);
13915ffd83dbSDimitry Andric Y = Builder.CreateSExt(Y, I32Ty);
13920b57cec5SDimitry Andric } else {
13935ffd83dbSDimitry Andric X = Builder.CreateZExt(X, I32Ty);
13945ffd83dbSDimitry Andric Y = Builder.CreateZExt(Y, I32Ty);
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric
13985ffd83dbSDimitry Andric if (Value *Res = expandDivRem24(Builder, I, X, Y, IsDiv, IsSigned)) {
13995ffd83dbSDimitry Andric return IsSigned ? Builder.CreateSExtOrTrunc(Res, Ty) :
14005ffd83dbSDimitry Andric Builder.CreateZExtOrTrunc(Res, Ty);
14010b57cec5SDimitry Andric }
14020b57cec5SDimitry Andric
14030b57cec5SDimitry Andric ConstantInt *Zero = Builder.getInt32(0);
14040b57cec5SDimitry Andric ConstantInt *One = Builder.getInt32(1);
14050b57cec5SDimitry Andric
14060b57cec5SDimitry Andric Value *Sign = nullptr;
14070b57cec5SDimitry Andric if (IsSigned) {
14085ffd83dbSDimitry Andric Value *SignX = getSign32(X, Builder, DL);
14095ffd83dbSDimitry Andric Value *SignY = getSign32(Y, Builder, DL);
14100b57cec5SDimitry Andric // Remainder sign is the same as LHS
14115ffd83dbSDimitry Andric Sign = IsDiv ? Builder.CreateXor(SignX, SignY) : SignX;
14120b57cec5SDimitry Andric
14135ffd83dbSDimitry Andric X = Builder.CreateAdd(X, SignX);
14145ffd83dbSDimitry Andric Y = Builder.CreateAdd(Y, SignY);
14150b57cec5SDimitry Andric
14165ffd83dbSDimitry Andric X = Builder.CreateXor(X, SignX);
14175ffd83dbSDimitry Andric Y = Builder.CreateXor(Y, SignY);
14180b57cec5SDimitry Andric }
14190b57cec5SDimitry Andric
14205ffd83dbSDimitry Andric // The algorithm here is based on ideas from "Software Integer Division", Tom
14215ffd83dbSDimitry Andric // Rodeheffer, August 2008.
14225ffd83dbSDimitry Andric //
14235ffd83dbSDimitry Andric // unsigned udiv(unsigned x, unsigned y) {
14245ffd83dbSDimitry Andric // // Initial estimate of inv(y). The constant is less than 2^32 to ensure
14255ffd83dbSDimitry Andric // // that this is a lower bound on inv(y), even if some of the calculations
14265ffd83dbSDimitry Andric // // round up.
14275ffd83dbSDimitry Andric // unsigned z = (unsigned)((4294967296.0 - 512.0) * v_rcp_f32((float)y));
14285ffd83dbSDimitry Andric //
14295ffd83dbSDimitry Andric // // One round of UNR (Unsigned integer Newton-Raphson) to improve z.
14305ffd83dbSDimitry Andric // // Empirically this is guaranteed to give a "two-y" lower bound on
14315ffd83dbSDimitry Andric // // inv(y).
14325ffd83dbSDimitry Andric // z += umulh(z, -y * z);
14335ffd83dbSDimitry Andric //
14345ffd83dbSDimitry Andric // // Quotient/remainder estimate.
14355ffd83dbSDimitry Andric // unsigned q = umulh(x, z);
14365ffd83dbSDimitry Andric // unsigned r = x - q * y;
14375ffd83dbSDimitry Andric //
14385ffd83dbSDimitry Andric // // Two rounds of quotient/remainder refinement.
14395ffd83dbSDimitry Andric // if (r >= y) {
14405ffd83dbSDimitry Andric // ++q;
14415ffd83dbSDimitry Andric // r -= y;
14425ffd83dbSDimitry Andric // }
14435ffd83dbSDimitry Andric // if (r >= y) {
14445ffd83dbSDimitry Andric // ++q;
14455ffd83dbSDimitry Andric // r -= y;
14465ffd83dbSDimitry Andric // }
14475ffd83dbSDimitry Andric //
14485ffd83dbSDimitry Andric // return q;
14495ffd83dbSDimitry Andric // }
14500b57cec5SDimitry Andric
14515ffd83dbSDimitry Andric // Initial estimate of inv(y).
14525ffd83dbSDimitry Andric Value *FloatY = Builder.CreateUIToFP(Y, F32Ty);
14535ffd83dbSDimitry Andric Function *Rcp = Intrinsic::getDeclaration(Mod, Intrinsic::amdgcn_rcp, F32Ty);
14545ffd83dbSDimitry Andric Value *RcpY = Builder.CreateCall(Rcp, {FloatY});
1455fe013be4SDimitry Andric Constant *Scale = ConstantFP::get(F32Ty, llvm::bit_cast<float>(0x4F7FFFFE));
14565ffd83dbSDimitry Andric Value *ScaledY = Builder.CreateFMul(RcpY, Scale);
14575ffd83dbSDimitry Andric Value *Z = Builder.CreateFPToUI(ScaledY, I32Ty);
14580b57cec5SDimitry Andric
14595ffd83dbSDimitry Andric // One round of UNR.
14605ffd83dbSDimitry Andric Value *NegY = Builder.CreateSub(Zero, Y);
14615ffd83dbSDimitry Andric Value *NegYZ = Builder.CreateMul(NegY, Z);
14625ffd83dbSDimitry Andric Z = Builder.CreateAdd(Z, getMulHu(Builder, Z, NegYZ));
14630b57cec5SDimitry Andric
14645ffd83dbSDimitry Andric // Quotient/remainder estimate.
14655ffd83dbSDimitry Andric Value *Q = getMulHu(Builder, X, Z);
14665ffd83dbSDimitry Andric Value *R = Builder.CreateSub(X, Builder.CreateMul(Q, Y));
14670b57cec5SDimitry Andric
14685ffd83dbSDimitry Andric // First quotient/remainder refinement.
14695ffd83dbSDimitry Andric Value *Cond = Builder.CreateICmpUGE(R, Y);
14705ffd83dbSDimitry Andric if (IsDiv)
14715ffd83dbSDimitry Andric Q = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14725ffd83dbSDimitry Andric R = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14730b57cec5SDimitry Andric
14745ffd83dbSDimitry Andric // Second quotient/remainder refinement.
14755ffd83dbSDimitry Andric Cond = Builder.CreateICmpUGE(R, Y);
14760b57cec5SDimitry Andric Value *Res;
14775ffd83dbSDimitry Andric if (IsDiv)
14785ffd83dbSDimitry Andric Res = Builder.CreateSelect(Cond, Builder.CreateAdd(Q, One), Q);
14795ffd83dbSDimitry Andric else
14805ffd83dbSDimitry Andric Res = Builder.CreateSelect(Cond, Builder.CreateSub(R, Y), R);
14810b57cec5SDimitry Andric
14820b57cec5SDimitry Andric if (IsSigned) {
14830b57cec5SDimitry Andric Res = Builder.CreateXor(Res, Sign);
14840b57cec5SDimitry Andric Res = Builder.CreateSub(Res, Sign);
14850b57cec5SDimitry Andric }
14860b57cec5SDimitry Andric
14870b57cec5SDimitry Andric Res = Builder.CreateTrunc(Res, Ty);
14880b57cec5SDimitry Andric
14890b57cec5SDimitry Andric return Res;
14900b57cec5SDimitry Andric }
14910b57cec5SDimitry Andric
shrinkDivRem64(IRBuilder<> & Builder,BinaryOperator & I,Value * Num,Value * Den) const1492fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::shrinkDivRem64(IRBuilder<> &Builder,
1493fe013be4SDimitry Andric BinaryOperator &I, Value *Num,
1494fe013be4SDimitry Andric Value *Den) const {
14955ffd83dbSDimitry Andric if (!ExpandDiv64InIR && divHasSpecialOptimization(I, Num, Den))
14965ffd83dbSDimitry Andric return nullptr; // Keep it for later optimization.
14975ffd83dbSDimitry Andric
14985ffd83dbSDimitry Andric Instruction::BinaryOps Opc = I.getOpcode();
14995ffd83dbSDimitry Andric
15005ffd83dbSDimitry Andric bool IsDiv = Opc == Instruction::SDiv || Opc == Instruction::UDiv;
15015ffd83dbSDimitry Andric bool IsSigned = Opc == Instruction::SDiv || Opc == Instruction::SRem;
15025ffd83dbSDimitry Andric
15035ffd83dbSDimitry Andric int NumDivBits = getDivNumBits(I, Num, Den, 32, IsSigned);
15045ffd83dbSDimitry Andric if (NumDivBits == -1)
15055ffd83dbSDimitry Andric return nullptr;
15065ffd83dbSDimitry Andric
15075ffd83dbSDimitry Andric Value *Narrowed = nullptr;
15085ffd83dbSDimitry Andric if (NumDivBits <= 24) {
15095ffd83dbSDimitry Andric Narrowed = expandDivRem24Impl(Builder, I, Num, Den, NumDivBits,
15105ffd83dbSDimitry Andric IsDiv, IsSigned);
15115ffd83dbSDimitry Andric } else if (NumDivBits <= 32) {
15125ffd83dbSDimitry Andric Narrowed = expandDivRem32(Builder, I, Num, Den);
15135ffd83dbSDimitry Andric }
15145ffd83dbSDimitry Andric
15155ffd83dbSDimitry Andric if (Narrowed) {
15165ffd83dbSDimitry Andric return IsSigned ? Builder.CreateSExt(Narrowed, Num->getType()) :
15175ffd83dbSDimitry Andric Builder.CreateZExt(Narrowed, Num->getType());
15185ffd83dbSDimitry Andric }
15195ffd83dbSDimitry Andric
15205ffd83dbSDimitry Andric return nullptr;
15215ffd83dbSDimitry Andric }
15225ffd83dbSDimitry Andric
expandDivRem64(BinaryOperator & I) const1523fe013be4SDimitry Andric void AMDGPUCodeGenPrepareImpl::expandDivRem64(BinaryOperator &I) const {
15245ffd83dbSDimitry Andric Instruction::BinaryOps Opc = I.getOpcode();
15255ffd83dbSDimitry Andric // Do the general expansion.
15265ffd83dbSDimitry Andric if (Opc == Instruction::UDiv || Opc == Instruction::SDiv) {
15275ffd83dbSDimitry Andric expandDivisionUpTo64Bits(&I);
15285ffd83dbSDimitry Andric return;
15295ffd83dbSDimitry Andric }
15305ffd83dbSDimitry Andric
15315ffd83dbSDimitry Andric if (Opc == Instruction::URem || Opc == Instruction::SRem) {
15325ffd83dbSDimitry Andric expandRemainderUpTo64Bits(&I);
15335ffd83dbSDimitry Andric return;
15345ffd83dbSDimitry Andric }
15355ffd83dbSDimitry Andric
15365ffd83dbSDimitry Andric llvm_unreachable("not a division");
15375ffd83dbSDimitry Andric }
15385ffd83dbSDimitry Andric
visitBinaryOperator(BinaryOperator & I)1539fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBinaryOperator(BinaryOperator &I) {
15405ffd83dbSDimitry Andric if (foldBinOpIntoSelect(I))
15415ffd83dbSDimitry Andric return true;
15425ffd83dbSDimitry Andric
15430b57cec5SDimitry Andric if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
1544fe013be4SDimitry Andric UA->isUniform(&I) && promoteUniformOpToI32(I))
15450b57cec5SDimitry Andric return true;
15460b57cec5SDimitry Andric
15478bcb0991SDimitry Andric if (UseMul24Intrin && replaceMulWithMul24(I))
15480b57cec5SDimitry Andric return true;
15490b57cec5SDimitry Andric
15500b57cec5SDimitry Andric bool Changed = false;
15510b57cec5SDimitry Andric Instruction::BinaryOps Opc = I.getOpcode();
15520b57cec5SDimitry Andric Type *Ty = I.getType();
15530b57cec5SDimitry Andric Value *NewDiv = nullptr;
15545ffd83dbSDimitry Andric unsigned ScalarSize = Ty->getScalarSizeInBits();
15555ffd83dbSDimitry Andric
15565ffd83dbSDimitry Andric SmallVector<BinaryOperator *, 8> Div64ToExpand;
15575ffd83dbSDimitry Andric
15580b57cec5SDimitry Andric if ((Opc == Instruction::URem || Opc == Instruction::UDiv ||
15590b57cec5SDimitry Andric Opc == Instruction::SRem || Opc == Instruction::SDiv) &&
15605ffd83dbSDimitry Andric ScalarSize <= 64 &&
15615ffd83dbSDimitry Andric !DisableIDivExpand) {
15620b57cec5SDimitry Andric Value *Num = I.getOperand(0);
15630b57cec5SDimitry Andric Value *Den = I.getOperand(1);
15640b57cec5SDimitry Andric IRBuilder<> Builder(&I);
15650b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
15660b57cec5SDimitry Andric
15675ffd83dbSDimitry Andric if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1568bdd1243dSDimitry Andric NewDiv = PoisonValue::get(VT);
15690b57cec5SDimitry Andric
15700b57cec5SDimitry Andric for (unsigned N = 0, E = VT->getNumElements(); N != E; ++N) {
15710b57cec5SDimitry Andric Value *NumEltN = Builder.CreateExtractElement(Num, N);
15720b57cec5SDimitry Andric Value *DenEltN = Builder.CreateExtractElement(Den, N);
15735ffd83dbSDimitry Andric
15745ffd83dbSDimitry Andric Value *NewElt;
15755ffd83dbSDimitry Andric if (ScalarSize <= 32) {
15765ffd83dbSDimitry Andric NewElt = expandDivRem32(Builder, I, NumEltN, DenEltN);
15770b57cec5SDimitry Andric if (!NewElt)
15780b57cec5SDimitry Andric NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15795ffd83dbSDimitry Andric } else {
15805ffd83dbSDimitry Andric // See if this 64-bit division can be shrunk to 32/24-bits before
15815ffd83dbSDimitry Andric // producing the general expansion.
15825ffd83dbSDimitry Andric NewElt = shrinkDivRem64(Builder, I, NumEltN, DenEltN);
15835ffd83dbSDimitry Andric if (!NewElt) {
15845ffd83dbSDimitry Andric // The general 64-bit expansion introduces control flow and doesn't
15855ffd83dbSDimitry Andric // return the new value. Just insert a scalar copy and defer
15865ffd83dbSDimitry Andric // expanding it.
15875ffd83dbSDimitry Andric NewElt = Builder.CreateBinOp(Opc, NumEltN, DenEltN);
15885ffd83dbSDimitry Andric Div64ToExpand.push_back(cast<BinaryOperator>(NewElt));
15895ffd83dbSDimitry Andric }
15905ffd83dbSDimitry Andric }
15915ffd83dbSDimitry Andric
15920b57cec5SDimitry Andric NewDiv = Builder.CreateInsertElement(NewDiv, NewElt, N);
15930b57cec5SDimitry Andric }
15940b57cec5SDimitry Andric } else {
15955ffd83dbSDimitry Andric if (ScalarSize <= 32)
15960b57cec5SDimitry Andric NewDiv = expandDivRem32(Builder, I, Num, Den);
15975ffd83dbSDimitry Andric else {
15985ffd83dbSDimitry Andric NewDiv = shrinkDivRem64(Builder, I, Num, Den);
15995ffd83dbSDimitry Andric if (!NewDiv)
16005ffd83dbSDimitry Andric Div64ToExpand.push_back(&I);
16015ffd83dbSDimitry Andric }
16020b57cec5SDimitry Andric }
16030b57cec5SDimitry Andric
16040b57cec5SDimitry Andric if (NewDiv) {
16050b57cec5SDimitry Andric I.replaceAllUsesWith(NewDiv);
16060b57cec5SDimitry Andric I.eraseFromParent();
16070b57cec5SDimitry Andric Changed = true;
16080b57cec5SDimitry Andric }
16090b57cec5SDimitry Andric }
16100b57cec5SDimitry Andric
16115ffd83dbSDimitry Andric if (ExpandDiv64InIR) {
16125ffd83dbSDimitry Andric // TODO: We get much worse code in specially handled constant cases.
16135ffd83dbSDimitry Andric for (BinaryOperator *Div : Div64ToExpand) {
16145ffd83dbSDimitry Andric expandDivRem64(*Div);
1615fe013be4SDimitry Andric FlowChanged = true;
16165ffd83dbSDimitry Andric Changed = true;
16175ffd83dbSDimitry Andric }
16185ffd83dbSDimitry Andric }
16195ffd83dbSDimitry Andric
16200b57cec5SDimitry Andric return Changed;
16210b57cec5SDimitry Andric }
16220b57cec5SDimitry Andric
visitLoadInst(LoadInst & I)1623fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitLoadInst(LoadInst &I) {
16240b57cec5SDimitry Andric if (!WidenLoads)
16250b57cec5SDimitry Andric return false;
16260b57cec5SDimitry Andric
16270b57cec5SDimitry Andric if ((I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
16280b57cec5SDimitry Andric I.getPointerAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
16290b57cec5SDimitry Andric canWidenScalarExtLoad(I)) {
16300b57cec5SDimitry Andric IRBuilder<> Builder(&I);
16310b57cec5SDimitry Andric Builder.SetCurrentDebugLocation(I.getDebugLoc());
16320b57cec5SDimitry Andric
16330b57cec5SDimitry Andric Type *I32Ty = Builder.getInt32Ty();
1634fe013be4SDimitry Andric LoadInst *WidenLoad = Builder.CreateLoad(I32Ty, I.getPointerOperand());
16350b57cec5SDimitry Andric WidenLoad->copyMetadata(I);
16360b57cec5SDimitry Andric
16370b57cec5SDimitry Andric // If we have range metadata, we need to convert the type, and not make
16380b57cec5SDimitry Andric // assumptions about the high bits.
16390b57cec5SDimitry Andric if (auto *Range = WidenLoad->getMetadata(LLVMContext::MD_range)) {
16400b57cec5SDimitry Andric ConstantInt *Lower =
16410b57cec5SDimitry Andric mdconst::extract<ConstantInt>(Range->getOperand(0));
16420b57cec5SDimitry Andric
1643349cc55cSDimitry Andric if (Lower->isNullValue()) {
16440b57cec5SDimitry Andric WidenLoad->setMetadata(LLVMContext::MD_range, nullptr);
16450b57cec5SDimitry Andric } else {
16460b57cec5SDimitry Andric Metadata *LowAndHigh[] = {
16470b57cec5SDimitry Andric ConstantAsMetadata::get(ConstantInt::get(I32Ty, Lower->getValue().zext(32))),
16480b57cec5SDimitry Andric // Don't make assumptions about the high bits.
16490b57cec5SDimitry Andric ConstantAsMetadata::get(ConstantInt::get(I32Ty, 0))
16500b57cec5SDimitry Andric };
16510b57cec5SDimitry Andric
16520b57cec5SDimitry Andric WidenLoad->setMetadata(LLVMContext::MD_range,
16530b57cec5SDimitry Andric MDNode::get(Mod->getContext(), LowAndHigh));
16540b57cec5SDimitry Andric }
16550b57cec5SDimitry Andric }
16560b57cec5SDimitry Andric
16570b57cec5SDimitry Andric int TySize = Mod->getDataLayout().getTypeSizeInBits(I.getType());
16580b57cec5SDimitry Andric Type *IntNTy = Builder.getIntNTy(TySize);
16590b57cec5SDimitry Andric Value *ValTrunc = Builder.CreateTrunc(WidenLoad, IntNTy);
16600b57cec5SDimitry Andric Value *ValOrig = Builder.CreateBitCast(ValTrunc, I.getType());
16610b57cec5SDimitry Andric I.replaceAllUsesWith(ValOrig);
16620b57cec5SDimitry Andric I.eraseFromParent();
16630b57cec5SDimitry Andric return true;
16640b57cec5SDimitry Andric }
16650b57cec5SDimitry Andric
16660b57cec5SDimitry Andric return false;
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric
visitICmpInst(ICmpInst & I)1669fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitICmpInst(ICmpInst &I) {
16700b57cec5SDimitry Andric bool Changed = false;
16710b57cec5SDimitry Andric
16720b57cec5SDimitry Andric if (ST->has16BitInsts() && needsPromotionToI32(I.getOperand(0)->getType()) &&
1673fe013be4SDimitry Andric UA->isUniform(&I))
16740b57cec5SDimitry Andric Changed |= promoteUniformOpToI32(I);
16750b57cec5SDimitry Andric
16760b57cec5SDimitry Andric return Changed;
16770b57cec5SDimitry Andric }
16780b57cec5SDimitry Andric
visitSelectInst(SelectInst & I)1679fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSelectInst(SelectInst &I) {
1680fe013be4SDimitry Andric Value *Cond = I.getCondition();
1681fe013be4SDimitry Andric Value *TrueVal = I.getTrueValue();
1682fe013be4SDimitry Andric Value *FalseVal = I.getFalseValue();
1683fe013be4SDimitry Andric Value *CmpVal;
1684fe013be4SDimitry Andric FCmpInst::Predicate Pred;
16850b57cec5SDimitry Andric
1686fe013be4SDimitry Andric if (ST->has16BitInsts() && needsPromotionToI32(I.getType())) {
1687fe013be4SDimitry Andric if (UA->isUniform(&I))
1688fe013be4SDimitry Andric return promoteUniformOpToI32(I);
1689fe013be4SDimitry Andric return false;
16900b57cec5SDimitry Andric }
16910b57cec5SDimitry Andric
1692fe013be4SDimitry Andric // Match fract pattern with nan check.
1693fe013be4SDimitry Andric if (!match(Cond, m_FCmp(Pred, m_Value(CmpVal), m_NonNaN())))
1694fe013be4SDimitry Andric return false;
1695fe013be4SDimitry Andric
1696fe013be4SDimitry Andric FPMathOperator *FPOp = dyn_cast<FPMathOperator>(&I);
1697fe013be4SDimitry Andric if (!FPOp)
1698fe013be4SDimitry Andric return false;
1699fe013be4SDimitry Andric
1700fe013be4SDimitry Andric IRBuilder<> Builder(&I);
1701fe013be4SDimitry Andric Builder.setFastMathFlags(FPOp->getFastMathFlags());
1702fe013be4SDimitry Andric
1703fe013be4SDimitry Andric auto *IITrue = dyn_cast<IntrinsicInst>(TrueVal);
1704fe013be4SDimitry Andric auto *IIFalse = dyn_cast<IntrinsicInst>(FalseVal);
1705fe013be4SDimitry Andric
1706fe013be4SDimitry Andric Value *Fract = nullptr;
1707fe013be4SDimitry Andric if (Pred == FCmpInst::FCMP_UNO && TrueVal == CmpVal && IIFalse &&
1708fe013be4SDimitry Andric CmpVal == matchFractPat(*IIFalse)) {
1709fe013be4SDimitry Andric // isnan(x) ? x : fract(x)
1710fe013be4SDimitry Andric Fract = applyFractPat(Builder, CmpVal);
1711fe013be4SDimitry Andric } else if (Pred == FCmpInst::FCMP_ORD && FalseVal == CmpVal && IITrue &&
1712fe013be4SDimitry Andric CmpVal == matchFractPat(*IITrue)) {
1713fe013be4SDimitry Andric // !isnan(x) ? fract(x) : x
1714fe013be4SDimitry Andric Fract = applyFractPat(Builder, CmpVal);
1715fe013be4SDimitry Andric } else
1716fe013be4SDimitry Andric return false;
1717fe013be4SDimitry Andric
1718fe013be4SDimitry Andric Fract->takeName(&I);
1719fe013be4SDimitry Andric I.replaceAllUsesWith(Fract);
1720fe013be4SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
1721fe013be4SDimitry Andric return true;
1722fe013be4SDimitry Andric }
1723fe013be4SDimitry Andric
areInSameBB(const Value * A,const Value * B)1724fe013be4SDimitry Andric static bool areInSameBB(const Value *A, const Value *B) {
1725fe013be4SDimitry Andric const auto *IA = dyn_cast<Instruction>(A);
1726fe013be4SDimitry Andric const auto *IB = dyn_cast<Instruction>(B);
1727fe013be4SDimitry Andric return IA && IB && IA->getParent() == IB->getParent();
1728fe013be4SDimitry Andric }
1729fe013be4SDimitry Andric
1730fe013be4SDimitry Andric // Helper for breaking large PHIs that returns true when an extractelement on V
1731fe013be4SDimitry Andric // is likely to be folded away by the DAG combiner.
isInterestingPHIIncomingValue(const Value * V)1732fe013be4SDimitry Andric static bool isInterestingPHIIncomingValue(const Value *V) {
1733fe013be4SDimitry Andric const auto *FVT = dyn_cast<FixedVectorType>(V->getType());
1734fe013be4SDimitry Andric if (!FVT)
1735fe013be4SDimitry Andric return false;
1736fe013be4SDimitry Andric
1737fe013be4SDimitry Andric const Value *CurVal = V;
1738fe013be4SDimitry Andric
1739fe013be4SDimitry Andric // Check for insertelements, keeping track of the elements covered.
1740fe013be4SDimitry Andric BitVector EltsCovered(FVT->getNumElements());
1741fe013be4SDimitry Andric while (const auto *IE = dyn_cast<InsertElementInst>(CurVal)) {
1742fe013be4SDimitry Andric const auto *Idx = dyn_cast<ConstantInt>(IE->getOperand(2));
1743fe013be4SDimitry Andric
1744fe013be4SDimitry Andric // Non constant index/out of bounds index -> folding is unlikely.
1745fe013be4SDimitry Andric // The latter is more of a sanity check because canonical IR should just
1746fe013be4SDimitry Andric // have replaced those with poison.
1747fe013be4SDimitry Andric if (!Idx || Idx->getSExtValue() >= FVT->getNumElements())
1748fe013be4SDimitry Andric return false;
1749fe013be4SDimitry Andric
1750fe013be4SDimitry Andric const auto *VecSrc = IE->getOperand(0);
1751fe013be4SDimitry Andric
1752fe013be4SDimitry Andric // If the vector source is another instruction, it must be in the same basic
1753fe013be4SDimitry Andric // block. Otherwise, the DAGCombiner won't see the whole thing and is
1754fe013be4SDimitry Andric // unlikely to be able to do anything interesting here.
1755fe013be4SDimitry Andric if (isa<Instruction>(VecSrc) && !areInSameBB(VecSrc, IE))
1756fe013be4SDimitry Andric return false;
1757fe013be4SDimitry Andric
1758fe013be4SDimitry Andric CurVal = VecSrc;
1759fe013be4SDimitry Andric EltsCovered.set(Idx->getSExtValue());
1760fe013be4SDimitry Andric
1761fe013be4SDimitry Andric // All elements covered.
1762fe013be4SDimitry Andric if (EltsCovered.all())
1763fe013be4SDimitry Andric return true;
1764fe013be4SDimitry Andric }
1765fe013be4SDimitry Andric
1766fe013be4SDimitry Andric // We either didn't find a single insertelement, or the insertelement chain
1767fe013be4SDimitry Andric // ended before all elements were covered. Check for other interesting values.
1768fe013be4SDimitry Andric
1769fe013be4SDimitry Andric // Constants are always interesting because we can just constant fold the
1770fe013be4SDimitry Andric // extractelements.
1771fe013be4SDimitry Andric if (isa<Constant>(CurVal))
1772fe013be4SDimitry Andric return true;
1773fe013be4SDimitry Andric
1774fe013be4SDimitry Andric // shufflevector is likely to be profitable if either operand is a constant,
1775fe013be4SDimitry Andric // or if either source is in the same block.
1776fe013be4SDimitry Andric // This is because shufflevector is most often lowered as a series of
1777fe013be4SDimitry Andric // insert/extract elements anyway.
1778fe013be4SDimitry Andric if (const auto *SV = dyn_cast<ShuffleVectorInst>(CurVal)) {
1779fe013be4SDimitry Andric return isa<Constant>(SV->getOperand(1)) ||
1780fe013be4SDimitry Andric areInSameBB(SV, SV->getOperand(0)) ||
1781fe013be4SDimitry Andric areInSameBB(SV, SV->getOperand(1));
1782fe013be4SDimitry Andric }
1783fe013be4SDimitry Andric
1784fe013be4SDimitry Andric return false;
1785fe013be4SDimitry Andric }
1786fe013be4SDimitry Andric
collectPHINodes(const PHINode & I,SmallPtrSet<const PHINode *,8> & SeenPHIs)1787*c9157d92SDimitry Andric static void collectPHINodes(const PHINode &I,
1788*c9157d92SDimitry Andric SmallPtrSet<const PHINode *, 8> &SeenPHIs) {
1789*c9157d92SDimitry Andric const auto [It, Inserted] = SeenPHIs.insert(&I);
1790*c9157d92SDimitry Andric if (!Inserted)
1791*c9157d92SDimitry Andric return;
1792*c9157d92SDimitry Andric
1793*c9157d92SDimitry Andric for (const Value *Inc : I.incoming_values()) {
1794*c9157d92SDimitry Andric if (const auto *PhiInc = dyn_cast<PHINode>(Inc))
1795*c9157d92SDimitry Andric collectPHINodes(*PhiInc, SeenPHIs);
1796*c9157d92SDimitry Andric }
1797*c9157d92SDimitry Andric
1798*c9157d92SDimitry Andric for (const User *U : I.users()) {
1799*c9157d92SDimitry Andric if (const auto *PhiU = dyn_cast<PHINode>(U))
1800*c9157d92SDimitry Andric collectPHINodes(*PhiU, SeenPHIs);
1801*c9157d92SDimitry Andric }
1802*c9157d92SDimitry Andric }
1803*c9157d92SDimitry Andric
canBreakPHINode(const PHINode & I)1804fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::canBreakPHINode(const PHINode &I) {
1805*c9157d92SDimitry Andric // Check in the cache first.
1806*c9157d92SDimitry Andric if (const auto It = BreakPhiNodesCache.find(&I);
1807*c9157d92SDimitry Andric It != BreakPhiNodesCache.end())
1808fe013be4SDimitry Andric return It->second;
1809fe013be4SDimitry Andric
1810*c9157d92SDimitry Andric // We consider PHI nodes as part of "chains", so given a PHI node I, we
1811*c9157d92SDimitry Andric // recursively consider all its users and incoming values that are also PHI
1812*c9157d92SDimitry Andric // nodes. We then make a decision about all of those PHIs at once. Either they
1813*c9157d92SDimitry Andric // all get broken up, or none of them do. That way, we avoid cases where a
1814*c9157d92SDimitry Andric // single PHI is/is not broken and we end up reforming/exploding a vector
1815*c9157d92SDimitry Andric // multiple times, or even worse, doing it in a loop.
1816*c9157d92SDimitry Andric SmallPtrSet<const PHINode *, 8> WorkList;
1817*c9157d92SDimitry Andric collectPHINodes(I, WorkList);
1818fe013be4SDimitry Andric
1819*c9157d92SDimitry Andric #ifndef NDEBUG
1820*c9157d92SDimitry Andric // Check that none of the PHI nodes in the worklist are in the map. If some of
1821*c9157d92SDimitry Andric // them are, it means we're not good enough at collecting related PHIs.
1822*c9157d92SDimitry Andric for (const PHINode *WLP : WorkList) {
1823*c9157d92SDimitry Andric assert(BreakPhiNodesCache.count(WLP) == 0);
1824*c9157d92SDimitry Andric }
1825*c9157d92SDimitry Andric #endif
1826*c9157d92SDimitry Andric
1827*c9157d92SDimitry Andric // To consider a PHI profitable to break, we need to see some interesting
1828*c9157d92SDimitry Andric // incoming values. At least 2/3rd (rounded up) of all PHIs in the worklist
1829*c9157d92SDimitry Andric // must have one to consider all PHIs breakable.
1830*c9157d92SDimitry Andric //
1831*c9157d92SDimitry Andric // This threshold has been determined through performance testing.
1832*c9157d92SDimitry Andric //
1833*c9157d92SDimitry Andric // Note that the computation below is equivalent to
1834*c9157d92SDimitry Andric //
1835*c9157d92SDimitry Andric // (unsigned)ceil((K / 3.0) * 2)
1836*c9157d92SDimitry Andric //
1837*c9157d92SDimitry Andric // It's simply written this way to avoid mixing integral/FP arithmetic.
1838*c9157d92SDimitry Andric const auto Threshold = (alignTo(WorkList.size() * 2, 3) / 3);
1839*c9157d92SDimitry Andric unsigned NumBreakablePHIs = 0;
1840*c9157d92SDimitry Andric bool CanBreak = false;
1841*c9157d92SDimitry Andric for (const PHINode *Cur : WorkList) {
1842fe013be4SDimitry Andric // Don't break PHIs that have no interesting incoming values. That is, where
1843*c9157d92SDimitry Andric // there is no clear opportunity to fold the "extractelement" instructions
1844*c9157d92SDimitry Andric // we would add.
1845fe013be4SDimitry Andric //
1846fe013be4SDimitry Andric // Note: IC does not run after this pass, so we're only interested in the
1847fe013be4SDimitry Andric // foldings that the DAG combiner can do.
1848*c9157d92SDimitry Andric if (any_of(Cur->incoming_values(), isInterestingPHIIncomingValue)) {
1849*c9157d92SDimitry Andric if (++NumBreakablePHIs >= Threshold) {
1850*c9157d92SDimitry Andric CanBreak = true;
1851*c9157d92SDimitry Andric break;
1852*c9157d92SDimitry Andric }
1853*c9157d92SDimitry Andric }
1854fe013be4SDimitry Andric }
1855fe013be4SDimitry Andric
1856*c9157d92SDimitry Andric for (const PHINode *Cur : WorkList)
1857*c9157d92SDimitry Andric BreakPhiNodesCache[Cur] = CanBreak;
1858fe013be4SDimitry Andric
1859*c9157d92SDimitry Andric return CanBreak;
1860fe013be4SDimitry Andric }
1861fe013be4SDimitry Andric
1862fe013be4SDimitry Andric /// Helper class for "break large PHIs" (visitPHINode).
1863fe013be4SDimitry Andric ///
1864fe013be4SDimitry Andric /// This represents a slice of a PHI's incoming value, which is made up of:
1865fe013be4SDimitry Andric /// - The type of the slice (Ty)
1866fe013be4SDimitry Andric /// - The index in the incoming value's vector where the slice starts (Idx)
1867fe013be4SDimitry Andric /// - The number of elements in the slice (NumElts).
1868fe013be4SDimitry Andric /// It also keeps track of the NewPHI node inserted for this particular slice.
1869fe013be4SDimitry Andric ///
1870fe013be4SDimitry Andric /// Slice examples:
1871fe013be4SDimitry Andric /// <4 x i64> -> Split into four i64 slices.
1872fe013be4SDimitry Andric /// -> [i64, 0, 1], [i64, 1, 1], [i64, 2, 1], [i64, 3, 1]
1873fe013be4SDimitry Andric /// <5 x i16> -> Split into 2 <2 x i16> slices + a i16 tail.
1874fe013be4SDimitry Andric /// -> [<2 x i16>, 0, 2], [<2 x i16>, 2, 2], [i16, 4, 1]
1875fe013be4SDimitry Andric class VectorSlice {
1876fe013be4SDimitry Andric public:
VectorSlice(Type * Ty,unsigned Idx,unsigned NumElts)1877fe013be4SDimitry Andric VectorSlice(Type *Ty, unsigned Idx, unsigned NumElts)
1878fe013be4SDimitry Andric : Ty(Ty), Idx(Idx), NumElts(NumElts) {}
1879fe013be4SDimitry Andric
1880fe013be4SDimitry Andric Type *Ty = nullptr;
1881fe013be4SDimitry Andric unsigned Idx = 0;
1882fe013be4SDimitry Andric unsigned NumElts = 0;
1883fe013be4SDimitry Andric PHINode *NewPHI = nullptr;
1884fe013be4SDimitry Andric
1885fe013be4SDimitry Andric /// Slice \p Inc according to the information contained within this slice.
1886fe013be4SDimitry Andric /// This is cached, so if called multiple times for the same \p BB & \p Inc
1887fe013be4SDimitry Andric /// pair, it returns the same Sliced value as well.
1888fe013be4SDimitry Andric ///
1889fe013be4SDimitry Andric /// Note this *intentionally* does not return the same value for, say,
1890fe013be4SDimitry Andric /// [%bb.0, %0] & [%bb.1, %0] as:
1891fe013be4SDimitry Andric /// - It could cause issues with dominance (e.g. if bb.1 is seen first, then
1892fe013be4SDimitry Andric /// the value in bb.1 may not be reachable from bb.0 if it's its
1893fe013be4SDimitry Andric /// predecessor.)
1894fe013be4SDimitry Andric /// - We also want to make our extract instructions as local as possible so
1895fe013be4SDimitry Andric /// the DAG has better chances of folding them out. Duplicating them like
1896fe013be4SDimitry Andric /// that is beneficial in that regard.
1897fe013be4SDimitry Andric ///
1898fe013be4SDimitry Andric /// This is both a minor optimization to avoid creating duplicate
1899fe013be4SDimitry Andric /// instructions, but also a requirement for correctness. It is not forbidden
1900fe013be4SDimitry Andric /// for a PHI node to have the same [BB, Val] pair multiple times. If we
1901fe013be4SDimitry Andric /// returned a new value each time, those previously identical pairs would all
1902fe013be4SDimitry Andric /// have different incoming values (from the same block) and it'd cause a "PHI
1903fe013be4SDimitry Andric /// node has multiple entries for the same basic block with different incoming
1904fe013be4SDimitry Andric /// values!" verifier error.
getSlicedVal(BasicBlock * BB,Value * Inc,StringRef NewValName)1905fe013be4SDimitry Andric Value *getSlicedVal(BasicBlock *BB, Value *Inc, StringRef NewValName) {
1906fe013be4SDimitry Andric Value *&Res = SlicedVals[{BB, Inc}];
1907fe013be4SDimitry Andric if (Res)
1908fe013be4SDimitry Andric return Res;
1909fe013be4SDimitry Andric
1910fe013be4SDimitry Andric IRBuilder<> B(BB->getTerminator());
1911fe013be4SDimitry Andric if (Instruction *IncInst = dyn_cast<Instruction>(Inc))
1912fe013be4SDimitry Andric B.SetCurrentDebugLocation(IncInst->getDebugLoc());
1913fe013be4SDimitry Andric
1914fe013be4SDimitry Andric if (NumElts > 1) {
1915fe013be4SDimitry Andric SmallVector<int, 4> Mask;
1916fe013be4SDimitry Andric for (unsigned K = Idx; K < (Idx + NumElts); ++K)
1917fe013be4SDimitry Andric Mask.push_back(K);
1918fe013be4SDimitry Andric Res = B.CreateShuffleVector(Inc, Mask, NewValName);
1919fe013be4SDimitry Andric } else
1920fe013be4SDimitry Andric Res = B.CreateExtractElement(Inc, Idx, NewValName);
1921fe013be4SDimitry Andric
1922fe013be4SDimitry Andric return Res;
1923fe013be4SDimitry Andric }
1924fe013be4SDimitry Andric
1925fe013be4SDimitry Andric private:
1926fe013be4SDimitry Andric SmallDenseMap<std::pair<BasicBlock *, Value *>, Value *> SlicedVals;
1927fe013be4SDimitry Andric };
1928fe013be4SDimitry Andric
visitPHINode(PHINode & I)1929fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitPHINode(PHINode &I) {
1930fe013be4SDimitry Andric // Break-up fixed-vector PHIs into smaller pieces.
1931fe013be4SDimitry Andric // Default threshold is 32, so it breaks up any vector that's >32 bits into
1932fe013be4SDimitry Andric // its elements, or into 32-bit pieces (for 8/16 bit elts).
1933fe013be4SDimitry Andric //
1934fe013be4SDimitry Andric // This is only helpful for DAGISel because it doesn't handle large PHIs as
1935fe013be4SDimitry Andric // well as GlobalISel. DAGISel lowers PHIs by using CopyToReg/CopyFromReg.
1936fe013be4SDimitry Andric // With large, odd-sized PHIs we may end up needing many `build_vector`
1937fe013be4SDimitry Andric // operations with most elements being "undef". This inhibits a lot of
1938fe013be4SDimitry Andric // optimization opportunities and can result in unreasonably high register
1939fe013be4SDimitry Andric // pressure and the inevitable stack spilling.
1940*c9157d92SDimitry Andric if (!BreakLargePHIs || getCGPassBuilderOption().EnableGlobalISelOption)
1941fe013be4SDimitry Andric return false;
1942fe013be4SDimitry Andric
1943fe013be4SDimitry Andric FixedVectorType *FVT = dyn_cast<FixedVectorType>(I.getType());
1944*c9157d92SDimitry Andric if (!FVT || FVT->getNumElements() == 1 ||
1945*c9157d92SDimitry Andric DL->getTypeSizeInBits(FVT) <= BreakLargePHIsThreshold)
1946fe013be4SDimitry Andric return false;
1947fe013be4SDimitry Andric
1948*c9157d92SDimitry Andric if (!ForceBreakLargePHIs && !canBreakPHINode(I))
1949fe013be4SDimitry Andric return false;
1950fe013be4SDimitry Andric
1951fe013be4SDimitry Andric std::vector<VectorSlice> Slices;
1952fe013be4SDimitry Andric
1953fe013be4SDimitry Andric Type *EltTy = FVT->getElementType();
1954fe013be4SDimitry Andric {
1955fe013be4SDimitry Andric unsigned Idx = 0;
1956fe013be4SDimitry Andric // For 8/16 bits type, don't scalarize fully but break it up into as many
1957fe013be4SDimitry Andric // 32-bit slices as we can, and scalarize the tail.
1958fe013be4SDimitry Andric const unsigned EltSize = DL->getTypeSizeInBits(EltTy);
1959fe013be4SDimitry Andric const unsigned NumElts = FVT->getNumElements();
1960fe013be4SDimitry Andric if (EltSize == 8 || EltSize == 16) {
1961fe013be4SDimitry Andric const unsigned SubVecSize = (32 / EltSize);
1962fe013be4SDimitry Andric Type *SubVecTy = FixedVectorType::get(EltTy, SubVecSize);
1963fe013be4SDimitry Andric for (unsigned End = alignDown(NumElts, SubVecSize); Idx < End;
1964fe013be4SDimitry Andric Idx += SubVecSize)
1965fe013be4SDimitry Andric Slices.emplace_back(SubVecTy, Idx, SubVecSize);
1966fe013be4SDimitry Andric }
1967fe013be4SDimitry Andric
1968fe013be4SDimitry Andric // Scalarize all remaining elements.
1969fe013be4SDimitry Andric for (; Idx < NumElts; ++Idx)
1970fe013be4SDimitry Andric Slices.emplace_back(EltTy, Idx, 1);
1971fe013be4SDimitry Andric }
1972fe013be4SDimitry Andric
1973*c9157d92SDimitry Andric assert(Slices.size() > 1);
1974fe013be4SDimitry Andric
1975fe013be4SDimitry Andric // Create one PHI per vector piece. The "VectorSlice" class takes care of
1976fe013be4SDimitry Andric // creating the necessary instruction to extract the relevant slices of each
1977fe013be4SDimitry Andric // incoming value.
1978fe013be4SDimitry Andric IRBuilder<> B(I.getParent());
1979fe013be4SDimitry Andric B.SetCurrentDebugLocation(I.getDebugLoc());
1980fe013be4SDimitry Andric
1981fe013be4SDimitry Andric unsigned IncNameSuffix = 0;
1982fe013be4SDimitry Andric for (VectorSlice &S : Slices) {
1983fe013be4SDimitry Andric // We need to reset the build on each iteration, because getSlicedVal may
1984fe013be4SDimitry Andric // have inserted something into I's BB.
1985fe013be4SDimitry Andric B.SetInsertPoint(I.getParent()->getFirstNonPHI());
1986fe013be4SDimitry Andric S.NewPHI = B.CreatePHI(S.Ty, I.getNumIncomingValues());
1987fe013be4SDimitry Andric
1988fe013be4SDimitry Andric for (const auto &[Idx, BB] : enumerate(I.blocks())) {
1989fe013be4SDimitry Andric S.NewPHI->addIncoming(S.getSlicedVal(BB, I.getIncomingValue(Idx),
1990fe013be4SDimitry Andric "largephi.extractslice" +
1991fe013be4SDimitry Andric std::to_string(IncNameSuffix++)),
1992fe013be4SDimitry Andric BB);
1993fe013be4SDimitry Andric }
1994fe013be4SDimitry Andric }
1995fe013be4SDimitry Andric
1996fe013be4SDimitry Andric // And replace this PHI with a vector of all the previous PHI values.
1997fe013be4SDimitry Andric Value *Vec = PoisonValue::get(FVT);
1998fe013be4SDimitry Andric unsigned NameSuffix = 0;
1999fe013be4SDimitry Andric for (VectorSlice &S : Slices) {
2000fe013be4SDimitry Andric const auto ValName = "largephi.insertslice" + std::to_string(NameSuffix++);
2001fe013be4SDimitry Andric if (S.NumElts > 1)
2002fe013be4SDimitry Andric Vec =
2003fe013be4SDimitry Andric B.CreateInsertVector(FVT, Vec, S.NewPHI, B.getInt64(S.Idx), ValName);
2004fe013be4SDimitry Andric else
2005fe013be4SDimitry Andric Vec = B.CreateInsertElement(Vec, S.NewPHI, S.Idx, ValName);
2006fe013be4SDimitry Andric }
2007fe013be4SDimitry Andric
2008fe013be4SDimitry Andric I.replaceAllUsesWith(Vec);
2009fe013be4SDimitry Andric I.eraseFromParent();
2010fe013be4SDimitry Andric return true;
2011fe013be4SDimitry Andric }
2012fe013be4SDimitry Andric
visitIntrinsicInst(IntrinsicInst & I)2013fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitIntrinsicInst(IntrinsicInst &I) {
20140b57cec5SDimitry Andric switch (I.getIntrinsicID()) {
20150b57cec5SDimitry Andric case Intrinsic::bitreverse:
20160b57cec5SDimitry Andric return visitBitreverseIntrinsicInst(I);
2017fe013be4SDimitry Andric case Intrinsic::minnum:
2018fe013be4SDimitry Andric return visitMinNum(I);
2019*c9157d92SDimitry Andric case Intrinsic::sqrt:
2020*c9157d92SDimitry Andric return visitSqrt(I);
20210b57cec5SDimitry Andric default:
20220b57cec5SDimitry Andric return false;
20230b57cec5SDimitry Andric }
20240b57cec5SDimitry Andric }
20250b57cec5SDimitry Andric
visitBitreverseIntrinsicInst(IntrinsicInst & I)2026fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitBitreverseIntrinsicInst(IntrinsicInst &I) {
20270b57cec5SDimitry Andric bool Changed = false;
20280b57cec5SDimitry Andric
20290b57cec5SDimitry Andric if (ST->has16BitInsts() && needsPromotionToI32(I.getType()) &&
2030fe013be4SDimitry Andric UA->isUniform(&I))
20310b57cec5SDimitry Andric Changed |= promoteUniformBitreverseToI32(I);
20320b57cec5SDimitry Andric
20330b57cec5SDimitry Andric return Changed;
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric
2036fe013be4SDimitry Andric /// Match non-nan fract pattern.
2037fe013be4SDimitry Andric /// minnum(fsub(x, floor(x)), nextafter(1.0, -1.0)
2038fe013be4SDimitry Andric ///
2039fe013be4SDimitry Andric /// If fract is a useful instruction for the subtarget. Does not account for the
2040fe013be4SDimitry Andric /// nan handling; the instruction has a nan check on the input value.
matchFractPat(IntrinsicInst & I)2041fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::matchFractPat(IntrinsicInst &I) {
2042fe013be4SDimitry Andric if (ST->hasFractBug())
2043fe013be4SDimitry Andric return nullptr;
2044fe013be4SDimitry Andric
2045fe013be4SDimitry Andric if (I.getIntrinsicID() != Intrinsic::minnum)
2046fe013be4SDimitry Andric return nullptr;
2047fe013be4SDimitry Andric
2048fe013be4SDimitry Andric Type *Ty = I.getType();
2049fe013be4SDimitry Andric if (!isLegalFloatingTy(Ty->getScalarType()))
2050fe013be4SDimitry Andric return nullptr;
2051fe013be4SDimitry Andric
2052fe013be4SDimitry Andric Value *Arg0 = I.getArgOperand(0);
2053fe013be4SDimitry Andric Value *Arg1 = I.getArgOperand(1);
2054fe013be4SDimitry Andric
2055fe013be4SDimitry Andric const APFloat *C;
2056fe013be4SDimitry Andric if (!match(Arg1, m_APFloat(C)))
2057fe013be4SDimitry Andric return nullptr;
2058fe013be4SDimitry Andric
2059fe013be4SDimitry Andric APFloat One(1.0);
2060fe013be4SDimitry Andric bool LosesInfo;
2061fe013be4SDimitry Andric One.convert(C->getSemantics(), APFloat::rmNearestTiesToEven, &LosesInfo);
2062fe013be4SDimitry Andric
2063fe013be4SDimitry Andric // Match nextafter(1.0, -1)
2064fe013be4SDimitry Andric One.next(true);
2065fe013be4SDimitry Andric if (One != *C)
2066fe013be4SDimitry Andric return nullptr;
2067fe013be4SDimitry Andric
2068fe013be4SDimitry Andric Value *FloorSrc;
2069fe013be4SDimitry Andric if (match(Arg0, m_FSub(m_Value(FloorSrc),
2070fe013be4SDimitry Andric m_Intrinsic<Intrinsic::floor>(m_Deferred(FloorSrc)))))
2071fe013be4SDimitry Andric return FloorSrc;
2072fe013be4SDimitry Andric return nullptr;
2073fe013be4SDimitry Andric }
2074fe013be4SDimitry Andric
applyFractPat(IRBuilder<> & Builder,Value * FractArg)2075fe013be4SDimitry Andric Value *AMDGPUCodeGenPrepareImpl::applyFractPat(IRBuilder<> &Builder,
2076fe013be4SDimitry Andric Value *FractArg) {
2077fe013be4SDimitry Andric SmallVector<Value *, 4> FractVals;
2078fe013be4SDimitry Andric extractValues(Builder, FractVals, FractArg);
2079fe013be4SDimitry Andric
2080fe013be4SDimitry Andric SmallVector<Value *, 4> ResultVals(FractVals.size());
2081fe013be4SDimitry Andric
2082fe013be4SDimitry Andric Type *Ty = FractArg->getType()->getScalarType();
2083fe013be4SDimitry Andric for (unsigned I = 0, E = FractVals.size(); I != E; ++I) {
2084fe013be4SDimitry Andric ResultVals[I] =
2085fe013be4SDimitry Andric Builder.CreateIntrinsic(Intrinsic::amdgcn_fract, {Ty}, {FractVals[I]});
2086fe013be4SDimitry Andric }
2087fe013be4SDimitry Andric
2088fe013be4SDimitry Andric return insertValues(Builder, FractArg->getType(), ResultVals);
2089fe013be4SDimitry Andric }
2090fe013be4SDimitry Andric
visitMinNum(IntrinsicInst & I)2091fe013be4SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitMinNum(IntrinsicInst &I) {
2092fe013be4SDimitry Andric Value *FractArg = matchFractPat(I);
2093fe013be4SDimitry Andric if (!FractArg)
2094fe013be4SDimitry Andric return false;
2095fe013be4SDimitry Andric
2096fe013be4SDimitry Andric // Match pattern for fract intrinsic in contexts where the nan check has been
2097fe013be4SDimitry Andric // optimized out (and hope the knowledge the source can't be nan wasn't lost).
2098fe013be4SDimitry Andric if (!I.hasNoNaNs() && !isKnownNeverNaN(FractArg, *DL, TLInfo))
2099fe013be4SDimitry Andric return false;
2100fe013be4SDimitry Andric
2101fe013be4SDimitry Andric IRBuilder<> Builder(&I);
2102fe013be4SDimitry Andric FastMathFlags FMF = I.getFastMathFlags();
2103fe013be4SDimitry Andric FMF.setNoNaNs();
2104fe013be4SDimitry Andric Builder.setFastMathFlags(FMF);
2105fe013be4SDimitry Andric
2106fe013be4SDimitry Andric Value *Fract = applyFractPat(Builder, FractArg);
2107fe013be4SDimitry Andric Fract->takeName(&I);
2108fe013be4SDimitry Andric I.replaceAllUsesWith(Fract);
2109fe013be4SDimitry Andric
2110fe013be4SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(&I, TLInfo);
2111fe013be4SDimitry Andric return true;
2112fe013be4SDimitry Andric }
2113fe013be4SDimitry Andric
isOneOrNegOne(const Value * Val)2114*c9157d92SDimitry Andric static bool isOneOrNegOne(const Value *Val) {
2115*c9157d92SDimitry Andric const APFloat *C;
2116*c9157d92SDimitry Andric return match(Val, m_APFloat(C)) && C->getExactLog2Abs() == 0;
2117*c9157d92SDimitry Andric }
2118*c9157d92SDimitry Andric
2119*c9157d92SDimitry Andric // Expand llvm.sqrt.f32 calls with !fpmath metadata in a semi-fast way.
visitSqrt(IntrinsicInst & Sqrt)2120*c9157d92SDimitry Andric bool AMDGPUCodeGenPrepareImpl::visitSqrt(IntrinsicInst &Sqrt) {
2121*c9157d92SDimitry Andric Type *Ty = Sqrt.getType()->getScalarType();
2122*c9157d92SDimitry Andric if (!Ty->isFloatTy() && (!Ty->isHalfTy() || ST->has16BitInsts()))
2123*c9157d92SDimitry Andric return false;
2124*c9157d92SDimitry Andric
2125*c9157d92SDimitry Andric const FPMathOperator *FPOp = cast<const FPMathOperator>(&Sqrt);
2126*c9157d92SDimitry Andric FastMathFlags SqrtFMF = FPOp->getFastMathFlags();
2127*c9157d92SDimitry Andric
2128*c9157d92SDimitry Andric // We're trying to handle the fast-but-not-that-fast case only. The lowering
2129*c9157d92SDimitry Andric // of fast llvm.sqrt will give the raw instruction anyway.
2130*c9157d92SDimitry Andric if (SqrtFMF.approxFunc() || HasUnsafeFPMath)
2131*c9157d92SDimitry Andric return false;
2132*c9157d92SDimitry Andric
2133*c9157d92SDimitry Andric const float ReqdAccuracy = FPOp->getFPAccuracy();
2134*c9157d92SDimitry Andric
2135*c9157d92SDimitry Andric // Defer correctly rounded expansion to codegen.
2136*c9157d92SDimitry Andric if (ReqdAccuracy < 1.0f)
2137*c9157d92SDimitry Andric return false;
2138*c9157d92SDimitry Andric
2139*c9157d92SDimitry Andric // FIXME: This is an ugly hack for this pass using forward iteration instead
2140*c9157d92SDimitry Andric // of reverse. If it worked like a normal combiner, the rsq would form before
2141*c9157d92SDimitry Andric // we saw a sqrt call.
2142*c9157d92SDimitry Andric auto *FDiv =
2143*c9157d92SDimitry Andric dyn_cast_or_null<FPMathOperator>(Sqrt.getUniqueUndroppableUser());
2144*c9157d92SDimitry Andric if (FDiv && FDiv->getOpcode() == Instruction::FDiv &&
2145*c9157d92SDimitry Andric FDiv->getFPAccuracy() >= 1.0f &&
2146*c9157d92SDimitry Andric canOptimizeWithRsq(FPOp, FDiv->getFastMathFlags(), SqrtFMF) &&
2147*c9157d92SDimitry Andric // TODO: We should also handle the arcp case for the fdiv with non-1 value
2148*c9157d92SDimitry Andric isOneOrNegOne(FDiv->getOperand(0)))
2149*c9157d92SDimitry Andric return false;
2150*c9157d92SDimitry Andric
2151*c9157d92SDimitry Andric Value *SrcVal = Sqrt.getOperand(0);
2152*c9157d92SDimitry Andric bool CanTreatAsDAZ = canIgnoreDenormalInput(SrcVal, &Sqrt);
2153*c9157d92SDimitry Andric
2154*c9157d92SDimitry Andric // The raw instruction is 1 ulp, but the correction for denormal handling
2155*c9157d92SDimitry Andric // brings it to 2.
2156*c9157d92SDimitry Andric if (!CanTreatAsDAZ && ReqdAccuracy < 2.0f)
2157*c9157d92SDimitry Andric return false;
2158*c9157d92SDimitry Andric
2159*c9157d92SDimitry Andric IRBuilder<> Builder(&Sqrt);
2160*c9157d92SDimitry Andric SmallVector<Value *, 4> SrcVals;
2161*c9157d92SDimitry Andric extractValues(Builder, SrcVals, SrcVal);
2162*c9157d92SDimitry Andric
2163*c9157d92SDimitry Andric SmallVector<Value *, 4> ResultVals(SrcVals.size());
2164*c9157d92SDimitry Andric for (int I = 0, E = SrcVals.size(); I != E; ++I) {
2165*c9157d92SDimitry Andric if (CanTreatAsDAZ)
2166*c9157d92SDimitry Andric ResultVals[I] = Builder.CreateCall(getSqrtF32(), SrcVals[I]);
2167*c9157d92SDimitry Andric else
2168*c9157d92SDimitry Andric ResultVals[I] = emitSqrtIEEE2ULP(Builder, SrcVals[I], SqrtFMF);
2169*c9157d92SDimitry Andric }
2170*c9157d92SDimitry Andric
2171*c9157d92SDimitry Andric Value *NewSqrt = insertValues(Builder, Sqrt.getType(), ResultVals);
2172*c9157d92SDimitry Andric NewSqrt->takeName(&Sqrt);
2173*c9157d92SDimitry Andric Sqrt.replaceAllUsesWith(NewSqrt);
2174*c9157d92SDimitry Andric Sqrt.eraseFromParent();
2175*c9157d92SDimitry Andric return true;
2176*c9157d92SDimitry Andric }
2177*c9157d92SDimitry Andric
doInitialization(Module & M)21780b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::doInitialization(Module &M) {
2179fe013be4SDimitry Andric Impl.Mod = &M;
2180fe013be4SDimitry Andric Impl.DL = &Impl.Mod->getDataLayout();
2181*c9157d92SDimitry Andric Impl.SqrtF32 = nullptr;
2182*c9157d92SDimitry Andric Impl.LdexpF32 = nullptr;
21830b57cec5SDimitry Andric return false;
21840b57cec5SDimitry Andric }
21850b57cec5SDimitry Andric
runOnFunction(Function & F)21860b57cec5SDimitry Andric bool AMDGPUCodeGenPrepare::runOnFunction(Function &F) {
21870b57cec5SDimitry Andric if (skipFunction(F))
21880b57cec5SDimitry Andric return false;
21890b57cec5SDimitry Andric
21900b57cec5SDimitry Andric auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
21910b57cec5SDimitry Andric if (!TPC)
21920b57cec5SDimitry Andric return false;
21930b57cec5SDimitry Andric
21940b57cec5SDimitry Andric const AMDGPUTargetMachine &TM = TPC->getTM<AMDGPUTargetMachine>();
2195fe013be4SDimitry Andric Impl.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2196fe013be4SDimitry Andric Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
2197fe013be4SDimitry Andric Impl.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2198fe013be4SDimitry Andric Impl.UA = &getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
21995ffd83dbSDimitry Andric auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2200fe013be4SDimitry Andric Impl.DT = DTWP ? &DTWP->getDomTree() : nullptr;
2201fe013be4SDimitry Andric Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
2202*c9157d92SDimitry Andric SIModeRegisterDefaults Mode(F, *Impl.ST);
2203fe013be4SDimitry Andric Impl.HasFP32DenormalFlush =
2204fe013be4SDimitry Andric Mode.FP32Denormals == DenormalMode::getPreserveSign();
2205fe013be4SDimitry Andric return Impl.run(F);
22060b57cec5SDimitry Andric }
22070b57cec5SDimitry Andric
run(Function & F,FunctionAnalysisManager & FAM)2208fe013be4SDimitry Andric PreservedAnalyses AMDGPUCodeGenPreparePass::run(Function &F,
2209fe013be4SDimitry Andric FunctionAnalysisManager &FAM) {
2210fe013be4SDimitry Andric AMDGPUCodeGenPrepareImpl Impl;
2211fe013be4SDimitry Andric Impl.Mod = F.getParent();
2212fe013be4SDimitry Andric Impl.DL = &Impl.Mod->getDataLayout();
2213fe013be4SDimitry Andric Impl.TLInfo = &FAM.getResult<TargetLibraryAnalysis>(F);
2214fe013be4SDimitry Andric Impl.ST = &TM.getSubtarget<GCNSubtarget>(F);
2215fe013be4SDimitry Andric Impl.AC = &FAM.getResult<AssumptionAnalysis>(F);
2216fe013be4SDimitry Andric Impl.UA = &FAM.getResult<UniformityInfoAnalysis>(F);
2217fe013be4SDimitry Andric Impl.DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
2218fe013be4SDimitry Andric Impl.HasUnsafeFPMath = hasUnsafeFPMath(F);
2219*c9157d92SDimitry Andric SIModeRegisterDefaults Mode(F, *Impl.ST);
2220fe013be4SDimitry Andric Impl.HasFP32DenormalFlush =
2221fe013be4SDimitry Andric Mode.FP32Denormals == DenormalMode::getPreserveSign();
2222fe013be4SDimitry Andric PreservedAnalyses PA = PreservedAnalyses::none();
2223fe013be4SDimitry Andric if (!Impl.FlowChanged)
2224fe013be4SDimitry Andric PA.preserveSet<CFGAnalyses>();
2225fe013be4SDimitry Andric return Impl.run(F) ? PA : PreservedAnalyses::all();
22260b57cec5SDimitry Andric }
22270b57cec5SDimitry Andric
22280b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(AMDGPUCodeGenPrepare, DEBUG_TYPE,
22290b57cec5SDimitry Andric "AMDGPU IR optimizations", false, false)
22300b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2231fe013be4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2232fe013be4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
22330b57cec5SDimitry Andric INITIALIZE_PASS_END(AMDGPUCodeGenPrepare, DEBUG_TYPE, "AMDGPU IR optimizations",
22340b57cec5SDimitry Andric false, false)
22350b57cec5SDimitry Andric
22360b57cec5SDimitry Andric char AMDGPUCodeGenPrepare::ID = 0;
22370b57cec5SDimitry Andric
createAMDGPUCodeGenPreparePass()22380b57cec5SDimitry Andric FunctionPass *llvm::createAMDGPUCodeGenPreparePass() {
22390b57cec5SDimitry Andric return new AMDGPUCodeGenPrepare();
22400b57cec5SDimitry Andric }
2241