92a5bb70f432f3ea0dcec72e438eee020ed0ba66
[oota-llvm.git] / lib / CodeGen / BasicTargetTransformInfo.cpp
1 //===- BasicTargetTransformInfo.cpp - Basic target-independent TTI impl ---===//
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 the implementation of a basic TargetTransformInfo pass
11 /// predicated on the target abstractions present in the target independent
12 /// code generator. It uses these (primarily TargetLowering) to model as much
13 /// of the TTI query interface as possible. It is included by most targets so
14 /// that they can specialize only a small subset of the query space.
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "basictti"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include <utility>
23
24 using namespace llvm;
25
26 namespace {
27
28 class BasicTTI : public ImmutablePass, public TargetTransformInfo {
29   const TargetLoweringBase *TLI;
30
31   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
32   /// are set if the result needs to be inserted and/or extracted from vectors.
33   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) const;
34
35 public:
36   BasicTTI() : ImmutablePass(ID), TLI(0) {
37     llvm_unreachable("This pass cannot be directly constructed");
38   }
39
40   BasicTTI(const TargetLoweringBase *TLI) : ImmutablePass(ID), TLI(TLI) {
41     initializeBasicTTIPass(*PassRegistry::getPassRegistry());
42   }
43
44   virtual void initializePass() {
45     pushTTIStack(this);
46   }
47
48   virtual void finalizePass() {
49     popTTIStack();
50   }
51
52   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53     TargetTransformInfo::getAnalysisUsage(AU);
54   }
55
56   /// Pass identification.
57   static char ID;
58
59   /// Provide necessary pointer adjustments for the two base classes.
60   virtual void *getAdjustedAnalysisPointer(const void *ID) {
61     if (ID == &TargetTransformInfo::ID)
62       return (TargetTransformInfo*)this;
63     return this;
64   }
65
66   /// \name Scalar TTI Implementations
67   /// @{
68
69   virtual bool isLegalAddImmediate(int64_t imm) const;
70   virtual bool isLegalICmpImmediate(int64_t imm) const;
71   virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
72                                      int64_t BaseOffset, bool HasBaseReg,
73                                      int64_t Scale) const;
74   virtual int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
75                                    int64_t BaseOffset, bool HasBaseReg,
76                                    int64_t Scale) const;
77   virtual bool isTruncateFree(Type *Ty1, Type *Ty2) const;
78   virtual bool isTypeLegal(Type *Ty) const;
79   virtual unsigned getJumpBufAlignment() const;
80   virtual unsigned getJumpBufSize() const;
81   virtual bool shouldBuildLookupTables() const;
82
83   /// @}
84
85   /// \name Vector TTI Implementations
86   /// @{
87
88   virtual unsigned getNumberOfRegisters(bool Vector) const;
89   virtual unsigned getMaximumUnrollFactor() const;
90   virtual unsigned getRegisterBitWidth(bool Vector) const;
91   virtual unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
92                                           OperandValueKind,
93                                           OperandValueKind) const;
94   virtual unsigned getShuffleCost(ShuffleKind Kind, Type *Tp,
95                                   int Index, Type *SubTp) const;
96   virtual unsigned getCastInstrCost(unsigned Opcode, Type *Dst,
97                                     Type *Src) const;
98   virtual unsigned getCFInstrCost(unsigned Opcode) const;
99   virtual unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
100                                       Type *CondTy) const;
101   virtual unsigned getVectorInstrCost(unsigned Opcode, Type *Val,
102                                       unsigned Index) const;
103   virtual unsigned getMemoryOpCost(unsigned Opcode, Type *Src,
104                                    unsigned Alignment,
105                                    unsigned AddressSpace) const;
106   virtual unsigned getIntrinsicInstrCost(Intrinsic::ID, Type *RetTy,
107                                          ArrayRef<Type*> Tys) const;
108   virtual unsigned getNumberOfParts(Type *Tp) const;
109   virtual unsigned getAddressComputationCost(Type *Ty) const;
110
111   /// @}
112 };
113
114 }
115
116 INITIALIZE_AG_PASS(BasicTTI, TargetTransformInfo, "basictti",
117                    "Target independent code generator's TTI", true, true, false)
118 char BasicTTI::ID = 0;
119
120 ImmutablePass *
121 llvm::createBasicTargetTransformInfoPass(const TargetLoweringBase *TLI) {
122   return new BasicTTI(TLI);
123 }
124
125
126 bool BasicTTI::isLegalAddImmediate(int64_t imm) const {
127   return TLI->isLegalAddImmediate(imm);
128 }
129
130 bool BasicTTI::isLegalICmpImmediate(int64_t imm) const {
131   return TLI->isLegalICmpImmediate(imm);
132 }
133
134 bool BasicTTI::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
135                                      int64_t BaseOffset, bool HasBaseReg,
136                                      int64_t Scale) const {
137   TargetLoweringBase::AddrMode AM;
138   AM.BaseGV = BaseGV;
139   AM.BaseOffs = BaseOffset;
140   AM.HasBaseReg = HasBaseReg;
141   AM.Scale = Scale;
142   return TLI->isLegalAddressingMode(AM, Ty);
143 }
144
145 int BasicTTI::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
146                                    int64_t BaseOffset, bool HasBaseReg,
147                                    int64_t Scale) const {
148   TargetLoweringBase::AddrMode AM;
149   AM.BaseGV = BaseGV;
150   AM.BaseOffs = BaseOffset;
151   AM.HasBaseReg = HasBaseReg;
152   AM.Scale = Scale;
153   return TLI->getScalingFactorCost(AM, Ty);
154 }
155
156 bool BasicTTI::isTruncateFree(Type *Ty1, Type *Ty2) const {
157   return TLI->isTruncateFree(Ty1, Ty2);
158 }
159
160 bool BasicTTI::isTypeLegal(Type *Ty) const {
161   EVT T = TLI->getValueType(Ty);
162   return TLI->isTypeLegal(T);
163 }
164
165 unsigned BasicTTI::getJumpBufAlignment() const {
166   return TLI->getJumpBufAlignment();
167 }
168
169 unsigned BasicTTI::getJumpBufSize() const {
170   return TLI->getJumpBufSize();
171 }
172
173 bool BasicTTI::shouldBuildLookupTables() const {
174   return TLI->supportJumpTables() &&
175       (TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
176        TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
177 }
178
179 //===----------------------------------------------------------------------===//
180 //
181 // Calls used by the vectorizers.
182 //
183 //===----------------------------------------------------------------------===//
184
185 unsigned BasicTTI::getScalarizationOverhead(Type *Ty, bool Insert,
186                                             bool Extract) const {
187   assert (Ty->isVectorTy() && "Can only scalarize vectors");
188   unsigned Cost = 0;
189
190   for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
191     if (Insert)
192       Cost += TopTTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
193     if (Extract)
194       Cost += TopTTI->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
195   }
196
197   return Cost;
198 }
199
200 unsigned BasicTTI::getNumberOfRegisters(bool Vector) const {
201   return 1;
202 }
203
204 unsigned BasicTTI::getRegisterBitWidth(bool Vector) const {
205   return 32;
206 }
207
208 unsigned BasicTTI::getMaximumUnrollFactor() const {
209   return 1;
210 }
211
212 unsigned BasicTTI::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
213                                           OperandValueKind,
214                                           OperandValueKind) const {
215   // Check if any of the operands are vector operands.
216   int ISD = TLI->InstructionOpcodeToISD(Opcode);
217   assert(ISD && "Invalid opcode");
218
219   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Ty);
220
221   bool IsFloat = Ty->getScalarType()->isFloatingPointTy();
222   // Assume that floating point arithmetic operations cost twice as much as
223   // integer operations.
224   unsigned OpCost = (IsFloat ? 2 : 1);
225
226   if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
227     // The operation is legal. Assume it costs 1.
228     // If the type is split to multiple registers, assume that there is some
229     // overhead to this.
230     // TODO: Once we have extract/insert subvector cost we need to use them.
231     if (LT.first > 1)
232       return LT.first * 2 * OpCost;
233     return LT.first * 1 * OpCost;
234   }
235
236   if (!TLI->isOperationExpand(ISD, LT.second)) {
237     // If the operation is custom lowered then assume
238     // thare the code is twice as expensive.
239     return LT.first * 2 * OpCost;
240   }
241
242   // Else, assume that we need to scalarize this op.
243   if (Ty->isVectorTy()) {
244     unsigned Num = Ty->getVectorNumElements();
245     unsigned Cost = TopTTI->getArithmeticInstrCost(Opcode, Ty->getScalarType());
246     // return the cost of multiple scalar invocation plus the cost of inserting
247     // and extracting the values.
248     return getScalarizationOverhead(Ty, true, true) + Num * Cost;
249   }
250
251   // We don't know anything about this scalar instruction.
252   return OpCost;
253 }
254
255 unsigned BasicTTI::getShuffleCost(ShuffleKind Kind, Type *Tp, int Index,
256                                   Type *SubTp) const {
257   return 1;
258 }
259
260 unsigned BasicTTI::getCastInstrCost(unsigned Opcode, Type *Dst,
261                                     Type *Src) const {
262   int ISD = TLI->InstructionOpcodeToISD(Opcode);
263   assert(ISD && "Invalid opcode");
264
265   std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(Src);
266   std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(Dst);
267
268   // Check for NOOP conversions.
269   if (SrcLT.first == DstLT.first &&
270       SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
271
272       // Bitcast between types that are legalized to the same type are free.
273       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
274         return 0;
275   }
276
277   if (Opcode == Instruction::Trunc &&
278       TLI->isTruncateFree(SrcLT.second, DstLT.second))
279     return 0;
280
281   if (Opcode == Instruction::ZExt &&
282       TLI->isZExtFree(SrcLT.second, DstLT.second))
283     return 0;
284
285   // If the cast is marked as legal (or promote) then assume low cost.
286   if (TLI->isOperationLegalOrPromote(ISD, DstLT.second))
287     return 1;
288
289   // Handle scalar conversions.
290   if (!Src->isVectorTy() && !Dst->isVectorTy()) {
291
292     // Scalar bitcasts are usually free.
293     if (Opcode == Instruction::BitCast)
294       return 0;
295
296     // Just check the op cost. If the operation is legal then assume it costs 1.
297     if (!TLI->isOperationExpand(ISD, DstLT.second))
298       return  1;
299
300     // Assume that illegal scalar instruction are expensive.
301     return 4;
302   }
303
304   // Check vector-to-vector casts.
305   if (Dst->isVectorTy() && Src->isVectorTy()) {
306
307     // If the cast is between same-sized registers, then the check is simple.
308     if (SrcLT.first == DstLT.first &&
309         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
310
311       // Assume that Zext is done using AND.
312       if (Opcode == Instruction::ZExt)
313         return 1;
314
315       // Assume that sext is done using SHL and SRA.
316       if (Opcode == Instruction::SExt)
317         return 2;
318
319       // Just check the op cost. If the operation is legal then assume it costs
320       // 1 and multiply by the type-legalization overhead.
321       if (!TLI->isOperationExpand(ISD, DstLT.second))
322         return SrcLT.first * 1;
323     }
324
325     // If we are converting vectors and the operation is illegal, or
326     // if the vectors are legalized to different types, estimate the
327     // scalarization costs.
328     unsigned Num = Dst->getVectorNumElements();
329     unsigned Cost = TopTTI->getCastInstrCost(Opcode, Dst->getScalarType(),
330                                              Src->getScalarType());
331
332     // Return the cost of multiple scalar invocation plus the cost of
333     // inserting and extracting the values.
334     return getScalarizationOverhead(Dst, true, true) + Num * Cost;
335   }
336
337   // We already handled vector-to-vector and scalar-to-scalar conversions. This
338   // is where we handle bitcast between vectors and scalars. We need to assume
339   //  that the conversion is scalarized in one way or another.
340   if (Opcode == Instruction::BitCast)
341     // Illegal bitcasts are done by storing and loading from a stack slot.
342     return (Src->isVectorTy()? getScalarizationOverhead(Src, false, true):0) +
343            (Dst->isVectorTy()? getScalarizationOverhead(Dst, true, false):0);
344
345   llvm_unreachable("Unhandled cast");
346  }
347
348 unsigned BasicTTI::getCFInstrCost(unsigned Opcode) const {
349   // Branches are assumed to be predicted.
350   return 0;
351 }
352
353 unsigned BasicTTI::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
354                                       Type *CondTy) const {
355   int ISD = TLI->InstructionOpcodeToISD(Opcode);
356   assert(ISD && "Invalid opcode");
357
358   // Selects on vectors are actually vector selects.
359   if (ISD == ISD::SELECT) {
360     assert(CondTy && "CondTy must exist");
361     if (CondTy->isVectorTy())
362       ISD = ISD::VSELECT;
363   }
364
365   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(ValTy);
366
367   if (!TLI->isOperationExpand(ISD, LT.second)) {
368     // The operation is legal. Assume it costs 1. Multiply
369     // by the type-legalization overhead.
370     return LT.first * 1;
371   }
372
373   // Otherwise, assume that the cast is scalarized.
374   if (ValTy->isVectorTy()) {
375     unsigned Num = ValTy->getVectorNumElements();
376     if (CondTy)
377       CondTy = CondTy->getScalarType();
378     unsigned Cost = TopTTI->getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
379                                                CondTy);
380
381     // Return the cost of multiple scalar invocation plus the cost of inserting
382     // and extracting the values.
383     return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
384   }
385
386   // Unknown scalar opcode.
387   return 1;
388 }
389
390 unsigned BasicTTI::getVectorInstrCost(unsigned Opcode, Type *Val,
391                                       unsigned Index) const {
392   return 1;
393 }
394
395 unsigned BasicTTI::getMemoryOpCost(unsigned Opcode, Type *Src,
396                                    unsigned Alignment,
397                                    unsigned AddressSpace) const {
398   assert(!Src->isVoidTy() && "Invalid type");
399   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Src);
400
401   // Assume that all loads of legal types cost 1.
402   return LT.first;
403 }
404
405 unsigned BasicTTI::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
406                                          ArrayRef<Type *> Tys) const {
407   unsigned ISD = 0;
408   switch (IID) {
409   default: {
410     // Assume that we need to scalarize this intrinsic.
411     unsigned ScalarizationCost = 0;
412     unsigned ScalarCalls = 1;
413     if (RetTy->isVectorTy()) {
414       ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
415       ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
416     }
417     for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
418       if (Tys[i]->isVectorTy()) {
419         ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
420         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
421       }
422     }
423
424     return ScalarCalls + ScalarizationCost;
425   }
426   // Look for intrinsics that can be lowered directly or turned into a scalar
427   // intrinsic call.
428   case Intrinsic::sqrt:    ISD = ISD::FSQRT;  break;
429   case Intrinsic::sin:     ISD = ISD::FSIN;   break;
430   case Intrinsic::cos:     ISD = ISD::FCOS;   break;
431   case Intrinsic::exp:     ISD = ISD::FEXP;   break;
432   case Intrinsic::exp2:    ISD = ISD::FEXP2;  break;
433   case Intrinsic::log:     ISD = ISD::FLOG;   break;
434   case Intrinsic::log10:   ISD = ISD::FLOG10; break;
435   case Intrinsic::log2:    ISD = ISD::FLOG2;  break;
436   case Intrinsic::fabs:    ISD = ISD::FABS;   break;
437   case Intrinsic::floor:   ISD = ISD::FFLOOR; break;
438   case Intrinsic::ceil:    ISD = ISD::FCEIL;  break;
439   case Intrinsic::trunc:   ISD = ISD::FTRUNC; break;
440   case Intrinsic::rint:    ISD = ISD::FRINT;  break;
441   case Intrinsic::pow:     ISD = ISD::FPOW;   break;
442   case Intrinsic::fma:     ISD = ISD::FMA;    break;
443   case Intrinsic::fmuladd: ISD = ISD::FMA;    break; // FIXME: mul + add?
444   }
445
446   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(RetTy);
447
448   if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
449     // The operation is legal. Assume it costs 1.
450     // If the type is split to multiple registers, assume that thre is some
451     // overhead to this.
452     // TODO: Once we have extract/insert subvector cost we need to use them.
453     if (LT.first > 1)
454       return LT.first * 2;
455     return LT.first * 1;
456   }
457
458   if (!TLI->isOperationExpand(ISD, LT.second)) {
459     // If the operation is custom lowered then assume
460     // thare the code is twice as expensive.
461     return LT.first * 2;
462   }
463
464   // Else, assume that we need to scalarize this intrinsic. For math builtins
465   // this will emit a costly libcall, adding call overhead and spills. Make it
466   // very expensive.
467   if (RetTy->isVectorTy()) {
468     unsigned Num = RetTy->getVectorNumElements();
469     unsigned Cost = TopTTI->getIntrinsicInstrCost(IID, RetTy->getScalarType(),
470                                                   Tys);
471     return 10 * Cost * Num;
472   }
473
474   // This is going to be turned into a library call, make it expensive.
475   return 10;
476 }
477
478 unsigned BasicTTI::getNumberOfParts(Type *Tp) const {
479   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(Tp);
480   return LT.first;
481 }
482
483 unsigned BasicTTI::getAddressComputationCost(Type *Ty) const {
484   return 0;
485 }