1//===-- NVPTXTargetTransformInfo.cpp - NVPTX specific TTI -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "NVPTXTargetTransformInfo.h"
10#include "NVVMProperties.h"
11#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/Analysis/LoopInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
17#include "llvm/Analysis/ValueTracking.h"
18#include "llvm/CodeGen/BasicTTIImpl.h"
19#include "llvm/CodeGen/TargetLowering.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Intrinsics.h"
23#include "llvm/IR/IntrinsicsNVPTX.h"
24#include "llvm/IR/NVVMIntrinsicUtils.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/Casting.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/NVPTXAddrSpace.h"
29#include "llvm/Transforms/InstCombine/InstCombiner.h"
30#include <optional>
31#include <utility>
32using namespace llvm;
33
34#define DEBUG_TYPE "NVPTXtti"
35
36// Whether the given intrinsic reads threadIdx.x/y/z.
37static bool readsThreadIndex(const IntrinsicInst *II) {
38 switch (II->getIntrinsicID()) {
39 default: return false;
40 case Intrinsic::nvvm_read_ptx_sreg_tid_x:
41 case Intrinsic::nvvm_read_ptx_sreg_tid_y:
42 case Intrinsic::nvvm_read_ptx_sreg_tid_z:
43 return true;
44 }
45}
46
47static bool readsLaneId(const IntrinsicInst *II) {
48 return II->getIntrinsicID() == Intrinsic::nvvm_read_ptx_sreg_laneid;
49}
50
51bool NVPTXTTIImpl::isSourceOfDivergence(const Value *V) const {
52 // Without inter-procedural analysis, we conservatively assume that arguments
53 // to __device__ functions are divergent.
54 if (const Argument *Arg = dyn_cast<Argument>(Val: V))
55 return !isKernelFunction(F: *Arg->getParent());
56
57 if (const Instruction *I = dyn_cast<Instruction>(Val: V)) {
58 // Without pointer analysis, we conservatively assume values loaded from
59 // generic or local address space are divergent.
60 if (const LoadInst *LI = dyn_cast<LoadInst>(Val: I)) {
61 unsigned AS = LI->getPointerAddressSpace();
62 return AS == ADDRESS_SPACE_GENERIC || AS == ADDRESS_SPACE_LOCAL;
63 }
64 // Atomic instructions may cause divergence. Atomic instructions are
65 // executed sequentially across all threads in a warp. Therefore, an earlier
66 // executed thread may see different memory inputs than a later executed
67 // thread. For example, suppose *a = 0 initially.
68 //
69 // atom.global.add.s32 d, [a], 1
70 //
71 // returns 0 for the first thread that enters the critical region, and 1 for
72 // the second thread.
73 if (I->isAtomic())
74 return true;
75 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
76 // Instructions that read threadIdx are obviously divergent.
77 if (readsThreadIndex(II) || readsLaneId(II))
78 return true;
79 }
80 // Conservatively consider the return value of function calls as divergent.
81 // We could analyze callees with bodies more precisely using
82 // inter-procedural analysis.
83 if (isa<CallInst>(Val: I))
84 return true;
85 }
86
87 return false;
88}
89
90// Convert NVVM intrinsics to target-generic LLVM code where possible.
91static Instruction *convertNvvmIntrinsicToLlvm(InstCombiner &IC,
92 IntrinsicInst *II) {
93 // Each NVVM intrinsic we can simplify can be replaced with one of:
94 //
95 // * an LLVM intrinsic,
96 // * an LLVM cast operation,
97 // * an LLVM binary operation, or
98 // * ad-hoc LLVM IR for the particular operation.
99
100 // Some transformations are only valid when the module's
101 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
102 // transformations are valid regardless of the module's ftz setting.
103 enum FtzRequirementTy {
104 FTZ_Any, // Any ftz setting is ok.
105 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
106 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
107 };
108 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
109 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
110 // simplify.
111 enum SpecialCase {
112 SPC_Reciprocal,
113 SCP_FunnelShiftClamp,
114 };
115
116 // SimplifyAction is a poor-man's variant (plus an additional flag) that
117 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
118 struct SimplifyAction {
119 // Invariant: At most one of these Optionals has a value.
120 std::optional<Intrinsic::ID> IID;
121 std::optional<Instruction::CastOps> CastOp;
122 std::optional<Instruction::BinaryOps> BinaryOp;
123 std::optional<SpecialCase> Special;
124
125 FtzRequirementTy FtzRequirement = FTZ_Any;
126 // Denormal handling is guarded by different attributes depending on the
127 // type (denormal-fp-math vs denormal-fp-math-f32), take note of halfs.
128 bool IsHalfTy = false;
129
130 SimplifyAction() = default;
131
132 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq,
133 bool IsHalfTy = false)
134 : IID(IID), FtzRequirement(FtzReq), IsHalfTy(IsHalfTy) {}
135
136 // Cast operations don't have anything to do with FTZ, so we skip that
137 // argument.
138 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
139
140 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
141 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
142
143 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
144 : Special(Special), FtzRequirement(FtzReq) {}
145 };
146
147 // Try to generate a SimplifyAction describing how to replace our
148 // IntrinsicInstr with target-generic LLVM IR.
149 const SimplifyAction Action = [II]() -> SimplifyAction {
150 switch (II->getIntrinsicID()) {
151 // NVVM intrinsics that map directly to LLVM intrinsics.
152 case Intrinsic::nvvm_ceil_d:
153 return {Intrinsic::ceil, FTZ_Any};
154 case Intrinsic::nvvm_ceil_f:
155 return {Intrinsic::ceil, FTZ_MustBeOff};
156 case Intrinsic::nvvm_ceil_ftz_f:
157 return {Intrinsic::ceil, FTZ_MustBeOn};
158 case Intrinsic::nvvm_floor_d:
159 return {Intrinsic::floor, FTZ_Any};
160 case Intrinsic::nvvm_floor_f:
161 return {Intrinsic::floor, FTZ_MustBeOff};
162 case Intrinsic::nvvm_floor_ftz_f:
163 return {Intrinsic::floor, FTZ_MustBeOn};
164 case Intrinsic::nvvm_fma:
165 case Intrinsic::nvvm_fma_ftz: {
166 // llvm.fma rounds to nearest-even, so only the rn variants map to it.
167 if (nvvm::GetRoundingModeFromImmArg(ImmArgVal: II->getArgOperand(i: 3)) !=
168 APFloat::rmNearestTiesToEven)
169 return {};
170 const bool IsFTZ = II->getIntrinsicID() == Intrinsic::nvvm_fma_ftz;
171 Type *EltTy = II->getType()->getScalarType();
172 if (EltTy->isDoubleTy())
173 return {Intrinsic::fma, FTZ_Any};
174 const bool IsHalfTy = EltTy->isHalfTy() || EltTy->isBFloatTy();
175 return {Intrinsic::fma, IsFTZ ? FTZ_MustBeOn : FTZ_MustBeOff, IsHalfTy};
176 }
177 case Intrinsic::nvvm_fmax_d:
178 return {Intrinsic::maximumnum, FTZ_Any};
179 case Intrinsic::nvvm_fmax_f:
180 return {Intrinsic::maximumnum, FTZ_MustBeOff};
181 case Intrinsic::nvvm_fmax_ftz_f:
182 return {Intrinsic::maximumnum, FTZ_MustBeOn};
183 case Intrinsic::nvvm_fmax_nan_f:
184 return {Intrinsic::maximum, FTZ_MustBeOff};
185 case Intrinsic::nvvm_fmax_ftz_nan_f:
186 return {Intrinsic::maximum, FTZ_MustBeOn};
187 case Intrinsic::nvvm_fmax_f16:
188 return {Intrinsic::maximumnum, FTZ_MustBeOff, true};
189 case Intrinsic::nvvm_fmax_ftz_f16:
190 return {Intrinsic::maximumnum, FTZ_MustBeOn, true};
191 case Intrinsic::nvvm_fmax_f16x2:
192 return {Intrinsic::maximumnum, FTZ_MustBeOff, true};
193 case Intrinsic::nvvm_fmax_ftz_f16x2:
194 return {Intrinsic::maximumnum, FTZ_MustBeOn, true};
195 case Intrinsic::nvvm_fmax_nan_f16:
196 return {Intrinsic::maximum, FTZ_MustBeOff, true};
197 case Intrinsic::nvvm_fmax_ftz_nan_f16:
198 return {Intrinsic::maximum, FTZ_MustBeOn, true};
199 case Intrinsic::nvvm_fmax_nan_f16x2:
200 return {Intrinsic::maximum, FTZ_MustBeOff, true};
201 case Intrinsic::nvvm_fmax_ftz_nan_f16x2:
202 return {Intrinsic::maximum, FTZ_MustBeOn, true};
203 case Intrinsic::nvvm_fmin_d:
204 return {Intrinsic::minimumnum, FTZ_Any};
205 case Intrinsic::nvvm_fmin_f:
206 return {Intrinsic::minimumnum, FTZ_MustBeOff};
207 case Intrinsic::nvvm_fmin_ftz_f:
208 return {Intrinsic::minimumnum, FTZ_MustBeOn};
209 case Intrinsic::nvvm_fmin_nan_f:
210 return {Intrinsic::minimum, FTZ_MustBeOff};
211 case Intrinsic::nvvm_fmin_ftz_nan_f:
212 return {Intrinsic::minimum, FTZ_MustBeOn};
213 case Intrinsic::nvvm_fmin_f16:
214 return {Intrinsic::minimumnum, FTZ_MustBeOff, true};
215 case Intrinsic::nvvm_fmin_ftz_f16:
216 return {Intrinsic::minimumnum, FTZ_MustBeOn, true};
217 case Intrinsic::nvvm_fmin_f16x2:
218 return {Intrinsic::minimumnum, FTZ_MustBeOff, true};
219 case Intrinsic::nvvm_fmin_ftz_f16x2:
220 return {Intrinsic::minimumnum, FTZ_MustBeOn, true};
221 case Intrinsic::nvvm_fmin_nan_f16:
222 return {Intrinsic::minimum, FTZ_MustBeOff, true};
223 case Intrinsic::nvvm_fmin_ftz_nan_f16:
224 return {Intrinsic::minimum, FTZ_MustBeOn, true};
225 case Intrinsic::nvvm_fmin_nan_f16x2:
226 return {Intrinsic::minimum, FTZ_MustBeOff, true};
227 case Intrinsic::nvvm_fmin_ftz_nan_f16x2:
228 return {Intrinsic::minimum, FTZ_MustBeOn, true};
229 case Intrinsic::nvvm_sqrt_rn_d:
230 return {Intrinsic::sqrt, FTZ_Any};
231 case Intrinsic::nvvm_sqrt_f:
232 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
233 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
234 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
235 // the versions with explicit ftz-ness.
236 return {Intrinsic::sqrt, FTZ_Any};
237 case Intrinsic::nvvm_trunc_d:
238 return {Intrinsic::trunc, FTZ_Any};
239 case Intrinsic::nvvm_trunc_f:
240 return {Intrinsic::trunc, FTZ_MustBeOff};
241 case Intrinsic::nvvm_trunc_ftz_f:
242 return {Intrinsic::trunc, FTZ_MustBeOn};
243
244 // NVVM intrinsics that map to LLVM cast operations.
245 // Note - we cannot map intrinsics like nvvm_d2ll_rz to LLVM's
246 // FPToSI, as NaN to int conversion with FPToSI is considered UB and is
247 // eliminated. NVVM conversion intrinsics are translated to PTX cvt
248 // instructions which define the outcome for NaN rather than leaving as UB.
249 // Therefore, translate NVVM intrinsics to sitofp/uitofp, but not to
250 // fptosi/fptoui.
251 case Intrinsic::nvvm_i2d_rn:
252 case Intrinsic::nvvm_i2f_rn:
253 case Intrinsic::nvvm_ll2d_rn:
254 case Intrinsic::nvvm_ll2f_rn:
255 return {Instruction::SIToFP};
256 case Intrinsic::nvvm_ui2d_rn:
257 case Intrinsic::nvvm_ui2f_rn:
258 case Intrinsic::nvvm_ull2d_rn:
259 case Intrinsic::nvvm_ull2f_rn:
260 return {Instruction::UIToFP};
261
262 // NVVM intrinsics that map to LLVM binary ops.
263 case Intrinsic::nvvm_div_rn_d:
264 return {Instruction::FDiv, FTZ_Any};
265
266 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
267 // need special handling.
268 //
269 // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
270 // as well.
271 case Intrinsic::nvvm_rcp_rn_d:
272 return {SPC_Reciprocal, FTZ_Any};
273
274 case Intrinsic::nvvm_fshl_clamp:
275 case Intrinsic::nvvm_fshr_clamp:
276 return {SCP_FunnelShiftClamp, FTZ_Any};
277
278 // We do not currently simplify intrinsics that give an approximate
279 // answer. These include:
280 //
281 // - nvvm_cos_approx_{f,ftz_f}
282 // - nvvm_ex2_approx(_ftz)
283 // - nvvm_lg2_approx_{d,f,ftz_f}
284 // - nvvm_sin_approx_{f,ftz_f}
285 // - nvvm_sqrt_approx_{f,ftz_f}
286 // - nvvm_rsqrt_approx_{d,f,ftz_f}
287 // - nvvm_div_approx_{ftz_d,ftz_f,f}
288 // - nvvm_rcp_approx_ftz_d
289 //
290 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
291 // means that fastmath is enabled in the intrinsic. Unfortunately only
292 // binary operators (currently) have a fastmath bit in SelectionDAG, so
293 // this information gets lost and we can't select on it.
294 //
295 // TODO: div and rcp are lowered to a binary op, so these we could in
296 // theory lower them to "fast fdiv".
297
298 default:
299 return {};
300 }
301 }();
302
303 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
304 // can bail out now. (Notice that in the case that IID is not an NVVM
305 // intrinsic, we don't have to look up any module metadata, as
306 // FtzRequirementTy will be FTZ_Any.)
307 if (Action.FtzRequirement != FTZ_Any) {
308 // FIXME: Broken for f64
309 DenormalMode Mode = II->getFunction()->getDenormalMode(
310 FPType: Action.IsHalfTy ? APFloat::IEEEhalf() : APFloat::IEEEsingle());
311 bool FtzEnabled = Mode.Input == DenormalMode::PreserveSign;
312
313 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
314 return nullptr;
315 }
316
317 // Simplify to target-generic intrinsic.
318 if (Action.IID) {
319 SmallVector<Value *, 4> Args(II->args());
320 // llvm.fma does not take the trailing rounding-mode operand.
321 if (II->getIntrinsicID() == Intrinsic::nvvm_fma ||
322 II->getIntrinsicID() == Intrinsic::nvvm_fma_ftz)
323 Args.pop_back();
324 // All the target-generic intrinsics currently of interest to us have one
325 // type argument, equal to that of the nvvm intrinsic's argument.
326 Type *Tys[] = {II->getArgOperand(i: 0)->getType()};
327 return CallInst::Create(
328 Func: Intrinsic::getOrInsertDeclaration(M: II->getModule(), id: *Action.IID, OverloadTys: Tys),
329 Args);
330 }
331
332 // Simplify to target-generic binary op.
333 if (Action.BinaryOp)
334 return BinaryOperator::Create(Op: *Action.BinaryOp, S1: II->getArgOperand(i: 0),
335 S2: II->getArgOperand(i: 1), Name: II->getName());
336
337 // Simplify to target-generic cast op.
338 if (Action.CastOp)
339 return CastInst::Create(*Action.CastOp, S: II->getArgOperand(i: 0), Ty: II->getType(),
340 Name: II->getName());
341
342 // All that's left are the special cases.
343 if (!Action.Special)
344 return nullptr;
345
346 switch (*Action.Special) {
347 case SPC_Reciprocal:
348 // Simplify reciprocal.
349 return BinaryOperator::Create(
350 Op: Instruction::FDiv, S1: ConstantFP::get(Ty: II->getArgOperand(i: 0)->getType(), V: 1),
351 S2: II->getArgOperand(i: 0), Name: II->getName());
352
353 case SCP_FunnelShiftClamp: {
354 // Canonicalize a clamping funnel shift to the generic llvm funnel shift
355 // when possible, as this is easier for llvm to optimize further.
356 if (const auto *ShiftConst = dyn_cast<ConstantInt>(Val: II->getArgOperand(i: 2))) {
357 const bool IsLeft = II->getIntrinsicID() == Intrinsic::nvvm_fshl_clamp;
358 if (ShiftConst->getZExtValue() >= II->getType()->getIntegerBitWidth())
359 return IC.replaceInstUsesWith(I&: *II, V: II->getArgOperand(i: IsLeft ? 1 : 0));
360
361 const unsigned FshIID = IsLeft ? Intrinsic::fshl : Intrinsic::fshr;
362 return CallInst::Create(Func: Intrinsic::getOrInsertDeclaration(
363 M: II->getModule(), id: FshIID, OverloadTys: II->getType()),
364 Args: SmallVector<Value *, 3>(II->args()));
365 }
366 return nullptr;
367 }
368 }
369 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
370}
371
372// Returns whether a pointer in AS is in the given specific address space, or
373// nullopt when this cannot be determined at compile time.
374static std::optional<bool> isInAddressSpace(unsigned AS, unsigned SpecificAS) {
375 if (AS == NVPTXAS::ADDRESS_SPACE_GENERIC ||
376 AS == NVPTXAS::ADDRESS_SPACE_ENTRY_PARAM)
377 return std::nullopt; // Got to check at run-time.
378 if (AS == NVPTXAS::ADDRESS_SPACE_SHARED_CLUSTER &&
379 SpecificAS == NVPTXAS::ADDRESS_SPACE_SHARED)
380 return std::nullopt;
381 return AS == SpecificAS ||
382 (AS == NVPTXAS::ADDRESS_SPACE_SHARED &&
383 SpecificAS == NVPTXAS::ADDRESS_SPACE_SHARED_CLUSTER);
384}
385
386// Returns true/false when we know the answer, nullopt otherwise.
387static std::optional<bool> evaluateIsSpace(Intrinsic::ID IID, unsigned AS) {
388 switch (IID) {
389 case Intrinsic::nvvm_isspacep_global:
390 return isInAddressSpace(AS, SpecificAS: NVPTXAS::ADDRESS_SPACE_GLOBAL);
391 case Intrinsic::nvvm_isspacep_local:
392 return isInAddressSpace(AS, SpecificAS: NVPTXAS::ADDRESS_SPACE_LOCAL);
393 case Intrinsic::nvvm_isspacep_shared:
394 return isInAddressSpace(AS, SpecificAS: NVPTXAS::ADDRESS_SPACE_SHARED);
395 case Intrinsic::nvvm_isspacep_shared_cluster:
396 return isInAddressSpace(AS, SpecificAS: NVPTXAS::ADDRESS_SPACE_SHARED_CLUSTER);
397 case Intrinsic::nvvm_isspacep_const:
398 return isInAddressSpace(AS, SpecificAS: NVPTXAS::ADDRESS_SPACE_CONST);
399 default:
400 llvm_unreachable("Unexpected intrinsic");
401 }
402}
403
404// Returns an instruction pointer (may be nullptr if we do not know the answer).
405// Returns nullopt if `II` is not one of the `isspacep` intrinsics.
406//
407// TODO: If InferAddressSpaces were run early enough in the pipeline this could
408// be removed in favor of the constant folding that occurs there through
409// rewriteIntrinsicWithAddressSpace
410static std::optional<Instruction *>
411handleSpaceCheckIntrinsics(InstCombiner &IC, IntrinsicInst &II) {
412
413 switch (auto IID = II.getIntrinsicID()) {
414 case Intrinsic::nvvm_isspacep_global:
415 case Intrinsic::nvvm_isspacep_local:
416 case Intrinsic::nvvm_isspacep_shared:
417 case Intrinsic::nvvm_isspacep_shared_cluster:
418 case Intrinsic::nvvm_isspacep_const: {
419 Value *Op0 = II.getArgOperand(i: 0);
420 unsigned AS = Op0->getType()->getPointerAddressSpace();
421 // Peek through ASC to generic AS.
422 // TODO: we could dig deeper through both ASCs and GEPs.
423 if (AS == NVPTXAS::ADDRESS_SPACE_GENERIC)
424 if (auto *ASCO = dyn_cast<AddrSpaceCastOperator>(Val: Op0))
425 AS = ASCO->getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace();
426
427 if (std::optional<bool> Answer = evaluateIsSpace(IID, AS))
428 return IC.replaceInstUsesWith(I&: II,
429 V: ConstantInt::get(Ty: II.getType(), V: *Answer));
430 return nullptr; // Don't know the answer, got to check at run time.
431 }
432 default:
433 return std::nullopt;
434 }
435}
436
437static Instruction *foldAbsIntoRedux(InstCombiner &IC, IntrinsicInst &II) {
438 Intrinsic::ID AbsIID;
439 switch (II.getIntrinsicID()) {
440 case Intrinsic::nvvm_redux_sync_fmin:
441 case Intrinsic::nvvm_redux_sync_fmin_abs:
442 AbsIID = Intrinsic::nvvm_redux_sync_fmin_abs;
443 break;
444 case Intrinsic::nvvm_redux_sync_fmax:
445 case Intrinsic::nvvm_redux_sync_fmax_abs:
446 AbsIID = Intrinsic::nvvm_redux_sync_fmax_abs;
447 break;
448 case Intrinsic::nvvm_redux_sync_fmin_NaN:
449 case Intrinsic::nvvm_redux_sync_fmin_abs_NaN:
450 AbsIID = Intrinsic::nvvm_redux_sync_fmin_abs_NaN;
451 break;
452 case Intrinsic::nvvm_redux_sync_fmax_NaN:
453 case Intrinsic::nvvm_redux_sync_fmax_abs_NaN:
454 AbsIID = Intrinsic::nvvm_redux_sync_fmax_abs_NaN;
455 break;
456 default:
457 return nullptr;
458 }
459
460 auto *Abs = dyn_cast<IntrinsicInst>(Val: II.getArgOperand(i: 0));
461 if (!Abs || Abs->getIntrinsicID() != Intrinsic::fabs)
462 return nullptr;
463
464 II.setCalledFunction(
465 Intrinsic::getOrInsertDeclaration(M: II.getModule(), id: AbsIID));
466 // These attributes described the absolute value, not its source.
467 II.removeParamAttr(ArgNo: 0, Kind: Attribute::NoFPClass);
468 II.removeParamAttr(ArgNo: 0, Kind: Attribute::Returned);
469 return IC.replaceOperand(I&: II, OpNum: 0, V: Abs->getArgOperand(i: 0));
470}
471
472std::optional<Instruction *>
473NVPTXTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
474 if (std::optional<Instruction *> I = handleSpaceCheckIntrinsics(IC, II))
475 return *I;
476 if (Instruction *I = convertNvvmIntrinsicToLlvm(IC, II: &II))
477 return I;
478 if (Instruction *I = foldAbsIntoRedux(IC, II))
479 return I;
480 return std::nullopt;
481}
482
483InstructionCost
484NVPTXTTIImpl::getInstructionCost(const User *U,
485 ArrayRef<const Value *> Operands,
486 TTI::TargetCostKind CostKind) const {
487 if (const auto *CI = dyn_cast<CallInst>(Val: U))
488 if (const auto *IA = dyn_cast<InlineAsm>(Val: CI->getCalledOperand())) {
489 // Without this implementation getCallCost() would return the number
490 // of arguments+1 as the cost. Because the cost-model assumes it is a call
491 // since it is classified as a call in the IR. A better cost model would
492 // be to return the number of asm instructions embedded in the asm
493 // string.
494 StringRef AsmStr = IA->getAsmString();
495 const unsigned InstCount =
496 count_if(Range: split(Str: AsmStr, Separator: ';'), P: [](StringRef AsmInst) {
497 // Trim off scopes denoted by '{' and '}' as these can be ignored
498 AsmInst = AsmInst.trim().ltrim(Chars: "{} \t\n\v\f\r");
499 // This is pretty coarse but does a reasonably good job of
500 // identifying things that look like instructions, possibly with a
501 // predicate ("@").
502 return !AsmInst.empty() &&
503 (AsmInst[0] == '@' || isAlpha(C: AsmInst[0]) ||
504 AsmInst.contains(Other: ".pragma"));
505 });
506 return InstCount * TargetTransformInfo::TCC_Basic;
507 }
508
509 return BaseT::getInstructionCost(U, Operands, CostKind);
510}
511
512InstructionCost NVPTXTTIImpl::getArithmeticInstrCost(
513 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
514 TTI::OperandValueInfo Op1Info, TTI::OperandValueInfo Op2Info,
515 ArrayRef<const Value *> Args, const Instruction *CtxI) const {
516 // Legalize the type.
517 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
518
519 int ISD = TLI->InstructionOpcodeToISD(Opcode);
520
521 switch (ISD) {
522 default:
523 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info: Op1Info,
524 Opd2Info: Op2Info);
525 case ISD::ADD:
526 case ISD::MUL:
527 case ISD::XOR:
528 case ISD::OR:
529 case ISD::AND:
530 // The machine code (SASS) simulates an i64 with two i32. Therefore, we
531 // estimate that arithmetic operations on i64 are twice as expensive as
532 // those on types that can fit into one machine register.
533 if (LT.second.SimpleTy == MVT::i64)
534 return 2 * LT.first;
535 // Delegate other cases to the basic TTI.
536 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info: Op1Info,
537 Opd2Info: Op2Info);
538 }
539}
540
541void NVPTXTTIImpl::getUnrollingPreferences(
542 Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP,
543 OptimizationRemarkEmitter *ORE) const {
544 BaseT::getUnrollingPreferences(L, SE, UP, ORE);
545
546 // Enable partial unrolling and runtime unrolling, but reduce the
547 // threshold. This partially unrolls small loops which are often
548 // unrolled by the PTX to SASS compiler and unrolling earlier can be
549 // beneficial.
550 UP.Partial = UP.Runtime = true;
551 UP.PartialThreshold = UP.Threshold / 4;
552}
553
554void NVPTXTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
555 TTI::PeelingPreferences &PP) const {
556 BaseT::getPeelingPreferences(L, SE, PP);
557}
558
559namespace {
560enum class InvalidAddressSpaceAction { LeaveUnchanged, Trap };
561
562// Describes how to specialize GenericID's PointerOperand from generic memory to
563// one of AddressSpaces, using SpecificID (which may be the same intrinsic).
564// Trap only when InvalidAction permits it and the pointer is provably outside
565// every listed address space; otherwise leave the intrinsic unchanged.
566struct IntrinsicAddressSpaceInfo {
567 Intrinsic::ID GenericID;
568 Intrinsic::ID SpecificID;
569 SmallVector<unsigned, 2> AddressSpaces;
570 InvalidAddressSpaceAction InvalidAction;
571 unsigned PointerOperand;
572
573 IntrinsicAddressSpaceInfo(
574 Intrinsic::ID GenericID, Intrinsic::ID SpecificID,
575 ArrayRef<unsigned> AddressSpaces = {NVPTXAS::ADDRESS_SPACE_SHARED},
576 InvalidAddressSpaceAction InvalidAction = InvalidAddressSpaceAction::Trap,
577 unsigned PointerOperand = 0)
578 : GenericID(GenericID), SpecificID(SpecificID),
579 AddressSpaces(AddressSpaces), InvalidAction(InvalidAction),
580 PointerOperand(PointerOperand) {}
581
582 IntrinsicAddressSpaceInfo(
583 Intrinsic::ID IID,
584 ArrayRef<unsigned> AddressSpaces = {NVPTXAS::ADDRESS_SPACE_SHARED},
585 InvalidAddressSpaceAction InvalidAction = InvalidAddressSpaceAction::Trap,
586 unsigned PointerOperand = 0)
587 : IntrinsicAddressSpaceInfo(IID, IID, AddressSpaces, InvalidAction,
588 PointerOperand) {}
589};
590} // namespace
591
592static const IntrinsicAddressSpaceInfo *
593getIntrinsicAddressSpaceInfo(Intrinsic::ID IID) {
594 static const auto Infos = [] {
595 const IntrinsicAddressSpaceInfo Entries[] = {
596 {Intrinsic::nvvm_mbarrier_init},
597 {Intrinsic::nvvm_mbarrier_inval, Intrinsic::nvvm_mbarrier_inval_shared},
598 {Intrinsic::nvvm_mbarrier_check_layout},
599 {Intrinsic::nvvm_mbarrier_arrive,
600 Intrinsic::nvvm_mbarrier_arrive_shared},
601 {Intrinsic::nvvm_mbarrier_arrive_noComplete,
602 Intrinsic::nvvm_mbarrier_arrive_noComplete_shared},
603 {Intrinsic::nvvm_mbarrier_arrive_drop,
604 Intrinsic::nvvm_mbarrier_arrive_drop_shared},
605 {Intrinsic::nvvm_mbarrier_arrive_drop_noComplete,
606 Intrinsic::nvvm_mbarrier_arrive_drop_noComplete_shared},
607 {Intrinsic::nvvm_mbarrier_test_wait,
608 Intrinsic::nvvm_mbarrier_test_wait_shared},
609 {Intrinsic::nvvm_cp_async_mbarrier_arrive,
610 Intrinsic::nvvm_cp_async_mbarrier_arrive_shared},
611 {Intrinsic::nvvm_cp_async_mbarrier_arrive_noinc,
612 Intrinsic::nvvm_cp_async_mbarrier_arrive_noinc_shared},
613 // Other address spaces cannot be specialized but do not imply undefined
614 // behavior for prefetch.tensormap.
615 {Intrinsic::nvvm_prefetch_tensormap,
616 {NVPTXAS::ADDRESS_SPACE_CONST, NVPTXAS::ADDRESS_SPACE_ENTRY_PARAM},
617 InvalidAddressSpaceAction::LeaveUnchanged},
618 };
619 return SmallDenseMap<Intrinsic::ID, IntrinsicAddressSpaceInfo, 16>(
620 llvm::from_range, llvm::map_range(C: Entries, F: [](const auto &Info) {
621 return std::pair{Info.GenericID, Info};
622 }));
623 }();
624 auto It = Infos.find(Val: IID);
625 return It == Infos.end() ? nullptr : &It->second;
626}
627
628bool NVPTXTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
629 Intrinsic::ID IID) const {
630 if (const auto *Info = getIntrinsicAddressSpaceInfo(IID)) {
631 OpIndexes.push_back(Elt: Info->PointerOperand);
632 return true;
633 }
634 switch (IID) {
635 case Intrinsic::nvvm_isspacep_const:
636 case Intrinsic::nvvm_isspacep_global:
637 case Intrinsic::nvvm_isspacep_local:
638 case Intrinsic::nvvm_isspacep_shared:
639 case Intrinsic::nvvm_isspacep_shared_cluster: {
640 OpIndexes.push_back(Elt: 0);
641 return true;
642 }
643 }
644 return false;
645}
646
647Value *NVPTXTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
648 Value *OldV,
649 Value *NewV) const {
650 const Intrinsic::ID IID = II->getIntrinsicID();
651 if (const auto *Info = getIntrinsicAddressSpaceInfo(IID)) {
652 if (II->getArgOperand(i: Info->PointerOperand) != OldV)
653 return nullptr;
654
655 unsigned NewAS = NewV->getType()->getPointerAddressSpace();
656 if (!llvm::is_contained(Range: Info->AddressSpaces, Element: NewAS)) {
657 // A missing rewrite is not necessarily invalid. Trap only when the
658 // address is provably outside every allowed space and the entry permits
659 // it.
660 if (Info->InvalidAction == InvalidAddressSpaceAction::LeaveUnchanged ||
661 !llvm::all_of(Range: Info->AddressSpaces, P: [NewAS](unsigned AS) {
662 return isInAddressSpace(AS: NewAS, SpecificAS: AS) == false;
663 }))
664 return nullptr;
665 // InferAddressSpaces preserves the CFG. Emit a trap here and leave
666 // truncating the block at the noreturn call to SimplifyCFG.
667 Value *Trap = IRBuilder<>(II).CreateIntrinsic(ID: Intrinsic::trap, Args: {});
668 return II->getType()->isVoidTy() ? Trap : PoisonValue::get(T: II->getType());
669 }
670
671 SmallVector<Type *, 8> ArgTypes(II->getFunctionType()->params());
672 ArgTypes[Info->PointerOperand] = NewV->getType();
673 FunctionType *FT = FunctionType::get(Result: II->getType(), Params: ArgTypes, isVarArg: false);
674 SmallVector<Type *, 4> OverloadTypes;
675 if (!Intrinsic::isSignatureValid(ID: Info->SpecificID, FT, OverloadTys&: OverloadTypes))
676 return nullptr;
677 Function *Decl = Intrinsic::getOrInsertDeclaration(
678 M: II->getModule(), id: Info->SpecificID, OverloadTys: OverloadTypes);
679 II->setArgOperand(i: Info->PointerOperand, v: NewV);
680 II->setCalledFunction(Decl);
681 return II;
682 }
683 switch (IID) {
684 case Intrinsic::nvvm_isspacep_const:
685 case Intrinsic::nvvm_isspacep_global:
686 case Intrinsic::nvvm_isspacep_local:
687 case Intrinsic::nvvm_isspacep_shared:
688 case Intrinsic::nvvm_isspacep_shared_cluster: {
689 const unsigned NewAS = NewV->getType()->getPointerAddressSpace();
690 if (const auto R = evaluateIsSpace(IID, AS: NewAS))
691 return ConstantInt::get(Ty: II->getType(), V: *R);
692 return nullptr;
693 }
694 }
695 return nullptr;
696}
697
698bool NVPTXTTIImpl::isLegalMaskedStore(Type *DataTy, Align Alignment,
699 unsigned AddrSpace,
700 TTI::MaskKind MaskKind) const {
701 if (MaskKind != TTI::MaskKind::ConstantMask)
702 return false;
703
704 // We currently only support this feature for 256-bit vectors, so the
705 // alignment must be at least 32
706 if (Alignment < 32)
707 return false;
708
709 if (!ST->has256BitVectorLoadStore(AS: AddrSpace))
710 return false;
711
712 auto *VTy = dyn_cast<FixedVectorType>(Val: DataTy);
713 if (!VTy)
714 return false;
715
716 auto *ElemTy = VTy->getScalarType();
717 return (ElemTy->getScalarSizeInBits() == 32 && VTy->getNumElements() == 8) ||
718 (ElemTy->getScalarSizeInBits() == 64 && VTy->getNumElements() == 4);
719}
720
721bool NVPTXTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment,
722 unsigned /*AddrSpace*/,
723 TTI::MaskKind MaskKind) const {
724 if (MaskKind != TTI::MaskKind::ConstantMask)
725 return false;
726
727 if (Alignment < DL.getTypeStoreSize(Ty: DataTy))
728 return false;
729
730 // We do not support sub-byte element type masked loads.
731 auto *VTy = dyn_cast<FixedVectorType>(Val: DataTy);
732 if (!VTy)
733 return false;
734 return VTy->getElementType()->getScalarSizeInBits() >= 8;
735}
736
737unsigned NVPTXTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
738 // 256 bit loads/stores are currently only supported for global address space
739 if (ST->has256BitVectorLoadStore(AS: AddrSpace))
740 return 256;
741 return 128;
742}
743
744unsigned NVPTXTTIImpl::getAssumedAddrSpace(const Value *V) const {
745 if (isa<AllocaInst>(Val: V))
746 return ADDRESS_SPACE_LOCAL;
747
748 if (const Argument *Arg = dyn_cast<Argument>(Val: V)) {
749 if (isKernelFunction(F: *Arg->getParent())) {
750 const NVPTXTargetMachine &TM =
751 static_cast<const NVPTXTargetMachine &>(getTLI()->getTargetMachine());
752 if (TM.getDrvInterface() == NVPTX::CUDA && !Arg->hasByValAttr())
753 return ADDRESS_SPACE_GLOBAL;
754 } else {
755 // We assume that all device parameters that are passed byval will be
756 // placed in the local AS. Very simple cases will be updated after ISel to
757 // use the device param space where possible.
758 if (Arg->hasByValAttr())
759 return ADDRESS_SPACE_LOCAL;
760 }
761 }
762
763 return -1;
764}
765
766void NVPTXTTIImpl::collectKernelLaunchBounds(
767 const Function &F,
768 SmallVectorImpl<std::pair<StringRef, int64_t>> &LB) const {
769 if (const auto Val = getMaxClusterRank(F))
770 LB.push_back(Elt: {"maxclusterrank", *Val});
771
772 const auto MaxNTID = getMaxNTID(F);
773 if (MaxNTID.size() > 0)
774 LB.push_back(Elt: {"maxntidx", MaxNTID[0]});
775 if (MaxNTID.size() > 1)
776 LB.push_back(Elt: {"maxntidy", MaxNTID[1]});
777 if (MaxNTID.size() > 2)
778 LB.push_back(Elt: {"maxntidz", MaxNTID[2]});
779}
780
781// Global addresses can only be materialized if they are in generic global or
782// constant space.
783bool NVPTXTTIImpl::shouldBuildLookupTablesForConstant(Constant *C) const {
784 if (const auto *GV = dyn_cast<GlobalValue>(Val: C)) {
785 const unsigned AS = GV->getAddressSpace();
786 return AS == NVPTXAS::ADDRESS_SPACE_GENERIC ||
787 AS == NVPTXAS::ADDRESS_SPACE_GLOBAL ||
788 AS == NVPTXAS::ADDRESS_SPACE_CONST;
789 }
790 return true;
791}
792
793ValueUniformity NVPTXTTIImpl::getValueUniformity(const Value *V) const {
794 if (isSourceOfDivergence(V))
795 return ValueUniformity::NeverUniform;
796
797 return ValueUniformity::Default;
798}
799