Path: blob/main/contrib/llvm-project/llvm/lib/Target/NVPTX/NVPTXTargetTransformInfo.cpp
35271 views
//===-- NVPTXTargetTransformInfo.cpp - NVPTX specific TTI -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "NVPTXTargetTransformInfo.h"9#include "NVPTXUtilities.h"10#include "llvm/Analysis/LoopInfo.h"11#include "llvm/Analysis/TargetTransformInfo.h"12#include "llvm/Analysis/ValueTracking.h"13#include "llvm/CodeGen/BasicTTIImpl.h"14#include "llvm/CodeGen/CostTable.h"15#include "llvm/CodeGen/TargetLowering.h"16#include "llvm/IR/IntrinsicsNVPTX.h"17#include "llvm/Support/Debug.h"18#include <optional>19using namespace llvm;2021#define DEBUG_TYPE "NVPTXtti"2223// Whether the given intrinsic reads threadIdx.x/y/z.24static bool readsThreadIndex(const IntrinsicInst *II) {25switch (II->getIntrinsicID()) {26default: return false;27case Intrinsic::nvvm_read_ptx_sreg_tid_x:28case Intrinsic::nvvm_read_ptx_sreg_tid_y:29case Intrinsic::nvvm_read_ptx_sreg_tid_z:30return true;31}32}3334static bool readsLaneId(const IntrinsicInst *II) {35return II->getIntrinsicID() == Intrinsic::nvvm_read_ptx_sreg_laneid;36}3738// Whether the given intrinsic is an atomic instruction in PTX.39static bool isNVVMAtomic(const IntrinsicInst *II) {40switch (II->getIntrinsicID()) {41default: return false;42case Intrinsic::nvvm_atomic_load_inc_32:43case Intrinsic::nvvm_atomic_load_dec_32:4445case Intrinsic::nvvm_atomic_add_gen_f_cta:46case Intrinsic::nvvm_atomic_add_gen_f_sys:47case Intrinsic::nvvm_atomic_add_gen_i_cta:48case Intrinsic::nvvm_atomic_add_gen_i_sys:49case Intrinsic::nvvm_atomic_and_gen_i_cta:50case Intrinsic::nvvm_atomic_and_gen_i_sys:51case Intrinsic::nvvm_atomic_cas_gen_i_cta:52case Intrinsic::nvvm_atomic_cas_gen_i_sys:53case Intrinsic::nvvm_atomic_dec_gen_i_cta:54case Intrinsic::nvvm_atomic_dec_gen_i_sys:55case Intrinsic::nvvm_atomic_inc_gen_i_cta:56case Intrinsic::nvvm_atomic_inc_gen_i_sys:57case Intrinsic::nvvm_atomic_max_gen_i_cta:58case Intrinsic::nvvm_atomic_max_gen_i_sys:59case Intrinsic::nvvm_atomic_min_gen_i_cta:60case Intrinsic::nvvm_atomic_min_gen_i_sys:61case Intrinsic::nvvm_atomic_or_gen_i_cta:62case Intrinsic::nvvm_atomic_or_gen_i_sys:63case Intrinsic::nvvm_atomic_exch_gen_i_cta:64case Intrinsic::nvvm_atomic_exch_gen_i_sys:65case Intrinsic::nvvm_atomic_xor_gen_i_cta:66case Intrinsic::nvvm_atomic_xor_gen_i_sys:67return true;68}69}7071bool NVPTXTTIImpl::isSourceOfDivergence(const Value *V) {72// Without inter-procedural analysis, we conservatively assume that arguments73// to __device__ functions are divergent.74if (const Argument *Arg = dyn_cast<Argument>(V))75return !isKernelFunction(*Arg->getParent());7677if (const Instruction *I = dyn_cast<Instruction>(V)) {78// Without pointer analysis, we conservatively assume values loaded from79// generic or local address space are divergent.80if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {81unsigned AS = LI->getPointerAddressSpace();82return AS == ADDRESS_SPACE_GENERIC || AS == ADDRESS_SPACE_LOCAL;83}84// Atomic instructions may cause divergence. Atomic instructions are85// executed sequentially across all threads in a warp. Therefore, an earlier86// executed thread may see different memory inputs than a later executed87// thread. For example, suppose *a = 0 initially.88//89// atom.global.add.s32 d, [a], 190//91// returns 0 for the first thread that enters the critical region, and 1 for92// the second thread.93if (I->isAtomic())94return true;95if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {96// Instructions that read threadIdx are obviously divergent.97if (readsThreadIndex(II) || readsLaneId(II))98return true;99// Handle the NVPTX atomic intrinsics that cannot be represented as an100// atomic IR instruction.101if (isNVVMAtomic(II))102return true;103}104// Conservatively consider the return value of function calls as divergent.105// We could analyze callees with bodies more precisely using106// inter-procedural analysis.107if (isa<CallInst>(I))108return true;109}110111return false;112}113114// Convert NVVM intrinsics to target-generic LLVM code where possible.115static Instruction *simplifyNvvmIntrinsic(IntrinsicInst *II, InstCombiner &IC) {116// Each NVVM intrinsic we can simplify can be replaced with one of:117//118// * an LLVM intrinsic,119// * an LLVM cast operation,120// * an LLVM binary operation, or121// * ad-hoc LLVM IR for the particular operation.122123// Some transformations are only valid when the module's124// flush-denormals-to-zero (ftz) setting is true/false, whereas other125// transformations are valid regardless of the module's ftz setting.126enum FtzRequirementTy {127FTZ_Any, // Any ftz setting is ok.128FTZ_MustBeOn, // Transformation is valid only if ftz is on.129FTZ_MustBeOff, // Transformation is valid only if ftz is off.130};131// Classes of NVVM intrinsics that can't be replaced one-to-one with a132// target-generic intrinsic, cast op, or binary op but that we can nonetheless133// simplify.134enum SpecialCase {135SPC_Reciprocal,136};137138// SimplifyAction is a poor-man's variant (plus an additional flag) that139// represents how to replace an NVVM intrinsic with target-generic LLVM IR.140struct SimplifyAction {141// Invariant: At most one of these Optionals has a value.142std::optional<Intrinsic::ID> IID;143std::optional<Instruction::CastOps> CastOp;144std::optional<Instruction::BinaryOps> BinaryOp;145std::optional<SpecialCase> Special;146147FtzRequirementTy FtzRequirement = FTZ_Any;148// Denormal handling is guarded by different attributes depending on the149// type (denormal-fp-math vs denormal-fp-math-f32), take note of halfs.150bool IsHalfTy = false;151152SimplifyAction() = default;153154SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq,155bool IsHalfTy = false)156: IID(IID), FtzRequirement(FtzReq), IsHalfTy(IsHalfTy) {}157158// Cast operations don't have anything to do with FTZ, so we skip that159// argument.160SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}161162SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)163: BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}164165SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)166: Special(Special), FtzRequirement(FtzReq) {}167};168169// Try to generate a SimplifyAction describing how to replace our170// IntrinsicInstr with target-generic LLVM IR.171const SimplifyAction Action = [II]() -> SimplifyAction {172switch (II->getIntrinsicID()) {173// NVVM intrinsics that map directly to LLVM intrinsics.174case Intrinsic::nvvm_ceil_d:175return {Intrinsic::ceil, FTZ_Any};176case Intrinsic::nvvm_ceil_f:177return {Intrinsic::ceil, FTZ_MustBeOff};178case Intrinsic::nvvm_ceil_ftz_f:179return {Intrinsic::ceil, FTZ_MustBeOn};180case Intrinsic::nvvm_fabs_d:181return {Intrinsic::fabs, FTZ_Any};182case Intrinsic::nvvm_floor_d:183return {Intrinsic::floor, FTZ_Any};184case Intrinsic::nvvm_floor_f:185return {Intrinsic::floor, FTZ_MustBeOff};186case Intrinsic::nvvm_floor_ftz_f:187return {Intrinsic::floor, FTZ_MustBeOn};188case Intrinsic::nvvm_fma_rn_d:189return {Intrinsic::fma, FTZ_Any};190case Intrinsic::nvvm_fma_rn_f:191return {Intrinsic::fma, FTZ_MustBeOff};192case Intrinsic::nvvm_fma_rn_ftz_f:193return {Intrinsic::fma, FTZ_MustBeOn};194case Intrinsic::nvvm_fma_rn_f16:195return {Intrinsic::fma, FTZ_MustBeOff, true};196case Intrinsic::nvvm_fma_rn_ftz_f16:197return {Intrinsic::fma, FTZ_MustBeOn, true};198case Intrinsic::nvvm_fma_rn_f16x2:199return {Intrinsic::fma, FTZ_MustBeOff, true};200case Intrinsic::nvvm_fma_rn_ftz_f16x2:201return {Intrinsic::fma, FTZ_MustBeOn, true};202case Intrinsic::nvvm_fma_rn_bf16:203return {Intrinsic::fma, FTZ_MustBeOff, true};204case Intrinsic::nvvm_fma_rn_ftz_bf16:205return {Intrinsic::fma, FTZ_MustBeOn, true};206case Intrinsic::nvvm_fma_rn_bf16x2:207return {Intrinsic::fma, FTZ_MustBeOff, true};208case Intrinsic::nvvm_fma_rn_ftz_bf16x2:209return {Intrinsic::fma, FTZ_MustBeOn, true};210case Intrinsic::nvvm_fmax_d:211return {Intrinsic::maxnum, FTZ_Any};212case Intrinsic::nvvm_fmax_f:213return {Intrinsic::maxnum, FTZ_MustBeOff};214case Intrinsic::nvvm_fmax_ftz_f:215return {Intrinsic::maxnum, FTZ_MustBeOn};216case Intrinsic::nvvm_fmax_nan_f:217return {Intrinsic::maximum, FTZ_MustBeOff};218case Intrinsic::nvvm_fmax_ftz_nan_f:219return {Intrinsic::maximum, FTZ_MustBeOn};220case Intrinsic::nvvm_fmax_f16:221return {Intrinsic::maxnum, FTZ_MustBeOff, true};222case Intrinsic::nvvm_fmax_ftz_f16:223return {Intrinsic::maxnum, FTZ_MustBeOn, true};224case Intrinsic::nvvm_fmax_f16x2:225return {Intrinsic::maxnum, FTZ_MustBeOff, true};226case Intrinsic::nvvm_fmax_ftz_f16x2:227return {Intrinsic::maxnum, FTZ_MustBeOn, true};228case Intrinsic::nvvm_fmax_nan_f16:229return {Intrinsic::maximum, FTZ_MustBeOff, true};230case Intrinsic::nvvm_fmax_ftz_nan_f16:231return {Intrinsic::maximum, FTZ_MustBeOn, true};232case Intrinsic::nvvm_fmax_nan_f16x2:233return {Intrinsic::maximum, FTZ_MustBeOff, true};234case Intrinsic::nvvm_fmax_ftz_nan_f16x2:235return {Intrinsic::maximum, FTZ_MustBeOn, true};236case Intrinsic::nvvm_fmin_d:237return {Intrinsic::minnum, FTZ_Any};238case Intrinsic::nvvm_fmin_f:239return {Intrinsic::minnum, FTZ_MustBeOff};240case Intrinsic::nvvm_fmin_ftz_f:241return {Intrinsic::minnum, FTZ_MustBeOn};242case Intrinsic::nvvm_fmin_nan_f:243return {Intrinsic::minimum, FTZ_MustBeOff};244case Intrinsic::nvvm_fmin_ftz_nan_f:245return {Intrinsic::minimum, FTZ_MustBeOn};246case Intrinsic::nvvm_fmin_f16:247return {Intrinsic::minnum, FTZ_MustBeOff, true};248case Intrinsic::nvvm_fmin_ftz_f16:249return {Intrinsic::minnum, FTZ_MustBeOn, true};250case Intrinsic::nvvm_fmin_f16x2:251return {Intrinsic::minnum, FTZ_MustBeOff, true};252case Intrinsic::nvvm_fmin_ftz_f16x2:253return {Intrinsic::minnum, FTZ_MustBeOn, true};254case Intrinsic::nvvm_fmin_nan_f16:255return {Intrinsic::minimum, FTZ_MustBeOff, true};256case Intrinsic::nvvm_fmin_ftz_nan_f16:257return {Intrinsic::minimum, FTZ_MustBeOn, true};258case Intrinsic::nvvm_fmin_nan_f16x2:259return {Intrinsic::minimum, FTZ_MustBeOff, true};260case Intrinsic::nvvm_fmin_ftz_nan_f16x2:261return {Intrinsic::minimum, FTZ_MustBeOn, true};262case Intrinsic::nvvm_sqrt_rn_d:263return {Intrinsic::sqrt, FTZ_Any};264case Intrinsic::nvvm_sqrt_f:265// nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the266// ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts267// the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are268// the versions with explicit ftz-ness.269return {Intrinsic::sqrt, FTZ_Any};270case Intrinsic::nvvm_trunc_d:271return {Intrinsic::trunc, FTZ_Any};272case Intrinsic::nvvm_trunc_f:273return {Intrinsic::trunc, FTZ_MustBeOff};274case Intrinsic::nvvm_trunc_ftz_f:275return {Intrinsic::trunc, FTZ_MustBeOn};276277// NVVM intrinsics that map to LLVM cast operations.278//279// Note that llvm's target-generic conversion operators correspond to the rz280// (round to zero) versions of the nvvm conversion intrinsics, even though281// most everything else here uses the rn (round to nearest even) nvvm ops.282case Intrinsic::nvvm_d2i_rz:283case Intrinsic::nvvm_f2i_rz:284case Intrinsic::nvvm_d2ll_rz:285case Intrinsic::nvvm_f2ll_rz:286return {Instruction::FPToSI};287case Intrinsic::nvvm_d2ui_rz:288case Intrinsic::nvvm_f2ui_rz:289case Intrinsic::nvvm_d2ull_rz:290case Intrinsic::nvvm_f2ull_rz:291return {Instruction::FPToUI};292case Intrinsic::nvvm_i2d_rz:293case Intrinsic::nvvm_i2f_rz:294case Intrinsic::nvvm_ll2d_rz:295case Intrinsic::nvvm_ll2f_rz:296return {Instruction::SIToFP};297case Intrinsic::nvvm_ui2d_rz:298case Intrinsic::nvvm_ui2f_rz:299case Intrinsic::nvvm_ull2d_rz:300case Intrinsic::nvvm_ull2f_rz:301return {Instruction::UIToFP};302303// NVVM intrinsics that map to LLVM binary ops.304case Intrinsic::nvvm_div_rn_d:305return {Instruction::FDiv, FTZ_Any};306307// The remainder of cases are NVVM intrinsics that map to LLVM idioms, but308// need special handling.309//310// We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just311// as well.312case Intrinsic::nvvm_rcp_rn_d:313return {SPC_Reciprocal, FTZ_Any};314315// We do not currently simplify intrinsics that give an approximate316// answer. These include:317//318// - nvvm_cos_approx_{f,ftz_f}319// - nvvm_ex2_approx_{d,f,ftz_f}320// - nvvm_lg2_approx_{d,f,ftz_f}321// - nvvm_sin_approx_{f,ftz_f}322// - nvvm_sqrt_approx_{f,ftz_f}323// - nvvm_rsqrt_approx_{d,f,ftz_f}324// - nvvm_div_approx_{ftz_d,ftz_f,f}325// - nvvm_rcp_approx_ftz_d326//327// Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"328// means that fastmath is enabled in the intrinsic. Unfortunately only329// binary operators (currently) have a fastmath bit in SelectionDAG, so330// this information gets lost and we can't select on it.331//332// TODO: div and rcp are lowered to a binary op, so these we could in333// theory lower them to "fast fdiv".334335default:336return {};337}338}();339340// If Action.FtzRequirementTy is not satisfied by the module's ftz state, we341// can bail out now. (Notice that in the case that IID is not an NVVM342// intrinsic, we don't have to look up any module metadata, as343// FtzRequirementTy will be FTZ_Any.)344if (Action.FtzRequirement != FTZ_Any) {345// FIXME: Broken for f64346DenormalMode Mode = II->getFunction()->getDenormalMode(347Action.IsHalfTy ? APFloat::IEEEhalf() : APFloat::IEEEsingle());348bool FtzEnabled = Mode.Output == DenormalMode::PreserveSign;349350if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))351return nullptr;352}353354// Simplify to target-generic intrinsic.355if (Action.IID) {356SmallVector<Value *, 4> Args(II->args());357// All the target-generic intrinsics currently of interest to us have one358// type argument, equal to that of the nvvm intrinsic's argument.359Type *Tys[] = {II->getArgOperand(0)->getType()};360return CallInst::Create(361Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);362}363364// Simplify to target-generic binary op.365if (Action.BinaryOp)366return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),367II->getArgOperand(1), II->getName());368369// Simplify to target-generic cast op.370if (Action.CastOp)371return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),372II->getName());373374// All that's left are the special cases.375if (!Action.Special)376return nullptr;377378switch (*Action.Special) {379case SPC_Reciprocal:380// Simplify reciprocal.381return BinaryOperator::Create(382Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),383II->getArgOperand(0), II->getName());384}385llvm_unreachable("All SpecialCase enumerators should be handled in switch.");386}387388std::optional<Instruction *>389NVPTXTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {390if (Instruction *I = simplifyNvvmIntrinsic(&II, IC)) {391return I;392}393return std::nullopt;394}395396InstructionCost NVPTXTTIImpl::getArithmeticInstrCost(397unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,398TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info,399ArrayRef<const Value *> Args,400const Instruction *CxtI) {401// Legalize the type.402std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);403404int ISD = TLI->InstructionOpcodeToISD(Opcode);405406switch (ISD) {407default:408return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,409Op2Info);410case ISD::ADD:411case ISD::MUL:412case ISD::XOR:413case ISD::OR:414case ISD::AND:415// The machine code (SASS) simulates an i64 with two i32. Therefore, we416// estimate that arithmetic operations on i64 are twice as expensive as417// those on types that can fit into one machine register.418if (LT.second.SimpleTy == MVT::i64)419return 2 * LT.first;420// Delegate other cases to the basic TTI.421return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,422Op2Info);423}424}425426void NVPTXTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,427TTI::UnrollingPreferences &UP,428OptimizationRemarkEmitter *ORE) {429BaseT::getUnrollingPreferences(L, SE, UP, ORE);430431// Enable partial unrolling and runtime unrolling, but reduce the432// threshold. This partially unrolls small loops which are often433// unrolled by the PTX to SASS compiler and unrolling earlier can be434// beneficial.435UP.Partial = UP.Runtime = true;436UP.PartialThreshold = UP.Threshold / 4;437}438439void NVPTXTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,440TTI::PeelingPreferences &PP) {441BaseT::getPeelingPreferences(L, SE, PP);442}443444445