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