xref: /llvm-project/llvm/lib/Target/PowerPC/PPCTargetTransformInfo.cpp (revision 3f78605a8cb121d005c0ad11cce83cf58be983f2)
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 bool PPCTTIImpl::mightUseCTR(BasicBlock *BB, TargetLibraryInfo *LibInfo,
339                              SmallPtrSetImpl<const Value *> &Visited) {
340   const PPCTargetMachine &TM = ST->getTargetMachine();
341 
342   // Loop through the inline asm constraints and look for something that
343   // clobbers ctr.
344   auto asmClobbersCTR = [](InlineAsm *IA) {
345     InlineAsm::ConstraintInfoVector CIV = IA->ParseConstraints();
346     for (unsigned i = 0, ie = CIV.size(); i < ie; ++i) {
347       InlineAsm::ConstraintInfo &C = CIV[i];
348       if (C.Type != InlineAsm::isInput)
349         for (unsigned j = 0, je = C.Codes.size(); j < je; ++j)
350           if (StringRef(C.Codes[j]).equals_lower("{ctr}"))
351             return true;
352     }
353     return false;
354   };
355 
356   // Determining the address of a TLS variable results in a function call in
357   // certain TLS models.
358   std::function<bool(const Value *)> memAddrUsesCTR =
359       [&memAddrUsesCTR, &TM, &Visited](const Value *MemAddr) -> bool {
360     // No need to traverse again if we already checked this operand.
361     if (!Visited.insert(MemAddr).second)
362       return false;
363     const auto *GV = dyn_cast<GlobalValue>(MemAddr);
364     if (!GV) {
365       // Recurse to check for constants that refer to TLS global variables.
366       if (const auto *CV = dyn_cast<Constant>(MemAddr))
367         for (const auto &CO : CV->operands())
368           if (memAddrUsesCTR(CO))
369             return true;
370 
371       return false;
372     }
373 
374     if (!GV->isThreadLocal())
375       return false;
376     TLSModel::Model Model = TM.getTLSModel(GV);
377     return Model == TLSModel::GeneralDynamic ||
378       Model == TLSModel::LocalDynamic;
379   };
380 
381   auto isLargeIntegerTy = [](bool Is32Bit, Type *Ty) {
382     if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
383       return ITy->getBitWidth() > (Is32Bit ? 32U : 64U);
384 
385     return false;
386   };
387 
388   for (BasicBlock::iterator J = BB->begin(), JE = BB->end();
389        J != JE; ++J) {
390     if (CallInst *CI = dyn_cast<CallInst>(J)) {
391       // Inline ASM is okay, unless it clobbers the ctr register.
392       if (InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand())) {
393         if (asmClobbersCTR(IA))
394           return true;
395         continue;
396       }
397 
398       if (Function *F = CI->getCalledFunction()) {
399         // Most intrinsics don't become function calls, but some might.
400         // sin, cos, exp and log are always calls.
401         unsigned Opcode = 0;
402         if (F->getIntrinsicID() != Intrinsic::not_intrinsic) {
403           switch (F->getIntrinsicID()) {
404           default: continue;
405           // If we have a call to loop_decrement or set_loop_iterations,
406           // we're definitely using CTR.
407           case Intrinsic::set_loop_iterations:
408           case Intrinsic::loop_decrement:
409             return true;
410 
411           // Binary operations on 128-bit value will use CTR.
412           case Intrinsic::experimental_constrained_fadd:
413           case Intrinsic::experimental_constrained_fsub:
414           case Intrinsic::experimental_constrained_fmul:
415           case Intrinsic::experimental_constrained_fdiv:
416           case Intrinsic::experimental_constrained_frem:
417             if (F->getType()->getScalarType()->isFP128Ty() ||
418                 F->getType()->getScalarType()->isPPC_FP128Ty())
419               return true;
420             break;
421 
422           case Intrinsic::experimental_constrained_fptosi:
423           case Intrinsic::experimental_constrained_fptoui:
424           case Intrinsic::experimental_constrained_sitofp:
425           case Intrinsic::experimental_constrained_uitofp: {
426             Type *SrcType = CI->getArgOperand(0)->getType()->getScalarType();
427             Type *DstType = CI->getType()->getScalarType();
428             if (SrcType->isPPC_FP128Ty() || DstType->isPPC_FP128Ty() ||
429                 isLargeIntegerTy(!TM.isPPC64(), SrcType) ||
430                 isLargeIntegerTy(!TM.isPPC64(), DstType))
431               return true;
432             break;
433           }
434 
435           // Exclude eh_sjlj_setjmp; we don't need to exclude eh_sjlj_longjmp
436           // because, although it does clobber the counter register, the
437           // control can't then return to inside the loop unless there is also
438           // an eh_sjlj_setjmp.
439           case Intrinsic::eh_sjlj_setjmp:
440 
441           case Intrinsic::memcpy:
442           case Intrinsic::memmove:
443           case Intrinsic::memset:
444           case Intrinsic::powi:
445           case Intrinsic::log:
446           case Intrinsic::log2:
447           case Intrinsic::log10:
448           case Intrinsic::exp:
449           case Intrinsic::exp2:
450           case Intrinsic::pow:
451           case Intrinsic::sin:
452           case Intrinsic::cos:
453           case Intrinsic::experimental_constrained_powi:
454           case Intrinsic::experimental_constrained_log:
455           case Intrinsic::experimental_constrained_log2:
456           case Intrinsic::experimental_constrained_log10:
457           case Intrinsic::experimental_constrained_exp:
458           case Intrinsic::experimental_constrained_exp2:
459           case Intrinsic::experimental_constrained_pow:
460           case Intrinsic::experimental_constrained_sin:
461           case Intrinsic::experimental_constrained_cos:
462             return true;
463           case Intrinsic::copysign:
464             if (CI->getArgOperand(0)->getType()->getScalarType()->
465                 isPPC_FP128Ty())
466               return true;
467             else
468               continue; // ISD::FCOPYSIGN is never a library call.
469           case Intrinsic::fma:                Opcode = ISD::FMA;        break;
470           case Intrinsic::sqrt:               Opcode = ISD::FSQRT;      break;
471           case Intrinsic::floor:              Opcode = ISD::FFLOOR;     break;
472           case Intrinsic::ceil:               Opcode = ISD::FCEIL;      break;
473           case Intrinsic::trunc:              Opcode = ISD::FTRUNC;     break;
474           case Intrinsic::rint:               Opcode = ISD::FRINT;      break;
475           case Intrinsic::lrint:              Opcode = ISD::LRINT;      break;
476           case Intrinsic::llrint:             Opcode = ISD::LLRINT;     break;
477           case Intrinsic::nearbyint:          Opcode = ISD::FNEARBYINT; break;
478           case Intrinsic::round:              Opcode = ISD::FROUND;     break;
479           case Intrinsic::lround:             Opcode = ISD::LROUND;     break;
480           case Intrinsic::llround:            Opcode = ISD::LLROUND;    break;
481           case Intrinsic::minnum:             Opcode = ISD::FMINNUM;    break;
482           case Intrinsic::maxnum:             Opcode = ISD::FMAXNUM;    break;
483           case Intrinsic::experimental_constrained_fcmp:
484             Opcode = ISD::STRICT_FSETCC;
485             break;
486           case Intrinsic::experimental_constrained_fcmps:
487             Opcode = ISD::STRICT_FSETCCS;
488             break;
489           case Intrinsic::experimental_constrained_fma:
490             Opcode = ISD::STRICT_FMA;
491             break;
492           case Intrinsic::experimental_constrained_sqrt:
493             Opcode = ISD::STRICT_FSQRT;
494             break;
495           case Intrinsic::experimental_constrained_floor:
496             Opcode = ISD::STRICT_FFLOOR;
497             break;
498           case Intrinsic::experimental_constrained_ceil:
499             Opcode = ISD::STRICT_FCEIL;
500             break;
501           case Intrinsic::experimental_constrained_trunc:
502             Opcode = ISD::STRICT_FTRUNC;
503             break;
504           case Intrinsic::experimental_constrained_rint:
505             Opcode = ISD::STRICT_FRINT;
506             break;
507           case Intrinsic::experimental_constrained_lrint:
508             Opcode = ISD::STRICT_LRINT;
509             break;
510           case Intrinsic::experimental_constrained_llrint:
511             Opcode = ISD::STRICT_LLRINT;
512             break;
513           case Intrinsic::experimental_constrained_nearbyint:
514             Opcode = ISD::STRICT_FNEARBYINT;
515             break;
516           case Intrinsic::experimental_constrained_round:
517             Opcode = ISD::STRICT_FROUND;
518             break;
519           case Intrinsic::experimental_constrained_lround:
520             Opcode = ISD::STRICT_LROUND;
521             break;
522           case Intrinsic::experimental_constrained_llround:
523             Opcode = ISD::STRICT_LLROUND;
524             break;
525           case Intrinsic::experimental_constrained_minnum:
526             Opcode = ISD::STRICT_FMINNUM;
527             break;
528           case Intrinsic::experimental_constrained_maxnum:
529             Opcode = ISD::STRICT_FMAXNUM;
530             break;
531           case Intrinsic::umul_with_overflow: Opcode = ISD::UMULO;      break;
532           case Intrinsic::smul_with_overflow: Opcode = ISD::SMULO;      break;
533           }
534         }
535 
536         // PowerPC does not use [US]DIVREM or other library calls for
537         // operations on regular types which are not otherwise library calls
538         // (i.e. soft float or atomics). If adapting for targets that do,
539         // additional care is required here.
540 
541         LibFunc Func;
542         if (!F->hasLocalLinkage() && F->hasName() && LibInfo &&
543             LibInfo->getLibFunc(F->getName(), Func) &&
544             LibInfo->hasOptimizedCodeGen(Func)) {
545           // Non-read-only functions are never treated as intrinsics.
546           if (!CI->onlyReadsMemory())
547             return true;
548 
549           // Conversion happens only for FP calls.
550           if (!CI->getArgOperand(0)->getType()->isFloatingPointTy())
551             return true;
552 
553           switch (Func) {
554           default: return true;
555           case LibFunc_copysign:
556           case LibFunc_copysignf:
557             continue; // ISD::FCOPYSIGN is never a library call.
558           case LibFunc_copysignl:
559             return true;
560           case LibFunc_fabs:
561           case LibFunc_fabsf:
562           case LibFunc_fabsl:
563             continue; // ISD::FABS is never a library call.
564           case LibFunc_sqrt:
565           case LibFunc_sqrtf:
566           case LibFunc_sqrtl:
567             Opcode = ISD::FSQRT; break;
568           case LibFunc_floor:
569           case LibFunc_floorf:
570           case LibFunc_floorl:
571             Opcode = ISD::FFLOOR; break;
572           case LibFunc_nearbyint:
573           case LibFunc_nearbyintf:
574           case LibFunc_nearbyintl:
575             Opcode = ISD::FNEARBYINT; break;
576           case LibFunc_ceil:
577           case LibFunc_ceilf:
578           case LibFunc_ceill:
579             Opcode = ISD::FCEIL; break;
580           case LibFunc_rint:
581           case LibFunc_rintf:
582           case LibFunc_rintl:
583             Opcode = ISD::FRINT; break;
584           case LibFunc_round:
585           case LibFunc_roundf:
586           case LibFunc_roundl:
587             Opcode = ISD::FROUND; break;
588           case LibFunc_trunc:
589           case LibFunc_truncf:
590           case LibFunc_truncl:
591             Opcode = ISD::FTRUNC; break;
592           case LibFunc_fmin:
593           case LibFunc_fminf:
594           case LibFunc_fminl:
595             Opcode = ISD::FMINNUM; break;
596           case LibFunc_fmax:
597           case LibFunc_fmaxf:
598           case LibFunc_fmaxl:
599             Opcode = ISD::FMAXNUM; break;
600           }
601         }
602 
603         if (Opcode) {
604           EVT EVTy =
605               TLI->getValueType(DL, CI->getArgOperand(0)->getType(), true);
606 
607           if (EVTy == MVT::Other)
608             return true;
609 
610           if (TLI->isOperationLegalOrCustom(Opcode, EVTy))
611             continue;
612           else if (EVTy.isVector() &&
613                    TLI->isOperationLegalOrCustom(Opcode, EVTy.getScalarType()))
614             continue;
615 
616           return true;
617         }
618       }
619 
620       return true;
621     } else if (isa<BinaryOperator>(J) &&
622                (J->getType()->getScalarType()->isFP128Ty() ||
623                 J->getType()->getScalarType()->isPPC_FP128Ty())) {
624       // Most operations on f128 or ppc_f128 values become calls.
625       return true;
626     } else if (isa<UIToFPInst>(J) || isa<SIToFPInst>(J) ||
627                isa<FPToUIInst>(J) || isa<FPToSIInst>(J)) {
628       CastInst *CI = cast<CastInst>(J);
629       if (CI->getSrcTy()->getScalarType()->isPPC_FP128Ty() ||
630           CI->getDestTy()->getScalarType()->isPPC_FP128Ty() ||
631           isLargeIntegerTy(!TM.isPPC64(), CI->getSrcTy()->getScalarType()) ||
632           isLargeIntegerTy(!TM.isPPC64(), CI->getDestTy()->getScalarType()))
633         return true;
634     } else if (isLargeIntegerTy(!TM.isPPC64(),
635                                 J->getType()->getScalarType()) &&
636                (J->getOpcode() == Instruction::UDiv ||
637                 J->getOpcode() == Instruction::SDiv ||
638                 J->getOpcode() == Instruction::URem ||
639                 J->getOpcode() == Instruction::SRem)) {
640       return true;
641     } else if (!TM.isPPC64() &&
642                isLargeIntegerTy(false, J->getType()->getScalarType()) &&
643                (J->getOpcode() == Instruction::Shl ||
644                 J->getOpcode() == Instruction::AShr ||
645                 J->getOpcode() == Instruction::LShr)) {
646       // Only on PPC32, for 128-bit integers (specifically not 64-bit
647       // integers), these might be runtime calls.
648       return true;
649     } else if (isa<IndirectBrInst>(J) || isa<InvokeInst>(J)) {
650       // On PowerPC, indirect jumps use the counter register.
651       return true;
652     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(J)) {
653       if (SI->getNumCases() + 1 >= (unsigned)TLI->getMinimumJumpTableEntries())
654         return true;
655     }
656 
657     // FREM is always a call.
658     if (J->getOpcode() == Instruction::FRem)
659       return true;
660 
661     if (ST->useSoftFloat()) {
662       switch(J->getOpcode()) {
663       case Instruction::FAdd:
664       case Instruction::FSub:
665       case Instruction::FMul:
666       case Instruction::FDiv:
667       case Instruction::FPTrunc:
668       case Instruction::FPExt:
669       case Instruction::FPToUI:
670       case Instruction::FPToSI:
671       case Instruction::UIToFP:
672       case Instruction::SIToFP:
673       case Instruction::FCmp:
674         return true;
675       }
676     }
677 
678     for (Value *Operand : J->operands())
679       if (memAddrUsesCTR(Operand))
680         return true;
681   }
682 
683   return false;
684 }
685 
686 bool PPCTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
687                                           AssumptionCache &AC,
688                                           TargetLibraryInfo *LibInfo,
689                                           HardwareLoopInfo &HWLoopInfo) {
690   const PPCTargetMachine &TM = ST->getTargetMachine();
691   TargetSchedModel SchedModel;
692   SchedModel.init(ST);
693 
694   // Do not convert small short loops to CTR loop.
695   unsigned ConstTripCount = SE.getSmallConstantTripCount(L);
696   if (ConstTripCount && ConstTripCount < SmallCTRLoopThreshold) {
697     SmallPtrSet<const Value *, 32> EphValues;
698     CodeMetrics::collectEphemeralValues(L, &AC, EphValues);
699     CodeMetrics Metrics;
700     for (BasicBlock *BB : L->blocks())
701       Metrics.analyzeBasicBlock(BB, *this, EphValues);
702     // 6 is an approximate latency for the mtctr instruction.
703     if (Metrics.NumInsts <= (6 * SchedModel.getIssueWidth()))
704       return false;
705   }
706 
707   // We don't want to spill/restore the counter register, and so we don't
708   // want to use the counter register if the loop contains calls.
709   SmallPtrSet<const Value *, 4> Visited;
710   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
711        I != IE; ++I)
712     if (mightUseCTR(*I, LibInfo, Visited))
713       return false;
714 
715   SmallVector<BasicBlock*, 4> ExitingBlocks;
716   L->getExitingBlocks(ExitingBlocks);
717 
718   // If there is an exit edge known to be frequently taken,
719   // we should not transform this loop.
720   for (auto &BB : ExitingBlocks) {
721     Instruction *TI = BB->getTerminator();
722     if (!TI) continue;
723 
724     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
725       uint64_t TrueWeight = 0, FalseWeight = 0;
726       if (!BI->isConditional() ||
727           !BI->extractProfMetadata(TrueWeight, FalseWeight))
728         continue;
729 
730       // If the exit path is more frequent than the loop path,
731       // we return here without further analysis for this loop.
732       bool TrueIsExit = !L->contains(BI->getSuccessor(0));
733       if (( TrueIsExit && FalseWeight < TrueWeight) ||
734           (!TrueIsExit && FalseWeight > TrueWeight))
735         return false;
736     }
737   }
738 
739   LLVMContext &C = L->getHeader()->getContext();
740   HWLoopInfo.CountType = TM.isPPC64() ?
741     Type::getInt64Ty(C) : Type::getInt32Ty(C);
742   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
743   return true;
744 }
745 
746 void PPCTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
747                                          TTI::UnrollingPreferences &UP) {
748   if (ST->getCPUDirective() == PPC::DIR_A2) {
749     // The A2 is in-order with a deep pipeline, and concatenation unrolling
750     // helps expose latency-hiding opportunities to the instruction scheduler.
751     UP.Partial = UP.Runtime = true;
752 
753     // We unroll a lot on the A2 (hundreds of instructions), and the benefits
754     // often outweigh the cost of a division to compute the trip count.
755     UP.AllowExpensiveTripCount = true;
756   }
757 
758   BaseT::getUnrollingPreferences(L, SE, UP);
759 }
760 
761 void PPCTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
762                                        TTI::PeelingPreferences &PP) {
763   BaseT::getPeelingPreferences(L, SE, PP);
764 }
765 // This function returns true to allow using coldcc calling convention.
766 // Returning true results in coldcc being used for functions which are cold at
767 // all call sites when the callers of the functions are not calling any other
768 // non coldcc functions.
769 bool PPCTTIImpl::useColdCCForColdCall(Function &F) {
770   return EnablePPCColdCC;
771 }
772 
773 bool PPCTTIImpl::enableAggressiveInterleaving(bool LoopHasReductions) {
774   // On the A2, always unroll aggressively.
775   if (ST->getCPUDirective() == PPC::DIR_A2)
776     return true;
777 
778   return LoopHasReductions;
779 }
780 
781 PPCTTIImpl::TTI::MemCmpExpansionOptions
782 PPCTTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
783   TTI::MemCmpExpansionOptions Options;
784   Options.LoadSizes = {8, 4, 2, 1};
785   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
786   return Options;
787 }
788 
789 bool PPCTTIImpl::enableInterleavedAccessVectorization() {
790   return true;
791 }
792 
793 unsigned PPCTTIImpl::getNumberOfRegisters(unsigned ClassID) const {
794   assert(ClassID == GPRRC || ClassID == FPRRC ||
795          ClassID == VRRC || ClassID == VSXRC);
796   if (ST->hasVSX()) {
797     assert(ClassID == GPRRC || ClassID == VSXRC || ClassID == VRRC);
798     return ClassID == VSXRC ? 64 : 32;
799   }
800   assert(ClassID == GPRRC || ClassID == FPRRC || ClassID == VRRC);
801   return 32;
802 }
803 
804 unsigned PPCTTIImpl::getRegisterClassForType(bool Vector, Type *Ty) const {
805   if (Vector)
806     return ST->hasVSX() ? VSXRC : VRRC;
807   else if (Ty && (Ty->getScalarType()->isFloatTy() ||
808                   Ty->getScalarType()->isDoubleTy()))
809     return ST->hasVSX() ? VSXRC : FPRRC;
810   else if (Ty && (Ty->getScalarType()->isFP128Ty() ||
811                   Ty->getScalarType()->isPPC_FP128Ty()))
812     return VRRC;
813   else if (Ty && Ty->getScalarType()->isHalfTy())
814     return VSXRC;
815   else
816     return GPRRC;
817 }
818 
819 const char* PPCTTIImpl::getRegisterClassName(unsigned ClassID) const {
820 
821   switch (ClassID) {
822     default:
823       llvm_unreachable("unknown register class");
824       return "PPC::unknown register class";
825     case GPRRC:       return "PPC::GPRRC";
826     case FPRRC:       return "PPC::FPRRC";
827     case VRRC:        return "PPC::VRRC";
828     case VSXRC:       return "PPC::VSXRC";
829   }
830 }
831 
832 unsigned PPCTTIImpl::getRegisterBitWidth(bool Vector) const {
833   if (Vector) {
834     if (ST->hasAltivec()) return 128;
835     return 0;
836   }
837 
838   if (ST->isPPC64())
839     return 64;
840   return 32;
841 
842 }
843 
844 unsigned PPCTTIImpl::getCacheLineSize() const {
845   // Check first if the user specified a custom line size.
846   if (CacheLineSize.getNumOccurrences() > 0)
847     return CacheLineSize;
848 
849   // Starting with P7 we have a cache line size of 128.
850   unsigned Directive = ST->getCPUDirective();
851   // Assume that Future CPU has the same cache line size as the others.
852   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
853       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
854       Directive == PPC::DIR_PWR_FUTURE)
855     return 128;
856 
857   // On other processors return a default of 64 bytes.
858   return 64;
859 }
860 
861 unsigned PPCTTIImpl::getPrefetchDistance() const {
862   return 300;
863 }
864 
865 unsigned PPCTTIImpl::getMaxInterleaveFactor(unsigned VF) {
866   unsigned Directive = ST->getCPUDirective();
867   // The 440 has no SIMD support, but floating-point instructions
868   // have a 5-cycle latency, so unroll by 5x for latency hiding.
869   if (Directive == PPC::DIR_440)
870     return 5;
871 
872   // The A2 has no SIMD support, but floating-point instructions
873   // have a 6-cycle latency, so unroll by 6x for latency hiding.
874   if (Directive == PPC::DIR_A2)
875     return 6;
876 
877   // FIXME: For lack of any better information, do no harm...
878   if (Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500)
879     return 1;
880 
881   // For P7 and P8, floating-point instructions have a 6-cycle latency and
882   // there are two execution units, so unroll by 12x for latency hiding.
883   // FIXME: the same for P9 as previous gen until POWER9 scheduling is ready
884   // FIXME: the same for P10 as previous gen until POWER10 scheduling is ready
885   // Assume that future is the same as the others.
886   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8 ||
887       Directive == PPC::DIR_PWR9 || Directive == PPC::DIR_PWR10 ||
888       Directive == PPC::DIR_PWR_FUTURE)
889     return 12;
890 
891   // For most things, modern systems have two execution units (and
892   // out-of-order execution).
893   return 2;
894 }
895 
896 // Adjust the cost of vector instructions on targets which there is overlap
897 // between the vector and scalar units, thereby reducing the overall throughput
898 // of vector code wrt. scalar code.
899 int PPCTTIImpl::vectorCostAdjustment(int Cost, unsigned Opcode, Type *Ty1,
900                                      Type *Ty2) {
901   if (!ST->vectorsUseTwoUnits() || !Ty1->isVectorTy())
902     return Cost;
903 
904   std::pair<int, MVT> LT1 = TLI->getTypeLegalizationCost(DL, Ty1);
905   // If type legalization involves splitting the vector, we don't want to
906   // double the cost at every step - only the last step.
907   if (LT1.first != 1 || !LT1.second.isVector())
908     return Cost;
909 
910   int ISD = TLI->InstructionOpcodeToISD(Opcode);
911   if (TLI->isOperationExpand(ISD, LT1.second))
912     return Cost;
913 
914   if (Ty2) {
915     std::pair<int, MVT> LT2 = TLI->getTypeLegalizationCost(DL, Ty2);
916     if (LT2.first != 1 || !LT2.second.isVector())
917       return Cost;
918   }
919 
920   return Cost * 2;
921 }
922 
923 int PPCTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
924                                        TTI::TargetCostKind CostKind,
925                                        TTI::OperandValueKind Op1Info,
926                                        TTI::OperandValueKind Op2Info,
927                                        TTI::OperandValueProperties Opd1PropInfo,
928                                        TTI::OperandValueProperties Opd2PropInfo,
929                                        ArrayRef<const Value *> Args,
930                                        const Instruction *CxtI) {
931   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
932   // TODO: Handle more cost kinds.
933   if (CostKind != TTI::TCK_RecipThroughput)
934     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
935                                          Op2Info, Opd1PropInfo,
936                                          Opd2PropInfo, Args, CxtI);
937 
938   // Fallback to the default implementation.
939   int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
940                                            Op2Info,
941                                            Opd1PropInfo, Opd2PropInfo);
942   return vectorCostAdjustment(Cost, Opcode, Ty, nullptr);
943 }
944 
945 int PPCTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
946                                Type *SubTp) {
947   // Legalize the type.
948   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
949 
950   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
951   // (at least in the sense that there need only be one non-loop-invariant
952   // instruction). We need one such shuffle instruction for each actual
953   // register (this is not true for arbitrary shuffles, but is true for the
954   // structured types of shuffles covered by TTI::ShuffleKind).
955   return vectorCostAdjustment(LT.first, Instruction::ShuffleVector, Tp,
956                               nullptr);
957 }
958 
959 int PPCTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) {
960   if (CostKind != TTI::TCK_RecipThroughput)
961     return Opcode == Instruction::PHI ? 0 : 1;
962   // Branches are assumed to be predicted.
963   return CostKind == TTI::TCK_RecipThroughput ? 0 : 1;
964 }
965 
966 int PPCTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
967                                  TTI::CastContextHint CCH,
968                                  TTI::TargetCostKind CostKind,
969                                  const Instruction *I) {
970   assert(TLI->InstructionOpcodeToISD(Opcode) && "Invalid opcode");
971 
972   int Cost = BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
973   Cost = vectorCostAdjustment(Cost, Opcode, Dst, Src);
974   // TODO: Allow non-throughput costs that aren't binary.
975   if (CostKind != TTI::TCK_RecipThroughput)
976     return Cost == 0 ? 0 : 1;
977   return Cost;
978 }
979 
980 int PPCTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
981                                    CmpInst::Predicate VecPred,
982                                    TTI::TargetCostKind CostKind,
983                                    const Instruction *I) {
984   int Cost =
985       BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
986   // TODO: Handle other cost kinds.
987   if (CostKind != TTI::TCK_RecipThroughput)
988     return Cost;
989   return vectorCostAdjustment(Cost, Opcode, ValTy, nullptr);
990 }
991 
992 int PPCTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
993   assert(Val->isVectorTy() && "This must be a vector type");
994 
995   int ISD = TLI->InstructionOpcodeToISD(Opcode);
996   assert(ISD && "Invalid opcode");
997 
998   int Cost = BaseT::getVectorInstrCost(Opcode, Val, Index);
999   Cost = vectorCostAdjustment(Cost, Opcode, Val, nullptr);
1000 
1001   if (ST->hasVSX() && Val->getScalarType()->isDoubleTy()) {
1002     // Double-precision scalars are already located in index #0 (or #1 if LE).
1003     if (ISD == ISD::EXTRACT_VECTOR_ELT &&
1004         Index == (ST->isLittleEndian() ? 1 : 0))
1005       return 0;
1006 
1007     return Cost;
1008 
1009   } else if (Val->getScalarType()->isIntegerTy() && Index != -1U) {
1010     if (ST->hasP9Altivec()) {
1011       if (ISD == ISD::INSERT_VECTOR_ELT)
1012         // A move-to VSR and a permute/insert.  Assume vector operation cost
1013         // for both (cost will be 2x on P9).
1014         return vectorCostAdjustment(2, Opcode, Val, nullptr);
1015 
1016       // It's an extract.  Maybe we can do a cheap move-from VSR.
1017       unsigned EltSize = Val->getScalarSizeInBits();
1018       if (EltSize == 64) {
1019         unsigned MfvsrdIndex = ST->isLittleEndian() ? 1 : 0;
1020         if (Index == MfvsrdIndex)
1021           return 1;
1022       } else if (EltSize == 32) {
1023         unsigned MfvsrwzIndex = ST->isLittleEndian() ? 2 : 1;
1024         if (Index == MfvsrwzIndex)
1025           return 1;
1026       }
1027 
1028       // We need a vector extract (or mfvsrld).  Assume vector operation cost.
1029       // The cost of the load constant for a vector extract is disregarded
1030       // (invariant, easily schedulable).
1031       return vectorCostAdjustment(1, Opcode, Val, nullptr);
1032 
1033     } else if (ST->hasDirectMove())
1034       // Assume permute has standard cost.
1035       // Assume move-to/move-from VSR have 2x standard cost.
1036       return 3;
1037   }
1038 
1039   // Estimated cost of a load-hit-store delay.  This was obtained
1040   // experimentally as a minimum needed to prevent unprofitable
1041   // vectorization for the paq8p benchmark.  It may need to be
1042   // raised further if other unprofitable cases remain.
1043   unsigned LHSPenalty = 2;
1044   if (ISD == ISD::INSERT_VECTOR_ELT)
1045     LHSPenalty += 7;
1046 
1047   // Vector element insert/extract with Altivec is very expensive,
1048   // because they require store and reload with the attendant
1049   // processor stall for load-hit-store.  Until VSX is available,
1050   // these need to be estimated as very costly.
1051   if (ISD == ISD::EXTRACT_VECTOR_ELT ||
1052       ISD == ISD::INSERT_VECTOR_ELT)
1053     return LHSPenalty + Cost;
1054 
1055   return Cost;
1056 }
1057 
1058 int PPCTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1059                                 MaybeAlign Alignment, unsigned AddressSpace,
1060                                 TTI::TargetCostKind CostKind,
1061                                 const Instruction *I) {
1062   if (TLI->getValueType(DL, Src,  true) == MVT::Other)
1063     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1064                                   CostKind);
1065   // Legalize the type.
1066   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1067   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
1068          "Invalid Opcode");
1069 
1070   int Cost = BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1071                                     CostKind);
1072   // TODO: Handle other cost kinds.
1073   if (CostKind != TTI::TCK_RecipThroughput)
1074     return Cost;
1075 
1076   Cost = vectorCostAdjustment(Cost, Opcode, Src, nullptr);
1077 
1078   bool IsAltivecType = ST->hasAltivec() &&
1079                        (LT.second == MVT::v16i8 || LT.second == MVT::v8i16 ||
1080                         LT.second == MVT::v4i32 || LT.second == MVT::v4f32);
1081   bool IsVSXType = ST->hasVSX() &&
1082                    (LT.second == MVT::v2f64 || LT.second == MVT::v2i64);
1083 
1084   // VSX has 32b/64b load instructions. Legalization can handle loading of
1085   // 32b/64b to VSR correctly and cheaply. But BaseT::getMemoryOpCost and
1086   // PPCTargetLowering can't compute the cost appropriately. So here we
1087   // explicitly check this case.
1088   unsigned MemBytes = Src->getPrimitiveSizeInBits();
1089   if (Opcode == Instruction::Load && ST->hasVSX() && IsAltivecType &&
1090       (MemBytes == 64 || (ST->hasP8Vector() && MemBytes == 32)))
1091     return 1;
1092 
1093   // Aligned loads and stores are easy.
1094   unsigned SrcBytes = LT.second.getStoreSize();
1095   if (!SrcBytes || !Alignment || *Alignment >= SrcBytes)
1096     return Cost;
1097 
1098   // If we can use the permutation-based load sequence, then this is also
1099   // relatively cheap (not counting loop-invariant instructions): one load plus
1100   // one permute (the last load in a series has extra cost, but we're
1101   // neglecting that here). Note that on the P7, we could do unaligned loads
1102   // for Altivec types using the VSX instructions, but that's more expensive
1103   // than using the permutation-based load sequence. On the P8, that's no
1104   // longer true.
1105   if (Opcode == Instruction::Load && (!ST->hasP8Vector() && IsAltivecType) &&
1106       *Alignment >= LT.second.getScalarType().getStoreSize())
1107     return Cost + LT.first; // Add the cost of the permutations.
1108 
1109   // For VSX, we can do unaligned loads and stores on Altivec/VSX types. On the
1110   // P7, unaligned vector loads are more expensive than the permutation-based
1111   // load sequence, so that might be used instead, but regardless, the net cost
1112   // is about the same (not counting loop-invariant instructions).
1113   if (IsVSXType || (ST->hasVSX() && IsAltivecType))
1114     return Cost;
1115 
1116   // Newer PPC supports unaligned memory access.
1117   if (TLI->allowsMisalignedMemoryAccesses(LT.second, 0))
1118     return Cost;
1119 
1120   // PPC in general does not support unaligned loads and stores. They'll need
1121   // to be decomposed based on the alignment factor.
1122 
1123   // Add the cost of each scalar load or store.
1124   assert(Alignment);
1125   Cost += LT.first * ((SrcBytes / Alignment->value()) - 1);
1126 
1127   // For a vector type, there is also scalarization overhead (only for
1128   // stores, loads are expanded using the vector-load + permutation sequence,
1129   // which is much less expensive).
1130   if (Src->isVectorTy() && Opcode == Instruction::Store)
1131     for (int i = 0, e = cast<FixedVectorType>(Src)->getNumElements(); i < e;
1132          ++i)
1133       Cost += getVectorInstrCost(Instruction::ExtractElement, Src, i);
1134 
1135   return Cost;
1136 }
1137 
1138 int PPCTTIImpl::getInterleavedMemoryOpCost(
1139     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1140     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1141     bool UseMaskForCond, bool UseMaskForGaps) {
1142   if (UseMaskForCond || UseMaskForGaps)
1143     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1144                                              Alignment, AddressSpace, CostKind,
1145                                              UseMaskForCond, UseMaskForGaps);
1146 
1147   assert(isa<VectorType>(VecTy) &&
1148          "Expect a vector type for interleaved memory op");
1149 
1150   // Legalize the type.
1151   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, VecTy);
1152 
1153   // Firstly, the cost of load/store operation.
1154   int Cost =
1155       getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace,
1156                       CostKind);
1157 
1158   // PPC, for both Altivec/VSX, support cheap arbitrary permutations
1159   // (at least in the sense that there need only be one non-loop-invariant
1160   // instruction). For each result vector, we need one shuffle per incoming
1161   // vector (except that the first shuffle can take two incoming vectors
1162   // because it does not need to take itself).
1163   Cost += Factor*(LT.first-1);
1164 
1165   return Cost;
1166 }
1167 
1168 unsigned PPCTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1169                                            TTI::TargetCostKind CostKind) {
1170   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1171 }
1172 
1173 bool PPCTTIImpl::canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
1174                             LoopInfo *LI, DominatorTree *DT,
1175                             AssumptionCache *AC, TargetLibraryInfo *LibInfo) {
1176   // Process nested loops first.
1177   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
1178     if (canSaveCmp(*I, BI, SE, LI, DT, AC, LibInfo))
1179       return false; // Stop search.
1180 
1181   HardwareLoopInfo HWLoopInfo(L);
1182 
1183   if (!HWLoopInfo.canAnalyze(*LI))
1184     return false;
1185 
1186   if (!isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo))
1187     return false;
1188 
1189   if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT))
1190     return false;
1191 
1192   *BI = HWLoopInfo.ExitBranch;
1193   return true;
1194 }
1195 
1196 bool PPCTTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
1197                                TargetTransformInfo::LSRCost &C2) {
1198   // PowerPC default behaviour here is "instruction number 1st priority".
1199   // If LsrNoInsnsCost is set, call default implementation.
1200   if (!LsrNoInsnsCost)
1201     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost, C1.NumIVMuls,
1202                     C1.NumBaseAdds, C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
1203            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost, C2.NumIVMuls,
1204                     C2.NumBaseAdds, C2.ScaleCost, C2.ImmCost, C2.SetupCost);
1205   else
1206     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
1207 }
1208 
1209 bool PPCTTIImpl::isNumRegsMajorCostOfLSR() {
1210   return false;
1211 }
1212 
1213 bool PPCTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
1214                                     MemIntrinsicInfo &Info) {
1215   switch (Inst->getIntrinsicID()) {
1216   case Intrinsic::ppc_altivec_lvx:
1217   case Intrinsic::ppc_altivec_lvxl:
1218   case Intrinsic::ppc_altivec_lvebx:
1219   case Intrinsic::ppc_altivec_lvehx:
1220   case Intrinsic::ppc_altivec_lvewx:
1221   case Intrinsic::ppc_vsx_lxvd2x:
1222   case Intrinsic::ppc_vsx_lxvw4x:
1223   case Intrinsic::ppc_vsx_lxvd2x_be:
1224   case Intrinsic::ppc_vsx_lxvw4x_be:
1225   case Intrinsic::ppc_vsx_lxvl:
1226   case Intrinsic::ppc_vsx_lxvll:
1227   case Intrinsic::ppc_mma_lxvp: {
1228     Info.PtrVal = Inst->getArgOperand(0);
1229     Info.ReadMem = true;
1230     Info.WriteMem = false;
1231     return true;
1232   }
1233   case Intrinsic::ppc_altivec_stvx:
1234   case Intrinsic::ppc_altivec_stvxl:
1235   case Intrinsic::ppc_altivec_stvebx:
1236   case Intrinsic::ppc_altivec_stvehx:
1237   case Intrinsic::ppc_altivec_stvewx:
1238   case Intrinsic::ppc_vsx_stxvd2x:
1239   case Intrinsic::ppc_vsx_stxvw4x:
1240   case Intrinsic::ppc_vsx_stxvd2x_be:
1241   case Intrinsic::ppc_vsx_stxvw4x_be:
1242   case Intrinsic::ppc_vsx_stxvl:
1243   case Intrinsic::ppc_vsx_stxvll:
1244   case Intrinsic::ppc_mma_stxvp: {
1245     Info.PtrVal = Inst->getArgOperand(1);
1246     Info.ReadMem = false;
1247     Info.WriteMem = true;
1248     return true;
1249   }
1250   default:
1251     break;
1252   }
1253 
1254   return false;
1255 }
1256