1 //===-- SystemZTargetTransformInfo.cpp - SystemZ-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 // This file implements a TargetTransformInfo analysis pass specific to the 10 // SystemZ target machine. It uses the target's detailed information to provide 11 // more precise answers to certain TTI queries, while letting the target 12 // independent and default TTI implementations handle the rest. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "SystemZTargetTransformInfo.h" 17 #include "llvm/Analysis/TargetTransformInfo.h" 18 #include "llvm/CodeGen/BasicTTIImpl.h" 19 #include "llvm/CodeGen/CostTable.h" 20 #include "llvm/CodeGen/TargetLowering.h" 21 #include "llvm/IR/IntrinsicInst.h" 22 #include "llvm/Support/Debug.h" 23 using namespace llvm; 24 25 #define DEBUG_TYPE "systemztti" 26 27 //===----------------------------------------------------------------------===// 28 // 29 // SystemZ cost model. 30 // 31 //===----------------------------------------------------------------------===// 32 33 InstructionCost SystemZTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 34 TTI::TargetCostKind CostKind) { 35 assert(Ty->isIntegerTy()); 36 37 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 38 // There is no cost model for constants with a bit size of 0. Return TCC_Free 39 // here, so that constant hoisting will ignore this constant. 40 if (BitSize == 0) 41 return TTI::TCC_Free; 42 // No cost model for operations on integers larger than 64 bit implemented yet. 43 if (BitSize > 64) 44 return TTI::TCC_Free; 45 46 if (Imm == 0) 47 return TTI::TCC_Free; 48 49 if (Imm.getBitWidth() <= 64) { 50 // Constants loaded via lgfi. 51 if (isInt<32>(Imm.getSExtValue())) 52 return TTI::TCC_Basic; 53 // Constants loaded via llilf. 54 if (isUInt<32>(Imm.getZExtValue())) 55 return TTI::TCC_Basic; 56 // Constants loaded via llihf: 57 if ((Imm.getZExtValue() & 0xffffffff) == 0) 58 return TTI::TCC_Basic; 59 60 return 2 * TTI::TCC_Basic; 61 } 62 63 return 4 * TTI::TCC_Basic; 64 } 65 66 InstructionCost SystemZTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 67 const APInt &Imm, Type *Ty, 68 TTI::TargetCostKind CostKind, 69 Instruction *Inst) { 70 assert(Ty->isIntegerTy()); 71 72 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 73 // There is no cost model for constants with a bit size of 0. Return TCC_Free 74 // here, so that constant hoisting will ignore this constant. 75 if (BitSize == 0) 76 return TTI::TCC_Free; 77 // No cost model for operations on integers larger than 64 bit implemented yet. 78 if (BitSize > 64) 79 return TTI::TCC_Free; 80 81 switch (Opcode) { 82 default: 83 return TTI::TCC_Free; 84 case Instruction::GetElementPtr: 85 // Always hoist the base address of a GetElementPtr. This prevents the 86 // creation of new constants for every base constant that gets constant 87 // folded with the offset. 88 if (Idx == 0) 89 return 2 * TTI::TCC_Basic; 90 return TTI::TCC_Free; 91 case Instruction::Store: 92 if (Idx == 0 && Imm.getBitWidth() <= 64) { 93 // Any 8-bit immediate store can by implemented via mvi. 94 if (BitSize == 8) 95 return TTI::TCC_Free; 96 // 16-bit immediate values can be stored via mvhhi/mvhi/mvghi. 97 if (isInt<16>(Imm.getSExtValue())) 98 return TTI::TCC_Free; 99 } 100 break; 101 case Instruction::ICmp: 102 if (Idx == 1 && Imm.getBitWidth() <= 64) { 103 // Comparisons against signed 32-bit immediates implemented via cgfi. 104 if (isInt<32>(Imm.getSExtValue())) 105 return TTI::TCC_Free; 106 // Comparisons against unsigned 32-bit immediates implemented via clgfi. 107 if (isUInt<32>(Imm.getZExtValue())) 108 return TTI::TCC_Free; 109 } 110 break; 111 case Instruction::Add: 112 case Instruction::Sub: 113 if (Idx == 1 && Imm.getBitWidth() <= 64) { 114 // We use algfi/slgfi to add/subtract 32-bit unsigned immediates. 115 if (isUInt<32>(Imm.getZExtValue())) 116 return TTI::TCC_Free; 117 // Or their negation, by swapping addition vs. subtraction. 118 if (isUInt<32>(-Imm.getSExtValue())) 119 return TTI::TCC_Free; 120 } 121 break; 122 case Instruction::Mul: 123 if (Idx == 1 && Imm.getBitWidth() <= 64) { 124 // We use msgfi to multiply by 32-bit signed immediates. 125 if (isInt<32>(Imm.getSExtValue())) 126 return TTI::TCC_Free; 127 } 128 break; 129 case Instruction::Or: 130 case Instruction::Xor: 131 if (Idx == 1 && Imm.getBitWidth() <= 64) { 132 // Masks supported by oilf/xilf. 133 if (isUInt<32>(Imm.getZExtValue())) 134 return TTI::TCC_Free; 135 // Masks supported by oihf/xihf. 136 if ((Imm.getZExtValue() & 0xffffffff) == 0) 137 return TTI::TCC_Free; 138 } 139 break; 140 case Instruction::And: 141 if (Idx == 1 && Imm.getBitWidth() <= 64) { 142 // Any 32-bit AND operation can by implemented via nilf. 143 if (BitSize <= 32) 144 return TTI::TCC_Free; 145 // 64-bit masks supported by nilf. 146 if (isUInt<32>(~Imm.getZExtValue())) 147 return TTI::TCC_Free; 148 // 64-bit masks supported by nilh. 149 if ((Imm.getZExtValue() & 0xffffffff) == 0xffffffff) 150 return TTI::TCC_Free; 151 // Some 64-bit AND operations can be implemented via risbg. 152 const SystemZInstrInfo *TII = ST->getInstrInfo(); 153 unsigned Start, End; 154 if (TII->isRxSBGMask(Imm.getZExtValue(), BitSize, Start, End)) 155 return TTI::TCC_Free; 156 } 157 break; 158 case Instruction::Shl: 159 case Instruction::LShr: 160 case Instruction::AShr: 161 // Always return TCC_Free for the shift value of a shift instruction. 162 if (Idx == 1) 163 return TTI::TCC_Free; 164 break; 165 case Instruction::UDiv: 166 case Instruction::SDiv: 167 case Instruction::URem: 168 case Instruction::SRem: 169 case Instruction::Trunc: 170 case Instruction::ZExt: 171 case Instruction::SExt: 172 case Instruction::IntToPtr: 173 case Instruction::PtrToInt: 174 case Instruction::BitCast: 175 case Instruction::PHI: 176 case Instruction::Call: 177 case Instruction::Select: 178 case Instruction::Ret: 179 case Instruction::Load: 180 break; 181 } 182 183 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind); 184 } 185 186 InstructionCost 187 SystemZTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 188 const APInt &Imm, Type *Ty, 189 TTI::TargetCostKind CostKind) { 190 assert(Ty->isIntegerTy()); 191 192 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 193 // There is no cost model for constants with a bit size of 0. Return TCC_Free 194 // here, so that constant hoisting will ignore this constant. 195 if (BitSize == 0) 196 return TTI::TCC_Free; 197 // No cost model for operations on integers larger than 64 bit implemented yet. 198 if (BitSize > 64) 199 return TTI::TCC_Free; 200 201 switch (IID) { 202 default: 203 return TTI::TCC_Free; 204 case Intrinsic::sadd_with_overflow: 205 case Intrinsic::uadd_with_overflow: 206 case Intrinsic::ssub_with_overflow: 207 case Intrinsic::usub_with_overflow: 208 // These get expanded to include a normal addition/subtraction. 209 if (Idx == 1 && Imm.getBitWidth() <= 64) { 210 if (isUInt<32>(Imm.getZExtValue())) 211 return TTI::TCC_Free; 212 if (isUInt<32>(-Imm.getSExtValue())) 213 return TTI::TCC_Free; 214 } 215 break; 216 case Intrinsic::smul_with_overflow: 217 case Intrinsic::umul_with_overflow: 218 // These get expanded to include a normal multiplication. 219 if (Idx == 1 && Imm.getBitWidth() <= 64) { 220 if (isInt<32>(Imm.getSExtValue())) 221 return TTI::TCC_Free; 222 } 223 break; 224 case Intrinsic::experimental_stackmap: 225 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 226 return TTI::TCC_Free; 227 break; 228 case Intrinsic::experimental_patchpoint_void: 229 case Intrinsic::experimental_patchpoint_i64: 230 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 231 return TTI::TCC_Free; 232 break; 233 } 234 return SystemZTTIImpl::getIntImmCost(Imm, Ty, CostKind); 235 } 236 237 TargetTransformInfo::PopcntSupportKind 238 SystemZTTIImpl::getPopcntSupport(unsigned TyWidth) { 239 assert(isPowerOf2_32(TyWidth) && "Type width must be power of 2"); 240 if (ST->hasPopulationCount() && TyWidth <= 64) 241 return TTI::PSK_FastHardware; 242 return TTI::PSK_Software; 243 } 244 245 void SystemZTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 246 TTI::UnrollingPreferences &UP) { 247 // Find out if L contains a call, what the machine instruction count 248 // estimate is, and how many stores there are. 249 bool HasCall = false; 250 InstructionCost NumStores = 0; 251 for (auto &BB : L->blocks()) 252 for (auto &I : *BB) { 253 if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) { 254 if (const Function *F = cast<CallBase>(I).getCalledFunction()) { 255 if (isLoweredToCall(F)) 256 HasCall = true; 257 if (F->getIntrinsicID() == Intrinsic::memcpy || 258 F->getIntrinsicID() == Intrinsic::memset) 259 NumStores++; 260 } else { // indirect call. 261 HasCall = true; 262 } 263 } 264 if (isa<StoreInst>(&I)) { 265 Type *MemAccessTy = I.getOperand(0)->getType(); 266 NumStores += getMemoryOpCost(Instruction::Store, MemAccessTy, None, 0, 267 TTI::TCK_RecipThroughput); 268 } 269 } 270 271 // The z13 processor will run out of store tags if too many stores 272 // are fed into it too quickly. Therefore make sure there are not 273 // too many stores in the resulting unrolled loop. 274 unsigned const NumStoresVal = *NumStores.getValue(); 275 unsigned const Max = (NumStoresVal ? (12 / NumStoresVal) : UINT_MAX); 276 277 if (HasCall) { 278 // Only allow full unrolling if loop has any calls. 279 UP.FullUnrollMaxCount = Max; 280 UP.MaxCount = 1; 281 return; 282 } 283 284 UP.MaxCount = Max; 285 if (UP.MaxCount <= 1) 286 return; 287 288 // Allow partial and runtime trip count unrolling. 289 UP.Partial = UP.Runtime = true; 290 291 UP.PartialThreshold = 75; 292 UP.DefaultUnrollRuntimeCount = 4; 293 294 // Allow expensive instructions in the pre-header of the loop. 295 UP.AllowExpensiveTripCount = true; 296 297 UP.Force = true; 298 } 299 300 void SystemZTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 301 TTI::PeelingPreferences &PP) { 302 BaseT::getPeelingPreferences(L, SE, PP); 303 } 304 305 bool SystemZTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1, 306 TargetTransformInfo::LSRCost &C2) { 307 // SystemZ specific: check instruction count (first), and don't care about 308 // ImmCost, since offsets are checked explicitly. 309 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, 310 C1.NumIVMuls, C1.NumBaseAdds, 311 C1.ScaleCost, C1.SetupCost) < 312 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, 313 C2.NumIVMuls, C2.NumBaseAdds, 314 C2.ScaleCost, C2.SetupCost); 315 } 316 317 unsigned SystemZTTIImpl::getNumberOfRegisters(unsigned ClassID) const { 318 bool Vector = (ClassID == 1); 319 if (!Vector) 320 // Discount the stack pointer. Also leave out %r0, since it can't 321 // be used in an address. 322 return 14; 323 if (ST->hasVector()) 324 return 32; 325 return 0; 326 } 327 328 TypeSize 329 SystemZTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const { 330 switch (K) { 331 case TargetTransformInfo::RGK_Scalar: 332 return TypeSize::getFixed(64); 333 case TargetTransformInfo::RGK_FixedWidthVector: 334 return TypeSize::getFixed(ST->hasVector() ? 128 : 0); 335 case TargetTransformInfo::RGK_ScalableVector: 336 return TypeSize::getScalable(0); 337 } 338 339 llvm_unreachable("Unsupported register kind"); 340 } 341 342 unsigned SystemZTTIImpl::getMinPrefetchStride(unsigned NumMemAccesses, 343 unsigned NumStridedMemAccesses, 344 unsigned NumPrefetches, 345 bool HasCall) const { 346 // Don't prefetch a loop with many far apart accesses. 347 if (NumPrefetches > 16) 348 return UINT_MAX; 349 350 // Emit prefetch instructions for smaller strides in cases where we think 351 // the hardware prefetcher might not be able to keep up. 352 if (NumStridedMemAccesses > 32 && !HasCall && 353 (NumMemAccesses - NumStridedMemAccesses) * 32 <= NumStridedMemAccesses) 354 return 1; 355 356 return ST->hasMiscellaneousExtensions3() ? 8192 : 2048; 357 } 358 359 bool SystemZTTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) { 360 EVT VT = TLI->getValueType(DL, DataType); 361 return (VT.isScalarInteger() && TLI->isTypeLegal(VT)); 362 } 363 364 // Return the bit size for the scalar type or vector element 365 // type. getScalarSizeInBits() returns 0 for a pointer type. 366 static unsigned getScalarSizeInBits(Type *Ty) { 367 unsigned Size = 368 (Ty->isPtrOrPtrVectorTy() ? 64U : Ty->getScalarSizeInBits()); 369 assert(Size > 0 && "Element must have non-zero size."); 370 return Size; 371 } 372 373 // getNumberOfParts() calls getTypeLegalizationCost() which splits the vector 374 // type until it is legal. This would e.g. return 4 for <6 x i64>, instead of 375 // 3. 376 static unsigned getNumVectorRegs(Type *Ty) { 377 auto *VTy = cast<FixedVectorType>(Ty); 378 unsigned WideBits = getScalarSizeInBits(Ty) * VTy->getNumElements(); 379 assert(WideBits > 0 && "Could not compute size of vector"); 380 return ((WideBits % 128U) ? ((WideBits / 128U) + 1) : (WideBits / 128U)); 381 } 382 383 InstructionCost SystemZTTIImpl::getArithmeticInstrCost( 384 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, 385 TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info, 386 TTI::OperandValueProperties Opd1PropInfo, 387 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 388 const Instruction *CxtI) { 389 390 // TODO: Handle more cost kinds. 391 if (CostKind != TTI::TCK_RecipThroughput) 392 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 393 Op2Info, Opd1PropInfo, 394 Opd2PropInfo, Args, CxtI); 395 396 // TODO: return a good value for BB-VECTORIZER that includes the 397 // immediate loads, which we do not want to count for the loop 398 // vectorizer, since they are hopefully hoisted out of the loop. This 399 // would require a new parameter 'InLoop', but not sure if constant 400 // args are common enough to motivate this. 401 402 unsigned ScalarBits = Ty->getScalarSizeInBits(); 403 404 // There are thre cases of division and remainder: Dividing with a register 405 // needs a divide instruction. A divisor which is a power of two constant 406 // can be implemented with a sequence of shifts. Any other constant needs a 407 // multiply and shifts. 408 const unsigned DivInstrCost = 20; 409 const unsigned DivMulSeqCost = 10; 410 const unsigned SDivPow2Cost = 4; 411 412 bool SignedDivRem = 413 Opcode == Instruction::SDiv || Opcode == Instruction::SRem; 414 bool UnsignedDivRem = 415 Opcode == Instruction::UDiv || Opcode == Instruction::URem; 416 417 // Check for a constant divisor. 418 bool DivRemConst = false; 419 bool DivRemConstPow2 = false; 420 if ((SignedDivRem || UnsignedDivRem) && Args.size() == 2) { 421 if (const Constant *C = dyn_cast<Constant>(Args[1])) { 422 const ConstantInt *CVal = 423 (C->getType()->isVectorTy() 424 ? dyn_cast_or_null<const ConstantInt>(C->getSplatValue()) 425 : dyn_cast<const ConstantInt>(C)); 426 if (CVal != nullptr && 427 (CVal->getValue().isPowerOf2() || (-CVal->getValue()).isPowerOf2())) 428 DivRemConstPow2 = true; 429 else 430 DivRemConst = true; 431 } 432 } 433 434 if (!Ty->isVectorTy()) { 435 // These FP operations are supported with a dedicated instruction for 436 // float, double and fp128 (base implementation assumes float generally 437 // costs 2). 438 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub || 439 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) 440 return 1; 441 442 // There is no native support for FRem. 443 if (Opcode == Instruction::FRem) 444 return LIBCALL_COST; 445 446 // Give discount for some combined logical operations if supported. 447 if (Args.size() == 2 && ST->hasMiscellaneousExtensions3()) { 448 if (Opcode == Instruction::Xor) { 449 for (const Value *A : Args) { 450 if (const Instruction *I = dyn_cast<Instruction>(A)) 451 if (I->hasOneUse() && 452 (I->getOpcode() == Instruction::And || 453 I->getOpcode() == Instruction::Or || 454 I->getOpcode() == Instruction::Xor)) 455 return 0; 456 } 457 } 458 else if (Opcode == Instruction::Or || Opcode == Instruction::And) { 459 for (const Value *A : Args) { 460 if (const Instruction *I = dyn_cast<Instruction>(A)) 461 if (I->hasOneUse() && I->getOpcode() == Instruction::Xor) 462 return 0; 463 } 464 } 465 } 466 467 // Or requires one instruction, although it has custom handling for i64. 468 if (Opcode == Instruction::Or) 469 return 1; 470 471 if (Opcode == Instruction::Xor && ScalarBits == 1) { 472 if (ST->hasLoadStoreOnCond2()) 473 return 5; // 2 * (li 0; loc 1); xor 474 return 7; // 2 * ipm sequences ; xor ; shift ; compare 475 } 476 477 if (DivRemConstPow2) 478 return (SignedDivRem ? SDivPow2Cost : 1); 479 if (DivRemConst) 480 return DivMulSeqCost; 481 if (SignedDivRem || UnsignedDivRem) 482 return DivInstrCost; 483 } 484 else if (ST->hasVector()) { 485 auto *VTy = cast<FixedVectorType>(Ty); 486 unsigned VF = VTy->getNumElements(); 487 unsigned NumVectors = getNumVectorRegs(Ty); 488 489 // These vector operations are custom handled, but are still supported 490 // with one instruction per vector, regardless of element size. 491 if (Opcode == Instruction::Shl || Opcode == Instruction::LShr || 492 Opcode == Instruction::AShr) { 493 return NumVectors; 494 } 495 496 if (DivRemConstPow2) 497 return (NumVectors * (SignedDivRem ? SDivPow2Cost : 1)); 498 if (DivRemConst) { 499 SmallVector<Type *> Tys(Args.size(), Ty); 500 return VF * DivMulSeqCost + getScalarizationOverhead(VTy, Args, Tys); 501 } 502 if ((SignedDivRem || UnsignedDivRem) && VF > 4) 503 // Temporary hack: disable high vectorization factors with integer 504 // division/remainder, which will get scalarized and handled with 505 // GR128 registers. The mischeduler is not clever enough to avoid 506 // spilling yet. 507 return 1000; 508 509 // These FP operations are supported with a single vector instruction for 510 // double (base implementation assumes float generally costs 2). For 511 // FP128, the scalar cost is 1, and there is no overhead since the values 512 // are already in scalar registers. 513 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub || 514 Opcode == Instruction::FMul || Opcode == Instruction::FDiv) { 515 switch (ScalarBits) { 516 case 32: { 517 // The vector enhancements facility 1 provides v4f32 instructions. 518 if (ST->hasVectorEnhancements1()) 519 return NumVectors; 520 // Return the cost of multiple scalar invocation plus the cost of 521 // inserting and extracting the values. 522 InstructionCost ScalarCost = 523 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind); 524 SmallVector<Type *> Tys(Args.size(), Ty); 525 InstructionCost Cost = 526 (VF * ScalarCost) + getScalarizationOverhead(VTy, Args, Tys); 527 // FIXME: VF 2 for these FP operations are currently just as 528 // expensive as for VF 4. 529 if (VF == 2) 530 Cost *= 2; 531 return Cost; 532 } 533 case 64: 534 case 128: 535 return NumVectors; 536 default: 537 break; 538 } 539 } 540 541 // There is no native support for FRem. 542 if (Opcode == Instruction::FRem) { 543 SmallVector<Type *> Tys(Args.size(), Ty); 544 unsigned Cost = 545 (VF * LIBCALL_COST) + getScalarizationOverhead(VTy, Args, Tys); 546 // FIXME: VF 2 for float is currently just as expensive as for VF 4. 547 if (VF == 2 && ScalarBits == 32) 548 Cost *= 2; 549 return Cost; 550 } 551 } 552 553 // Fallback to the default implementation. 554 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info, 555 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 556 } 557 558 InstructionCost SystemZTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, 559 VectorType *Tp, 560 ArrayRef<int> Mask, int Index, 561 VectorType *SubTp) { 562 if (ST->hasVector()) { 563 unsigned NumVectors = getNumVectorRegs(Tp); 564 565 // TODO: Since fp32 is expanded, the shuffle cost should always be 0. 566 567 // FP128 values are always in scalar registers, so there is no work 568 // involved with a shuffle, except for broadcast. In that case register 569 // moves are done with a single instruction per element. 570 if (Tp->getScalarType()->isFP128Ty()) 571 return (Kind == TargetTransformInfo::SK_Broadcast ? NumVectors - 1 : 0); 572 573 switch (Kind) { 574 case TargetTransformInfo::SK_ExtractSubvector: 575 // ExtractSubvector Index indicates start offset. 576 577 // Extracting a subvector from first index is a noop. 578 return (Index == 0 ? 0 : NumVectors); 579 580 case TargetTransformInfo::SK_Broadcast: 581 // Loop vectorizer calls here to figure out the extra cost of 582 // broadcasting a loaded value to all elements of a vector. Since vlrep 583 // loads and replicates with a single instruction, adjust the returned 584 // value. 585 return NumVectors - 1; 586 587 default: 588 589 // SystemZ supports single instruction permutation / replication. 590 return NumVectors; 591 } 592 } 593 594 return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp); 595 } 596 597 // Return the log2 difference of the element sizes of the two vector types. 598 static unsigned getElSizeLog2Diff(Type *Ty0, Type *Ty1) { 599 unsigned Bits0 = Ty0->getScalarSizeInBits(); 600 unsigned Bits1 = Ty1->getScalarSizeInBits(); 601 602 if (Bits1 > Bits0) 603 return (Log2_32(Bits1) - Log2_32(Bits0)); 604 605 return (Log2_32(Bits0) - Log2_32(Bits1)); 606 } 607 608 // Return the number of instructions needed to truncate SrcTy to DstTy. 609 unsigned SystemZTTIImpl:: 610 getVectorTruncCost(Type *SrcTy, Type *DstTy) { 611 assert (SrcTy->isVectorTy() && DstTy->isVectorTy()); 612 assert(SrcTy->getPrimitiveSizeInBits().getFixedSize() > 613 DstTy->getPrimitiveSizeInBits().getFixedSize() && 614 "Packing must reduce size of vector type."); 615 assert(cast<FixedVectorType>(SrcTy)->getNumElements() == 616 cast<FixedVectorType>(DstTy)->getNumElements() && 617 "Packing should not change number of elements."); 618 619 // TODO: Since fp32 is expanded, the extract cost should always be 0. 620 621 unsigned NumParts = getNumVectorRegs(SrcTy); 622 if (NumParts <= 2) 623 // Up to 2 vector registers can be truncated efficiently with pack or 624 // permute. The latter requires an immediate mask to be loaded, which 625 // typically gets hoisted out of a loop. TODO: return a good value for 626 // BB-VECTORIZER that includes the immediate loads, which we do not want 627 // to count for the loop vectorizer. 628 return 1; 629 630 unsigned Cost = 0; 631 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy); 632 unsigned VF = cast<FixedVectorType>(SrcTy)->getNumElements(); 633 for (unsigned P = 0; P < Log2Diff; ++P) { 634 if (NumParts > 1) 635 NumParts /= 2; 636 Cost += NumParts; 637 } 638 639 // Currently, a general mix of permutes and pack instructions is output by 640 // isel, which follow the cost computation above except for this case which 641 // is one instruction less: 642 if (VF == 8 && SrcTy->getScalarSizeInBits() == 64 && 643 DstTy->getScalarSizeInBits() == 8) 644 Cost--; 645 646 return Cost; 647 } 648 649 // Return the cost of converting a vector bitmask produced by a compare 650 // (SrcTy), to the type of the select or extend instruction (DstTy). 651 unsigned SystemZTTIImpl:: 652 getVectorBitmaskConversionCost(Type *SrcTy, Type *DstTy) { 653 assert (SrcTy->isVectorTy() && DstTy->isVectorTy() && 654 "Should only be called with vector types."); 655 656 unsigned PackCost = 0; 657 unsigned SrcScalarBits = SrcTy->getScalarSizeInBits(); 658 unsigned DstScalarBits = DstTy->getScalarSizeInBits(); 659 unsigned Log2Diff = getElSizeLog2Diff(SrcTy, DstTy); 660 if (SrcScalarBits > DstScalarBits) 661 // The bitmask will be truncated. 662 PackCost = getVectorTruncCost(SrcTy, DstTy); 663 else if (SrcScalarBits < DstScalarBits) { 664 unsigned DstNumParts = getNumVectorRegs(DstTy); 665 // Each vector select needs its part of the bitmask unpacked. 666 PackCost = Log2Diff * DstNumParts; 667 // Extra cost for moving part of mask before unpacking. 668 PackCost += DstNumParts - 1; 669 } 670 671 return PackCost; 672 } 673 674 // Return the type of the compared operands. This is needed to compute the 675 // cost for a Select / ZExt or SExt instruction. 676 static Type *getCmpOpsType(const Instruction *I, unsigned VF = 1) { 677 Type *OpTy = nullptr; 678 if (CmpInst *CI = dyn_cast<CmpInst>(I->getOperand(0))) 679 OpTy = CI->getOperand(0)->getType(); 680 else if (Instruction *LogicI = dyn_cast<Instruction>(I->getOperand(0))) 681 if (LogicI->getNumOperands() == 2) 682 if (CmpInst *CI0 = dyn_cast<CmpInst>(LogicI->getOperand(0))) 683 if (isa<CmpInst>(LogicI->getOperand(1))) 684 OpTy = CI0->getOperand(0)->getType(); 685 686 if (OpTy != nullptr) { 687 if (VF == 1) { 688 assert (!OpTy->isVectorTy() && "Expected scalar type"); 689 return OpTy; 690 } 691 // Return the potentially vectorized type based on 'I' and 'VF'. 'I' may 692 // be either scalar or already vectorized with a same or lesser VF. 693 Type *ElTy = OpTy->getScalarType(); 694 return FixedVectorType::get(ElTy, VF); 695 } 696 697 return nullptr; 698 } 699 700 // Get the cost of converting a boolean vector to a vector with same width 701 // and element size as Dst, plus the cost of zero extending if needed. 702 unsigned SystemZTTIImpl:: 703 getBoolVecToIntConversionCost(unsigned Opcode, Type *Dst, 704 const Instruction *I) { 705 auto *DstVTy = cast<FixedVectorType>(Dst); 706 unsigned VF = DstVTy->getNumElements(); 707 unsigned Cost = 0; 708 // If we know what the widths of the compared operands, get any cost of 709 // converting it to match Dst. Otherwise assume same widths. 710 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr); 711 if (CmpOpTy != nullptr) 712 Cost = getVectorBitmaskConversionCost(CmpOpTy, Dst); 713 if (Opcode == Instruction::ZExt || Opcode == Instruction::UIToFP) 714 // One 'vn' per dst vector with an immediate mask. 715 Cost += getNumVectorRegs(Dst); 716 return Cost; 717 } 718 719 InstructionCost SystemZTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, 720 Type *Src, 721 TTI::CastContextHint CCH, 722 TTI::TargetCostKind CostKind, 723 const Instruction *I) { 724 // FIXME: Can the logic below also be used for these cost kinds? 725 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) { 726 auto BaseCost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 727 return BaseCost == 0 ? BaseCost : 1; 728 } 729 730 unsigned DstScalarBits = Dst->getScalarSizeInBits(); 731 unsigned SrcScalarBits = Src->getScalarSizeInBits(); 732 733 if (!Src->isVectorTy()) { 734 assert (!Dst->isVectorTy()); 735 736 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP) { 737 if (SrcScalarBits >= 32 || 738 (I != nullptr && isa<LoadInst>(I->getOperand(0)))) 739 return 1; 740 return SrcScalarBits > 1 ? 2 /*i8/i16 extend*/ : 5 /*branch seq.*/; 741 } 742 743 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) && 744 Src->isIntegerTy(1)) { 745 if (ST->hasLoadStoreOnCond2()) 746 return 2; // li 0; loc 1 747 748 // This should be extension of a compare i1 result, which is done with 749 // ipm and a varying sequence of instructions. 750 unsigned Cost = 0; 751 if (Opcode == Instruction::SExt) 752 Cost = (DstScalarBits < 64 ? 3 : 4); 753 if (Opcode == Instruction::ZExt) 754 Cost = 3; 755 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I) : nullptr); 756 if (CmpOpTy != nullptr && CmpOpTy->isFloatingPointTy()) 757 // If operands of an fp-type was compared, this costs +1. 758 Cost++; 759 return Cost; 760 } 761 } 762 else if (ST->hasVector()) { 763 // Vector to scalar cast. 764 auto *SrcVecTy = cast<FixedVectorType>(Src); 765 auto *DstVecTy = dyn_cast<FixedVectorType>(Dst); 766 if (!DstVecTy) { 767 // TODO: tune vector-to-scalar cast. 768 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 769 } 770 unsigned VF = SrcVecTy->getNumElements(); 771 unsigned NumDstVectors = getNumVectorRegs(Dst); 772 unsigned NumSrcVectors = getNumVectorRegs(Src); 773 774 if (Opcode == Instruction::Trunc) { 775 if (Src->getScalarSizeInBits() == Dst->getScalarSizeInBits()) 776 return 0; // Check for NOOP conversions. 777 return getVectorTruncCost(Src, Dst); 778 } 779 780 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) { 781 if (SrcScalarBits >= 8) { 782 // ZExt/SExt will be handled with one unpack per doubling of width. 783 unsigned NumUnpacks = getElSizeLog2Diff(Src, Dst); 784 785 // For types that spans multiple vector registers, some additional 786 // instructions are used to setup the unpacking. 787 unsigned NumSrcVectorOps = 788 (NumUnpacks > 1 ? (NumDstVectors - NumSrcVectors) 789 : (NumDstVectors / 2)); 790 791 return (NumUnpacks * NumDstVectors) + NumSrcVectorOps; 792 } 793 else if (SrcScalarBits == 1) 794 return getBoolVecToIntConversionCost(Opcode, Dst, I); 795 } 796 797 if (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP || 798 Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI) { 799 // TODO: Fix base implementation which could simplify things a bit here 800 // (seems to miss on differentiating on scalar/vector types). 801 802 // Only 64 bit vector conversions are natively supported before z15. 803 if (DstScalarBits == 64 || ST->hasVectorEnhancements2()) { 804 if (SrcScalarBits == DstScalarBits) 805 return NumDstVectors; 806 807 if (SrcScalarBits == 1) 808 return getBoolVecToIntConversionCost(Opcode, Dst, I) + NumDstVectors; 809 } 810 811 // Return the cost of multiple scalar invocation plus the cost of 812 // inserting and extracting the values. Base implementation does not 813 // realize float->int gets scalarized. 814 InstructionCost ScalarCost = getCastInstrCost( 815 Opcode, Dst->getScalarType(), Src->getScalarType(), CCH, CostKind); 816 InstructionCost TotCost = VF * ScalarCost; 817 bool NeedsInserts = true, NeedsExtracts = true; 818 // FP128 registers do not get inserted or extracted. 819 if (DstScalarBits == 128 && 820 (Opcode == Instruction::SIToFP || Opcode == Instruction::UIToFP)) 821 NeedsInserts = false; 822 if (SrcScalarBits == 128 && 823 (Opcode == Instruction::FPToSI || Opcode == Instruction::FPToUI)) 824 NeedsExtracts = false; 825 826 TotCost += getScalarizationOverhead(SrcVecTy, false, NeedsExtracts); 827 TotCost += getScalarizationOverhead(DstVecTy, NeedsInserts, false); 828 829 // FIXME: VF 2 for float<->i32 is currently just as expensive as for VF 4. 830 if (VF == 2 && SrcScalarBits == 32 && DstScalarBits == 32) 831 TotCost *= 2; 832 833 return TotCost; 834 } 835 836 if (Opcode == Instruction::FPTrunc) { 837 if (SrcScalarBits == 128) // fp128 -> double/float + inserts of elements. 838 return VF /*ldxbr/lexbr*/ + 839 getScalarizationOverhead(DstVecTy, true, false); 840 else // double -> float 841 return VF / 2 /*vledb*/ + std::max(1U, VF / 4 /*vperm*/); 842 } 843 844 if (Opcode == Instruction::FPExt) { 845 if (SrcScalarBits == 32 && DstScalarBits == 64) { 846 // float -> double is very rare and currently unoptimized. Instead of 847 // using vldeb, which can do two at a time, all conversions are 848 // scalarized. 849 return VF * 2; 850 } 851 // -> fp128. VF * lxdb/lxeb + extraction of elements. 852 return VF + getScalarizationOverhead(SrcVecTy, false, true); 853 } 854 } 855 856 return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 857 } 858 859 // Scalar i8 / i16 operations will typically be made after first extending 860 // the operands to i32. 861 static unsigned getOperandsExtensionCost(const Instruction *I) { 862 unsigned ExtCost = 0; 863 for (Value *Op : I->operands()) 864 // A load of i8 or i16 sign/zero extends to i32. 865 if (!isa<LoadInst>(Op) && !isa<ConstantInt>(Op)) 866 ExtCost++; 867 868 return ExtCost; 869 } 870 871 InstructionCost SystemZTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 872 Type *CondTy, 873 CmpInst::Predicate VecPred, 874 TTI::TargetCostKind CostKind, 875 const Instruction *I) { 876 if (CostKind != TTI::TCK_RecipThroughput) 877 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind); 878 879 if (!ValTy->isVectorTy()) { 880 switch (Opcode) { 881 case Instruction::ICmp: { 882 // A loaded value compared with 0 with multiple users becomes Load and 883 // Test. The load is then not foldable, so return 0 cost for the ICmp. 884 unsigned ScalarBits = ValTy->getScalarSizeInBits(); 885 if (I != nullptr && ScalarBits >= 32) 886 if (LoadInst *Ld = dyn_cast<LoadInst>(I->getOperand(0))) 887 if (const ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1))) 888 if (!Ld->hasOneUse() && Ld->getParent() == I->getParent() && 889 C->isZero()) 890 return 0; 891 892 unsigned Cost = 1; 893 if (ValTy->isIntegerTy() && ValTy->getScalarSizeInBits() <= 16) 894 Cost += (I != nullptr ? getOperandsExtensionCost(I) : 2); 895 return Cost; 896 } 897 case Instruction::Select: 898 if (ValTy->isFloatingPointTy()) 899 return 4; // No load on condition for FP - costs a conditional jump. 900 return 1; // Load On Condition / Select Register. 901 } 902 } 903 else if (ST->hasVector()) { 904 unsigned VF = cast<FixedVectorType>(ValTy)->getNumElements(); 905 906 // Called with a compare instruction. 907 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) { 908 unsigned PredicateExtraCost = 0; 909 if (I != nullptr) { 910 // Some predicates cost one or two extra instructions. 911 switch (cast<CmpInst>(I)->getPredicate()) { 912 case CmpInst::Predicate::ICMP_NE: 913 case CmpInst::Predicate::ICMP_UGE: 914 case CmpInst::Predicate::ICMP_ULE: 915 case CmpInst::Predicate::ICMP_SGE: 916 case CmpInst::Predicate::ICMP_SLE: 917 PredicateExtraCost = 1; 918 break; 919 case CmpInst::Predicate::FCMP_ONE: 920 case CmpInst::Predicate::FCMP_ORD: 921 case CmpInst::Predicate::FCMP_UEQ: 922 case CmpInst::Predicate::FCMP_UNO: 923 PredicateExtraCost = 2; 924 break; 925 default: 926 break; 927 } 928 } 929 930 // Float is handled with 2*vmr[lh]f + 2*vldeb + vfchdb for each pair of 931 // floats. FIXME: <2 x float> generates same code as <4 x float>. 932 unsigned CmpCostPerVector = (ValTy->getScalarType()->isFloatTy() ? 10 : 1); 933 unsigned NumVecs_cmp = getNumVectorRegs(ValTy); 934 935 unsigned Cost = (NumVecs_cmp * (CmpCostPerVector + PredicateExtraCost)); 936 return Cost; 937 } 938 else { // Called with a select instruction. 939 assert (Opcode == Instruction::Select); 940 941 // We can figure out the extra cost of packing / unpacking if the 942 // instruction was passed and the compare instruction is found. 943 unsigned PackCost = 0; 944 Type *CmpOpTy = ((I != nullptr) ? getCmpOpsType(I, VF) : nullptr); 945 if (CmpOpTy != nullptr) 946 PackCost = 947 getVectorBitmaskConversionCost(CmpOpTy, ValTy); 948 949 return getNumVectorRegs(ValTy) /*vsel*/ + PackCost; 950 } 951 } 952 953 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind); 954 } 955 956 InstructionCost SystemZTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, 957 unsigned Index) { 958 // vlvgp will insert two grs into a vector register, so only count half the 959 // number of instructions. 960 if (Opcode == Instruction::InsertElement && Val->isIntOrIntVectorTy(64)) 961 return ((Index % 2 == 0) ? 1 : 0); 962 963 if (Opcode == Instruction::ExtractElement) { 964 int Cost = ((getScalarSizeInBits(Val) == 1) ? 2 /*+test-under-mask*/ : 1); 965 966 // Give a slight penalty for moving out of vector pipeline to FXU unit. 967 if (Index == 0 && Val->isIntOrIntVectorTy()) 968 Cost += 1; 969 970 return Cost; 971 } 972 973 return BaseT::getVectorInstrCost(Opcode, Val, Index); 974 } 975 976 // Check if a load may be folded as a memory operand in its user. 977 bool SystemZTTIImpl:: 978 isFoldableLoad(const LoadInst *Ld, const Instruction *&FoldedValue) { 979 if (!Ld->hasOneUse()) 980 return false; 981 FoldedValue = Ld; 982 const Instruction *UserI = cast<Instruction>(*Ld->user_begin()); 983 unsigned LoadedBits = getScalarSizeInBits(Ld->getType()); 984 unsigned TruncBits = 0; 985 unsigned SExtBits = 0; 986 unsigned ZExtBits = 0; 987 if (UserI->hasOneUse()) { 988 unsigned UserBits = UserI->getType()->getScalarSizeInBits(); 989 if (isa<TruncInst>(UserI)) 990 TruncBits = UserBits; 991 else if (isa<SExtInst>(UserI)) 992 SExtBits = UserBits; 993 else if (isa<ZExtInst>(UserI)) 994 ZExtBits = UserBits; 995 } 996 if (TruncBits || SExtBits || ZExtBits) { 997 FoldedValue = UserI; 998 UserI = cast<Instruction>(*UserI->user_begin()); 999 // Load (single use) -> trunc/extend (single use) -> UserI 1000 } 1001 if ((UserI->getOpcode() == Instruction::Sub || 1002 UserI->getOpcode() == Instruction::SDiv || 1003 UserI->getOpcode() == Instruction::UDiv) && 1004 UserI->getOperand(1) != FoldedValue) 1005 return false; // Not commutative, only RHS foldable. 1006 // LoadOrTruncBits holds the number of effectively loaded bits, but 0 if an 1007 // extension was made of the load. 1008 unsigned LoadOrTruncBits = 1009 ((SExtBits || ZExtBits) ? 0 : (TruncBits ? TruncBits : LoadedBits)); 1010 switch (UserI->getOpcode()) { 1011 case Instruction::Add: // SE: 16->32, 16/32->64, z14:16->64. ZE: 32->64 1012 case Instruction::Sub: 1013 case Instruction::ICmp: 1014 if (LoadedBits == 32 && ZExtBits == 64) 1015 return true; 1016 LLVM_FALLTHROUGH; 1017 case Instruction::Mul: // SE: 16->32, 32->64, z14:16->64 1018 if (UserI->getOpcode() != Instruction::ICmp) { 1019 if (LoadedBits == 16 && 1020 (SExtBits == 32 || 1021 (SExtBits == 64 && ST->hasMiscellaneousExtensions2()))) 1022 return true; 1023 if (LoadOrTruncBits == 16) 1024 return true; 1025 } 1026 LLVM_FALLTHROUGH; 1027 case Instruction::SDiv:// SE: 32->64 1028 if (LoadedBits == 32 && SExtBits == 64) 1029 return true; 1030 LLVM_FALLTHROUGH; 1031 case Instruction::UDiv: 1032 case Instruction::And: 1033 case Instruction::Or: 1034 case Instruction::Xor: 1035 // This also makes sense for float operations, but disabled for now due 1036 // to regressions. 1037 // case Instruction::FCmp: 1038 // case Instruction::FAdd: 1039 // case Instruction::FSub: 1040 // case Instruction::FMul: 1041 // case Instruction::FDiv: 1042 1043 // All possible extensions of memory checked above. 1044 1045 // Comparison between memory and immediate. 1046 if (UserI->getOpcode() == Instruction::ICmp) 1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(UserI->getOperand(1))) 1048 if (CI->getValue().isIntN(16)) 1049 return true; 1050 return (LoadOrTruncBits == 32 || LoadOrTruncBits == 64); 1051 break; 1052 } 1053 return false; 1054 } 1055 1056 static bool isBswapIntrinsicCall(const Value *V) { 1057 if (const Instruction *I = dyn_cast<Instruction>(V)) 1058 if (auto *CI = dyn_cast<CallInst>(I)) 1059 if (auto *F = CI->getCalledFunction()) 1060 if (F->getIntrinsicID() == Intrinsic::bswap) 1061 return true; 1062 return false; 1063 } 1064 1065 InstructionCost SystemZTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, 1066 MaybeAlign Alignment, 1067 unsigned AddressSpace, 1068 TTI::TargetCostKind CostKind, 1069 const Instruction *I) { 1070 assert(!Src->isVoidTy() && "Invalid type"); 1071 1072 // TODO: Handle other cost kinds. 1073 if (CostKind != TTI::TCK_RecipThroughput) 1074 return 1; 1075 1076 if (!Src->isVectorTy() && Opcode == Instruction::Load && I != nullptr) { 1077 // Store the load or its truncated or extended value in FoldedValue. 1078 const Instruction *FoldedValue = nullptr; 1079 if (isFoldableLoad(cast<LoadInst>(I), FoldedValue)) { 1080 const Instruction *UserI = cast<Instruction>(*FoldedValue->user_begin()); 1081 assert (UserI->getNumOperands() == 2 && "Expected a binop."); 1082 1083 // UserI can't fold two loads, so in that case return 0 cost only 1084 // half of the time. 1085 for (unsigned i = 0; i < 2; ++i) { 1086 if (UserI->getOperand(i) == FoldedValue) 1087 continue; 1088 1089 if (Instruction *OtherOp = dyn_cast<Instruction>(UserI->getOperand(i))){ 1090 LoadInst *OtherLoad = dyn_cast<LoadInst>(OtherOp); 1091 if (!OtherLoad && 1092 (isa<TruncInst>(OtherOp) || isa<SExtInst>(OtherOp) || 1093 isa<ZExtInst>(OtherOp))) 1094 OtherLoad = dyn_cast<LoadInst>(OtherOp->getOperand(0)); 1095 if (OtherLoad && isFoldableLoad(OtherLoad, FoldedValue/*dummy*/)) 1096 return i == 0; // Both operands foldable. 1097 } 1098 } 1099 1100 return 0; // Only I is foldable in user. 1101 } 1102 } 1103 1104 unsigned NumOps = 1105 (Src->isVectorTy() ? getNumVectorRegs(Src) : getNumberOfParts(Src)); 1106 1107 // Store/Load reversed saves one instruction. 1108 if (((!Src->isVectorTy() && NumOps == 1) || ST->hasVectorEnhancements2()) && 1109 I != nullptr) { 1110 if (Opcode == Instruction::Load && I->hasOneUse()) { 1111 const Instruction *LdUser = cast<Instruction>(*I->user_begin()); 1112 // In case of load -> bswap -> store, return normal cost for the load. 1113 if (isBswapIntrinsicCall(LdUser) && 1114 (!LdUser->hasOneUse() || !isa<StoreInst>(*LdUser->user_begin()))) 1115 return 0; 1116 } 1117 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) { 1118 const Value *StoredVal = SI->getValueOperand(); 1119 if (StoredVal->hasOneUse() && isBswapIntrinsicCall(StoredVal)) 1120 return 0; 1121 } 1122 } 1123 1124 if (Src->getScalarSizeInBits() == 128) 1125 // 128 bit scalars are held in a pair of two 64 bit registers. 1126 NumOps *= 2; 1127 1128 return NumOps; 1129 } 1130 1131 // The generic implementation of getInterleavedMemoryOpCost() is based on 1132 // adding costs of the memory operations plus all the extracts and inserts 1133 // needed for using / defining the vector operands. The SystemZ version does 1134 // roughly the same but bases the computations on vector permutations 1135 // instead. 1136 InstructionCost SystemZTTIImpl::getInterleavedMemoryOpCost( 1137 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 1138 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 1139 bool UseMaskForCond, bool UseMaskForGaps) { 1140 if (UseMaskForCond || UseMaskForGaps) 1141 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 1142 Alignment, AddressSpace, CostKind, 1143 UseMaskForCond, UseMaskForGaps); 1144 assert(isa<VectorType>(VecTy) && 1145 "Expect a vector type for interleaved memory op"); 1146 1147 // Return the ceiling of dividing A by B. 1148 auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; }; 1149 1150 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements(); 1151 assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor"); 1152 unsigned VF = NumElts / Factor; 1153 unsigned NumEltsPerVecReg = (128U / getScalarSizeInBits(VecTy)); 1154 unsigned NumVectorMemOps = getNumVectorRegs(VecTy); 1155 unsigned NumPermutes = 0; 1156 1157 if (Opcode == Instruction::Load) { 1158 // Loading interleave groups may have gaps, which may mean fewer 1159 // loads. Find out how many vectors will be loaded in total, and in how 1160 // many of them each value will be in. 1161 BitVector UsedInsts(NumVectorMemOps, false); 1162 std::vector<BitVector> ValueVecs(Factor, BitVector(NumVectorMemOps, false)); 1163 for (unsigned Index : Indices) 1164 for (unsigned Elt = 0; Elt < VF; ++Elt) { 1165 unsigned Vec = (Index + Elt * Factor) / NumEltsPerVecReg; 1166 UsedInsts.set(Vec); 1167 ValueVecs[Index].set(Vec); 1168 } 1169 NumVectorMemOps = UsedInsts.count(); 1170 1171 for (unsigned Index : Indices) { 1172 // Estimate that each loaded source vector containing this Index 1173 // requires one operation, except that vperm can handle two input 1174 // registers first time for each dst vector. 1175 unsigned NumSrcVecs = ValueVecs[Index].count(); 1176 unsigned NumDstVecs = ceil(VF * getScalarSizeInBits(VecTy), 128U); 1177 assert (NumSrcVecs >= NumDstVecs && "Expected at least as many sources"); 1178 NumPermutes += std::max(1U, NumSrcVecs - NumDstVecs); 1179 } 1180 } else { 1181 // Estimate the permutes for each stored vector as the smaller of the 1182 // number of elements and the number of source vectors. Subtract one per 1183 // dst vector for vperm (S.A.). 1184 unsigned NumSrcVecs = std::min(NumEltsPerVecReg, Factor); 1185 unsigned NumDstVecs = NumVectorMemOps; 1186 assert (NumSrcVecs > 1 && "Expected at least two source vectors."); 1187 NumPermutes += (NumDstVecs * NumSrcVecs) - NumDstVecs; 1188 } 1189 1190 // Cost of load/store operations and the permutations needed. 1191 return NumVectorMemOps + NumPermutes; 1192 } 1193 1194 static int getVectorIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy) { 1195 if (RetTy->isVectorTy() && ID == Intrinsic::bswap) 1196 return getNumVectorRegs(RetTy); // VPERM 1197 return -1; 1198 } 1199 1200 InstructionCost 1201 SystemZTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 1202 TTI::TargetCostKind CostKind) { 1203 InstructionCost Cost = 1204 getVectorIntrinsicInstrCost(ICA.getID(), ICA.getReturnType()); 1205 if (Cost != -1) 1206 return Cost; 1207 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 1208 } 1209