d75b5eb95d02cf66b0a8e8a9e39821b5fefbd367
[oota-llvm.git] / include / llvm / CodeGen / BasicTTIImpl.h
1 //===- BasicTTIImpl.h -------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file provides a helper that implements much of the TTI interface in
11 /// terms of the target-independent code generator and TargetLowering
12 /// interfaces.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_CODEGEN_BASICTTIIMPL_H
17 #define LLVM_CODEGEN_BASICTTIIMPL_H
18
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetTransformInfoImpl.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetSubtargetInfo.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25
26 namespace llvm {
27
28 extern cl::opt<unsigned> PartialUnrollingThreshold;
29
30 /// \brief Base class which can be used to help build a TTI implementation.
31 ///
32 /// This class provides as much implementation of the TTI interface as is
33 /// possible using the target independent parts of the code generator.
34 ///
35 /// In order to subclass it, your class must implement a getST() method to
36 /// return the subtarget, and a getTLI() method to return the target lowering.
37 /// We need these methods implemented in the derived class so that this class
38 /// doesn't have to duplicate storage for them.
39 template <typename T>
40 class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
41 private:
42   typedef TargetTransformInfoImplCRTPBase<T> BaseT;
43   typedef TargetTransformInfo TTI;
44
45   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
46   /// are set if the result needs to be inserted and/or extracted from vectors.
47   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
48     assert(Ty->isVectorTy() && "Can only scalarize vectors");
49     unsigned Cost = 0;
50
51     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
52       if (Insert)
53         Cost += static_cast<T *>(this)
54                     ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
55       if (Extract)
56         Cost += static_cast<T *>(this)
57                     ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
58     }
59
60     return Cost;
61   }
62
63   /// Estimate the cost overhead of SK_Alternate shuffle.
64   unsigned getAltShuffleOverhead(Type *Ty) {
65     assert(Ty->isVectorTy() && "Can only shuffle vectors");
66     unsigned Cost = 0;
67     // Shuffle cost is equal to the cost of extracting element from its argument
68     // plus the cost of inserting them onto the result vector.
69
70     // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
71     // index 0 of first vector, index 1 of second vector,index 2 of first
72     // vector and finally index 3 of second vector and insert them at index
73     // <0,1,2,3> of result vector.
74     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
75       Cost += static_cast<T *>(this)
76                   ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
77       Cost += static_cast<T *>(this)
78                   ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
79     }
80     return Cost;
81   }
82
83   /// \brief Local query method delegates up to T which *must* implement this!
84   const TargetSubtargetInfo *getST() const {
85     return static_cast<const T *>(this)->getST();
86   }
87
88   /// \brief Local query method delegates up to T which *must* implement this!
89   const TargetLoweringBase *getTLI() const {
90     return static_cast<const T *>(this)->getTLI();
91   }
92
93 protected:
94   explicit BasicTTIImplBase(const TargetMachine *TM)
95       : BaseT(TM->getDataLayout()) {}
96
97 public:
98   // Provide value semantics. MSVC requires that we spell all of these out.
99   BasicTTIImplBase(const BasicTTIImplBase &Arg)
100       : BaseT(static_cast<const BaseT &>(Arg)) {}
101   BasicTTIImplBase(BasicTTIImplBase &&Arg)
102       : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
103   BasicTTIImplBase &operator=(const BasicTTIImplBase &RHS) {
104     BaseT::operator=(static_cast<const BaseT &>(RHS));
105     return *this;
106   }
107   BasicTTIImplBase &operator=(BasicTTIImplBase &&RHS) {
108     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
109     return *this;
110   }
111
112   /// \name Scalar TTI Implementations
113   /// @{
114
115   bool hasBranchDivergence() { return false; }
116
117   bool isLegalAddImmediate(int64_t imm) {
118     return getTLI()->isLegalAddImmediate(imm);
119   }
120
121   bool isLegalICmpImmediate(int64_t imm) {
122     return getTLI()->isLegalICmpImmediate(imm);
123   }
124
125   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
126                              bool HasBaseReg, int64_t Scale) {
127     TargetLoweringBase::AddrMode AM;
128     AM.BaseGV = BaseGV;
129     AM.BaseOffs = BaseOffset;
130     AM.HasBaseReg = HasBaseReg;
131     AM.Scale = Scale;
132     return getTLI()->isLegalAddressingMode(AM, Ty);
133   }
134
135   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
136                            bool HasBaseReg, int64_t Scale) {
137     TargetLoweringBase::AddrMode AM;
138     AM.BaseGV = BaseGV;
139     AM.BaseOffs = BaseOffset;
140     AM.HasBaseReg = HasBaseReg;
141     AM.Scale = Scale;
142     return getTLI()->getScalingFactorCost(AM, Ty);
143   }
144
145   bool isTruncateFree(Type *Ty1, Type *Ty2) {
146     return getTLI()->isTruncateFree(Ty1, Ty2);
147   }
148
149   bool isProfitableToHoist(Instruction *I) {
150     return getTLI()->isProfitableToHoist(I);
151   }
152
153   bool isTypeLegal(Type *Ty) {
154     EVT VT = getTLI()->getValueType(Ty);
155     return getTLI()->isTypeLegal(VT);
156   }
157
158   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
159                             ArrayRef<const Value *> Arguments) {
160     return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
161   }
162
163   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
164                             ArrayRef<Type *> ParamTys) {
165     if (IID == Intrinsic::cttz) {
166       if (getTLI()->isCheapToSpeculateCttz())
167         return TargetTransformInfo::TCC_Basic;
168       return TargetTransformInfo::TCC_Expensive;
169     }
170
171     if (IID == Intrinsic::ctlz) {
172        if (getTLI()->isCheapToSpeculateCtlz())
173         return TargetTransformInfo::TCC_Basic;
174       return TargetTransformInfo::TCC_Expensive;
175     }
176
177     return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
178   }
179
180   unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
181
182   unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
183
184   bool shouldBuildLookupTables() {
185     const TargetLoweringBase *TLI = getTLI();
186     return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
187            TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
188   }
189
190   bool haveFastSqrt(Type *Ty) {
191     const TargetLoweringBase *TLI = getTLI();
192     EVT VT = TLI->getValueType(Ty);
193     return TLI->isTypeLegal(VT) &&
194            TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
195   }
196
197   unsigned getFPOpCost(Type *Ty) {
198     // By default, FP instructions are no more expensive since they are
199     // implemented in HW.  Target specific TTI can override this.
200     return TargetTransformInfo::TCC_Basic;
201   }
202
203   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
204     const TargetLoweringBase *TLI = getTLI();
205     switch (Opcode) {
206     default: break;
207     case Instruction::Trunc: {
208       if (TLI->isTruncateFree(OpTy, Ty))
209         return TargetTransformInfo::TCC_Free;
210       return TargetTransformInfo::TCC_Basic;
211     }
212     case Instruction::ZExt: {
213       if (TLI->isZExtFree(OpTy, Ty))
214         return TargetTransformInfo::TCC_Free;
215       return TargetTransformInfo::TCC_Basic;
216     }
217     }
218
219     return BaseT::getOperationCost(Opcode, Ty, OpTy);
220   }
221
222   void getUnrollingPreferences(Loop *L, TTI::UnrollingPreferences &UP) {
223     // This unrolling functionality is target independent, but to provide some
224     // motivation for its intended use, for x86:
225
226     // According to the Intel 64 and IA-32 Architectures Optimization Reference
227     // Manual, Intel Core models and later have a loop stream detector (and
228     // associated uop queue) that can benefit from partial unrolling.
229     // The relevant requirements are:
230     //  - The loop must have no more than 4 (8 for Nehalem and later) branches
231     //    taken, and none of them may be calls.
232     //  - The loop can have no more than 18 (28 for Nehalem and later) uops.
233
234     // According to the Software Optimization Guide for AMD Family 15h
235     // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
236     // and loop buffer which can benefit from partial unrolling.
237     // The relevant requirements are:
238     //  - The loop must have fewer than 16 branches
239     //  - The loop must have less than 40 uops in all executed loop branches
240
241     // The number of taken branches in a loop is hard to estimate here, and
242     // benchmarking has revealed that it is better not to be conservative when
243     // estimating the branch count. As a result, we'll ignore the branch limits
244     // until someone finds a case where it matters in practice.
245
246     unsigned MaxOps;
247     const TargetSubtargetInfo *ST = getST();
248     if (PartialUnrollingThreshold.getNumOccurrences() > 0)
249       MaxOps = PartialUnrollingThreshold;
250     else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
251       MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
252     else
253       return;
254
255     // Scan the loop: don't unroll loops with calls.
256     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
257          ++I) {
258       BasicBlock *BB = *I;
259
260       for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
261         if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
262           ImmutableCallSite CS(J);
263           if (const Function *F = CS.getCalledFunction()) {
264             if (!static_cast<T *>(this)->isLoweredToCall(F))
265               continue;
266           }
267
268           return;
269         }
270     }
271
272     // Enable runtime and partial unrolling up to the specified size.
273     UP.Partial = UP.Runtime = true;
274     UP.PartialThreshold = UP.PartialOptSizeThreshold = MaxOps;
275   }
276
277   /// @}
278
279   /// \name Vector TTI Implementations
280   /// @{
281
282   unsigned getNumberOfRegisters(bool Vector) { return 1; }
283
284   unsigned getRegisterBitWidth(bool Vector) { return 32; }
285
286   unsigned getMaxInterleaveFactor() { return 1; }
287
288   unsigned getArithmeticInstrCost(
289       unsigned Opcode, Type *Ty,
290       TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
291       TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
292       TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
293       TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None) {
294     // Check if any of the operands are vector operands.
295     const TargetLoweringBase *TLI = getTLI();
296     int ISD = TLI->InstructionOpcodeToISD(Opcode);
297     assert(ISD && "Invalid opcode");
298
299     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
300
301     bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
302     // Assume that floating point arithmetic operations cost twice as much as
303     // integer operations.
304     unsigned OpCost = (IsFloat ? 2 : 1);
305
306     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
307       // The operation is legal. Assume it costs 1.
308       // If the type is split to multiple registers, assume that there is some
309       // overhead to this.
310       // TODO: Once we have extract/insert subvector cost we need to use them.
311       if (LT.first > 1)
312         return LT.first * 2 * OpCost;
313       return LT.first * 1 * OpCost;
314     }
315
316     if (!TLI->isOperationExpand(ISD, LT.second)) {
317       // If the operation is custom lowered then assume
318       // thare the code is twice as expensive.
319       return LT.first * 2 * OpCost;
320     }
321
322     // Else, assume that we need to scalarize this op.
323     if (Ty->isVectorTy()) {
324       unsigned Num = Ty->getVectorNumElements();
325       unsigned Cost = static_cast<T *>(this)
326                           ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
327       // return the cost of multiple scalar invocation plus the cost of
328       // inserting
329       // and extracting the values.
330       return getScalarizationOverhead(Ty, true, true) + Num * Cost;
331     }
332
333     // We don't know anything about this scalar instruction.
334     return OpCost;
335   }
336
337   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
338                           Type *SubTp) {
339     if (Kind == TTI::SK_Alternate) {
340       return getAltShuffleOverhead(Tp);
341     }
342     return 1;
343   }
344
345   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
346     const TargetLoweringBase *TLI = getTLI();
347     int ISD = TLI->InstructionOpcodeToISD(Opcode);
348     assert(ISD && "Invalid opcode");
349
350     std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
351     std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
352
353     // Check for NOOP conversions.
354     if (SrcLT.first == DstLT.first &&
355         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
356
357       // Bitcast between types that are legalized to the same type are free.
358       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
359         return 0;
360     }
361
362     if (Opcode == Instruction::Trunc &&
363         TLI->isTruncateFree(SrcLT.second, DstLT.second))
364       return 0;
365
366     if (Opcode == Instruction::ZExt &&
367         TLI->isZExtFree(SrcLT.second, DstLT.second))
368       return 0;
369
370     // If the cast is marked as legal (or promote) then assume low cost.
371     if (SrcLT.first == DstLT.first &&
372         TLI->isOperationLegalOrPromote(ISD, DstLT.second))
373       return 1;
374
375     // Handle scalar conversions.
376     if (!Src->isVectorTy() && !Dst->isVectorTy()) {
377
378       // Scalar bitcasts are usually free.
379       if (Opcode == Instruction::BitCast)
380         return 0;
381
382       // Just check the op cost. If the operation is legal then assume it costs
383       // 1.
384       if (!TLI->isOperationExpand(ISD, DstLT.second))
385         return 1;
386
387       // Assume that illegal scalar instruction are expensive.
388       return 4;
389     }
390
391     // Check vector-to-vector casts.
392     if (Dst->isVectorTy() && Src->isVectorTy()) {
393
394       // If the cast is between same-sized registers, then the check is simple.
395       if (SrcLT.first == DstLT.first &&
396           SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
397
398         // Assume that Zext is done using AND.
399         if (Opcode == Instruction::ZExt)
400           return 1;
401
402         // Assume that sext is done using SHL and SRA.
403         if (Opcode == Instruction::SExt)
404           return 2;
405
406         // Just check the op cost. If the operation is legal then assume it
407         // costs
408         // 1 and multiply by the type-legalization overhead.
409         if (!TLI->isOperationExpand(ISD, DstLT.second))
410           return SrcLT.first * 1;
411       }
412
413       // If we are converting vectors and the operation is illegal, or
414       // if the vectors are legalized to different types, estimate the
415       // scalarization costs.
416       unsigned Num = Dst->getVectorNumElements();
417       unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
418           Opcode, Dst->getScalarType(), Src->getScalarType());
419
420       // Return the cost of multiple scalar invocation plus the cost of
421       // inserting and extracting the values.
422       return getScalarizationOverhead(Dst, true, true) + Num * Cost;
423     }
424
425     // We already handled vector-to-vector and scalar-to-scalar conversions.
426     // This
427     // is where we handle bitcast between vectors and scalars. We need to assume
428     //  that the conversion is scalarized in one way or another.
429     if (Opcode == Instruction::BitCast)
430       // Illegal bitcasts are done by storing and loading from a stack slot.
431       return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
432                                 : 0) +
433              (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
434                                 : 0);
435
436     llvm_unreachable("Unhandled cast");
437   }
438
439   unsigned getCFInstrCost(unsigned Opcode) {
440     // Branches are assumed to be predicted.
441     return 0;
442   }
443
444   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
445     const TargetLoweringBase *TLI = getTLI();
446     int ISD = TLI->InstructionOpcodeToISD(Opcode);
447     assert(ISD && "Invalid opcode");
448
449     // Selects on vectors are actually vector selects.
450     if (ISD == ISD::SELECT) {
451       assert(CondTy && "CondTy must exist");
452       if (CondTy->isVectorTy())
453         ISD = ISD::VSELECT;
454     }
455
456     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
457
458     if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
459         !TLI->isOperationExpand(ISD, LT.second)) {
460       // The operation is legal. Assume it costs 1. Multiply
461       // by the type-legalization overhead.
462       return LT.first * 1;
463     }
464
465     // Otherwise, assume that the cast is scalarized.
466     if (ValTy->isVectorTy()) {
467       unsigned Num = ValTy->getVectorNumElements();
468       if (CondTy)
469         CondTy = CondTy->getScalarType();
470       unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
471           Opcode, ValTy->getScalarType(), CondTy);
472
473       // Return the cost of multiple scalar invocation plus the cost of
474       // inserting
475       // and extracting the values.
476       return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
477     }
478
479     // Unknown scalar opcode.
480     return 1;
481   }
482
483   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
484     std::pair<unsigned, MVT> LT =
485         getTLI()->getTypeLegalizationCost(Val->getScalarType());
486
487     return LT.first;
488   }
489
490   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
491                            unsigned AddressSpace) {
492     assert(!Src->isVoidTy() && "Invalid type");
493     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Src);
494
495     // Assuming that all loads of legal types cost 1.
496     unsigned Cost = LT.first;
497
498     if (Src->isVectorTy() &&
499         Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
500       // This is a vector load that legalizes to a larger type than the vector
501       // itself. Unless the corresponding extending load or truncating store is
502       // legal, then this will scalarize.
503       TargetLowering::LegalizeAction LA = TargetLowering::Expand;
504       EVT MemVT = getTLI()->getValueType(Src, true);
505       if (MemVT.isSimple() && MemVT != MVT::Other) {
506         if (Opcode == Instruction::Store)
507           LA = getTLI()->getTruncStoreAction(LT.second, MemVT.getSimpleVT());
508         else
509           LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
510       }
511
512       if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
513         // This is a vector load/store for some illegal type that is scalarized.
514         // We must account for the cost of building or decomposing the vector.
515         Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
516                                          Opcode == Instruction::Store);
517       }
518     }
519
520     return Cost;
521   }
522
523   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
524                                  ArrayRef<Type *> Tys) {
525     unsigned ISD = 0;
526     switch (IID) {
527     default: {
528       // Assume that we need to scalarize this intrinsic.
529       unsigned ScalarizationCost = 0;
530       unsigned ScalarCalls = 1;
531       if (RetTy->isVectorTy()) {
532         ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
533         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
534       }
535       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
536         if (Tys[i]->isVectorTy()) {
537           ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
538           ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
539         }
540       }
541
542       return ScalarCalls + ScalarizationCost;
543     }
544     // Look for intrinsics that can be lowered directly or turned into a scalar
545     // intrinsic call.
546     case Intrinsic::sqrt:
547       ISD = ISD::FSQRT;
548       break;
549     case Intrinsic::sin:
550       ISD = ISD::FSIN;
551       break;
552     case Intrinsic::cos:
553       ISD = ISD::FCOS;
554       break;
555     case Intrinsic::exp:
556       ISD = ISD::FEXP;
557       break;
558     case Intrinsic::exp2:
559       ISD = ISD::FEXP2;
560       break;
561     case Intrinsic::log:
562       ISD = ISD::FLOG;
563       break;
564     case Intrinsic::log10:
565       ISD = ISD::FLOG10;
566       break;
567     case Intrinsic::log2:
568       ISD = ISD::FLOG2;
569       break;
570     case Intrinsic::fabs:
571       ISD = ISD::FABS;
572       break;
573     case Intrinsic::minnum:
574       ISD = ISD::FMINNUM;
575       break;
576     case Intrinsic::maxnum:
577       ISD = ISD::FMAXNUM;
578       break;
579     case Intrinsic::copysign:
580       ISD = ISD::FCOPYSIGN;
581       break;
582     case Intrinsic::floor:
583       ISD = ISD::FFLOOR;
584       break;
585     case Intrinsic::ceil:
586       ISD = ISD::FCEIL;
587       break;
588     case Intrinsic::trunc:
589       ISD = ISD::FTRUNC;
590       break;
591     case Intrinsic::nearbyint:
592       ISD = ISD::FNEARBYINT;
593       break;
594     case Intrinsic::rint:
595       ISD = ISD::FRINT;
596       break;
597     case Intrinsic::round:
598       ISD = ISD::FROUND;
599       break;
600     case Intrinsic::pow:
601       ISD = ISD::FPOW;
602       break;
603     case Intrinsic::fma:
604       ISD = ISD::FMA;
605       break;
606     case Intrinsic::fmuladd:
607       ISD = ISD::FMA;
608       break;
609     // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
610     case Intrinsic::lifetime_start:
611     case Intrinsic::lifetime_end:
612       return 0;
613     case Intrinsic::masked_store:
614       return static_cast<T *>(this)
615           ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
616     case Intrinsic::masked_load:
617       return static_cast<T *>(this)
618           ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
619     }
620
621     const TargetLoweringBase *TLI = getTLI();
622     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
623
624     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
625       // The operation is legal. Assume it costs 1.
626       // If the type is split to multiple registers, assume that there is some
627       // overhead to this.
628       // TODO: Once we have extract/insert subvector cost we need to use them.
629       if (LT.first > 1)
630         return LT.first * 2;
631       return LT.first * 1;
632     }
633
634     if (!TLI->isOperationExpand(ISD, LT.second)) {
635       // If the operation is custom lowered then assume
636       // thare the code is twice as expensive.
637       return LT.first * 2;
638     }
639
640     // If we can't lower fmuladd into an FMA estimate the cost as a floating
641     // point mul followed by an add.
642     if (IID == Intrinsic::fmuladd)
643       return static_cast<T *>(this)
644                  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
645              static_cast<T *>(this)
646                  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
647
648     // Else, assume that we need to scalarize this intrinsic. For math builtins
649     // this will emit a costly libcall, adding call overhead and spills. Make it
650     // very expensive.
651     if (RetTy->isVectorTy()) {
652       unsigned Num = RetTy->getVectorNumElements();
653       unsigned Cost = static_cast<T *>(this)->getIntrinsicInstrCost(
654           IID, RetTy->getScalarType(), Tys);
655       return 10 * Cost * Num;
656     }
657
658     // This is going to be turned into a library call, make it expensive.
659     return 10;
660   }
661
662   /// \brief Compute a cost of the given call instruction.
663   ///
664   /// Compute the cost of calling function F with return type RetTy and
665   /// argument types Tys. F might be nullptr, in this case the cost of an
666   /// arbitrary call with the specified signature will be returned.
667   /// This is used, for instance,  when we estimate call of a vector
668   /// counterpart of the given function.
669   /// \param F Called function, might be nullptr.
670   /// \param RetTy,Tys Return value and argument types.
671   /// \returns The cost of Call instruction.
672   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
673     return 10;
674   }
675
676   unsigned getNumberOfParts(Type *Tp) {
677     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(Tp);
678     return LT.first;
679   }
680
681   unsigned getAddressComputationCost(Type *Ty, bool IsComplex) { return 0; }
682
683   unsigned getReductionCost(unsigned Opcode, Type *Ty, bool IsPairwise) {
684     assert(Ty->isVectorTy() && "Expect a vector type");
685     unsigned NumVecElts = Ty->getVectorNumElements();
686     unsigned NumReduxLevels = Log2_32(NumVecElts);
687     unsigned ArithCost =
688         NumReduxLevels *
689         static_cast<T *>(this)->getArithmeticInstrCost(Opcode, Ty);
690     // Assume the pairwise shuffles add a cost.
691     unsigned ShuffleCost =
692         NumReduxLevels * (IsPairwise + 1) *
693         static_cast<T *>(this)
694             ->getShuffleCost(TTI::SK_ExtractSubvector, Ty, NumVecElts / 2, Ty);
695     return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
696   }
697
698   /// @}
699 };
700
701 /// \brief Concrete BasicTTIImpl that can be used if no further customization
702 /// is needed.
703 class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
704   typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
705   friend class BasicTTIImplBase<BasicTTIImpl>;
706
707   const TargetSubtargetInfo *ST;
708   const TargetLoweringBase *TLI;
709
710   const TargetSubtargetInfo *getST() const { return ST; }
711   const TargetLoweringBase *getTLI() const { return TLI; }
712
713 public:
714   explicit BasicTTIImpl(const TargetMachine *ST, Function &F);
715
716   // Provide value semantics. MSVC requires that we spell all of these out.
717   BasicTTIImpl(const BasicTTIImpl &Arg)
718       : BaseT(static_cast<const BaseT &>(Arg)), ST(Arg.ST), TLI(Arg.TLI) {}
719   BasicTTIImpl(BasicTTIImpl &&Arg)
720       : BaseT(std::move(static_cast<BaseT &>(Arg))), ST(std::move(Arg.ST)),
721         TLI(std::move(Arg.TLI)) {}
722   BasicTTIImpl &operator=(const BasicTTIImpl &RHS) {
723     BaseT::operator=(static_cast<const BaseT &>(RHS));
724     ST = RHS.ST;
725     TLI = RHS.TLI;
726     return *this;
727   }
728   BasicTTIImpl &operator=(BasicTTIImpl &&RHS) {
729     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
730     ST = std::move(RHS.ST);
731     TLI = std::move(RHS.TLI);
732     return *this;
733   }
734 };
735
736 }
737
738 #endif