1 //===- AMDGPInstCombineIntrinsic.cpp - AMDGPU specific InstCombine pass ---===// 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 // \file 10 // This file implements a TargetTransformInfo analysis pass specific to the 11 // AMDGPU target machine. It uses the target's detailed information to provide 12 // more precise answers to certain TTI queries, while letting the target 13 // independent and default TTI implementations handle the rest. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "AMDGPUInstrInfo.h" 18 #include "AMDGPUTargetTransformInfo.h" 19 #include "GCNSubtarget.h" 20 #include "llvm/ADT/FloatingPointMode.h" 21 #include "llvm/IR/IntrinsicsAMDGPU.h" 22 #include "llvm/Transforms/InstCombine/InstCombiner.h" 23 #include <optional> 24 25 using namespace llvm; 26 using namespace llvm::PatternMatch; 27 28 #define DEBUG_TYPE "AMDGPUtti" 29 30 namespace { 31 32 struct AMDGPUImageDMaskIntrinsic { 33 unsigned Intr; 34 }; 35 36 #define GET_AMDGPUImageDMaskIntrinsicTable_IMPL 37 #include "InstCombineTables.inc" 38 39 } // end anonymous namespace 40 41 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs. 42 // 43 // A single NaN input is folded to minnum, so we rely on that folding for 44 // handling NaNs. 45 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1, 46 const APFloat &Src2) { 47 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2); 48 49 APFloat::cmpResult Cmp0 = Max3.compare(Src0); 50 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately"); 51 if (Cmp0 == APFloat::cmpEqual) 52 return maxnum(Src1, Src2); 53 54 APFloat::cmpResult Cmp1 = Max3.compare(Src1); 55 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately"); 56 if (Cmp1 == APFloat::cmpEqual) 57 return maxnum(Src0, Src2); 58 59 return maxnum(Src0, Src1); 60 } 61 62 // Check if a value can be converted to a 16-bit value without losing 63 // precision. 64 // The value is expected to be either a float (IsFloat = true) or an unsigned 65 // integer (IsFloat = false). 66 static bool canSafelyConvertTo16Bit(Value &V, bool IsFloat) { 67 Type *VTy = V.getType(); 68 if (VTy->isHalfTy() || VTy->isIntegerTy(16)) { 69 // The value is already 16-bit, so we don't want to convert to 16-bit again! 70 return false; 71 } 72 if (IsFloat) { 73 if (ConstantFP *ConstFloat = dyn_cast<ConstantFP>(&V)) { 74 // We need to check that if we cast the index down to a half, we do not 75 // lose precision. 76 APFloat FloatValue(ConstFloat->getValueAPF()); 77 bool LosesInfo = true; 78 FloatValue.convert(APFloat::IEEEhalf(), APFloat::rmTowardZero, 79 &LosesInfo); 80 return !LosesInfo; 81 } 82 } else { 83 if (ConstantInt *ConstInt = dyn_cast<ConstantInt>(&V)) { 84 // We need to check that if we cast the index down to an i16, we do not 85 // lose precision. 86 APInt IntValue(ConstInt->getValue()); 87 return IntValue.getActiveBits() <= 16; 88 } 89 } 90 91 Value *CastSrc; 92 bool IsExt = IsFloat ? match(&V, m_FPExt(PatternMatch::m_Value(CastSrc))) 93 : match(&V, m_ZExt(PatternMatch::m_Value(CastSrc))); 94 if (IsExt) { 95 Type *CastSrcTy = CastSrc->getType(); 96 if (CastSrcTy->isHalfTy() || CastSrcTy->isIntegerTy(16)) 97 return true; 98 } 99 100 return false; 101 } 102 103 // Convert a value to 16-bit. 104 static Value *convertTo16Bit(Value &V, InstCombiner::BuilderTy &Builder) { 105 Type *VTy = V.getType(); 106 if (isa<FPExtInst>(&V) || isa<SExtInst>(&V) || isa<ZExtInst>(&V)) 107 return cast<Instruction>(&V)->getOperand(0); 108 if (VTy->isIntegerTy()) 109 return Builder.CreateIntCast(&V, Type::getInt16Ty(V.getContext()), false); 110 if (VTy->isFloatingPointTy()) 111 return Builder.CreateFPCast(&V, Type::getHalfTy(V.getContext())); 112 113 llvm_unreachable("Should never be called!"); 114 } 115 116 /// Applies Func(OldIntr.Args, OldIntr.ArgTys), creates intrinsic call with 117 /// modified arguments (based on OldIntr) and replaces InstToReplace with 118 /// this newly created intrinsic call. 119 static std::optional<Instruction *> modifyIntrinsicCall( 120 IntrinsicInst &OldIntr, Instruction &InstToReplace, unsigned NewIntr, 121 InstCombiner &IC, 122 std::function<void(SmallVectorImpl<Value *> &, SmallVectorImpl<Type *> &)> 123 Func) { 124 SmallVector<Type *, 4> ArgTys; 125 if (!Intrinsic::getIntrinsicSignature(OldIntr.getCalledFunction(), ArgTys)) 126 return std::nullopt; 127 128 SmallVector<Value *, 8> Args(OldIntr.args()); 129 130 // Modify arguments and types 131 Func(Args, ArgTys); 132 133 Function *I = Intrinsic::getDeclaration(OldIntr.getModule(), NewIntr, ArgTys); 134 135 CallInst *NewCall = IC.Builder.CreateCall(I, Args); 136 NewCall->takeName(&OldIntr); 137 NewCall->copyMetadata(OldIntr); 138 if (isa<FPMathOperator>(NewCall)) 139 NewCall->copyFastMathFlags(&OldIntr); 140 141 // Erase and replace uses 142 if (!InstToReplace.getType()->isVoidTy()) 143 IC.replaceInstUsesWith(InstToReplace, NewCall); 144 145 bool RemoveOldIntr = &OldIntr != &InstToReplace; 146 147 auto RetValue = IC.eraseInstFromFunction(InstToReplace); 148 if (RemoveOldIntr) 149 IC.eraseInstFromFunction(OldIntr); 150 151 return RetValue; 152 } 153 154 static std::optional<Instruction *> 155 simplifyAMDGCNImageIntrinsic(const GCNSubtarget *ST, 156 const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr, 157 IntrinsicInst &II, InstCombiner &IC) { 158 // Optimize _L to _LZ when _L is zero 159 if (const auto *LZMappingInfo = 160 AMDGPU::getMIMGLZMappingInfo(ImageDimIntr->BaseOpcode)) { 161 if (auto *ConstantLod = 162 dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->LodIndex))) { 163 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 164 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr = 165 AMDGPU::getImageDimIntrinsicByBaseOpcode(LZMappingInfo->LZ, 166 ImageDimIntr->Dim); 167 return modifyIntrinsicCall( 168 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) { 169 Args.erase(Args.begin() + ImageDimIntr->LodIndex); 170 }); 171 } 172 } 173 } 174 175 // Optimize _mip away, when 'lod' is zero 176 if (const auto *MIPMappingInfo = 177 AMDGPU::getMIMGMIPMappingInfo(ImageDimIntr->BaseOpcode)) { 178 if (auto *ConstantMip = 179 dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->MipIndex))) { 180 if (ConstantMip->isZero()) { 181 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr = 182 AMDGPU::getImageDimIntrinsicByBaseOpcode(MIPMappingInfo->NONMIP, 183 ImageDimIntr->Dim); 184 return modifyIntrinsicCall( 185 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) { 186 Args.erase(Args.begin() + ImageDimIntr->MipIndex); 187 }); 188 } 189 } 190 } 191 192 // Optimize _bias away when 'bias' is zero 193 if (const auto *BiasMappingInfo = 194 AMDGPU::getMIMGBiasMappingInfo(ImageDimIntr->BaseOpcode)) { 195 if (auto *ConstantBias = 196 dyn_cast<ConstantFP>(II.getOperand(ImageDimIntr->BiasIndex))) { 197 if (ConstantBias->isZero()) { 198 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr = 199 AMDGPU::getImageDimIntrinsicByBaseOpcode(BiasMappingInfo->NoBias, 200 ImageDimIntr->Dim); 201 return modifyIntrinsicCall( 202 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) { 203 Args.erase(Args.begin() + ImageDimIntr->BiasIndex); 204 ArgTys.erase(ArgTys.begin() + ImageDimIntr->BiasTyArg); 205 }); 206 } 207 } 208 } 209 210 // Optimize _offset away when 'offset' is zero 211 if (const auto *OffsetMappingInfo = 212 AMDGPU::getMIMGOffsetMappingInfo(ImageDimIntr->BaseOpcode)) { 213 if (auto *ConstantOffset = 214 dyn_cast<ConstantInt>(II.getOperand(ImageDimIntr->OffsetIndex))) { 215 if (ConstantOffset->isZero()) { 216 const AMDGPU::ImageDimIntrinsicInfo *NewImageDimIntr = 217 AMDGPU::getImageDimIntrinsicByBaseOpcode( 218 OffsetMappingInfo->NoOffset, ImageDimIntr->Dim); 219 return modifyIntrinsicCall( 220 II, II, NewImageDimIntr->Intr, IC, [&](auto &Args, auto &ArgTys) { 221 Args.erase(Args.begin() + ImageDimIntr->OffsetIndex); 222 }); 223 } 224 } 225 } 226 227 // Try to use D16 228 if (ST->hasD16Images()) { 229 230 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 231 AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode); 232 233 if (BaseOpcode->HasD16) { 234 235 // If the only use of image intrinsic is a fptrunc (with conversion to 236 // half) then both fptrunc and image intrinsic will be replaced with image 237 // intrinsic with D16 flag. 238 if (II.hasOneUse()) { 239 Instruction *User = II.user_back(); 240 241 if (User->getOpcode() == Instruction::FPTrunc && 242 User->getType()->getScalarType()->isHalfTy()) { 243 244 return modifyIntrinsicCall(II, *User, ImageDimIntr->Intr, IC, 245 [&](auto &Args, auto &ArgTys) { 246 // Change return type of image intrinsic. 247 // Set it to return type of fptrunc. 248 ArgTys[0] = User->getType(); 249 }); 250 } 251 } 252 } 253 } 254 255 // Try to use A16 or G16 256 if (!ST->hasA16() && !ST->hasG16()) 257 return std::nullopt; 258 259 // Address is interpreted as float if the instruction has a sampler or as 260 // unsigned int if there is no sampler. 261 bool HasSampler = 262 AMDGPU::getMIMGBaseOpcodeInfo(ImageDimIntr->BaseOpcode)->Sampler; 263 bool FloatCoord = false; 264 // true means derivatives can be converted to 16 bit, coordinates not 265 bool OnlyDerivatives = false; 266 267 for (unsigned OperandIndex = ImageDimIntr->GradientStart; 268 OperandIndex < ImageDimIntr->VAddrEnd; OperandIndex++) { 269 Value *Coord = II.getOperand(OperandIndex); 270 // If the values are not derived from 16-bit values, we cannot optimize. 271 if (!canSafelyConvertTo16Bit(*Coord, HasSampler)) { 272 if (OperandIndex < ImageDimIntr->CoordStart || 273 ImageDimIntr->GradientStart == ImageDimIntr->CoordStart) { 274 return std::nullopt; 275 } 276 // All gradients can be converted, so convert only them 277 OnlyDerivatives = true; 278 break; 279 } 280 281 assert(OperandIndex == ImageDimIntr->GradientStart || 282 FloatCoord == Coord->getType()->isFloatingPointTy()); 283 FloatCoord = Coord->getType()->isFloatingPointTy(); 284 } 285 286 if (!OnlyDerivatives && !ST->hasA16()) 287 OnlyDerivatives = true; // Only supports G16 288 289 // Check if there is a bias parameter and if it can be converted to f16 290 if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) { 291 Value *Bias = II.getOperand(ImageDimIntr->BiasIndex); 292 assert(HasSampler && 293 "Only image instructions with a sampler can have a bias"); 294 if (!canSafelyConvertTo16Bit(*Bias, HasSampler)) 295 OnlyDerivatives = true; 296 } 297 298 if (OnlyDerivatives && (!ST->hasG16() || ImageDimIntr->GradientStart == 299 ImageDimIntr->CoordStart)) 300 return std::nullopt; 301 302 Type *CoordType = FloatCoord ? Type::getHalfTy(II.getContext()) 303 : Type::getInt16Ty(II.getContext()); 304 305 return modifyIntrinsicCall( 306 II, II, II.getIntrinsicID(), IC, [&](auto &Args, auto &ArgTys) { 307 ArgTys[ImageDimIntr->GradientTyArg] = CoordType; 308 if (!OnlyDerivatives) { 309 ArgTys[ImageDimIntr->CoordTyArg] = CoordType; 310 311 // Change the bias type 312 if (ImageDimIntr->NumBiasArgs != 0) 313 ArgTys[ImageDimIntr->BiasTyArg] = Type::getHalfTy(II.getContext()); 314 } 315 316 unsigned EndIndex = 317 OnlyDerivatives ? ImageDimIntr->CoordStart : ImageDimIntr->VAddrEnd; 318 for (unsigned OperandIndex = ImageDimIntr->GradientStart; 319 OperandIndex < EndIndex; OperandIndex++) { 320 Args[OperandIndex] = 321 convertTo16Bit(*II.getOperand(OperandIndex), IC.Builder); 322 } 323 324 // Convert the bias 325 if (!OnlyDerivatives && ImageDimIntr->NumBiasArgs != 0) { 326 Value *Bias = II.getOperand(ImageDimIntr->BiasIndex); 327 Args[ImageDimIntr->BiasIndex] = convertTo16Bit(*Bias, IC.Builder); 328 } 329 }); 330 } 331 332 bool GCNTTIImpl::canSimplifyLegacyMulToMul(const Instruction &I, 333 const Value *Op0, const Value *Op1, 334 InstCombiner &IC) const { 335 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or 336 // infinity, gives +0.0. If we can prove we don't have one of the special 337 // cases then we can use a normal multiply instead. 338 // TODO: Create and use isKnownFiniteNonZero instead of just matching 339 // constants here. 340 if (match(Op0, PatternMatch::m_FiniteNonZero()) || 341 match(Op1, PatternMatch::m_FiniteNonZero())) { 342 // One operand is not zero or infinity or NaN. 343 return true; 344 } 345 346 auto *TLI = &IC.getTargetLibraryInfo(); 347 if (isKnownNeverInfOrNaN(Op0, IC.getDataLayout(), TLI, 0, 348 &IC.getAssumptionCache(), &I, &IC.getDominatorTree(), 349 &IC.getOptimizationRemarkEmitter()) && 350 isKnownNeverInfOrNaN(Op1, IC.getDataLayout(), TLI, 0, 351 &IC.getAssumptionCache(), &I, &IC.getDominatorTree(), 352 &IC.getOptimizationRemarkEmitter())) { 353 // Neither operand is infinity or NaN. 354 return true; 355 } 356 return false; 357 } 358 359 /// Match an fpext from half to float, or a constant we can convert. 360 static bool matchFPExtFromF16(Value *Arg, Value *&FPExtSrc) { 361 if (match(Arg, m_OneUse(m_FPExt(m_Value(FPExtSrc))))) 362 return FPExtSrc->getType()->isHalfTy(); 363 364 ConstantFP *CFP; 365 if (match(Arg, m_ConstantFP(CFP))) { 366 bool LosesInfo; 367 APFloat Val(CFP->getValueAPF()); 368 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &LosesInfo); 369 if (LosesInfo) 370 return false; 371 372 FPExtSrc = ConstantFP::get(Type::getHalfTy(Arg->getContext()), Val); 373 return true; 374 } 375 376 return false; 377 } 378 379 std::optional<Instruction *> 380 GCNTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const { 381 Intrinsic::ID IID = II.getIntrinsicID(); 382 switch (IID) { 383 case Intrinsic::amdgcn_rcp: { 384 Value *Src = II.getArgOperand(0); 385 386 // TODO: Move to ConstantFolding/InstSimplify? 387 if (isa<UndefValue>(Src)) { 388 Type *Ty = II.getType(); 389 auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics())); 390 return IC.replaceInstUsesWith(II, QNaN); 391 } 392 393 if (II.isStrictFP()) 394 break; 395 396 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 397 const APFloat &ArgVal = C->getValueAPF(); 398 APFloat Val(ArgVal.getSemantics(), 1); 399 Val.divide(ArgVal, APFloat::rmNearestTiesToEven); 400 401 // This is more precise than the instruction may give. 402 // 403 // TODO: The instruction always flushes denormal results (except for f16), 404 // should this also? 405 return IC.replaceInstUsesWith(II, ConstantFP::get(II.getContext(), Val)); 406 } 407 408 break; 409 } 410 case Intrinsic::amdgcn_sqrt: 411 case Intrinsic::amdgcn_rsq: { 412 Value *Src = II.getArgOperand(0); 413 414 // TODO: Move to ConstantFolding/InstSimplify? 415 if (isa<UndefValue>(Src)) { 416 Type *Ty = II.getType(); 417 auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics())); 418 return IC.replaceInstUsesWith(II, QNaN); 419 } 420 421 break; 422 } 423 case Intrinsic::amdgcn_frexp_mant: 424 case Intrinsic::amdgcn_frexp_exp: { 425 Value *Src = II.getArgOperand(0); 426 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) { 427 int Exp; 428 APFloat Significand = 429 frexp(C->getValueAPF(), Exp, APFloat::rmNearestTiesToEven); 430 431 if (IID == Intrinsic::amdgcn_frexp_mant) { 432 return IC.replaceInstUsesWith( 433 II, ConstantFP::get(II.getContext(), Significand)); 434 } 435 436 // Match instruction special case behavior. 437 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf) 438 Exp = 0; 439 440 return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), Exp)); 441 } 442 443 if (isa<UndefValue>(Src)) { 444 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType())); 445 } 446 447 break; 448 } 449 case Intrinsic::amdgcn_class: { 450 Value *Src0 = II.getArgOperand(0); 451 Value *Src1 = II.getArgOperand(1); 452 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1); 453 if (CMask) { 454 II.setCalledOperand(Intrinsic::getDeclaration( 455 II.getModule(), Intrinsic::is_fpclass, Src0->getType())); 456 457 // Clamp any excess bits, as they're illegal for the generic intrinsic. 458 II.setArgOperand(1, ConstantInt::get(Src1->getType(), 459 CMask->getZExtValue() & fcAllFlags)); 460 return &II; 461 } 462 463 // FIXME: Should propagate poison. 464 if (isa<UndefValue>(Src0)) 465 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType())); 466 467 if (isa<UndefValue>(Src1)) { 468 return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), false)); 469 } 470 471 break; 472 } 473 case Intrinsic::amdgcn_cvt_pkrtz: { 474 Value *Src0 = II.getArgOperand(0); 475 Value *Src1 = II.getArgOperand(1); 476 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 477 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 478 const fltSemantics &HalfSem = 479 II.getType()->getScalarType()->getFltSemantics(); 480 bool LosesInfo; 481 APFloat Val0 = C0->getValueAPF(); 482 APFloat Val1 = C1->getValueAPF(); 483 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 484 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo); 485 486 Constant *Folded = 487 ConstantVector::get({ConstantFP::get(II.getContext(), Val0), 488 ConstantFP::get(II.getContext(), Val1)}); 489 return IC.replaceInstUsesWith(II, Folded); 490 } 491 } 492 493 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) { 494 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType())); 495 } 496 497 break; 498 } 499 case Intrinsic::amdgcn_cvt_pknorm_i16: 500 case Intrinsic::amdgcn_cvt_pknorm_u16: 501 case Intrinsic::amdgcn_cvt_pk_i16: 502 case Intrinsic::amdgcn_cvt_pk_u16: { 503 Value *Src0 = II.getArgOperand(0); 504 Value *Src1 = II.getArgOperand(1); 505 506 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1)) { 507 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType())); 508 } 509 510 break; 511 } 512 case Intrinsic::amdgcn_ubfe: 513 case Intrinsic::amdgcn_sbfe: { 514 // Decompose simple cases into standard shifts. 515 Value *Src = II.getArgOperand(0); 516 if (isa<UndefValue>(Src)) { 517 return IC.replaceInstUsesWith(II, Src); 518 } 519 520 unsigned Width; 521 Type *Ty = II.getType(); 522 unsigned IntSize = Ty->getIntegerBitWidth(); 523 524 ConstantInt *CWidth = dyn_cast<ConstantInt>(II.getArgOperand(2)); 525 if (CWidth) { 526 Width = CWidth->getZExtValue(); 527 if ((Width & (IntSize - 1)) == 0) { 528 return IC.replaceInstUsesWith(II, ConstantInt::getNullValue(Ty)); 529 } 530 531 // Hardware ignores high bits, so remove those. 532 if (Width >= IntSize) { 533 return IC.replaceOperand( 534 II, 2, ConstantInt::get(CWidth->getType(), Width & (IntSize - 1))); 535 } 536 } 537 538 unsigned Offset; 539 ConstantInt *COffset = dyn_cast<ConstantInt>(II.getArgOperand(1)); 540 if (COffset) { 541 Offset = COffset->getZExtValue(); 542 if (Offset >= IntSize) { 543 return IC.replaceOperand( 544 II, 1, 545 ConstantInt::get(COffset->getType(), Offset & (IntSize - 1))); 546 } 547 } 548 549 bool Signed = IID == Intrinsic::amdgcn_sbfe; 550 551 if (!CWidth || !COffset) 552 break; 553 554 // The case of Width == 0 is handled above, which makes this transformation 555 // safe. If Width == 0, then the ashr and lshr instructions become poison 556 // value since the shift amount would be equal to the bit size. 557 assert(Width != 0); 558 559 // TODO: This allows folding to undef when the hardware has specific 560 // behavior? 561 if (Offset + Width < IntSize) { 562 Value *Shl = IC.Builder.CreateShl(Src, IntSize - Offset - Width); 563 Value *RightShift = Signed ? IC.Builder.CreateAShr(Shl, IntSize - Width) 564 : IC.Builder.CreateLShr(Shl, IntSize - Width); 565 RightShift->takeName(&II); 566 return IC.replaceInstUsesWith(II, RightShift); 567 } 568 569 Value *RightShift = Signed ? IC.Builder.CreateAShr(Src, Offset) 570 : IC.Builder.CreateLShr(Src, Offset); 571 572 RightShift->takeName(&II); 573 return IC.replaceInstUsesWith(II, RightShift); 574 } 575 case Intrinsic::amdgcn_exp: 576 case Intrinsic::amdgcn_exp_row: 577 case Intrinsic::amdgcn_exp_compr: { 578 ConstantInt *En = cast<ConstantInt>(II.getArgOperand(1)); 579 unsigned EnBits = En->getZExtValue(); 580 if (EnBits == 0xf) 581 break; // All inputs enabled. 582 583 bool IsCompr = IID == Intrinsic::amdgcn_exp_compr; 584 bool Changed = false; 585 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) { 586 if ((!IsCompr && (EnBits & (1 << I)) == 0) || 587 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) { 588 Value *Src = II.getArgOperand(I + 2); 589 if (!isa<UndefValue>(Src)) { 590 IC.replaceOperand(II, I + 2, UndefValue::get(Src->getType())); 591 Changed = true; 592 } 593 } 594 } 595 596 if (Changed) { 597 return &II; 598 } 599 600 break; 601 } 602 case Intrinsic::amdgcn_fmed3: { 603 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled 604 // for the shader. 605 606 Value *Src0 = II.getArgOperand(0); 607 Value *Src1 = II.getArgOperand(1); 608 Value *Src2 = II.getArgOperand(2); 609 610 // Checking for NaN before canonicalization provides better fidelity when 611 // mapping other operations onto fmed3 since the order of operands is 612 // unchanged. 613 CallInst *NewCall = nullptr; 614 if (match(Src0, PatternMatch::m_NaN()) || isa<UndefValue>(Src0)) { 615 NewCall = IC.Builder.CreateMinNum(Src1, Src2); 616 } else if (match(Src1, PatternMatch::m_NaN()) || isa<UndefValue>(Src1)) { 617 NewCall = IC.Builder.CreateMinNum(Src0, Src2); 618 } else if (match(Src2, PatternMatch::m_NaN()) || isa<UndefValue>(Src2)) { 619 NewCall = IC.Builder.CreateMaxNum(Src0, Src1); 620 } 621 622 if (NewCall) { 623 NewCall->copyFastMathFlags(&II); 624 NewCall->takeName(&II); 625 return IC.replaceInstUsesWith(II, NewCall); 626 } 627 628 bool Swap = false; 629 // Canonicalize constants to RHS operands. 630 // 631 // fmed3(c0, x, c1) -> fmed3(x, c0, c1) 632 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 633 std::swap(Src0, Src1); 634 Swap = true; 635 } 636 637 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) { 638 std::swap(Src1, Src2); 639 Swap = true; 640 } 641 642 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) { 643 std::swap(Src0, Src1); 644 Swap = true; 645 } 646 647 if (Swap) { 648 II.setArgOperand(0, Src0); 649 II.setArgOperand(1, Src1); 650 II.setArgOperand(2, Src2); 651 return &II; 652 } 653 654 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) { 655 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) { 656 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) { 657 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(), 658 C2->getValueAPF()); 659 return IC.replaceInstUsesWith( 660 II, ConstantFP::get(IC.Builder.getContext(), Result)); 661 } 662 } 663 } 664 665 if (!ST->hasMed3_16()) 666 break; 667 668 Value *X, *Y, *Z; 669 670 // Repeat floating-point width reduction done for minnum/maxnum. 671 // fmed3((fpext X), (fpext Y), (fpext Z)) -> fpext (fmed3(X, Y, Z)) 672 if (matchFPExtFromF16(Src0, X) && matchFPExtFromF16(Src1, Y) && 673 matchFPExtFromF16(Src2, Z)) { 674 Value *NewCall = IC.Builder.CreateIntrinsic(IID, {X->getType()}, 675 {X, Y, Z}, &II, II.getName()); 676 return new FPExtInst(NewCall, II.getType()); 677 } 678 679 break; 680 } 681 case Intrinsic::amdgcn_icmp: 682 case Intrinsic::amdgcn_fcmp: { 683 const ConstantInt *CC = cast<ConstantInt>(II.getArgOperand(2)); 684 // Guard against invalid arguments. 685 int64_t CCVal = CC->getZExtValue(); 686 bool IsInteger = IID == Intrinsic::amdgcn_icmp; 687 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE || 688 CCVal > CmpInst::LAST_ICMP_PREDICATE)) || 689 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE || 690 CCVal > CmpInst::LAST_FCMP_PREDICATE))) 691 break; 692 693 Value *Src0 = II.getArgOperand(0); 694 Value *Src1 = II.getArgOperand(1); 695 696 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) { 697 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) { 698 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1); 699 if (CCmp->isNullValue()) { 700 return IC.replaceInstUsesWith( 701 II, ConstantExpr::getSExt(CCmp, II.getType())); 702 } 703 704 // The result of V_ICMP/V_FCMP assembly instructions (which this 705 // intrinsic exposes) is one bit per thread, masked with the EXEC 706 // register (which contains the bitmask of live threads). So a 707 // comparison that always returns true is the same as a read of the 708 // EXEC register. 709 Function *NewF = Intrinsic::getDeclaration( 710 II.getModule(), Intrinsic::read_register, II.getType()); 711 Metadata *MDArgs[] = {MDString::get(II.getContext(), "exec")}; 712 MDNode *MD = MDNode::get(II.getContext(), MDArgs); 713 Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)}; 714 CallInst *NewCall = IC.Builder.CreateCall(NewF, Args); 715 NewCall->addFnAttr(Attribute::Convergent); 716 NewCall->takeName(&II); 717 return IC.replaceInstUsesWith(II, NewCall); 718 } 719 720 // Canonicalize constants to RHS. 721 CmpInst::Predicate SwapPred = 722 CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal)); 723 II.setArgOperand(0, Src1); 724 II.setArgOperand(1, Src0); 725 II.setArgOperand( 726 2, ConstantInt::get(CC->getType(), static_cast<int>(SwapPred))); 727 return &II; 728 } 729 730 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE) 731 break; 732 733 // Canonicalize compare eq with true value to compare != 0 734 // llvm.amdgcn.icmp(zext (i1 x), 1, eq) 735 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne) 736 // llvm.amdgcn.icmp(sext (i1 x), -1, eq) 737 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne) 738 Value *ExtSrc; 739 if (CCVal == CmpInst::ICMP_EQ && 740 ((match(Src1, PatternMatch::m_One()) && 741 match(Src0, m_ZExt(PatternMatch::m_Value(ExtSrc)))) || 742 (match(Src1, PatternMatch::m_AllOnes()) && 743 match(Src0, m_SExt(PatternMatch::m_Value(ExtSrc))))) && 744 ExtSrc->getType()->isIntegerTy(1)) { 745 IC.replaceOperand(II, 1, ConstantInt::getNullValue(Src1->getType())); 746 IC.replaceOperand(II, 2, 747 ConstantInt::get(CC->getType(), CmpInst::ICMP_NE)); 748 return &II; 749 } 750 751 CmpInst::Predicate SrcPred; 752 Value *SrcLHS; 753 Value *SrcRHS; 754 755 // Fold compare eq/ne with 0 from a compare result as the predicate to the 756 // intrinsic. The typical use is a wave vote function in the library, which 757 // will be fed from a user code condition compared with 0. Fold in the 758 // redundant compare. 759 760 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne) 761 // -> llvm.amdgcn.[if]cmp(a, b, pred) 762 // 763 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq) 764 // -> llvm.amdgcn.[if]cmp(a, b, inv pred) 765 if (match(Src1, PatternMatch::m_Zero()) && 766 match(Src0, PatternMatch::m_ZExtOrSExt( 767 m_Cmp(SrcPred, PatternMatch::m_Value(SrcLHS), 768 PatternMatch::m_Value(SrcRHS))))) { 769 if (CCVal == CmpInst::ICMP_EQ) 770 SrcPred = CmpInst::getInversePredicate(SrcPred); 771 772 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) 773 ? Intrinsic::amdgcn_fcmp 774 : Intrinsic::amdgcn_icmp; 775 776 Type *Ty = SrcLHS->getType(); 777 if (auto *CmpType = dyn_cast<IntegerType>(Ty)) { 778 // Promote to next legal integer type. 779 unsigned Width = CmpType->getBitWidth(); 780 unsigned NewWidth = Width; 781 782 // Don't do anything for i1 comparisons. 783 if (Width == 1) 784 break; 785 786 if (Width <= 16) 787 NewWidth = 16; 788 else if (Width <= 32) 789 NewWidth = 32; 790 else if (Width <= 64) 791 NewWidth = 64; 792 else if (Width > 64) 793 break; // Can't handle this. 794 795 if (Width != NewWidth) { 796 IntegerType *CmpTy = IC.Builder.getIntNTy(NewWidth); 797 if (CmpInst::isSigned(SrcPred)) { 798 SrcLHS = IC.Builder.CreateSExt(SrcLHS, CmpTy); 799 SrcRHS = IC.Builder.CreateSExt(SrcRHS, CmpTy); 800 } else { 801 SrcLHS = IC.Builder.CreateZExt(SrcLHS, CmpTy); 802 SrcRHS = IC.Builder.CreateZExt(SrcRHS, CmpTy); 803 } 804 } 805 } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy()) 806 break; 807 808 Function *NewF = Intrinsic::getDeclaration( 809 II.getModule(), NewIID, {II.getType(), SrcLHS->getType()}); 810 Value *Args[] = {SrcLHS, SrcRHS, 811 ConstantInt::get(CC->getType(), SrcPred)}; 812 CallInst *NewCall = IC.Builder.CreateCall(NewF, Args); 813 NewCall->takeName(&II); 814 return IC.replaceInstUsesWith(II, NewCall); 815 } 816 817 break; 818 } 819 case Intrinsic::amdgcn_ballot: { 820 if (auto *Src = dyn_cast<ConstantInt>(II.getArgOperand(0))) { 821 if (Src->isZero()) { 822 // amdgcn.ballot(i1 0) is zero. 823 return IC.replaceInstUsesWith(II, Constant::getNullValue(II.getType())); 824 } 825 826 if (Src->isOne()) { 827 // amdgcn.ballot(i1 1) is exec. 828 const char *RegName = "exec"; 829 if (II.getType()->isIntegerTy(32)) 830 RegName = "exec_lo"; 831 else if (!II.getType()->isIntegerTy(64)) 832 break; 833 834 Function *NewF = Intrinsic::getDeclaration( 835 II.getModule(), Intrinsic::read_register, II.getType()); 836 Metadata *MDArgs[] = {MDString::get(II.getContext(), RegName)}; 837 MDNode *MD = MDNode::get(II.getContext(), MDArgs); 838 Value *Args[] = {MetadataAsValue::get(II.getContext(), MD)}; 839 CallInst *NewCall = IC.Builder.CreateCall(NewF, Args); 840 NewCall->addFnAttr(Attribute::Convergent); 841 NewCall->takeName(&II); 842 return IC.replaceInstUsesWith(II, NewCall); 843 } 844 } 845 break; 846 } 847 case Intrinsic::amdgcn_wqm_vote: { 848 // wqm_vote is identity when the argument is constant. 849 if (!isa<Constant>(II.getArgOperand(0))) 850 break; 851 852 return IC.replaceInstUsesWith(II, II.getArgOperand(0)); 853 } 854 case Intrinsic::amdgcn_kill: { 855 const ConstantInt *C = dyn_cast<ConstantInt>(II.getArgOperand(0)); 856 if (!C || !C->getZExtValue()) 857 break; 858 859 // amdgcn.kill(i1 1) is a no-op 860 return IC.eraseInstFromFunction(II); 861 } 862 case Intrinsic::amdgcn_update_dpp: { 863 Value *Old = II.getArgOperand(0); 864 865 auto *BC = cast<ConstantInt>(II.getArgOperand(5)); 866 auto *RM = cast<ConstantInt>(II.getArgOperand(3)); 867 auto *BM = cast<ConstantInt>(II.getArgOperand(4)); 868 if (BC->isZeroValue() || RM->getZExtValue() != 0xF || 869 BM->getZExtValue() != 0xF || isa<UndefValue>(Old)) 870 break; 871 872 // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value. 873 return IC.replaceOperand(II, 0, UndefValue::get(Old->getType())); 874 } 875 case Intrinsic::amdgcn_permlane16: 876 case Intrinsic::amdgcn_permlanex16: { 877 // Discard vdst_in if it's not going to be read. 878 Value *VDstIn = II.getArgOperand(0); 879 if (isa<UndefValue>(VDstIn)) 880 break; 881 882 ConstantInt *FetchInvalid = cast<ConstantInt>(II.getArgOperand(4)); 883 ConstantInt *BoundCtrl = cast<ConstantInt>(II.getArgOperand(5)); 884 if (!FetchInvalid->getZExtValue() && !BoundCtrl->getZExtValue()) 885 break; 886 887 return IC.replaceOperand(II, 0, UndefValue::get(VDstIn->getType())); 888 } 889 case Intrinsic::amdgcn_permlane64: 890 // A constant value is trivially uniform. 891 if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) { 892 return IC.replaceInstUsesWith(II, C); 893 } 894 break; 895 case Intrinsic::amdgcn_readfirstlane: 896 case Intrinsic::amdgcn_readlane: { 897 // A constant value is trivially uniform. 898 if (Constant *C = dyn_cast<Constant>(II.getArgOperand(0))) { 899 return IC.replaceInstUsesWith(II, C); 900 } 901 902 // The rest of these may not be safe if the exec may not be the same between 903 // the def and use. 904 Value *Src = II.getArgOperand(0); 905 Instruction *SrcInst = dyn_cast<Instruction>(Src); 906 if (SrcInst && SrcInst->getParent() != II.getParent()) 907 break; 908 909 // readfirstlane (readfirstlane x) -> readfirstlane x 910 // readlane (readfirstlane x), y -> readfirstlane x 911 if (match(Src, 912 PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readfirstlane>())) { 913 return IC.replaceInstUsesWith(II, Src); 914 } 915 916 if (IID == Intrinsic::amdgcn_readfirstlane) { 917 // readfirstlane (readlane x, y) -> readlane x, y 918 if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>())) { 919 return IC.replaceInstUsesWith(II, Src); 920 } 921 } else { 922 // readlane (readlane x, y), y -> readlane x, y 923 if (match(Src, PatternMatch::m_Intrinsic<Intrinsic::amdgcn_readlane>( 924 PatternMatch::m_Value(), 925 PatternMatch::m_Specific(II.getArgOperand(1))))) { 926 return IC.replaceInstUsesWith(II, Src); 927 } 928 } 929 930 break; 931 } 932 case Intrinsic::amdgcn_ldexp: { 933 // FIXME: This doesn't introduce new instructions and belongs in 934 // InstructionSimplify. 935 Type *Ty = II.getType(); 936 Value *Op0 = II.getArgOperand(0); 937 Value *Op1 = II.getArgOperand(1); 938 939 // Folding undef to qnan is safe regardless of the FP mode. 940 if (isa<UndefValue>(Op0)) { 941 auto *QNaN = ConstantFP::get(Ty, APFloat::getQNaN(Ty->getFltSemantics())); 942 return IC.replaceInstUsesWith(II, QNaN); 943 } 944 945 const APFloat *C = nullptr; 946 match(Op0, PatternMatch::m_APFloat(C)); 947 948 // FIXME: Should flush denorms depending on FP mode, but that's ignored 949 // everywhere else. 950 // 951 // These cases should be safe, even with strictfp. 952 // ldexp(0.0, x) -> 0.0 953 // ldexp(-0.0, x) -> -0.0 954 // ldexp(inf, x) -> inf 955 // ldexp(-inf, x) -> -inf 956 if (C && (C->isZero() || C->isInfinity())) { 957 return IC.replaceInstUsesWith(II, Op0); 958 } 959 960 // With strictfp, be more careful about possibly needing to flush denormals 961 // or not, and snan behavior depends on ieee_mode. 962 if (II.isStrictFP()) 963 break; 964 965 if (C && C->isNaN()) 966 return IC.replaceInstUsesWith(II, ConstantFP::get(Ty, C->makeQuiet())); 967 968 // ldexp(x, 0) -> x 969 // ldexp(x, undef) -> x 970 if (isa<UndefValue>(Op1) || match(Op1, PatternMatch::m_ZeroInt())) { 971 return IC.replaceInstUsesWith(II, Op0); 972 } 973 974 break; 975 } 976 case Intrinsic::amdgcn_fmul_legacy: { 977 Value *Op0 = II.getArgOperand(0); 978 Value *Op1 = II.getArgOperand(1); 979 980 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or 981 // infinity, gives +0.0. 982 // TODO: Move to InstSimplify? 983 if (match(Op0, PatternMatch::m_AnyZeroFP()) || 984 match(Op1, PatternMatch::m_AnyZeroFP())) 985 return IC.replaceInstUsesWith(II, ConstantFP::getZero(II.getType())); 986 987 // If we can prove we don't have one of the special cases then we can use a 988 // normal fmul instruction instead. 989 if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) { 990 auto *FMul = IC.Builder.CreateFMulFMF(Op0, Op1, &II); 991 FMul->takeName(&II); 992 return IC.replaceInstUsesWith(II, FMul); 993 } 994 break; 995 } 996 case Intrinsic::amdgcn_fma_legacy: { 997 Value *Op0 = II.getArgOperand(0); 998 Value *Op1 = II.getArgOperand(1); 999 Value *Op2 = II.getArgOperand(2); 1000 1001 // The legacy behaviour is that multiplying +/-0.0 by anything, even NaN or 1002 // infinity, gives +0.0. 1003 // TODO: Move to InstSimplify? 1004 if (match(Op0, PatternMatch::m_AnyZeroFP()) || 1005 match(Op1, PatternMatch::m_AnyZeroFP())) { 1006 // It's tempting to just return Op2 here, but that would give the wrong 1007 // result if Op2 was -0.0. 1008 auto *Zero = ConstantFP::getZero(II.getType()); 1009 auto *FAdd = IC.Builder.CreateFAddFMF(Zero, Op2, &II); 1010 FAdd->takeName(&II); 1011 return IC.replaceInstUsesWith(II, FAdd); 1012 } 1013 1014 // If we can prove we don't have one of the special cases then we can use a 1015 // normal fma instead. 1016 if (canSimplifyLegacyMulToMul(II, Op0, Op1, IC)) { 1017 II.setCalledOperand(Intrinsic::getDeclaration( 1018 II.getModule(), Intrinsic::fma, II.getType())); 1019 return &II; 1020 } 1021 break; 1022 } 1023 case Intrinsic::amdgcn_is_shared: 1024 case Intrinsic::amdgcn_is_private: { 1025 if (isa<UndefValue>(II.getArgOperand(0))) 1026 return IC.replaceInstUsesWith(II, UndefValue::get(II.getType())); 1027 1028 if (isa<ConstantPointerNull>(II.getArgOperand(0))) 1029 return IC.replaceInstUsesWith(II, ConstantInt::getFalse(II.getType())); 1030 break; 1031 } 1032 default: { 1033 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 1034 AMDGPU::getImageDimIntrinsicInfo(II.getIntrinsicID())) { 1035 return simplifyAMDGCNImageIntrinsic(ST, ImageDimIntr, II, IC); 1036 } 1037 } 1038 } 1039 return std::nullopt; 1040 } 1041 1042 /// Implement SimplifyDemandedVectorElts for amdgcn buffer and image intrinsics. 1043 /// 1044 /// Note: This only supports non-TFE/LWE image intrinsic calls; those have 1045 /// struct returns. 1046 static Value *simplifyAMDGCNMemoryIntrinsicDemanded(InstCombiner &IC, 1047 IntrinsicInst &II, 1048 APInt DemandedElts, 1049 int DMaskIdx = -1) { 1050 1051 auto *IIVTy = cast<FixedVectorType>(II.getType()); 1052 unsigned VWidth = IIVTy->getNumElements(); 1053 if (VWidth == 1) 1054 return nullptr; 1055 Type *EltTy = IIVTy->getElementType(); 1056 1057 IRBuilderBase::InsertPointGuard Guard(IC.Builder); 1058 IC.Builder.SetInsertPoint(&II); 1059 1060 // Assume the arguments are unchanged and later override them, if needed. 1061 SmallVector<Value *, 16> Args(II.args()); 1062 1063 if (DMaskIdx < 0) { 1064 // Buffer case. 1065 1066 const unsigned ActiveBits = DemandedElts.getActiveBits(); 1067 const unsigned UnusedComponentsAtFront = DemandedElts.countr_zero(); 1068 1069 // Start assuming the prefix of elements is demanded, but possibly clear 1070 // some other bits if there are trailing zeros (unused components at front) 1071 // and update offset. 1072 DemandedElts = (1 << ActiveBits) - 1; 1073 1074 if (UnusedComponentsAtFront > 0) { 1075 static const unsigned InvalidOffsetIdx = 0xf; 1076 1077 unsigned OffsetIdx; 1078 switch (II.getIntrinsicID()) { 1079 case Intrinsic::amdgcn_raw_buffer_load: 1080 OffsetIdx = 1; 1081 break; 1082 case Intrinsic::amdgcn_s_buffer_load: 1083 // If resulting type is vec3, there is no point in trimming the 1084 // load with updated offset, as the vec3 would most likely be widened to 1085 // vec4 anyway during lowering. 1086 if (ActiveBits == 4 && UnusedComponentsAtFront == 1) 1087 OffsetIdx = InvalidOffsetIdx; 1088 else 1089 OffsetIdx = 1; 1090 break; 1091 case Intrinsic::amdgcn_struct_buffer_load: 1092 OffsetIdx = 2; 1093 break; 1094 default: 1095 // TODO: handle tbuffer* intrinsics. 1096 OffsetIdx = InvalidOffsetIdx; 1097 break; 1098 } 1099 1100 if (OffsetIdx != InvalidOffsetIdx) { 1101 // Clear demanded bits and update the offset. 1102 DemandedElts &= ~((1 << UnusedComponentsAtFront) - 1); 1103 auto *Offset = Args[OffsetIdx]; 1104 unsigned SingleComponentSizeInBits = 1105 IC.getDataLayout().getTypeSizeInBits(EltTy); 1106 unsigned OffsetAdd = 1107 UnusedComponentsAtFront * SingleComponentSizeInBits / 8; 1108 auto *OffsetAddVal = ConstantInt::get(Offset->getType(), OffsetAdd); 1109 Args[OffsetIdx] = IC.Builder.CreateAdd(Offset, OffsetAddVal); 1110 } 1111 } 1112 } else { 1113 // Image case. 1114 1115 ConstantInt *DMask = cast<ConstantInt>(Args[DMaskIdx]); 1116 unsigned DMaskVal = DMask->getZExtValue() & 0xf; 1117 1118 // Mask off values that are undefined because the dmask doesn't cover them 1119 DemandedElts &= (1 << llvm::popcount(DMaskVal)) - 1; 1120 1121 unsigned NewDMaskVal = 0; 1122 unsigned OrigLoadIdx = 0; 1123 for (unsigned SrcIdx = 0; SrcIdx < 4; ++SrcIdx) { 1124 const unsigned Bit = 1 << SrcIdx; 1125 if (!!(DMaskVal & Bit)) { 1126 if (!!DemandedElts[OrigLoadIdx]) 1127 NewDMaskVal |= Bit; 1128 OrigLoadIdx++; 1129 } 1130 } 1131 1132 if (DMaskVal != NewDMaskVal) 1133 Args[DMaskIdx] = ConstantInt::get(DMask->getType(), NewDMaskVal); 1134 } 1135 1136 unsigned NewNumElts = DemandedElts.popcount(); 1137 if (!NewNumElts) 1138 return UndefValue::get(IIVTy); 1139 1140 if (NewNumElts >= VWidth && DemandedElts.isMask()) { 1141 if (DMaskIdx >= 0) 1142 II.setArgOperand(DMaskIdx, Args[DMaskIdx]); 1143 return nullptr; 1144 } 1145 1146 // Validate function argument and return types, extracting overloaded types 1147 // along the way. 1148 SmallVector<Type *, 6> OverloadTys; 1149 if (!Intrinsic::getIntrinsicSignature(II.getCalledFunction(), OverloadTys)) 1150 return nullptr; 1151 1152 Type *NewTy = 1153 (NewNumElts == 1) ? EltTy : FixedVectorType::get(EltTy, NewNumElts); 1154 OverloadTys[0] = NewTy; 1155 1156 Function *NewIntrin = Intrinsic::getDeclaration( 1157 II.getModule(), II.getIntrinsicID(), OverloadTys); 1158 CallInst *NewCall = IC.Builder.CreateCall(NewIntrin, Args); 1159 NewCall->takeName(&II); 1160 NewCall->copyMetadata(II); 1161 1162 if (NewNumElts == 1) { 1163 return IC.Builder.CreateInsertElement(UndefValue::get(IIVTy), NewCall, 1164 DemandedElts.countr_zero()); 1165 } 1166 1167 SmallVector<int, 8> EltMask; 1168 unsigned NewLoadIdx = 0; 1169 for (unsigned OrigLoadIdx = 0; OrigLoadIdx < VWidth; ++OrigLoadIdx) { 1170 if (!!DemandedElts[OrigLoadIdx]) 1171 EltMask.push_back(NewLoadIdx++); 1172 else 1173 EltMask.push_back(NewNumElts); 1174 } 1175 1176 Value *Shuffle = IC.Builder.CreateShuffleVector(NewCall, EltMask); 1177 1178 return Shuffle; 1179 } 1180 1181 std::optional<Value *> GCNTTIImpl::simplifyDemandedVectorEltsIntrinsic( 1182 InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, 1183 APInt &UndefElts2, APInt &UndefElts3, 1184 std::function<void(Instruction *, unsigned, APInt, APInt &)> 1185 SimplifyAndSetOp) const { 1186 switch (II.getIntrinsicID()) { 1187 case Intrinsic::amdgcn_buffer_load: 1188 case Intrinsic::amdgcn_buffer_load_format: 1189 case Intrinsic::amdgcn_raw_buffer_load: 1190 case Intrinsic::amdgcn_raw_buffer_load_format: 1191 case Intrinsic::amdgcn_raw_tbuffer_load: 1192 case Intrinsic::amdgcn_s_buffer_load: 1193 case Intrinsic::amdgcn_struct_buffer_load: 1194 case Intrinsic::amdgcn_struct_buffer_load_format: 1195 case Intrinsic::amdgcn_struct_tbuffer_load: 1196 case Intrinsic::amdgcn_tbuffer_load: 1197 return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts); 1198 default: { 1199 if (getAMDGPUImageDMaskIntrinsic(II.getIntrinsicID())) { 1200 return simplifyAMDGCNMemoryIntrinsicDemanded(IC, II, DemandedElts, 0); 1201 } 1202 break; 1203 } 1204 } 1205 return std::nullopt; 1206 } 1207