1 //===-- PPCTargetTransformInfo.cpp - PPC specific TTI ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "PPCTargetTransformInfo.h" 10 #include "llvm/Analysis/CodeMetrics.h" 11 #include "llvm/Analysis/TargetLibraryInfo.h" 12 #include "llvm/Analysis/TargetTransformInfo.h" 13 #include "llvm/CodeGen/BasicTTIImpl.h" 14 #include "llvm/CodeGen/CostTable.h" 15 #include "llvm/CodeGen/TargetLowering.h" 16 #include "llvm/CodeGen/TargetSchedule.h" 17 #include "llvm/IR/IntrinsicsPowerPC.h" 18 #include "llvm/Support/CommandLine.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/KnownBits.h" 21 #include "llvm/Transforms/InstCombine/InstCombiner.h" 22 #include "llvm/Transforms/Utils/Local.h" 23 24 using namespace llvm; 25 26 #define DEBUG_TYPE "ppctti" 27 28 static cl::opt<bool> DisablePPCConstHoist("disable-ppc-constant-hoisting", 29 cl::desc("disable constant hoisting on PPC"), cl::init(false), cl::Hidden); 30 31 // This is currently only used for the data prefetch pass 32 static cl::opt<unsigned> 33 CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64), 34 cl::desc("The loop prefetch cache line size")); 35 36 static cl::opt<bool> 37 EnablePPCColdCC("ppc-enable-coldcc", cl::Hidden, cl::init(false), 38 cl::desc("Enable using coldcc calling conv for cold " 39 "internal functions")); 40 41 static cl::opt<bool> 42 LsrNoInsnsCost("ppc-lsr-no-insns-cost", cl::Hidden, cl::init(false), 43 cl::desc("Do not add instruction count to lsr cost model")); 44 45 // The latency of mtctr is only justified if there are more than 4 46 // comparisons that will be removed as a result. 47 static cl::opt<unsigned> 48 SmallCTRLoopThreshold("min-ctr-loop-threshold", cl::init(4), cl::Hidden, 49 cl::desc("Loops with a constant trip count smaller than " 50 "this value will not use the count register.")); 51 52 //===----------------------------------------------------------------------===// 53 // 54 // PPC cost model. 55 // 56 //===----------------------------------------------------------------------===// 57 58 TargetTransformInfo::PopcntSupportKind 59 PPCTTIImpl::getPopcntSupport(unsigned TyWidth) { 60 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2"); 61 if (ST->hasPOPCNTD() != PPCSubtarget::POPCNTD_Unavailable && TyWidth <= 64) 62 return ST->hasPOPCNTD() == PPCSubtarget::POPCNTD_Slow ? 63 TTI::PSK_SlowHardware : TTI::PSK_FastHardware; 64 return TTI::PSK_Software; 65 } 66 67 Optional<Instruction *> 68 PPCTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const { 69 Intrinsic::ID IID = II.getIntrinsicID(); 70 switch (IID) { 71 default: 72 break; 73 case Intrinsic::ppc_altivec_lvx: 74 case Intrinsic::ppc_altivec_lvxl: 75 // Turn PPC lvx -> load if the pointer is known aligned. 76 if (getOrEnforceKnownAlignment( 77 II.getArgOperand(0), Align(16), IC.getDataLayout(), &II, 78 &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) { 79 Value *Ptr = IC.Builder.CreateBitCast( 80 II.getArgOperand(0), PointerType::getUnqual(II.getType())); 81 return new LoadInst(II.getType(), Ptr, "", false, Align(16)); 82 } 83 break; 84 case Intrinsic::ppc_vsx_lxvw4x: 85 case Intrinsic::ppc_vsx_lxvd2x: { 86 // Turn PPC VSX loads into normal loads. 87 Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(0), 88 PointerType::getUnqual(II.getType())); 89 return new LoadInst(II.getType(), Ptr, Twine(""), false, Align(1)); 90 } 91 case Intrinsic::ppc_altivec_stvx: 92 case Intrinsic::ppc_altivec_stvxl: 93 // Turn stvx -> store if the pointer is known aligned. 94 if (getOrEnforceKnownAlignment( 95 II.getArgOperand(1), Align(16), IC.getDataLayout(), &II, 96 &IC.getAssumptionCache(), &IC.getDominatorTree()) >= 16) { 97 Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType()); 98 Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy); 99 return new StoreInst(II.getArgOperand(0), Ptr, false, Align(16)); 100 } 101 break; 102 case Intrinsic::ppc_vsx_stxvw4x: 103 case Intrinsic::ppc_vsx_stxvd2x: { 104 // Turn PPC VSX stores into normal stores. 105 Type *OpPtrTy = PointerType::getUnqual(II.getArgOperand(0)->getType()); 106 Value *Ptr = IC.Builder.CreateBitCast(II.getArgOperand(1), OpPtrTy); 107 return new StoreInst(II.getArgOperand(0), Ptr, false, Align(1)); 108 } 109 case Intrinsic::ppc_altivec_vperm: 110 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 111 // Note that ppc_altivec_vperm has a big-endian bias, so when creating 112 // a vectorshuffle for little endian, we must undo the transformation 113 // performed on vec_perm in altivec.h. That is, we must complement 114 // the permutation mask with respect to 31 and reverse the order of 115 // V1 and V2. 116 if (Constant *Mask = dyn_cast<Constant>(II.getArgOperand(2))) { 117 assert(cast<FixedVectorType>(Mask->getType())->getNumElements() == 16 && 118 "Bad type for intrinsic!"); 119 120 // Check that all of the elements are integer constants or undefs. 121 bool AllEltsOk = true; 122 for (unsigned i = 0; i != 16; ++i) { 123 Constant *Elt = Mask->getAggregateElement(i); 124 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 125 AllEltsOk = false; 126 break; 127 } 128 } 129 130 if (AllEltsOk) { 131 // Cast the input vectors to byte vectors. 132 Value *Op0 = 133 IC.Builder.CreateBitCast(II.getArgOperand(0), Mask->getType()); 134 Value *Op1 = 135 IC.Builder.CreateBitCast(II.getArgOperand(1), Mask->getType()); 136 Value *Result = UndefValue::get(Op0->getType()); 137 138 // Only extract each element once. 139 Value *ExtractedElts[32]; 140 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 141 142 for (unsigned i = 0; i != 16; ++i) { 143 if (isa<UndefValue>(Mask->getAggregateElement(i))) 144 continue; 145 unsigned Idx = 146 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 147 Idx &= 31; // Match the hardware behavior. 148 if (DL.isLittleEndian()) 149 Idx = 31 - Idx; 150 151 if (!ExtractedElts[Idx]) { 152 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0; 153 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1; 154 ExtractedElts[Idx] = IC.Builder.CreateExtractElement( 155 Idx < 16 ? Op0ToUse : Op1ToUse, IC.Builder.getInt32(Idx & 15)); 156 } 157 158 // Insert this value into the result vector. 159 Result = IC.Builder.CreateInsertElement(Result, ExtractedElts[Idx], 160 IC.Builder.getInt32(i)); 161 } 162 return CastInst::Create(Instruction::BitCast, Result, II.getType()); 163 } 164 } 165 break; 166 } 167 return None; 168 } 169 170 int PPCTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 171 TTI::TargetCostKind CostKind) { 172 if (DisablePPCConstHoist) 173 return BaseT::getIntImmCost(Imm, Ty, CostKind); 174 175 assert(Ty->isIntegerTy()); 176 177 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 178 if (BitSize == 0) 179 return ~0U; 180 181 if (Imm == 0) 182 return TTI::TCC_Free; 183 184 if (Imm.getBitWidth() <= 64) { 185 if (isInt<16>(Imm.getSExtValue())) 186 return TTI::TCC_Basic; 187 188 if (isInt<32>(Imm.getSExtValue())) { 189 // A constant that can be materialized using lis. 190 if ((Imm.getZExtValue() & 0xFFFF) == 0) 191 return TTI::TCC_Basic; 192 193 return 2 * TTI::TCC_Basic; 194 } 195 } 196 197 return 4 * TTI::TCC_Basic; 198 } 199 200 int PPCTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 201 const APInt &Imm, Type *Ty, 202 TTI::TargetCostKind CostKind) { 203 if (DisablePPCConstHoist) 204 return BaseT::getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind); 205 206 assert(Ty->isIntegerTy()); 207 208 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 209 if (BitSize == 0) 210 return ~0U; 211 212 switch (IID) { 213 default: 214 return TTI::TCC_Free; 215 case Intrinsic::sadd_with_overflow: 216 case Intrinsic::uadd_with_overflow: 217 case Intrinsic::ssub_with_overflow: 218 case Intrinsic::usub_with_overflow: 219 if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<16>(Imm.getSExtValue())) 220 return TTI::TCC_Free; 221 break; 222 case Intrinsic::experimental_stackmap: 223 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 224 return TTI::TCC_Free; 225 break; 226 case Intrinsic::experimental_patchpoint_void: 227 case Intrinsic::experimental_patchpoint_i64: 228 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 229 return TTI::TCC_Free; 230 break; 231 } 232 return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind); 233 } 234 235 int PPCTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 236 const APInt &Imm, Type *Ty, 237 TTI::TargetCostKind CostKind, 238 Instruction *Inst) { 239 if (DisablePPCConstHoist) 240 return BaseT::getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind, Inst); 241 242 assert(Ty->isIntegerTy()); 243 244 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 245 if (BitSize == 0) 246 return ~0U; 247 248 unsigned ImmIdx = ~0U; 249 bool ShiftedFree = false, RunFree = false, UnsignedFree = false, 250 ZeroFree = false; 251 switch (Opcode) { 252 default: 253 return TTI::TCC_Free; 254 case Instruction::GetElementPtr: 255 // Always hoist the base address of a GetElementPtr. This prevents the 256 // creation of new constants for every base constant that gets constant 257 // folded with the offset. 258 if (Idx == 0) 259 return 2 * TTI::TCC_Basic; 260 return TTI::TCC_Free; 261 case Instruction::And: 262 RunFree = true; // (for the rotate-and-mask instructions) 263 LLVM_FALLTHROUGH; 264 case Instruction::Add: 265 case Instruction::Or: 266 case Instruction::Xor: 267 ShiftedFree = true; 268 LLVM_FALLTHROUGH; 269 case Instruction::Sub: 270 case Instruction::Mul: 271 case Instruction::Shl: 272 case Instruction::LShr: 273 case Instruction::AShr: 274 ImmIdx = 1; 275 break; 276 case Instruction::ICmp: 277 UnsignedFree = true; 278 ImmIdx = 1; 279 // Zero comparisons can use record-form instructions. 280 LLVM_FALLTHROUGH; 281 case Instruction::Select: 282 ZeroFree = true; 283 break; 284 case Instruction::PHI: 285 case Instruction::Call: 286 case Instruction::Ret: 287 case Instruction::Load: 288 case Instruction::Store: 289 break; 290 } 291 292 if (ZeroFree && Imm == 0) 293 return TTI::TCC_Free; 294 295 if (Idx == ImmIdx && Imm.getBitWidth() <= 64) { 296 if (isInt<16>(Imm.getSExtValue())) 297 return TTI::TCC_Free; 298 299 if (RunFree) { 300 if (Imm.getBitWidth() <= 32 && 301 (isShiftedMask_32(Imm.getZExtValue()) || 302 isShiftedMask_32(~Imm.getZExtValue()))) 303 return TTI::TCC_Free; 304 305 if (ST->isPPC64() && 306 (isShiftedMask_64(Imm.getZExtValue()) || 307 isShiftedMask_64(~Imm.getZExtValue()))) 308 return TTI::TCC_Free; 309 } 310 311 if (UnsignedFree && isUInt<16>(Imm.getZExtValue())) 312 return TTI::TCC_Free; 313 314 if (ShiftedFree && (Imm.getZExtValue() & 0xFFFF) == 0) 315 return TTI::TCC_Free; 316 } 317 318 return PPCTTIImpl::getIntImmCost(Imm, Ty, CostKind); 319 } 320 321 unsigned 322 PPCTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands, 323 TTI::TargetCostKind CostKind) { 324 // We already implement getCastInstrCost and getMemoryOpCost where we perform 325 // the vector adjustment there. 326 if (isa<CastInst>(U) || isa<LoadInst>(U) || isa<StoreInst>(U)) 327 return BaseT::getUserCost(U, Operands, CostKind); 328 329 if (U->getType()->isVectorTy()) { 330 // Instructions that need to be split should cost more. 331 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, U->getType()); 332 return LT.first * BaseT::getUserCost(U, Operands, CostKind); 333 } 334 335 return BaseT::getUserCost(U, Operands, CostKind); 336 } 337 338 // Determining the address of a TLS variable results in a function call in 339 // certain TLS models. 340 static bool memAddrUsesCTR(const Value *MemAddr, const PPCTargetMachine &TM, 341 SmallPtrSetImpl<const Value *> &Visited) { 342 // No need to traverse again if we already checked this operand. 343 if (!Visited.insert(MemAddr).second) 344 return false; 345 const auto *GV = dyn_cast<GlobalValue>(MemAddr); 346 if (!GV) { 347 // Recurse to check for constants that refer to TLS global variables. 348 if (const auto *CV = dyn_cast<Constant>(MemAddr)) 349 for (const auto &CO : CV->operands()) 350 if (memAddrUsesCTR(CO, TM, Visited)) 351 return true; 352 return false; 353 } 354 355 if (!GV->isThreadLocal()) 356 return false; 357 TLSModel::Model Model = TM.getTLSModel(GV); 358 return Model == TLSModel::GeneralDynamic || Model == TLSModel::LocalDynamic; 359 } 360 361 bool PPCTTIImpl::mightUseCTR(BasicBlock *BB, TargetLibraryInfo *LibInfo, 362 SmallPtrSetImpl<const Value *> &Visited) { 363 const PPCTargetMachine &TM = ST->getTargetMachine(); 364 365 // Loop through the inline asm constraints and look for something that 366 // clobbers ctr. 367 auto asmClobbersCTR = [](InlineAsm *IA) { 368 InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints(); 369 for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) { 370 InlineAsm::ConstraintInfo &C = CIV[i]; 371 if (C.Type != InlineAsm::isInput) 372 for (unsigned j = 0, je = C.Codes.size(); j < je; ++j) 373 if (StringRef(C.Codes[j]).equals_lower("{ctr}")) 374 return true; 375 } 376 return false; 377 }; 378 379 auto isLargeIntegerTy = [](bool Is32Bit, Type *Ty) { 380 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) 381 return ITy->getBitWidth() > (Is32Bit ? 32U : 64U); 382 383 return false; 384 }; 385 386 for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); 387 J != JE; ++J) { 388 if (CallInst *CI = dyn_cast<CallInst>(J)) { 389 // Inline ASM is okay, unless it clobbers the ctr register. 390 if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand())) { 391 if (asmClobbersCTR(IA)) 392 return true; 393 continue; 394 } 395 396 if (Function *F = CI->getCalledFunction()) { 397 // Most intrinsics don't become function calls, but some might. 398 // sin, cos, exp and log are always calls. 399 unsigned Opcode = 0; 400 if (F->getIntrinsicID() != Intrinsic::not_intrinsic) { 401 switch (F->getIntrinsicID()) { 402 default: continue; 403 // If we have a call to loop_decrement or set_loop_iterations, 404 // we're definitely using CTR. 405 case Intrinsic::set_loop_iterations: 406 case Intrinsic::loop_decrement: 407 return true; 408 409 // Binary operations on 128-bit value will use CTR. 410 case Intrinsic::experimental_constrained_fadd: 411 case Intrinsic::experimental_constrained_fsub: 412 case Intrinsic::experimental_constrained_fmul: 413 case Intrinsic::experimental_constrained_fdiv: 414 case Intrinsic::experimental_constrained_frem: 415 if (F->getType()->getScalarType()->isFP128Ty() || 416 F->getType()->getScalarType()->isPPC_FP128Ty()) 417 return true; 418 break; 419 420 case Intrinsic::experimental_constrained_fptosi: 421 case Intrinsic::experimental_constrained_fptoui: 422 case Intrinsic::experimental_constrained_sitofp: 423 case Intrinsic::experimental_constrained_uitofp: { 424 Type *SrcType = CI->getArgOperand(0)->getType()->getScalarType(); 425 Type *DstType = CI->getType()->getScalarType(); 426 if (SrcType->isPPC_FP128Ty() || DstType->isPPC_FP128Ty() || 427 isLargeIntegerTy(!TM.isPPC64(), SrcType) || 428 isLargeIntegerTy(!TM.isPPC64(), DstType)) 429 return true; 430 break; 431 } 432 433 // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp 434 // because, although it does clobber the counter register, the 435 // control can't then return to inside the loop unless there is also 436 // an eh_sjlj_setjmp. 437 case Intrinsic::eh_sjlj_setjmp: 438 439 case Intrinsic::memcpy: 440 case Intrinsic::memmove: 441 case Intrinsic::memset: 442 case Intrinsic::powi: 443 case Intrinsic::log: 444 case Intrinsic::log2: 445 case Intrinsic::log10: 446 case Intrinsic::exp: 447 case Intrinsic::exp2: 448 case Intrinsic::pow: 449 case Intrinsic::sin: 450 case Intrinsic::cos: 451 case Intrinsic::experimental_constrained_powi: 452 case Intrinsic::experimental_constrained_log: 453 case Intrinsic::experimental_constrained_log2: 454 case Intrinsic::experimental_constrained_log10: 455 case Intrinsic::experimental_constrained_exp: 456 case Intrinsic::experimental_constrained_exp2: 457 case Intrinsic::experimental_constrained_pow: 458 case Intrinsic::experimental_constrained_sin: 459 case Intrinsic::experimental_constrained_cos: 460 return true; 461 case Intrinsic::copysign: 462 if (CI->getArgOperand(0)->getType()->getScalarType()-> 463 isPPC_FP128Ty()) 464 return true; 465 else 466 continue; // ISD::FCOPYSIGN is never a library call. 467 case Intrinsic::fma: Opcode = ISD::FMA; break; 468 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 469 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 470 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 471 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 472 case Intrinsic::rint: Opcode = ISD::FRINT; break; 473 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 474 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 475 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 476 case Intrinsic::round: Opcode = ISD::FROUND; break; 477 case Intrinsic::lround: Opcode = ISD::LROUND; break; 478 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 479 case Intrinsic::minnum: Opcode = ISD::FMINNUM; break; 480 case Intrinsic::maxnum: Opcode = ISD::FMAXNUM; break; 481 case Intrinsic::experimental_constrained_fcmp: 482 Opcode = ISD::STRICT_FSETCC; 483 break; 484 case Intrinsic::experimental_constrained_fcmps: 485 Opcode = ISD::STRICT_FSETCCS; 486 break; 487 case Intrinsic::experimental_constrained_fma: 488 Opcode = ISD::STRICT_FMA; 489 break; 490 case Intrinsic::experimental_constrained_sqrt: 491 Opcode = ISD::STRICT_FSQRT; 492 break; 493 case Intrinsic::experimental_constrained_floor: 494 Opcode = ISD::STRICT_FFLOOR; 495 break; 496 case Intrinsic::experimental_constrained_ceil: 497 Opcode = ISD::STRICT_FCEIL; 498 break; 499 case Intrinsic::experimental_constrained_trunc: 500 Opcode = ISD::STRICT_FTRUNC; 501 break; 502 case Intrinsic::experimental_constrained_rint: 503 Opcode = ISD::STRICT_FRINT; 504 break; 505 case Intrinsic::experimental_constrained_lrint: 506 Opcode = ISD::STRICT_LRINT; 507 break; 508 case Intrinsic::experimental_constrained_llrint: 509 Opcode = ISD::STRICT_LLRINT; 510 break; 511 case Intrinsic::experimental_constrained_nearbyint: 512 Opcode = ISD::STRICT_FNEARBYINT; 513 break; 514 case Intrinsic::experimental_constrained_round: 515 Opcode = ISD::STRICT_FROUND; 516 break; 517 case Intrinsic::experimental_constrained_lround: 518 Opcode = ISD::STRICT_LROUND; 519 break; 520 case Intrinsic::experimental_constrained_llround: 521 Opcode = ISD::STRICT_LLROUND; 522 break; 523 case Intrinsic::experimental_constrained_minnum: 524 Opcode = ISD::STRICT_FMINNUM; 525 break; 526 case Intrinsic::experimental_constrained_maxnum: 527 Opcode = ISD::STRICT_FMAXNUM; 528 break; 529 case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO; break; 530 case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO; break; 531 } 532 } 533 534 // PowerPC does not use [US]DIVREM or other library calls for 535 // operations on regular types which are not otherwise library calls 536 // (i.e. soft float or atomics). If adapting for targets that do, 537 // additional care is required here. 538 539 LibFunc Func; 540 if (!F->hasLocalLinkage() && F->hasName() && LibInfo && 541 LibInfo->getLibFunc(F->getName(), Func) && 542 LibInfo->hasOptimizedCodeGen(Func)) { 543 // Non-read-only functions are never treated as intrinsics. 544 if (!CI->onlyReadsMemory()) 545 return true; 546 547 // Conversion happens only for FP calls. 548 if (!CI->getArgOperand(0)->getType()->isFloatingPointTy()) 549 return true; 550 551 switch (Func) { 552 default: return true; 553 case LibFunc_copysign: 554 case LibFunc_copysignf: 555 continue; // ISD::FCOPYSIGN is never a library call. 556 case LibFunc_copysignl: 557 return true; 558 case LibFunc_fabs: 559 case LibFunc_fabsf: 560 case LibFunc_fabsl: 561 continue; // ISD::FABS is never a library call. 562 case LibFunc_sqrt: 563 case LibFunc_sqrtf: 564 case LibFunc_sqrtl: 565 Opcode = ISD::FSQRT; break; 566 case LibFunc_floor: 567 case LibFunc_floorf: 568 case LibFunc_floorl: 569 Opcode = ISD::FFLOOR; break; 570 case LibFunc_nearbyint: 571 case LibFunc_nearbyintf: 572 case LibFunc_nearbyintl: 573 Opcode = ISD::FNEARBYINT; break; 574 case LibFunc_ceil: 575 case LibFunc_ceilf: 576 case LibFunc_ceill: 577 Opcode = ISD::FCEIL; break; 578 case LibFunc_rint: 579 case LibFunc_rintf: 580 case LibFunc_rintl: 581 Opcode = ISD::FRINT; break; 582 case LibFunc_round: 583 case LibFunc_roundf: 584 case LibFunc_roundl: 585 Opcode = ISD::FROUND; break; 586 case LibFunc_trunc: 587 case LibFunc_truncf: 588 case LibFunc_truncl: 589 Opcode = ISD::FTRUNC; break; 590 case LibFunc_fmin: 591 case LibFunc_fminf: 592 case LibFunc_fminl: 593 Opcode = ISD::FMINNUM; break; 594 case LibFunc_fmax: 595 case LibFunc_fmaxf: 596 case LibFunc_fmaxl: 597 Opcode = ISD::FMAXNUM; break; 598 } 599 } 600 601 if (Opcode) { 602 EVT EVTy = 603 TLI->getValueType(DL, CI->getArgOperand(0)->getType(), true); 604 605 if (EVTy == MVT::Other) 606 return true; 607 608 if (TLI->isOperationLegalOrCustom(Opcode, EVTy)) 609 continue; 610 else if (EVTy.isVector() && 611 TLI->isOperationLegalOrCustom(Opcode, EVTy.getScalarType())) 612 continue; 613 614 return true; 615 } 616 } 617 618 return true; 619 } else if (isa<BinaryOperator>(J) && 620 (J->getType()->getScalarType()->isFP128Ty() || 621 J->getType()->getScalarType()->isPPC_FP128Ty())) { 622 // Most operations on f128 or ppc_f128 values become calls. 623 return true; 624 } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) || 625 isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) { 626 CastInst *CI = cast<CastInst>(J); 627 if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() || 628 CI->getDestTy()->getScalarType()->isPPC_FP128Ty() || 629 isLargeIntegerTy(!TM.isPPC64(), CI->getSrcTy()->getScalarType()) || 630 isLargeIntegerTy(!TM.isPPC64(), CI->getDestTy()->getScalarType())) 631 return true; 632 if (!ST->isISA3_0() && 633 (CI->getSrcTy()->getScalarType()->isHalfTy() || 634 CI->getDestTy()->getScalarType()->isHalfTy())) 635 return true; 636 } else if (isLargeIntegerTy(!TM.isPPC64(), 637 J->getType()->getScalarType()) && 638 (J->getOpcode() == Instruction::UDiv || 639 J->getOpcode() == Instruction::SDiv || 640 J->getOpcode() == Instruction::URem || 641 J->getOpcode() == Instruction::SRem)) { 642 return true; 643 } else if (!TM.isPPC64() && 644 isLargeIntegerTy(false, J->getType()->getScalarType()) && 645 (J->getOpcode() == Instruction::Shl || 646 J->getOpcode() == Instruction::AShr || 647 J->getOpcode() == Instruction::LShr)) { 648 // Only on PPC32, for 128-bit integers (specifically not 64-bit 649 // integers), these might be runtime calls. 650 return true; 651 } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) { 652 // On PowerPC, indirect jumps use the counter register. 653 return true; 654 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) { 655 if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries()) 656 return true; 657 } 658 659 // FREM is always a call. 660 if (J->getOpcode() == Instruction::FRem) 661 return true; 662 663 if (ST->useSoftFloat()) { 664 switch(J->getOpcode()) { 665 case Instruction::FAdd: 666 case Instruction::FSub: 667 case Instruction::FMul: 668 case Instruction::FDiv: 669 case Instruction::FPTrunc: 670 case Instruction::FPExt: 671 case Instruction::FPToUI: 672 case Instruction::FPToSI: 673 case Instruction::UIToFP: 674 case Instruction::SIToFP: 675 case Instruction::FCmp: 676 return true; 677 } 678 } 679 680 for (Value *Operand : J->operands()) 681 if (memAddrUsesCTR(Operand, TM, Visited)) 682 return true; 683 } 684 685 return false; 686 } 687 688 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, 689 AssumptionCache &AC, 690 TargetLibraryInfo *LibInfo, 691 HardwareLoopInfo &HWLoopInfo) { 692 const PPCTargetMachine &TM = ST->getTargetMachine(); 693 TargetSchedModel SchedModel; 694 SchedModel.init(ST); 695 696 // Do not convert small short loops to CTR loop. 697 unsigned ConstTripCount = SE.getSmallConstantTripCount(L); 698 if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) { 699 SmallPtrSet<const Value *, 32> EphValues; 700 CodeMetrics::collectEphemeralValues(L, &AC, EphValues); 701 CodeMetrics Metrics; 702 for (BasicBlock *BB : L->blocks()) 703 Metrics.analyzeBasicBlock(BB, *this, EphValues); 704 // 6 is an approximate latency for the mtctr instruction. 705 if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth())) 706 return false; 707 } 708 709 // We don't want to spill/restore the counter register, and so we don't 710 // want to use the counter register if the loop contains calls. 711 SmallPtrSet<const Value *, 4> Visited; 712 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end(); 713 I != IE; ++I) 714 if (mightUseCTR(*I, LibInfo, Visited)) 715 return false; 716 717 SmallVector<BasicBlock*, 4> ExitingBlocks; 718 L->getExitingBlocks(ExitingBlocks); 719 720 // If there is an exit edge known to be frequently taken, 721 // we should not transform this loop. 722 for (auto &BB : ExitingBlocks) { 723 Instruction *TI = BB->getTerminator(); 724 if (!TI) continue; 725 726 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 727 uint64_t TrueWeight = 0, FalseWeight = 0; 728 if (!BI->isConditional() || 729 !BI->extractProfMetadata(TrueWeight, FalseWeight)) 730 continue; 731 732 // If the exit path is more frequent than the loop path, 733 // we return here without further analysis for this loop. 734 bool TrueIsExit = !L->contains(BI->getSuccessor(0)); 735 if (( TrueIsExit && FalseWeight < TrueWeight) || 736 (!TrueIsExit && FalseWeight > TrueWeight)) 737 return false; 738 } 739 } 740 741 // If an exit block has a PHI that accesses a TLS variable as one of the 742 // incoming values from the loop, we cannot produce a CTR loop because the 743 // address for that value will be computed in the loop. 744 SmallVector<BasicBlock *, 4> ExitBlocks; 745 L->getExitBlocks(ExitBlocks); 746 for (auto &BB : ExitBlocks) { 747 for (auto &PHI : BB->phis()) { 748 for (int Idx = 0, EndIdx = PHI.getNumIncomingValues(); Idx < EndIdx; 749 Idx++) { 750 const BasicBlock *IncomingBB = PHI.getIncomingBlock(Idx); 751 const Value *IncomingValue = PHI.getIncomingValue(Idx); 752 if (L->contains(IncomingBB) && 753 memAddrUsesCTR(IncomingValue, TM, Visited)) 754 return false; 755 } 756 } 757 } 758 759 LLVMContext &C = L->getHeader()->getContext(); 760 HWLoopInfo.CountType = TM.isPPC64() ? 761 Type::getInt64Ty(C) : Type::getInt32Ty(C); 762 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1); 763 return true; 764 } 765 766 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 767 TTI::UnrollingPreferences &UP) { 768 if (ST->getCPUDirective() == PPC::DIR_A2) { 769 // The A2 is in-order with a deep pipeline, and concatenation unrolling 770 // helps expose latency-hiding opportunities to the instruction scheduler. 771 UP.Partial = UP.Runtime = true; 772 773 // We unroll a lot on the A2 (hundreds of instructions), and the benefits 774 // often outweigh the cost of a division to compute the trip count. 775 UP.AllowExpensiveTripCount = true; 776 } 777 778 BaseT::getUnrollingPreferences(L, SE, UP); 779 } 780 781 void PPCTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 782 TTI::PeelingPreferences &PP) { 783 BaseT::getPeelingPreferences(L, SE, PP); 784 } 785 // This function returns true to allow using coldcc calling convention. 786 // Returning true results in coldcc being used for functions which are cold at 787 // all call sites when the callers of the functions are not calling any other 788 // non coldcc functions. 789 bool PPCTTIImpl::useColdCCForColdCall(Function &F) { 790 return EnablePPCColdCC; 791 } 792 793 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) { 794 // On the A2, always unroll aggressively. 795 if (ST->getCPUDirective() == PPC::DIR_A2) 796 return true; 797 798 return LoopHasReductions; 799 } 800 801 PPCTTIImpl::TTI::MemCmpExpansionOptions 802 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const { 803 TTI::MemCmpExpansionOptions Options; 804 Options.LoadSizes = {8, 4, 2, 1}; 805 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize); 806 return Options; 807 } 808 809 bool PPCTTIImpl::enableInterleavedAccessVectorization() { 810 return true; 811 } 812 813 unsigned PPCTTIImpl::getNumberOfRegisters(unsigned ClassID) const { 814 assert(ClassID == GPRRC || ClassID == FPRRC || 815 ClassID == VRRC || ClassID == VSXRC); 816 if (ST->hasVSX()) { 817 assert(ClassID == GPRRC || ClassID == VSXRC || ClassID == VRRC); 818 return ClassID == VSXRC ? 64 : 32; 819 } 820 assert(ClassID == GPRRC || ClassID == FPRRC || ClassID == VRRC); 821 return 32; 822 } 823 824 unsigned PPCTTIImpl::getRegisterClassForType(bool Vector, Type *Ty) const { 825 if (Vector) 826 return ST->hasVSX() ? VSXRC : VRRC; 827 else if (Ty && (Ty->getScalarType()->isFloatTy() || 828 Ty->getScalarType()->isDoubleTy())) 829 return ST->hasVSX() ? VSXRC : FPRRC; 830 else if (Ty && (Ty->getScalarType()->isFP128Ty() || 831 Ty->getScalarType()->isPPC_FP128Ty())) 832 return VRRC; 833 else if (Ty && Ty->getScalarType()->isHalfTy()) 834 return VSXRC; 835 else 836 return GPRRC; 837 } 838 839 const char* PPCTTIImpl::getRegisterClassName(unsigned ClassID) const { 840 841 switch (ClassID) { 842 default: 843 llvm_unreachable("unknown register class"); 844 return "PPC::unknown register class"; 845 case GPRRC: return "PPC::GPRRC"; 846 case FPRRC: return "PPC::FPRRC"; 847 case VRRC: return "PPC::VRRC"; 848 case VSXRC: return "PPC::VSXRC"; 849 } 850 } 851 852 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const { 853 if (Vector) { 854 if (ST->hasAltivec()) return 128; 855 return 0; 856 } 857 858 if (ST->isPPC64()) 859 return 64; 860 return 32; 861 862 } 863 864 unsigned PPCTTIImpl::getCacheLineSize() const { 865 // Check first if the user specified a custom line size. 866 if (CacheLineSize.getNumOccurrences() > 0) 867 return CacheLineSize; 868 869 // Starting with P7 we have a cache line size of 128. 870 unsigned Directive = ST->getCPUDirective(); 871 // Assume that Future CPU has the same cache line size as the others. 872 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 || 873 Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 || 874 Directive == PPC::DIR_PWR_FUTURE) 875 return 128; 876 877 // On other processors return a default of 64 bytes. 878 return 64; 879 } 880 881 unsigned PPCTTIImpl::getPrefetchDistance() const { 882 return 300; 883 } 884 885 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) { 886 unsigned Directive = ST->getCPUDirective(); 887 // The 440 has no SIMD support, but floating-point instructions 888 // have a 5-cycle latency, so unroll by 5x for latency hiding. 889 if (Directive == PPC::DIR_440) 890 return 5; 891 892 // The A2 has no SIMD support, but floating-point instructions 893 // have a 6-cycle latency, so unroll by 6x for latency hiding. 894 if (Directive == PPC::DIR_A2) 895 return 6; 896 897 // FIXME: For lack of any better information, do no harm... 898 if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) 899 return 1; 900 901 // For P7 and P8, floating-point instructions have a 6-cycle latency and 902 // there are two execution units, so unroll by 12x for latency hiding. 903 // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready 904 // FIXME: the same for P10 as previous gen until POWER10 scheduling is ready 905 // Assume that future is the same as the others. 906 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 || 907 Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 || 908 Directive == PPC::DIR_PWR_FUTURE) 909 return 12; 910 911 // For most things, modern systems have two execution units (and 912 // out-of-order execution). 913 return 2; 914 } 915 916 // Adjust the cost of vector instructions on targets which there is overlap 917 // between the vector and scalar units, thereby reducing the overall throughput 918 // of vector code wrt. scalar code. 919 int PPCTTIImpl::vectorCostAdjustment(int Cost, unsigned Opcode, Type *Ty1, 920 Type *Ty2) { 921 if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy()) 922 return Cost; 923 924 std::pair<int, MVT> LT1 = TLI->getTypeLegalizationCost(DL, Ty1); 925 // If type legalization involves splitting the vector, we don't want to 926 // double the cost at every step - only the last step. 927 if (LT1.first != 1 || !LT1.second.isVector()) 928 return Cost; 929 930 int ISD = TLI->InstructionOpcodeToISD(Opcode); 931 if (TLI->isOperationExpand(ISD, LT1.second)) 932 return Cost; 933 934 if (Ty2) { 935 std::pair<int, MVT> LT2 = TLI->getTypeLegalizationCost(DL, Ty2); 936 if (LT2.first != 1 || !LT2.second.isVector()) 937 return Cost; 938 } 939 940 return Cost * 2; 941 } 942 943 int PPCTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 944 TTI::TargetCostKind CostKind, 945 TTI::OperandValueKind Op1Info, 946 TTI::OperandValueKind Op2Info, 947 TTI::OperandValueProperties Opd1PropInfo, 948 TTI::OperandValueProperties Opd2PropInfo, 949 ArrayRef<const Value *> Args, 950 const Instruction *CxtI) { 951 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode"); 952 // TODO: Handle more cost kinds. 953 if (CostKind != TTI::TCK_RecipThroughput) 954 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 955 Op2Info, Opd1PropInfo, 956 Opd2PropInfo, Args, CxtI); 957 958 // Fallback to the default implementation. 959 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 960 Op2Info, 961 Opd1PropInfo, Opd2PropInfo); 962 return vectorCostAdjustment(Cost, Opcode, Ty, nullptr); 963 } 964 965 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, 966 Type *SubTp) { 967 // Legalize the type. 968 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 969 970 // PPC, for both Altivec/VSX, support cheap arbitrary permutations 971 // (at least in the sense that there need only be one non-loop-invariant 972 // instruction). We need one such shuffle instruction for each actual 973 // register (this is not true for arbitrary shuffles, but is true for the 974 // structured types of shuffles covered by TTI::ShuffleKind). 975 return vectorCostAdjustment(LT.first, Instruction::ShuffleVector, Tp, 976 nullptr); 977 } 978 979 int PPCTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) { 980 if (CostKind != TTI::TCK_RecipThroughput) 981 return Opcode == Instruction::PHI ? 0 : 1; 982 // Branches are assumed to be predicted. 983 return CostKind == TTI::TCK_RecipThroughput ? 0 : 1; 984 } 985 986 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 987 TTI::CastContextHint CCH, 988 TTI::TargetCostKind CostKind, 989 const Instruction *I) { 990 assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode"); 991 992 int Cost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I); 993 Cost = vectorCostAdjustment(Cost, Opcode, Dst, Src); 994 // TODO: Allow non-throughput costs that aren't binary. 995 if (CostKind != TTI::TCK_RecipThroughput) 996 return Cost == 0 ? 0 : 1; 997 return Cost; 998 } 999 1000 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, 1001 CmpInst::Predicate VecPred, 1002 TTI::TargetCostKind CostKind, 1003 const Instruction *I) { 1004 int Cost = 1005 BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I); 1006 // TODO: Handle other cost kinds. 1007 if (CostKind != TTI::TCK_RecipThroughput) 1008 return Cost; 1009 return vectorCostAdjustment(Cost, Opcode, ValTy, nullptr); 1010 } 1011 1012 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) { 1013 assert(Val->isVectorTy() && "This must be a vector type"); 1014 1015 int ISD = TLI->InstructionOpcodeToISD(Opcode); 1016 assert(ISD && "Invalid opcode"); 1017 1018 int Cost = BaseT::getVectorInstrCost(Opcode, Val, Index); 1019 Cost = vectorCostAdjustment(Cost, Opcode, Val, nullptr); 1020 1021 if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) { 1022 // Double-precision scalars are already located in index #0 (or #1 if LE). 1023 if (ISD == ISD::EXTRACT_VECTOR_ELT && 1024 Index == (ST->isLittleEndian() ? 1 : 0)) 1025 return 0; 1026 1027 return Cost; 1028 1029 } else if (Val->getScalarType()->isIntegerTy() && Index != -1U) { 1030 if (ST->hasP9Altivec()) { 1031 if (ISD == ISD::INSERT_VECTOR_ELT) 1032 // A move-to VSR and a permute/insert. Assume vector operation cost 1033 // for both (cost will be 2x on P9). 1034 return vectorCostAdjustment(2, Opcode, Val, nullptr); 1035 1036 // It's an extract. Maybe we can do a cheap move-from VSR. 1037 unsigned EltSize = Val->getScalarSizeInBits(); 1038 if (EltSize == 64) { 1039 unsigned MfvsrdIndex = ST->isLittleEndian() ? 1 : 0; 1040 if (Index == MfvsrdIndex) 1041 return 1; 1042 } else if (EltSize == 32) { 1043 unsigned MfvsrwzIndex = ST->isLittleEndian() ? 2 : 1; 1044 if (Index == MfvsrwzIndex) 1045 return 1; 1046 } 1047 1048 // We need a vector extract (or mfvsrld). Assume vector operation cost. 1049 // The cost of the load constant for a vector extract is disregarded 1050 // (invariant, easily schedulable). 1051 return vectorCostAdjustment(1, Opcode, Val, nullptr); 1052 1053 } else if (ST->hasDirectMove()) 1054 // Assume permute has standard cost. 1055 // Assume move-to/move-from VSR have 2x standard cost. 1056 return 3; 1057 } 1058 1059 // Estimated cost of a load-hit-store delay. This was obtained 1060 // experimentally as a minimum needed to prevent unprofitable 1061 // vectorization for the paq8p benchmark. It may need to be 1062 // raised further if other unprofitable cases remain. 1063 unsigned LHSPenalty = 2; 1064 if (ISD == ISD::INSERT_VECTOR_ELT) 1065 LHSPenalty += 7; 1066 1067 // Vector element insert/extract with Altivec is very expensive, 1068 // because they require store and reload with the attendant 1069 // processor stall for load-hit-store. Until VSX is available, 1070 // these need to be estimated as very costly. 1071 if (ISD == ISD::EXTRACT_VECTOR_ELT || 1072 ISD == ISD::INSERT_VECTOR_ELT) 1073 return LHSPenalty + Cost; 1074 1075 return Cost; 1076 } 1077 1078 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, 1079 MaybeAlign Alignment, unsigned AddressSpace, 1080 TTI::TargetCostKind CostKind, 1081 const Instruction *I) { 1082 if (TLI->getValueType(DL, Src, true) == MVT::Other) 1083 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1084 CostKind); 1085 // Legalize the type. 1086 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src); 1087 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) && 1088 "Invalid Opcode"); 1089 1090 int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1091 CostKind); 1092 // TODO: Handle other cost kinds. 1093 if (CostKind != TTI::TCK_RecipThroughput) 1094 return Cost; 1095 1096 Cost = vectorCostAdjustment(Cost, Opcode, Src, nullptr); 1097 1098 bool IsAltivecType = ST->hasAltivec() && 1099 (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 || 1100 LT.second == MVT::v4i32 || LT.second == MVT::v4f32); 1101 bool IsVSXType = ST->hasVSX() && 1102 (LT.second == MVT::v2f64 || LT.second == MVT::v2i64); 1103 1104 // VSX has 32b/64b load instructions. Legalization can handle loading of 1105 // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and 1106 // PPCTargetLowering can't compute the cost appropriately. So here we 1107 // explicitly check this case. 1108 unsigned MemBytes = Src->getPrimitiveSizeInBits(); 1109 if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType && 1110 (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32))) 1111 return 1; 1112 1113 // Aligned loads and stores are easy. 1114 unsigned SrcBytes = LT.second.getStoreSize(); 1115 if (!SrcBytes || !Alignment || *Alignment >= SrcBytes) 1116 return Cost; 1117 1118 // If we can use the permutation-based load sequence, then this is also 1119 // relatively cheap (not counting loop-invariant instructions): one load plus 1120 // one permute (the last load in a series has extra cost, but we're 1121 // neglecting that here). Note that on the P7, we could do unaligned loads 1122 // for Altivec types using the VSX instructions, but that's more expensive 1123 // than using the permutation-based load sequence. On the P8, that's no 1124 // longer true. 1125 if (Opcode == Instruction::Load && (!ST->hasP8Vector() && IsAltivecType) && 1126 *Alignment >= LT.second.getScalarType().getStoreSize()) 1127 return Cost + LT.first; // Add the cost of the permutations. 1128 1129 // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the 1130 // P7, unaligned vector loads are more expensive than the permutation-based 1131 // load sequence, so that might be used instead, but regardless, the net cost 1132 // is about the same (not counting loop-invariant instructions). 1133 if (IsVSXType || (ST->hasVSX() && IsAltivecType)) 1134 return Cost; 1135 1136 // Newer PPC supports unaligned memory access. 1137 if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0)) 1138 return Cost; 1139 1140 // PPC in general does not support unaligned loads and stores. They'll need 1141 // to be decomposed based on the alignment factor. 1142 1143 // Add the cost of each scalar load or store. 1144 assert(Alignment); 1145 Cost += LT.first * ((SrcBytes / Alignment->value()) - 1); 1146 1147 // For a vector type, there is also scalarization overhead (only for 1148 // stores, loads are expanded using the vector-load + permutation sequence, 1149 // which is much less expensive). 1150 if (Src->isVectorTy() && Opcode == Instruction::Store) 1151 for (int i = 0, e = cast<FixedVectorType>(Src)->getNumElements(); i < e; 1152 ++i) 1153 Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i); 1154 1155 return Cost; 1156 } 1157 1158 int PPCTTIImpl::getInterleavedMemoryOpCost( 1159 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 1160 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 1161 bool UseMaskForCond, bool UseMaskForGaps) { 1162 if (UseMaskForCond || UseMaskForGaps) 1163 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 1164 Alignment, AddressSpace, CostKind, 1165 UseMaskForCond, UseMaskForGaps); 1166 1167 assert(isa<VectorType>(VecTy) && 1168 "Expect a vector type for interleaved memory op"); 1169 1170 // Legalize the type. 1171 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy); 1172 1173 // Firstly, the cost of load/store operation. 1174 int Cost = 1175 getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace, 1176 CostKind); 1177 1178 // PPC, for both Altivec/VSX, support cheap arbitrary permutations 1179 // (at least in the sense that there need only be one non-loop-invariant 1180 // instruction). For each result vector, we need one shuffle per incoming 1181 // vector (except that the first shuffle can take two incoming vectors 1182 // because it does not need to take itself). 1183 Cost += Factor*(LT.first-1); 1184 1185 return Cost; 1186 } 1187 1188 unsigned PPCTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 1189 TTI::TargetCostKind CostKind) { 1190 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 1191 } 1192 1193 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, 1194 LoopInfo *LI, DominatorTree *DT, 1195 AssumptionCache *AC, TargetLibraryInfo *LibInfo) { 1196 // Process nested loops first. 1197 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 1198 if (canSaveCmp(*I, BI, SE, LI, DT, AC, LibInfo)) 1199 return false; // Stop search. 1200 1201 HardwareLoopInfo HWLoopInfo(L); 1202 1203 if (!HWLoopInfo.canAnalyze(*LI)) 1204 return false; 1205 1206 if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) 1207 return false; 1208 1209 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT)) 1210 return false; 1211 1212 *BI = HWLoopInfo.ExitBranch; 1213 return true; 1214 } 1215 1216 bool PPCTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1, 1217 TargetTransformInfo::LSRCost &C2) { 1218 // PowerPC default behaviour here is "instruction number 1st priority". 1219 // If LsrNoInsnsCost is set, call default implementation. 1220 if (!LsrNoInsnsCost) 1221 return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, C1.NumIVMuls, 1222 C1.NumBaseAdds, C1.ScaleCost, C1.ImmCost, C1.SetupCost) < 1223 std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, C2.NumIVMuls, 1224 C2.NumBaseAdds, C2.ScaleCost, C2.ImmCost, C2.SetupCost); 1225 else 1226 return TargetTransformInfoImplBase::isLSRCostLess(C1, C2); 1227 } 1228 1229 bool PPCTTIImpl::isNumRegsMajorCostOfLSR() { 1230 return false; 1231 } 1232 1233 bool PPCTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 1234 MemIntrinsicInfo &Info) { 1235 switch (Inst->getIntrinsicID()) { 1236 case Intrinsic::ppc_altivec_lvx: 1237 case Intrinsic::ppc_altivec_lvxl: 1238 case Intrinsic::ppc_altivec_lvebx: 1239 case Intrinsic::ppc_altivec_lvehx: 1240 case Intrinsic::ppc_altivec_lvewx: 1241 case Intrinsic::ppc_vsx_lxvd2x: 1242 case Intrinsic::ppc_vsx_lxvw4x: 1243 case Intrinsic::ppc_vsx_lxvd2x_be: 1244 case Intrinsic::ppc_vsx_lxvw4x_be: 1245 case Intrinsic::ppc_vsx_lxvl: 1246 case Intrinsic::ppc_vsx_lxvll: 1247 case Intrinsic::ppc_vsx_lxvp: { 1248 Info.PtrVal = Inst->getArgOperand(0); 1249 Info.ReadMem = true; 1250 Info.WriteMem = false; 1251 return true; 1252 } 1253 case Intrinsic::ppc_altivec_stvx: 1254 case Intrinsic::ppc_altivec_stvxl: 1255 case Intrinsic::ppc_altivec_stvebx: 1256 case Intrinsic::ppc_altivec_stvehx: 1257 case Intrinsic::ppc_altivec_stvewx: 1258 case Intrinsic::ppc_vsx_stxvd2x: 1259 case Intrinsic::ppc_vsx_stxvw4x: 1260 case Intrinsic::ppc_vsx_stxvd2x_be: 1261 case Intrinsic::ppc_vsx_stxvw4x_be: 1262 case Intrinsic::ppc_vsx_stxvl: 1263 case Intrinsic::ppc_vsx_stxvll: 1264 case Intrinsic::ppc_vsx_stxvp: { 1265 Info.PtrVal = Inst->getArgOperand(1); 1266 Info.ReadMem = false; 1267 Info.WriteMem = true; 1268 return true; 1269 } 1270 default: 1271 break; 1272 } 1273 1274 return false; 1275 } 1276