1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI 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 "AMDGPUTargetTransformInfo.h" 18 #include "AMDGPUSubtarget.h" 19 #include "Utils/AMDGPUBaseInfo.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/CodeGen/ISDOpcodes.h" 25 #include "llvm/CodeGen/ValueTypes.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CallingConv.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/MC/SubtargetFeature.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MachineValueType.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <limits> 51 #include <utility> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "AMDGPUtti" 56 57 static cl::opt<unsigned> UnrollThresholdPrivate( 58 "amdgpu-unroll-threshold-private", 59 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 60 cl::init(2700), cl::Hidden); 61 62 static cl::opt<unsigned> UnrollThresholdLocal( 63 "amdgpu-unroll-threshold-local", 64 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 65 cl::init(1000), cl::Hidden); 66 67 static cl::opt<unsigned> UnrollThresholdIf( 68 "amdgpu-unroll-threshold-if", 69 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 70 cl::init(150), cl::Hidden); 71 72 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 73 unsigned Depth = 0) { 74 const Instruction *I = dyn_cast<Instruction>(Cond); 75 if (!I) 76 return false; 77 78 for (const Value *V : I->operand_values()) { 79 if (!L->contains(I)) 80 continue; 81 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 82 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 83 return SubLoop->contains(PHI); })) 84 return true; 85 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 86 return true; 87 } 88 return false; 89 } 90 91 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 92 TTI::UnrollingPreferences &UP) { 93 const Function &F = *L->getHeader()->getParent(); 94 UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300); 95 UP.MaxCount = std::numeric_limits<unsigned>::max(); 96 UP.Partial = true; 97 98 // TODO: Do we want runtime unrolling? 99 100 // Maximum alloca size than can fit registers. Reserve 16 registers. 101 const unsigned MaxAlloca = (256 - 16) * 4; 102 unsigned ThresholdPrivate = UnrollThresholdPrivate; 103 unsigned ThresholdLocal = UnrollThresholdLocal; 104 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 105 for (const BasicBlock *BB : L->getBlocks()) { 106 const DataLayout &DL = BB->getModule()->getDataLayout(); 107 unsigned LocalGEPsSeen = 0; 108 109 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 110 return SubLoop->contains(BB); })) 111 continue; // Block belongs to an inner loop. 112 113 for (const Instruction &I : *BB) { 114 // Unroll a loop which contains an "if" statement whose condition 115 // defined by a PHI belonging to the loop. This may help to eliminate 116 // if region and potentially even PHI itself, saving on both divergence 117 // and registers used for the PHI. 118 // Add a small bonus for each of such "if" statements. 119 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 120 if (UP.Threshold < MaxBoost && Br->isConditional()) { 121 BasicBlock *Succ0 = Br->getSuccessor(0); 122 BasicBlock *Succ1 = Br->getSuccessor(1); 123 if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) || 124 (L->contains(Succ1) && L->isLoopExiting(Succ1))) 125 continue; 126 if (dependsOnLocalPhi(L, Br->getCondition())) { 127 UP.Threshold += UnrollThresholdIf; 128 LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 129 << " for loop:\n" 130 << *L << " due to " << *Br << '\n'); 131 if (UP.Threshold >= MaxBoost) 132 return; 133 } 134 } 135 continue; 136 } 137 138 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 139 if (!GEP) 140 continue; 141 142 unsigned AS = GEP->getAddressSpace(); 143 unsigned Threshold = 0; 144 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 145 Threshold = ThresholdPrivate; 146 else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) 147 Threshold = ThresholdLocal; 148 else 149 continue; 150 151 if (UP.Threshold >= Threshold) 152 continue; 153 154 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 155 const Value *Ptr = GEP->getPointerOperand(); 156 const AllocaInst *Alloca = 157 dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL)); 158 if (!Alloca || !Alloca->isStaticAlloca()) 159 continue; 160 Type *Ty = Alloca->getAllocatedType(); 161 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 162 if (AllocaSize > MaxAlloca) 163 continue; 164 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 165 AS == AMDGPUAS::REGION_ADDRESS) { 166 LocalGEPsSeen++; 167 // Inhibit unroll for local memory if we have seen addressing not to 168 // a variable, most likely we will be unable to combine it. 169 // Do not unroll too deep inner loops for local memory to give a chance 170 // to unroll an outer loop for a more important reason. 171 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 172 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 173 !isa<Argument>(GEP->getPointerOperand()))) 174 continue; 175 } 176 177 // Check if GEP depends on a value defined by this loop itself. 178 bool HasLoopDef = false; 179 for (const Value *Op : GEP->operands()) { 180 const Instruction *Inst = dyn_cast<Instruction>(Op); 181 if (!Inst || L->isLoopInvariant(Op)) 182 continue; 183 184 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 185 return SubLoop->contains(Inst); })) 186 continue; 187 HasLoopDef = true; 188 break; 189 } 190 if (!HasLoopDef) 191 continue; 192 193 // We want to do whatever we can to limit the number of alloca 194 // instructions that make it through to the code generator. allocas 195 // require us to use indirect addressing, which is slow and prone to 196 // compiler bugs. If this loop does an address calculation on an 197 // alloca ptr, then we want to use a higher than normal loop unroll 198 // threshold. This will give SROA a better chance to eliminate these 199 // allocas. 200 // 201 // We also want to have more unrolling for local memory to let ds 202 // instructions with different offsets combine. 203 // 204 // Don't use the maximum allowed value here as it will make some 205 // programs way too big. 206 UP.Threshold = Threshold; 207 LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold 208 << " for loop:\n" 209 << *L << " due to " << *GEP << '\n'); 210 if (UP.Threshold >= MaxBoost) 211 return; 212 } 213 } 214 } 215 216 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 217 // The concept of vector registers doesn't really exist. Some packed vector 218 // operations operate on the normal 32-bit registers. 219 return 256; 220 } 221 222 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const { 223 // This is really the number of registers to fill when vectorizing / 224 // interleaving loops, so we lie to avoid trying to use all registers. 225 return getHardwareNumberOfRegisters(Vec) >> 3; 226 } 227 228 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const { 229 return 32; 230 } 231 232 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 233 return 32; 234 } 235 236 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 237 unsigned ChainSizeInBytes, 238 VectorType *VecTy) const { 239 unsigned VecRegBitWidth = VF * LoadSize; 240 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 241 // TODO: Support element-size less than 32bit? 242 return 128 / LoadSize; 243 244 return VF; 245 } 246 247 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 248 unsigned ChainSizeInBytes, 249 VectorType *VecTy) const { 250 unsigned VecRegBitWidth = VF * StoreSize; 251 if (VecRegBitWidth > 128) 252 return 128 / StoreSize; 253 254 return VF; 255 } 256 257 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 258 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 259 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 260 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 261 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 262 return 512; 263 } 264 265 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS || 266 AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 267 AddrSpace == AMDGPUAS::REGION_ADDRESS) 268 return 128; 269 270 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 271 return 8 * ST->getMaxPrivateElementSize(); 272 273 llvm_unreachable("unhandled address space"); 274 } 275 276 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 277 unsigned Alignment, 278 unsigned AddrSpace) const { 279 // We allow vectorization of flat stores, even though we may need to decompose 280 // them later if they may access private memory. We don't have enough context 281 // here, and legalization can handle it. 282 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 283 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 284 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 285 } 286 return true; 287 } 288 289 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 290 unsigned Alignment, 291 unsigned AddrSpace) const { 292 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 293 } 294 295 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 296 unsigned Alignment, 297 unsigned AddrSpace) const { 298 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 299 } 300 301 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 302 // Disable unrolling if the loop is not vectorized. 303 // TODO: Enable this again. 304 if (VF == 1) 305 return 1; 306 307 return 8; 308 } 309 310 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 311 MemIntrinsicInfo &Info) const { 312 switch (Inst->getIntrinsicID()) { 313 case Intrinsic::amdgcn_atomic_inc: 314 case Intrinsic::amdgcn_atomic_dec: 315 case Intrinsic::amdgcn_ds_ordered_add: 316 case Intrinsic::amdgcn_ds_ordered_swap: 317 case Intrinsic::amdgcn_ds_fadd: 318 case Intrinsic::amdgcn_ds_fmin: 319 case Intrinsic::amdgcn_ds_fmax: { 320 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 321 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 322 if (!Ordering || !Volatile) 323 return false; // Invalid. 324 325 unsigned OrderingVal = Ordering->getZExtValue(); 326 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 327 return false; 328 329 Info.PtrVal = Inst->getArgOperand(0); 330 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 331 Info.ReadMem = true; 332 Info.WriteMem = true; 333 Info.IsVolatile = !Volatile->isNullValue(); 334 return true; 335 } 336 default: 337 return false; 338 } 339 } 340 341 int GCNTTIImpl::getArithmeticInstrCost( 342 unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, 343 TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, 344 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args ) { 345 EVT OrigTy = TLI->getValueType(DL, Ty); 346 if (!OrigTy.isSimple()) { 347 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 348 Opd1PropInfo, Opd2PropInfo); 349 } 350 351 // Legalize the type. 352 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 353 int ISD = TLI->InstructionOpcodeToISD(Opcode); 354 355 // Because we don't have any legal vector operations, but the legal types, we 356 // need to account for split vectors. 357 unsigned NElts = LT.second.isVector() ? 358 LT.second.getVectorNumElements() : 1; 359 360 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 361 362 switch (ISD) { 363 case ISD::SHL: 364 case ISD::SRL: 365 case ISD::SRA: 366 if (SLT == MVT::i64) 367 return get64BitInstrCost() * LT.first * NElts; 368 369 // i32 370 return getFullRateInstrCost() * LT.first * NElts; 371 case ISD::ADD: 372 case ISD::SUB: 373 case ISD::AND: 374 case ISD::OR: 375 case ISD::XOR: 376 if (SLT == MVT::i64){ 377 // and, or and xor are typically split into 2 VALU instructions. 378 return 2 * getFullRateInstrCost() * LT.first * NElts; 379 } 380 381 return LT.first * NElts * getFullRateInstrCost(); 382 case ISD::MUL: { 383 const int QuarterRateCost = getQuarterRateInstrCost(); 384 if (SLT == MVT::i64) { 385 const int FullRateCost = getFullRateInstrCost(); 386 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 387 } 388 389 // i32 390 return QuarterRateCost * NElts * LT.first; 391 } 392 case ISD::FADD: 393 case ISD::FSUB: 394 case ISD::FMUL: 395 if (SLT == MVT::f64) 396 return LT.first * NElts * get64BitInstrCost(); 397 398 if (SLT == MVT::f32 || SLT == MVT::f16) 399 return LT.first * NElts * getFullRateInstrCost(); 400 break; 401 case ISD::FDIV: 402 case ISD::FREM: 403 // FIXME: frem should be handled separately. The fdiv in it is most of it, 404 // but the current lowering is also not entirely correct. 405 if (SLT == MVT::f64) { 406 int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost(); 407 // Add cost of workaround. 408 if (!ST->hasUsableDivScaleConditionOutput()) 409 Cost += 3 * getFullRateInstrCost(); 410 411 return LT.first * Cost * NElts; 412 } 413 414 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 415 // TODO: This is more complicated, unsafe flags etc. 416 if ((SLT == MVT::f32 && !HasFP32Denormals) || 417 (SLT == MVT::f16 && ST->has16BitInsts())) { 418 return LT.first * getQuarterRateInstrCost() * NElts; 419 } 420 } 421 422 if (SLT == MVT::f16 && ST->has16BitInsts()) { 423 // 2 x v_cvt_f32_f16 424 // f32 rcp 425 // f32 fmul 426 // v_cvt_f16_f32 427 // f16 div_fixup 428 int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(); 429 return LT.first * Cost * NElts; 430 } 431 432 if (SLT == MVT::f32 || SLT == MVT::f16) { 433 int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost(); 434 435 if (!HasFP32Denormals) { 436 // FP mode switches. 437 Cost += 2 * getFullRateInstrCost(); 438 } 439 440 return LT.first * NElts * Cost; 441 } 442 break; 443 default: 444 break; 445 } 446 447 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 448 Opd1PropInfo, Opd2PropInfo); 449 } 450 451 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode) { 452 // XXX - For some reason this isn't called for switch. 453 switch (Opcode) { 454 case Instruction::Br: 455 case Instruction::Ret: 456 return 10; 457 default: 458 return BaseT::getCFInstrCost(Opcode); 459 } 460 } 461 462 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, Type *Ty, 463 bool IsPairwise) { 464 EVT OrigTy = TLI->getValueType(DL, Ty); 465 466 // Computes cost on targets that have packed math instructions(which support 467 // 16-bit types only). 468 if (IsPairwise || 469 !ST->hasVOP3PInsts() || 470 OrigTy.getScalarSizeInBits() != 16) 471 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise); 472 473 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 474 return LT.first * getFullRateInstrCost(); 475 } 476 477 int GCNTTIImpl::getMinMaxReductionCost(Type *Ty, Type *CondTy, 478 bool IsPairwise, 479 bool IsUnsigned) { 480 EVT OrigTy = TLI->getValueType(DL, Ty); 481 482 // Computes cost on targets that have packed math instructions(which support 483 // 16-bit types only). 484 if (IsPairwise || 485 !ST->hasVOP3PInsts() || 486 OrigTy.getScalarSizeInBits() != 16) 487 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned); 488 489 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 490 return LT.first * getHalfRateInstrCost(); 491 } 492 493 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 494 unsigned Index) { 495 switch (Opcode) { 496 case Instruction::ExtractElement: 497 case Instruction::InsertElement: { 498 unsigned EltSize 499 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 500 if (EltSize < 32) { 501 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 502 return 0; 503 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 504 } 505 506 // Extracts are just reads of a subregister, so are free. Inserts are 507 // considered free because we don't want to have any cost for scalarizing 508 // operations, and we don't have to copy into a different register class. 509 510 // Dynamic indexing isn't free and is best avoided. 511 return Index == ~0u ? 2 : 0; 512 } 513 default: 514 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 515 } 516 } 517 518 519 520 static bool isArgPassedInSGPR(const Argument *A) { 521 const Function *F = A->getParent(); 522 523 // Arguments to compute shaders are never a source of divergence. 524 CallingConv::ID CC = F->getCallingConv(); 525 switch (CC) { 526 case CallingConv::AMDGPU_KERNEL: 527 case CallingConv::SPIR_KERNEL: 528 return true; 529 case CallingConv::AMDGPU_VS: 530 case CallingConv::AMDGPU_LS: 531 case CallingConv::AMDGPU_HS: 532 case CallingConv::AMDGPU_ES: 533 case CallingConv::AMDGPU_GS: 534 case CallingConv::AMDGPU_PS: 535 case CallingConv::AMDGPU_CS: 536 // For non-compute shaders, SGPR inputs are marked with either inreg or byval. 537 // Everything else is in VGPRs. 538 return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) || 539 F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal); 540 default: 541 // TODO: Should calls support inreg for SGPR inputs? 542 return false; 543 } 544 } 545 546 /// \returns true if the result of the value could potentially be 547 /// different across workitems in a wavefront. 548 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 549 if (const Argument *A = dyn_cast<Argument>(V)) 550 return !isArgPassedInSGPR(A); 551 552 // Loads from the private and flat address spaces are divergent, because 553 // threads can execute the load instruction with the same inputs and get 554 // different results. 555 // 556 // All other loads are not divergent, because if threads issue loads with the 557 // same arguments, they will always get the same result. 558 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 559 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 560 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 561 562 // Atomics are divergent because they are executed sequentially: when an 563 // atomic operation refers to the same address in each thread, then each 564 // thread after the first sees the value written by the previous thread as 565 // original value. 566 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 567 return true; 568 569 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 570 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 571 572 // Assume all function calls are a source of divergence. 573 if (isa<CallInst>(V) || isa<InvokeInst>(V)) 574 return true; 575 576 return false; 577 } 578 579 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 580 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 581 switch (Intrinsic->getIntrinsicID()) { 582 default: 583 return false; 584 case Intrinsic::amdgcn_readfirstlane: 585 case Intrinsic::amdgcn_readlane: 586 case Intrinsic::amdgcn_icmp: 587 case Intrinsic::amdgcn_fcmp: 588 return true; 589 } 590 } 591 return false; 592 } 593 594 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 595 Intrinsic::ID IID) const { 596 switch (IID) { 597 case Intrinsic::amdgcn_atomic_inc: 598 case Intrinsic::amdgcn_atomic_dec: 599 case Intrinsic::amdgcn_ds_fadd: 600 case Intrinsic::amdgcn_ds_fmin: 601 case Intrinsic::amdgcn_ds_fmax: 602 case Intrinsic::amdgcn_is_shared: 603 case Intrinsic::amdgcn_is_private: 604 OpIndexes.push_back(0); 605 return true; 606 default: 607 return false; 608 } 609 } 610 611 bool GCNTTIImpl::rewriteIntrinsicWithAddressSpace( 612 IntrinsicInst *II, Value *OldV, Value *NewV) const { 613 auto IntrID = II->getIntrinsicID(); 614 switch (IntrID) { 615 case Intrinsic::amdgcn_atomic_inc: 616 case Intrinsic::amdgcn_atomic_dec: 617 case Intrinsic::amdgcn_ds_fadd: 618 case Intrinsic::amdgcn_ds_fmin: 619 case Intrinsic::amdgcn_ds_fmax: { 620 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 621 if (!IsVolatile->isZero()) 622 return false; 623 Module *M = II->getParent()->getParent()->getParent(); 624 Type *DestTy = II->getType(); 625 Type *SrcTy = NewV->getType(); 626 Function *NewDecl = 627 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 628 II->setArgOperand(0, NewV); 629 II->setCalledFunction(NewDecl); 630 return true; 631 } 632 case Intrinsic::amdgcn_is_shared: 633 case Intrinsic::amdgcn_is_private: { 634 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 635 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 636 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 637 LLVMContext &Ctx = NewV->getType()->getContext(); 638 ConstantInt *NewVal = (TrueAS == NewAS) ? 639 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 640 II->replaceAllUsesWith(NewVal); 641 II->eraseFromParent(); 642 return true; 643 } 644 default: 645 return false; 646 } 647 } 648 649 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, 650 Type *SubTp) { 651 if (ST->hasVOP3PInsts()) { 652 VectorType *VT = cast<VectorType>(Tp); 653 if (VT->getNumElements() == 2 && 654 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 655 // With op_sel VOP3P instructions freely can access the low half or high 656 // half of a register, so any swizzle is free. 657 658 switch (Kind) { 659 case TTI::SK_Broadcast: 660 case TTI::SK_Reverse: 661 case TTI::SK_PermuteSingleSrc: 662 return 0; 663 default: 664 break; 665 } 666 } 667 } 668 669 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 670 } 671 672 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 673 const Function *Callee) const { 674 const TargetMachine &TM = getTLI()->getTargetMachine(); 675 const GCNSubtarget *CallerST 676 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 677 const GCNSubtarget *CalleeST 678 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 679 680 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 681 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 682 683 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 684 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 685 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 686 return false; 687 688 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 689 // no way to support merge for backend defined attributes. 690 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller, *CallerST); 691 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee, *CalleeST); 692 return CallerMode.isInlineCompatible(CalleeMode); 693 } 694 695 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 696 TTI::UnrollingPreferences &UP) { 697 CommonTTI.getUnrollingPreferences(L, SE, UP); 698 } 699 700 unsigned GCNTTIImpl::getUserCost(const User *U, 701 ArrayRef<const Value *> Operands) { 702 const Instruction *I = dyn_cast<Instruction>(U); 703 if (!I) 704 return BaseT::getUserCost(U, Operands); 705 706 // Estimate different operations to be optimized out 707 switch (I->getOpcode()) { 708 case Instruction::ExtractElement: { 709 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 710 unsigned Idx = -1; 711 if (CI) 712 Idx = CI->getZExtValue(); 713 return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx); 714 } 715 case Instruction::InsertElement: { 716 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 717 unsigned Idx = -1; 718 if (CI) 719 Idx = CI->getZExtValue(); 720 return getVectorInstrCost(I->getOpcode(), I->getType(), Idx); 721 } 722 case Instruction::Call: { 723 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) { 724 SmallVector<Value *, 4> Args(II->arg_operands()); 725 FastMathFlags FMF; 726 if (auto *FPMO = dyn_cast<FPMathOperator>(II)) 727 FMF = FPMO->getFastMathFlags(); 728 return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(), Args, 729 FMF); 730 } else { 731 return BaseT::getUserCost(U, Operands); 732 } 733 } 734 case Instruction::ShuffleVector: { 735 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); 736 Type *Ty = Shuffle->getType(); 737 Type *SrcTy = Shuffle->getOperand(0)->getType(); 738 739 // TODO: Identify and add costs for insert subvector, etc. 740 int SubIndex; 741 if (Shuffle->isExtractSubvectorMask(SubIndex)) 742 return getShuffleCost(TTI::SK_ExtractSubvector, SrcTy, SubIndex, Ty); 743 744 if (Shuffle->changesLength()) 745 return BaseT::getUserCost(U, Operands); 746 747 if (Shuffle->isIdentity()) 748 return 0; 749 750 if (Shuffle->isReverse()) 751 return getShuffleCost(TTI::SK_Reverse, Ty, 0, nullptr); 752 753 if (Shuffle->isSelect()) 754 return getShuffleCost(TTI::SK_Select, Ty, 0, nullptr); 755 756 if (Shuffle->isTranspose()) 757 return getShuffleCost(TTI::SK_Transpose, Ty, 0, nullptr); 758 759 if (Shuffle->isZeroEltSplat()) 760 return getShuffleCost(TTI::SK_Broadcast, Ty, 0, nullptr); 761 762 if (Shuffle->isSingleSource()) 763 return getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, 0, nullptr); 764 765 return getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, 0, nullptr); 766 } 767 case Instruction::ZExt: 768 case Instruction::SExt: 769 case Instruction::FPToUI: 770 case Instruction::FPToSI: 771 case Instruction::FPExt: 772 case Instruction::PtrToInt: 773 case Instruction::IntToPtr: 774 case Instruction::SIToFP: 775 case Instruction::UIToFP: 776 case Instruction::Trunc: 777 case Instruction::FPTrunc: 778 case Instruction::BitCast: 779 case Instruction::AddrSpaceCast: { 780 return getCastInstrCost(I->getOpcode(), I->getType(), 781 I->getOperand(0)->getType(), I); 782 } 783 case Instruction::Add: 784 case Instruction::FAdd: 785 case Instruction::Sub: 786 case Instruction::FSub: 787 case Instruction::Mul: 788 case Instruction::FMul: 789 case Instruction::UDiv: 790 case Instruction::SDiv: 791 case Instruction::FDiv: 792 case Instruction::URem: 793 case Instruction::SRem: 794 case Instruction::FRem: 795 case Instruction::Shl: 796 case Instruction::LShr: 797 case Instruction::AShr: 798 case Instruction::And: 799 case Instruction::Or: 800 case Instruction::Xor: 801 case Instruction::FNeg: { 802 return getArithmeticInstrCost(I->getOpcode(), I->getType(), 803 TTI::OK_AnyValue, TTI::OK_AnyValue, 804 TTI::OP_None, TTI::OP_None, Operands); 805 } 806 default: 807 break; 808 } 809 810 return BaseT::getUserCost(U, Operands); 811 } 812 813 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 814 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 815 } 816 817 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 818 return getHardwareNumberOfRegisters(Vec); 819 } 820 821 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const { 822 return 32; 823 } 824 825 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 826 return 32; 827 } 828 829 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 830 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 831 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 832 return 128; 833 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 834 AddrSpace == AMDGPUAS::REGION_ADDRESS) 835 return 64; 836 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 837 return 32; 838 839 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 840 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 841 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 842 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 843 return 128; 844 llvm_unreachable("unhandled address space"); 845 } 846 847 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 848 unsigned Alignment, 849 unsigned AddrSpace) const { 850 // We allow vectorization of flat stores, even though we may need to decompose 851 // them later if they may access private memory. We don't have enough context 852 // here, and legalization can handle it. 853 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 854 } 855 856 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 857 unsigned Alignment, 858 unsigned AddrSpace) const { 859 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 860 } 861 862 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 863 unsigned Alignment, 864 unsigned AddrSpace) const { 865 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 866 } 867 868 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 869 // Disable unrolling if the loop is not vectorized. 870 // TODO: Enable this again. 871 if (VF == 1) 872 return 1; 873 874 return 8; 875 } 876 877 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode) { 878 // XXX - For some reason this isn't called for switch. 879 switch (Opcode) { 880 case Instruction::Br: 881 case Instruction::Ret: 882 return 10; 883 default: 884 return BaseT::getCFInstrCost(Opcode); 885 } 886 } 887 888 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 889 unsigned Index) { 890 switch (Opcode) { 891 case Instruction::ExtractElement: 892 case Instruction::InsertElement: { 893 unsigned EltSize 894 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 895 if (EltSize < 32) { 896 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 897 } 898 899 // Extracts are just reads of a subregister, so are free. Inserts are 900 // considered free because we don't want to have any cost for scalarizing 901 // operations, and we don't have to copy into a different register class. 902 903 // Dynamic indexing isn't free and is best avoided. 904 return Index == ~0u ? 2 : 0; 905 } 906 default: 907 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 908 } 909 } 910 911 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 912 TTI::UnrollingPreferences &UP) { 913 CommonTTI.getUnrollingPreferences(L, SE, UP); 914 } 915