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