LCOV - code coverage report
Current view: top level - include/llvm/CodeGen - BasicTTIImpl.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 456 484 94.2 %
Date: 2017-09-14 15:23:50 Functions: 100 236 42.4 %
Legend: Lines: hit not hit

          Line data    Source code
       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/TargetLibraryInfo.h"
      21             : #include "llvm/Analysis/TargetTransformInfoImpl.h"
      22             : #include "llvm/Support/CommandLine.h"
      23             : #include "llvm/Target/TargetLowering.h"
      24             : #include "llvm/Target/TargetSubtargetInfo.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     6823392 : class BasicTTIImplBase : public TargetTransformInfoImplCRTPBase<T> {
      41             : private:
      42             :   typedef TargetTransformInfoImplCRTPBase<T> BaseT;
      43             :   typedef TargetTransformInfo TTI;
      44             : 
      45             :   /// Estimate a cost of shuffle as a sequence of extract and insert
      46             :   /// operations.
      47           4 :   unsigned getPermuteShuffleOverhead(Type *Ty) {
      48             :     assert(Ty->isVectorTy() && "Can only shuffle vectors");
      49           4 :     unsigned Cost = 0;
      50             :     // Shuffle cost is equal to the cost of extracting element from its argument
      51             :     // plus the cost of inserting them onto the result vector.
      52             : 
      53             :     // e.g. <4 x float> has a mask of <0,5,2,7> i.e we need to extract from
      54             :     // index 0 of first vector, index 1 of second vector,index 2 of first
      55             :     // vector and finally index 3 of second vector and insert them at index
      56             :     // <0,1,2,3> of result vector.
      57          16 :     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
      58           8 :       Cost += static_cast<T *>(this)
      59             :                   ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
      60           8 :       Cost += static_cast<T *>(this)
      61             :                   ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
      62             :     }
      63           4 :     return Cost;
      64             :   }
      65             : 
      66             :   /// \brief Local query method delegates up to T which *must* implement this!
      67             :   const TargetSubtargetInfo *getST() const {
      68        5218 :     return static_cast<const T *>(this)->getST();
      69             :   }
      70             : 
      71             :   /// \brief Local query method delegates up to T which *must* implement this!
      72             :   const TargetLoweringBase *getTLI() const {
      73     1869751 :     return static_cast<const T *>(this)->getTLI();
      74             :   }
      75             : 
      76             : protected:
      77             :   explicit BasicTTIImplBase(const TargetMachine *TM, const DataLayout &DL)
      78     3411696 :       : BaseT(DL) {}
      79             : 
      80             :   using TargetTransformInfoImplBase::DL;
      81             : 
      82             : public:
      83             :   /// \name Scalar TTI Implementations
      84             :   /// @{
      85         772 :   bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
      86             :                                       unsigned BitWidth, unsigned AddressSpace,
      87             :                                       unsigned Alignment, bool *Fast) const {
      88         772 :     EVT E = EVT::getIntegerVT(Context, BitWidth);
      89         772 :     return getTLI()->allowsMisalignedMemoryAccesses(E, AddressSpace, Alignment, Fast);
      90             :   }
      91             : 
      92             :   bool hasBranchDivergence() { return false; }
      93             : 
      94             :   bool isSourceOfDivergence(const Value *V) { return false; }
      95             : 
      96             :   bool isAlwaysUniform(const Value *V) { return false; }
      97             : 
      98             :   unsigned getFlatAddressSpace() {
      99             :     // Return an invalid address space.
     100             :     return -1;
     101             :   }
     102             : 
     103             :   bool isLegalAddImmediate(int64_t imm) {
     104       14977 :     return getTLI()->isLegalAddImmediate(imm);
     105             :   }
     106             : 
     107             :   bool isLegalICmpImmediate(int64_t imm) {
     108       20291 :     return getTLI()->isLegalICmpImmediate(imm);
     109             :   }
     110             : 
     111             :   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
     112             :                              bool HasBaseReg, int64_t Scale,
     113             :                              unsigned AddrSpace, Instruction *I = nullptr) {
     114             :     TargetLoweringBase::AddrMode AM;
     115      596292 :     AM.BaseGV = BaseGV;
     116      596292 :     AM.BaseOffs = BaseOffset;
     117      596292 :     AM.HasBaseReg = HasBaseReg;
     118      596292 :     AM.Scale = Scale;
     119      596292 :     return getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace, I);
     120             :   }
     121             : 
     122             :   bool isLSRCostLess(TTI::LSRCost C1, TTI::LSRCost C2) {
     123       11430 :     return TargetTransformInfoImplBase::isLSRCostLess(C1, C2);
     124             :   }
     125             : 
     126             :   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
     127             :                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
     128             :     TargetLoweringBase::AddrMode AM;
     129       63746 :     AM.BaseGV = BaseGV;
     130       63746 :     AM.BaseOffs = BaseOffset;
     131       63746 :     AM.HasBaseReg = HasBaseReg;
     132       63746 :     AM.Scale = Scale;
     133       63746 :     return getTLI()->getScalingFactorCost(DL, AM, Ty, AddrSpace);
     134             :   }
     135             : 
     136             :   bool isTruncateFree(Type *Ty1, Type *Ty2) {
     137        8982 :     return getTLI()->isTruncateFree(Ty1, Ty2);
     138             :   }
     139             : 
     140             :   bool isProfitableToHoist(Instruction *I) {
     141        3377 :     return getTLI()->isProfitableToHoist(I);
     142             :   }
     143             : 
     144         231 :   bool isTypeLegal(Type *Ty) {
     145         231 :     EVT VT = getTLI()->getValueType(DL, Ty);
     146         462 :     return getTLI()->isTypeLegal(VT);
     147             :   }
     148             : 
     149             :   int getGEPCost(Type *PointeeType, const Value *Ptr,
     150             :                  ArrayRef<const Value *> Operands) {
     151      309494 :     return BaseT::getGEPCost(PointeeType, Ptr, Operands);
     152             :   }
     153             : 
     154       16924 :   int getExtCost(const Instruction *I, const Value *Src) {
     155       16924 :     if (getTLI()->isExtFree(I))
     156             :       return TargetTransformInfo::TCC_Free;
     157             : 
     158       27112 :     if (isa<ZExtInst>(I) || isa<SExtInst>(I))
     159        4245 :       if (const LoadInst *LI = dyn_cast<LoadInst>(Src))
     160        4245 :         if (getTLI()->isExtLoad(LI, I, DL))
     161             :           return TargetTransformInfo::TCC_Free;
     162             : 
     163             :     return TargetTransformInfo::TCC_Basic;
     164             :   }
     165             : 
     166             :   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
     167             :                             ArrayRef<const Value *> Arguments) {
     168           4 :     return BaseT::getIntrinsicCost(IID, RetTy, Arguments);
     169             :   }
     170             : 
     171      281799 :   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
     172             :                             ArrayRef<Type *> ParamTys) {
     173      281799 :     if (IID == Intrinsic::cttz) {
     174         528 :       if (getTLI()->isCheapToSpeculateCttz())
     175             :         return TargetTransformInfo::TCC_Basic;
     176             :       return TargetTransformInfo::TCC_Expensive;
     177             :     }
     178             : 
     179      281271 :     if (IID == Intrinsic::ctlz) {
     180         440 :       if (getTLI()->isCheapToSpeculateCtlz())
     181             :         return TargetTransformInfo::TCC_Basic;
     182             :       return TargetTransformInfo::TCC_Expensive;
     183             :     }
     184             : 
     185      280831 :     return BaseT::getIntrinsicCost(IID, RetTy, ParamTys);
     186             :   }
     187             : 
     188        1234 :   unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
     189             :                                             unsigned &JumpTableSize) {
     190             :     /// Try to find the estimated number of clusters. Note that the number of
     191             :     /// clusters identified in this function could be different from the actural
     192             :     /// numbers found in lowering. This function ignore switches that are
     193             :     /// lowered with a mix of jump table / bit test / BTree. This function was
     194             :     /// initially intended to be used when estimating the cost of switch in
     195             :     /// inline cost heuristic, but it's a generic cost model to be used in other
     196             :     /// places (e.g., in loop unrolling).
     197        1234 :     unsigned N = SI.getNumCases();
     198        1234 :     const TargetLoweringBase *TLI = getTLI();
     199        2468 :     const DataLayout &DL = this->getDataLayout();
     200             : 
     201        1234 :     JumpTableSize = 0;
     202        1234 :     bool IsJTAllowed = TLI->areJTsAllowed(SI.getParent()->getParent());
     203             : 
     204             :     // Early exit if both a jump table and bit test are not allowed.
     205        1234 :     if (N < 1 || (!IsJTAllowed && DL.getPointerSizeInBits() < N))
     206             :       return N;
     207             : 
     208        6170 :     APInt MaxCaseVal = SI.case_begin()->getCaseValue()->getValue();
     209        2468 :     APInt MinCaseVal = MaxCaseVal;
     210        6858 :     for (auto CI : SI.cases()) {
     211        8780 :       const APInt &CaseVal = CI.getCaseValue()->getValue();
     212        4390 :       if (CaseVal.sgt(MaxCaseVal))
     213         750 :         MaxCaseVal = CaseVal;
     214        4390 :       if (CaseVal.slt(MinCaseVal))
     215        1230 :         MinCaseVal = CaseVal;
     216             :     }
     217             : 
     218             :     // Check if suitable for a bit test
     219        1234 :     if (N <= DL.getPointerSizeInBits()) {
     220        2443 :       SmallPtrSet<const BasicBlock *, 4> Dests;
     221        6858 :       for (auto I : SI.cases())
     222        4390 :         Dests.insert(I.getCaseSuccessor());
     223             : 
     224        2468 :       if (TLI->isSuitableForBitTests(Dests.size(), N, MinCaseVal, MaxCaseVal,
     225             :                                      DL))
     226          50 :         return 1;
     227             :     }
     228             : 
     229             :     // Check if suitable for a jump table.
     230        1209 :     if (IsJTAllowed) {
     231        1209 :       if (N < 2 || N < TLI->getMinimumJumpTableEntries())
     232             :         return N;
     233         254 :       uint64_t Range =
     234        1270 :           (MaxCaseVal - MinCaseVal).getLimitedValue(UINT64_MAX - 1) + 1;
     235             :       // Check whether a range of clusters is dense enough for a jump table
     236         254 :       if (TLI->isSuitableForJumpTable(&SI, N, Range)) {
     237         202 :         JumpTableSize = Range;
     238         202 :         return 1;
     239             :       }
     240             :     }
     241             :     return N;
     242             :   }
     243             : 
     244           0 :   unsigned getJumpBufAlignment() { return getTLI()->getJumpBufAlignment(); }
     245             : 
     246           0 :   unsigned getJumpBufSize() { return getTLI()->getJumpBufSize(); }
     247             : 
     248             :   bool shouldBuildLookupTables() {
     249         321 :     const TargetLoweringBase *TLI = getTLI();
     250         616 :     return TLI->isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
     251         295 :            TLI->isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
     252             :   }
     253             : 
     254          45 :   bool haveFastSqrt(Type *Ty) {
     255          45 :     const TargetLoweringBase *TLI = getTLI();
     256          45 :     EVT VT = TLI->getValueType(DL, Ty);
     257          88 :     return TLI->isTypeLegal(VT) &&
     258          88 :            TLI->isOperationLegalOrCustom(ISD::FSQRT, VT);
     259             :   }
     260             : 
     261             :   unsigned getFPOpCost(Type *Ty) {
     262             :     // By default, FP instructions are no more expensive since they are
     263             :     // implemented in HW.  Target specific TTI can override this.
     264             :     return TargetTransformInfo::TCC_Basic;
     265             :   }
     266             : 
     267      876673 :   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
     268      876673 :     const TargetLoweringBase *TLI = getTLI();
     269      876673 :     switch (Opcode) {
     270             :     default: break;
     271        5745 :     case Instruction::Trunc: {
     272        5745 :       if (TLI->isTruncateFree(OpTy, Ty))
     273             :         return TargetTransformInfo::TCC_Free;
     274          10 :       return TargetTransformInfo::TCC_Basic;
     275             :     }
     276           0 :     case Instruction::ZExt: {
     277           0 :       if (TLI->isZExtFree(OpTy, Ty))
     278             :         return TargetTransformInfo::TCC_Free;
     279           0 :       return TargetTransformInfo::TCC_Basic;
     280             :     }
     281             :     }
     282             : 
     283      870928 :     return BaseT::getOperationCost(Opcode, Ty, OpTy);
     284             :   }
     285             : 
     286             :   unsigned getInliningThresholdMultiplier() { return 1; }
     287             : 
     288        5218 :   void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
     289             :                                TTI::UnrollingPreferences &UP) {
     290             :     // This unrolling functionality is target independent, but to provide some
     291             :     // motivation for its intended use, for x86:
     292             : 
     293             :     // According to the Intel 64 and IA-32 Architectures Optimization Reference
     294             :     // Manual, Intel Core models and later have a loop stream detector (and
     295             :     // associated uop queue) that can benefit from partial unrolling.
     296             :     // The relevant requirements are:
     297             :     //  - The loop must have no more than 4 (8 for Nehalem and later) branches
     298             :     //    taken, and none of them may be calls.
     299             :     //  - The loop can have no more than 18 (28 for Nehalem and later) uops.
     300             : 
     301             :     // According to the Software Optimization Guide for AMD Family 15h
     302             :     // Processors, models 30h-4fh (Steamroller and later) have a loop predictor
     303             :     // and loop buffer which can benefit from partial unrolling.
     304             :     // The relevant requirements are:
     305             :     //  - The loop must have fewer than 16 branches
     306             :     //  - The loop must have less than 40 uops in all executed loop branches
     307             : 
     308             :     // The number of taken branches in a loop is hard to estimate here, and
     309             :     // benchmarking has revealed that it is better not to be conservative when
     310             :     // estimating the branch count. As a result, we'll ignore the branch limits
     311             :     // until someone finds a case where it matters in practice.
     312             : 
     313             :     unsigned MaxOps;
     314        5218 :     const TargetSubtargetInfo *ST = getST();
     315        5218 :     if (PartialUnrollingThreshold.getNumOccurrences() > 0)
     316           0 :       MaxOps = PartialUnrollingThreshold;
     317        5218 :     else if (ST->getSchedModel().LoopMicroOpBufferSize > 0)
     318             :       MaxOps = ST->getSchedModel().LoopMicroOpBufferSize;
     319             :     else
     320             :       return;
     321             : 
     322             :     // Scan the loop: don't unroll loops with calls.
     323       18932 :     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
     324             :          ++I) {
     325        7510 :       BasicBlock *BB = *I;
     326             : 
     327       15020 :       for (BasicBlock::iterator J = BB->begin(), JE = BB->end(); J != JE; ++J)
     328      172602 :         if (isa<CallInst>(J) || isa<InvokeInst>(J)) {
     329       44652 :           ImmutableCallSite CS(&*J);
     330       22211 :           if (const Function *F = CS.getCalledFunction()) {
     331       22211 :             if (!static_cast<T *>(this)->isLoweredToCall(F))
     332       20304 :               continue;
     333             :           }
     334             : 
     335             :           return;
     336             :         }
     337             :     }
     338             : 
     339             :     // Enable runtime and partial unrolling up to the specified size.
     340             :     // Enable using trip count upper bound to unroll loops.
     341        1339 :     UP.Partial = UP.Runtime = UP.UpperBound = true;
     342        1339 :     UP.PartialThreshold = MaxOps;
     343             : 
     344             :     // Avoid unrolling when optimizing for size.
     345        1339 :     UP.OptSizeThreshold = 0;
     346        1339 :     UP.PartialOptSizeThreshold = 0;
     347             : 
     348             :     // Set number of instructions optimized when "back edge"
     349             :     // becomes "fall through" to default value of 2.
     350        1339 :     UP.BEInsns = 2;
     351             :   }
     352             : 
     353             :   int getInstructionLatency(const Instruction *I) {
     354           6 :     if (isa<LoadInst>(I))
     355             :       return getST()->getSchedModel().DefaultLoadLatency;
     356             : 
     357           2 :     return BaseT::getInstructionLatency(I);
     358             :   }
     359             : 
     360             :   /// @}
     361             : 
     362             :   /// \name Vector TTI Implementations
     363             :   /// @{
     364             : 
     365         656 :   unsigned getNumberOfRegisters(bool Vector) { return Vector ? 0 : 1; }
     366             : 
     367             :   unsigned getRegisterBitWidth(bool Vector) const { return 32; }
     368             : 
     369             :   /// Estimate the overhead of scalarizing an instruction. Insert and Extract
     370             :   /// are set if the result needs to be inserted and/or extracted from vectors.
     371        8899 :   unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
     372             :     assert(Ty->isVectorTy() && "Can only scalarize vectors");
     373        8899 :     unsigned Cost = 0;
     374             : 
     375       85418 :     for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
     376       67620 :       if (Insert)
     377       38946 :         Cost += static_cast<T *>(this)
     378             :                     ->getVectorInstrCost(Instruction::InsertElement, Ty, i);
     379       67620 :       if (Extract)
     380       31117 :         Cost += static_cast<T *>(this)
     381             :                     ->getVectorInstrCost(Instruction::ExtractElement, Ty, i);
     382             :     }
     383             : 
     384        8899 :     return Cost;
     385             :   }
     386             : 
     387             :   /// Estimate the overhead of scalarizing an instructions unique
     388             :   /// non-constant operands. The types of the arguments are ordinarily
     389             :   /// scalar, in which case the costs are multiplied with VF.
     390        2426 :   unsigned getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
     391             :                                             unsigned VF) {
     392        2426 :     unsigned Cost = 0;
     393        4852 :     SmallPtrSet<const Value*, 4> UniqueOperands;
     394        8544 :     for (const Value *A : Args) {
     395        6210 :       if (!isa<Constant>(A) && UniqueOperands.insert(A).second) {
     396        2517 :         Type *VecTy = nullptr;
     397        5034 :         if (A->getType()->isVectorTy()) {
     398             :           VecTy = A->getType();
     399             :           // If A is a vector operand, VF should be 1 or correspond to A.
     400             :           assert ((VF == 1 || VF == VecTy->getVectorNumElements()) &&
     401             :                   "Vector argument does not match VF");
     402             :         }
     403             :         else
     404        1757 :           VecTy = VectorType::get(A->getType(), VF);
     405             : 
     406        2517 :         Cost += getScalarizationOverhead(VecTy, false, true);
     407             :       }
     408             :     }
     409             : 
     410        4852 :     return Cost;
     411             :   }
     412             : 
     413         323 :   unsigned getScalarizationOverhead(Type *VecTy, ArrayRef<const Value *> Args) {
     414             :     assert (VecTy->isVectorTy());
     415             : 
     416         323 :     unsigned Cost = 0;
     417             : 
     418         323 :     Cost += getScalarizationOverhead(VecTy, true, false);
     419         323 :     if (!Args.empty())
     420          84 :       Cost += getOperandsScalarizationOverhead(Args,
     421             :                                                VecTy->getVectorNumElements());
     422             :     else
     423             :       // When no information on arguments is provided, we add the cost
     424             :       // associated with one argument as a heuristic.
     425         239 :       Cost += getScalarizationOverhead(VecTy, false, true);
     426             : 
     427         323 :     return Cost;
     428             :   }
     429             : 
     430             :   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
     431             : 
     432      142689 :   unsigned getArithmeticInstrCost(
     433             :       unsigned Opcode, Type *Ty,
     434             :       TTI::OperandValueKind Opd1Info = TTI::OK_AnyValue,
     435             :       TTI::OperandValueKind Opd2Info = TTI::OK_AnyValue,
     436             :       TTI::OperandValueProperties Opd1PropInfo = TTI::OP_None,
     437             :       TTI::OperandValueProperties Opd2PropInfo = TTI::OP_None,
     438             :       ArrayRef<const Value *> Args = ArrayRef<const Value *>()) {
     439             :     // Check if any of the operands are vector operands.
     440      142689 :     const TargetLoweringBase *TLI = getTLI();
     441      142689 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     442             :     assert(ISD && "Invalid opcode");
     443             : 
     444      285378 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
     445             : 
     446      141219 :     bool IsFloat = Ty->isFPOrFPVectorTy();
     447             :     // Assume that floating point arithmetic operations cost twice as much as
     448             :     // integer operations.
     449      142689 :     unsigned OpCost = (IsFloat ? 2 : 1);
     450             : 
     451      142689 :     if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
     452             :       // The operation is legal. Assume it costs 1.
     453             :       // TODO: Once we have extract/insert subvector cost we need to use them.
     454      141899 :       return LT.first * OpCost;
     455             :     }
     456             : 
     457        1550 :     if (!TLI->isOperationExpand(ISD, LT.second)) {
     458             :       // If the operation is custom lowered, then assume that the code is twice
     459             :       // as expensive.
     460          30 :       return LT.first * 2 * OpCost;
     461             :     }
     462             : 
     463             :     // Else, assume that we need to scalarize this op.
     464             :     // TODO: If one of the types get legalized by splitting, handle this
     465             :     // similarly to what getCastInstrCost() does.
     466         760 :     if (Ty->isVectorTy()) {
     467         307 :       unsigned Num = Ty->getVectorNumElements();
     468         614 :       unsigned Cost = static_cast<T *>(this)
     469             :                           ->getArithmeticInstrCost(Opcode, Ty->getScalarType());
     470             :       // Return the cost of multiple scalar invocation plus the cost of
     471             :       // inserting and extracting the values.
     472         307 :       return getScalarizationOverhead(Ty, Args) + Num * Cost;
     473             :     }
     474             : 
     475             :     // We don't know anything about this scalar instruction.
     476             :     return OpCost;
     477             :   }
     478             : 
     479             :   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
     480             :                           Type *SubTp) {
     481        2041 :     if (Kind == TTI::SK_Alternate || Kind == TTI::SK_PermuteTwoSrc ||
     482             :         Kind == TTI::SK_PermuteSingleSrc) {
     483           4 :       return getPermuteShuffleOverhead(Tp);
     484             :     }
     485             :     return 1;
     486             :   }
     487             : 
     488        3494 :   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
     489             :                             const Instruction *I = nullptr) {
     490        3498 :     const TargetLoweringBase *TLI = getTLI();
     491        3498 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     492             :     assert(ISD && "Invalid opcode");
     493        6996 :     std::pair<unsigned, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, Src);
     494        6996 :     std::pair<unsigned, MVT> DstLT = TLI->getTypeLegalizationCost(DL, Dst);
     495             : 
     496             :     // Check for NOOP conversions.
     497        6574 :     if (SrcLT.first == DstLT.first &&
     498        3076 :         SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
     499             : 
     500             :       // Bitcast between types that are legalized to the same type are free.
     501        1481 :       if (Opcode == Instruction::BitCast || Opcode == Instruction::Trunc)
     502             :         return 0;
     503             :     }
     504             : 
     505        3653 :     if (Opcode == Instruction::Trunc &&
     506        4327 :         TLI->isTruncateFree(SrcLT.second, DstLT.second))
     507             :       return 0;
     508             : 
     509        3174 :     if (Opcode == Instruction::ZExt &&
     510        3476 :         TLI->isZExtFree(SrcLT.second, DstLT.second))
     511             :       return 0;
     512             : 
     513        3030 :     if (Opcode == Instruction::AddrSpaceCast &&
     514          36 :         TLI->isNoopAddrSpaceCast(Src->getPointerAddressSpace(),
     515             :                                  Dst->getPointerAddressSpace()))
     516             :       return 0;
     517             : 
     518             :     // If this is a zext/sext of a load, return 0 if the corresponding
     519             :     // extending load exists on target.
     520        3260 :     if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
     521        3065 :         I && isa<LoadInst>(I->getOperand(0))) {
     522          12 :         EVT ExtVT = EVT::getEVT(Dst);
     523          12 :         EVT LoadVT = EVT::getEVT(Src);
     524          12 :         unsigned LType =
     525             :           ((Opcode == Instruction::ZExt) ? ISD::ZEXTLOAD : ISD::SEXTLOAD);
     526          24 :         if (TLI->isLoadExtLegal(LType, ExtVT, LoadVT))
     527          12 :           return 0;
     528             :     }
     529             : 
     530             :     // If the cast is marked as legal (or promote) then assume low cost.
     531        5588 :     if (SrcLT.first == DstLT.first &&
     532        2585 :         TLI->isOperationLegalOrPromote(ISD, DstLT.second))
     533             :       return 1;
     534             : 
     535             :     // Handle scalar conversions.
     536        2037 :     if (!Src->isVectorTy() && !Dst->isVectorTy()) {
     537             : 
     538             :       // Scalar bitcasts are usually free.
     539         500 :       if (Opcode == Instruction::BitCast)
     540             :         return 0;
     541             : 
     542             :       // Just check the op cost. If the operation is legal then assume it costs
     543             :       // 1.
     544         788 :       if (!TLI->isOperationExpand(ISD, DstLT.second))
     545             :         return 1;
     546             : 
     547             :       // Assume that illegal scalar instruction are expensive.
     548             :       return 4;
     549             :     }
     550             : 
     551             :     // Check vector-to-vector casts.
     552        2074 :     if (Dst->isVectorTy() && Src->isVectorTy()) {
     553             : 
     554             :       // If the cast is between same-sized registers, then the check is simple.
     555        1680 :       if (SrcLT.first == DstLT.first &&
     556         643 :           SrcLT.second.getSizeInBits() == DstLT.second.getSizeInBits()) {
     557             : 
     558             :         // Assume that Zext is done using AND.
     559         466 :         if (Opcode == Instruction::ZExt)
     560             :           return 1;
     561             : 
     562             :         // Assume that sext is done using SHL and SRA.
     563         453 :         if (Opcode == Instruction::SExt)
     564             :           return 2;
     565             : 
     566             :         // Just check the op cost. If the operation is legal then assume it
     567             :         // costs
     568             :         // 1 and multiply by the type-legalization overhead.
     569         435 :         if (!TLI->isOperationExpand(ISD, DstLT.second))
     570             :           return SrcLT.first * 1;
     571             :       }
     572             : 
     573             :       // If we are legalizing by splitting, query the concrete TTI for the cost
     574             :       // of casting the original vector twice. We also need to factor int the
     575             :       // cost of the split itself. Count that as 1, to be consistent with
     576             :       // TLI->getTypeLegalizationCost().
     577        1988 :       if ((TLI->getTypeAction(Src->getContext(), TLI->getValueType(DL, Src)) ==
     578        1664 :            TargetLowering::TypeSplitVector) ||
     579        1340 :           (TLI->getTypeAction(Dst->getContext(), TLI->getValueType(DL, Dst)) ==
     580             :            TargetLowering::TypeSplitVector)) {
     581         906 :         Type *SplitDst = VectorType::get(Dst->getVectorElementType(),
     582         453 :                                          Dst->getVectorNumElements() / 2);
     583         906 :         Type *SplitSrc = VectorType::get(Src->getVectorElementType(),
     584         453 :                                          Src->getVectorNumElements() / 2);
     585         453 :         T *TTI = static_cast<T *>(this);
     586         453 :         return TTI->getVectorSplitCost() +
     587         453 :                (2 * TTI->getCastInstrCost(Opcode, SplitDst, SplitSrc, I));
     588             :       }
     589             : 
     590             :       // In other cases where the source or destination are illegal, assume
     591             :       // the operation will get scalarized.
     592         541 :       unsigned Num = Dst->getVectorNumElements();
     593        1084 :       unsigned Cost = static_cast<T *>(this)->getCastInstrCost(
     594             :           Opcode, Dst->getScalarType(), Src->getScalarType(), I);
     595             : 
     596             :       // Return the cost of multiple scalar invocation plus the cost of
     597             :       // inserting and extracting the values.
     598         541 :       return getScalarizationOverhead(Dst, true, true) + Num * Cost;
     599             :     }
     600             : 
     601             :     // We already handled vector-to-vector and scalar-to-scalar conversions.
     602             :     // This
     603             :     // is where we handle bitcast between vectors and scalars. We need to assume
     604             :     //  that the conversion is scalarized in one way or another.
     605           0 :     if (Opcode == Instruction::BitCast)
     606             :       // Illegal bitcasts are done by storing and loading from a stack slot.
     607           0 :       return (Src->isVectorTy() ? getScalarizationOverhead(Src, false, true)
     608             :                                 : 0) +
     609           0 :              (Dst->isVectorTy() ? getScalarizationOverhead(Dst, true, false)
     610           0 :                                 : 0);
     611             : 
     612           0 :     llvm_unreachable("Unhandled cast");
     613             :   }
     614             : 
     615           4 :   unsigned getExtractWithExtendCost(unsigned Opcode, Type *Dst,
     616             :                                     VectorType *VecTy, unsigned Index) {
     617             :     return static_cast<T *>(this)->getVectorInstrCost(
     618           4 :                Instruction::ExtractElement, VecTy, Index) +
     619             :            static_cast<T *>(this)->getCastInstrCost(Opcode, Dst,
     620           4 :                                                     VecTy->getElementType());
     621             :   }
     622             : 
     623             :   unsigned getCFInstrCost(unsigned Opcode) {
     624             :     // Branches are assumed to be predicted.
     625             :     return 0;
     626             :   }
     627             : 
     628        8673 :   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
     629             :                               const Instruction *I) {
     630        8673 :     const TargetLoweringBase *TLI = getTLI();
     631        8673 :     int ISD = TLI->InstructionOpcodeToISD(Opcode);
     632             :     assert(ISD && "Invalid opcode");
     633             : 
     634             :     // Selects on vectors are actually vector selects.
     635        8673 :     if (ISD == ISD::SELECT) {
     636             :       assert(CondTy && "CondTy must exist");
     637        3739 :       if (CondTy->isVectorTy())
     638        2097 :         ISD = ISD::VSELECT;
     639             :     }
     640       17346 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
     641             : 
     642       12442 :     if (!(ValTy->isVectorTy() && !LT.second.isVector()) &&
     643        8672 :         !TLI->isOperationExpand(ISD, LT.second)) {
     644             :       // The operation is legal. Assume it costs 1. Multiply
     645             :       // by the type-legalization overhead.
     646        6978 :       return LT.first * 1;
     647             :     }
     648             : 
     649             :     // Otherwise, assume that the cast is scalarized.
     650             :     // TODO: If one of the types get legalized by splitting, handle this
     651             :     // similarly to what getCastInstrCost() does.
     652        1695 :     if (ValTy->isVectorTy()) {
     653        1662 :       unsigned Num = ValTy->getVectorNumElements();
     654        1662 :       if (CondTy)
     655             :         CondTy = CondTy->getScalarType();
     656        1662 :       unsigned Cost = static_cast<T *>(this)->getCmpSelInstrCost(
     657             :           Opcode, ValTy->getScalarType(), CondTy, I);
     658             : 
     659             :       // Return the cost of multiple scalar invocation plus the cost of
     660             :       // inserting and extracting the values.
     661        1662 :       return getScalarizationOverhead(ValTy, true, false) + Num * Cost;
     662             :     }
     663             : 
     664             :     // Unknown scalar opcode.
     665             :     return 1;
     666             :   }
     667             : 
     668             :   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
     669      269550 :     std::pair<unsigned, MVT> LT =
     670             :         getTLI()->getTypeLegalizationCost(DL, Val->getScalarType());
     671             : 
     672             :     return LT.first;
     673             :   }
     674             : 
     675         805 :   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
     676             :                        unsigned AddressSpace, const Instruction *I = nullptr) {
     677             :     assert(!Src->isVoidTy() && "Invalid type");
     678        1610 :     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Src);
     679             : 
     680             :     // Assuming that all loads of legal types cost 1.
     681         805 :     unsigned Cost = LT.first;
     682             : 
     683        1265 :     if (Src->isVectorTy() &&
     684         460 :         Src->getPrimitiveSizeInBits() < LT.second.getSizeInBits()) {
     685             :       // This is a vector load that legalizes to a larger type than the vector
     686             :       // itself. Unless the corresponding extending load or truncating store is
     687             :       // legal, then this will scalarize.
     688          57 :       TargetLowering::LegalizeAction LA = TargetLowering::Expand;
     689          57 :       EVT MemVT = getTLI()->getValueType(DL, Src);
     690          57 :       if (Opcode == Instruction::Store)
     691          57 :         LA = getTLI()->getTruncStoreAction(LT.second, MemVT);
     692             :       else
     693         114 :         LA = getTLI()->getLoadExtAction(ISD::EXTLOAD, LT.second, MemVT);
     694             : 
     695          57 :       if (LA != TargetLowering::Legal && LA != TargetLowering::Custom) {
     696             :         // This is a vector load/store for some illegal type that is scalarized.
     697             :         // We must account for the cost of building or decomposing the vector.
     698          52 :         Cost += getScalarizationOverhead(Src, Opcode != Instruction::Store,
     699             :                                          Opcode == Instruction::Store);
     700             :       }
     701             :     }
     702             : 
     703         805 :     return Cost;
     704             :   }
     705             : 
     706          17 :   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
     707             :                                       unsigned Factor,
     708             :                                       ArrayRef<unsigned> Indices,
     709             :                                       unsigned Alignment,
     710             :                                       unsigned AddressSpace) {
     711          17 :     VectorType *VT = dyn_cast<VectorType>(VecTy);
     712             :     assert(VT && "Expect a vector type for interleaved memory op");
     713             : 
     714          17 :     unsigned NumElts = VT->getNumElements();
     715             :     assert(Factor > 1 && NumElts % Factor == 0 && "Invalid interleave factor");
     716             : 
     717          17 :     unsigned NumSubElts = NumElts / Factor;
     718          17 :     VectorType *SubVT = VectorType::get(VT->getElementType(), NumSubElts);
     719             : 
     720             :     // Firstly, the cost of load/store operation.
     721          17 :     unsigned Cost = static_cast<T *>(this)->getMemoryOpCost(
     722             :         Opcode, VecTy, Alignment, AddressSpace);
     723             : 
     724             :     // Legalize the vector type, and get the legalized and unlegalized type
     725             :     // sizes.
     726          17 :     MVT VecTyLT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
     727          17 :     unsigned VecTySize =
     728          34 :         static_cast<T *>(this)->getDataLayout().getTypeStoreSize(VecTy);
     729          17 :     unsigned VecTyLTSize = VecTyLT.getStoreSize();
     730             : 
     731             :     // Return the ceiling of dividing A by B.
     732          18 :     auto ceil = [](unsigned A, unsigned B) { return (A + B - 1) / B; };
     733             : 
     734             :     // Scale the cost of the memory operation by the fraction of legalized
     735             :     // instructions that will actually be used. We shouldn't account for the
     736             :     // cost of dead instructions since they will be removed.
     737             :     //
     738             :     // E.g., An interleaved load of factor 8:
     739             :     //       %vec = load <16 x i64>, <16 x i64>* %ptr
     740             :     //       %v0 = shufflevector %vec, undef, <0, 8>
     741             :     //
     742             :     // If <16 x i64> is legalized to 8 v2i64 loads, only 2 of the loads will be
     743             :     // used (those corresponding to elements [0:1] and [8:9] of the unlegalized
     744             :     // type). The other loads are unused.
     745             :     //
     746             :     // We only scale the cost of loads since interleaved store groups aren't
     747             :     // allowed to have gaps.
     748          17 :     if (Opcode == Instruction::Load && VecTySize > VecTyLTSize) {
     749             : 
     750             :       // The number of loads of a legal type it will take to represent a load
     751             :       // of the unlegalized vector type.
     752           9 :       unsigned NumLegalInsts = ceil(VecTySize, VecTyLTSize);
     753             : 
     754             :       // The number of elements of the unlegalized type that correspond to a
     755             :       // single legal instruction.
     756           9 :       unsigned NumEltsPerLegalInst = ceil(NumElts, NumLegalInsts);
     757             : 
     758             :       // Determine which legal instructions will be used.
     759          18 :       BitVector UsedInsts(NumLegalInsts, false);
     760          40 :       for (unsigned Index : Indices)
     761          74 :         for (unsigned Elt = 0; Elt < NumSubElts; ++Elt)
     762         104 :           UsedInsts.set((Index + Elt * Factor) / NumEltsPerLegalInst);
     763             : 
     764             :       // Scale the cost of the load by the fraction of legal instructions that
     765             :       // will be used.
     766           9 :       Cost *= UsedInsts.count() / NumLegalInsts;
     767             :     }
     768             : 
     769             :     // Then plus the cost of interleave operation.
     770          17 :     if (Opcode == Instruction::Load) {
     771             :       // The interleave cost is similar to extract sub vectors' elements
     772             :       // from the wide vector, and insert them into sub vectors.
     773             :       //
     774             :       // E.g. An interleaved load of factor 2 (with one member of index 0):
     775             :       //      %vec = load <8 x i32>, <8 x i32>* %ptr
     776             :       //      %v0 = shuffle %vec, undef, <0, 2, 4, 6>         ; Index 0
     777             :       // The cost is estimated as extract elements at 0, 2, 4, 6 from the
     778             :       // <8 x i32> vector and insert them into a <4 x i32> vector.
     779             : 
     780             :       assert(Indices.size() <= Factor &&
     781             :              "Interleaved memory op has too many members");
     782             : 
     783          48 :       for (unsigned Index : Indices) {
     784             :         assert(Index < Factor && "Invalid index for interleaved memory op");
     785             : 
     786             :         // Extract elements from loaded vector for each sub vector.
     787          86 :         for (unsigned i = 0; i < NumSubElts; i++)
     788          60 :           Cost += static_cast<T *>(this)->getVectorInstrCost(
     789          60 :               Instruction::ExtractElement, VT, Index + i * Factor);
     790             :       }
     791             : 
     792             :       unsigned InsSubCost = 0;
     793          63 :       for (unsigned i = 0; i < NumSubElts; i++)
     794          26 :         InsSubCost += static_cast<T *>(this)->getVectorInstrCost(
     795             :             Instruction::InsertElement, SubVT, i);
     796             : 
     797          11 :       Cost += Indices.size() * InsSubCost;
     798             :     } else {
     799             :       // The interleave cost is extract all elements from sub vectors, and
     800             :       // insert them into the wide vector.
     801             :       //
     802             :       // E.g. An interleaved store of factor 2:
     803             :       //      %v0_v1 = shuffle %v0, %v1, <0, 4, 1, 5, 2, 6, 3, 7>
     804             :       //      store <8 x i32> %interleaved.vec, <8 x i32>* %ptr
     805             :       // The cost is estimated as extract all elements from both <4 x i32>
     806             :       // vectors and insert into the <8 x i32> vector.
     807             : 
     808             :       unsigned ExtSubCost = 0;
     809          34 :       for (unsigned i = 0; i < NumSubElts; i++)
     810          14 :         ExtSubCost += static_cast<T *>(this)->getVectorInstrCost(
     811             :             Instruction::ExtractElement, SubVT, i);
     812           6 :       Cost += ExtSubCost * Factor;
     813             : 
     814          48 :       for (unsigned i = 0; i < NumElts; i++)
     815          42 :         Cost += static_cast<T *>(this)
     816             :                     ->getVectorInstrCost(Instruction::InsertElement, VT, i);
     817             :     }
     818             : 
     819          17 :     return Cost;
     820             :   }
     821             : 
     822             :   /// Get intrinsic cost based on arguments.
     823        2284 :   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
     824             :                                  ArrayRef<Value *> Args, FastMathFlags FMF,
     825             :                                  unsigned VF = 1) {
     826        3205 :     unsigned RetVF = (RetTy->isVectorTy() ? RetTy->getVectorNumElements() : 1);
     827             :     assert ((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type");
     828             : 
     829        2284 :     switch (IID) {
     830        2247 :     default: {
     831             :       // Assume that we need to scalarize this intrinsic.
     832        4494 :       SmallVector<Type *, 4> Types;
     833        8028 :       for (Value *Op : Args) {
     834        3534 :         Type *OpTy = Op->getType();
     835             :         assert (VF == 1 || !OpTy->isVectorTy());
     836        3534 :         Types.push_back(VF == 1 ? OpTy : VectorType::get(OpTy, VF));
     837             :       }
     838             : 
     839        3296 :       if (VF > 1 && !RetTy->isVoidTy())
     840        1045 :         RetTy = VectorType::get(RetTy, VF);
     841             : 
     842             :       // Compute the scalarization overhead based on Args for a vector
     843             :       // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while
     844             :       // CostModel will pass a vector RetTy and VF is 1.
     845        2247 :       unsigned ScalarizationCost = UINT_MAX;
     846        2247 :       if (RetVF > 1 || VF > 1) {
     847        1942 :         ScalarizationCost = 0;
     848        1942 :         if (!RetTy->isVoidTy())
     849        1938 :           ScalarizationCost += getScalarizationOverhead(RetTy, true, false);
     850        1942 :         ScalarizationCost += getOperandsScalarizationOverhead(Args, VF);
     851             :       }
     852             : 
     853             :       return static_cast<T *>(this)->
     854        2280 :         getIntrinsicInstrCost(IID, RetTy, Types, FMF, ScalarizationCost);
     855             :     }
     856           9 :     case Intrinsic::masked_scatter: {
     857             :       assert (VF == 1 && "Can't vectorize types here.");
     858           9 :       Value *Mask = Args[3];
     859          18 :       bool VarMask = !isa<Constant>(Mask);
     860          27 :       unsigned Alignment = cast<ConstantInt>(Args[2])->getZExtValue();
     861             :       return
     862             :         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Store,
     863           9 :                                                        Args[0]->getType(),
     864             :                                                        Args[1], VarMask,
     865          18 :                                                        Alignment);
     866             :     }
     867          28 :     case Intrinsic::masked_gather: {
     868             :       assert (VF == 1 && "Can't vectorize types here.");
     869          28 :       Value *Mask = Args[2];
     870          56 :       bool VarMask = !isa<Constant>(Mask);
     871          84 :       unsigned Alignment = cast<ConstantInt>(Args[1])->getZExtValue();
     872             :       return
     873             :         static_cast<T *>(this)->getGatherScatterOpCost(Instruction::Load,
     874             :                                                        RetTy, Args[0], VarMask,
     875          28 :                                                        Alignment);
     876             :     }
     877             :     }
     878             :   }
     879             : 
     880             :   /// Get intrinsic cost based on argument types.
     881             :   /// If ScalarizationCostPassed is UINT_MAX, the cost of scalarizing the
     882             :   /// arguments and the return value will be computed based on types.
     883        2218 :   unsigned getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
     884             :                           ArrayRef<Type *> Tys, FastMathFlags FMF,
     885             :                           unsigned ScalarizationCostPassed = UINT_MAX) {
     886        4436 :     SmallVector<unsigned, 2> ISDs;
     887        2218 :     unsigned SingleCallCost = 10; // Library call cost. Make it expensive.
     888        2218 :     switch (IID) {
     889         425 :     default: {
     890             :       // Assume that we need to scalarize this intrinsic.
     891         425 :       unsigned ScalarizationCost = ScalarizationCostPassed;
     892         425 :       unsigned ScalarCalls = 1;
     893         425 :       Type *ScalarRetTy = RetTy;
     894         425 :       if (RetTy->isVectorTy()) {
     895           7 :         if (ScalarizationCostPassed == UINT_MAX)
     896           0 :           ScalarizationCost = getScalarizationOverhead(RetTy, true, false);
     897          14 :         ScalarCalls = std::max(ScalarCalls, RetTy->getVectorNumElements());
     898             :         ScalarRetTy = RetTy->getScalarType();
     899             :       }
     900         850 :       SmallVector<Type *, 4> ScalarTys;
     901        1238 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
     902        1626 :         Type *Ty = Tys[i];
     903        1626 :         if (Ty->isVectorTy()) {
     904           9 :           if (ScalarizationCostPassed == UINT_MAX)
     905           0 :             ScalarizationCost += getScalarizationOverhead(Ty, false, true);
     906          27 :           ScalarCalls = std::max(ScalarCalls, Ty->getVectorNumElements());
     907          18 :           Ty = Ty->getScalarType();
     908             :         }
     909         813 :         ScalarTys.push_back(Ty);
     910             :       }
     911         425 :       if (ScalarCalls == 1)
     912             :         return 1; // Return cost of a scalar intrinsic. Assume it to be cheap.
     913             : 
     914          12 :       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
     915             :           IID, ScalarRetTy, ScalarTys, FMF);
     916             : 
     917           7 :       return ScalarCalls * ScalarCost + ScalarizationCost;
     918             :     }
     919             :     // Look for intrinsics that can be lowered directly or turned into a scalar
     920             :     // intrinsic call.
     921           6 :     case Intrinsic::sqrt:
     922           6 :       ISDs.push_back(ISD::FSQRT);
     923           6 :       break;
     924          25 :     case Intrinsic::sin:
     925          25 :       ISDs.push_back(ISD::FSIN);
     926          25 :       break;
     927          25 :     case Intrinsic::cos:
     928          25 :       ISDs.push_back(ISD::FCOS);
     929          25 :       break;
     930          44 :     case Intrinsic::exp:
     931          44 :       ISDs.push_back(ISD::FEXP);
     932          44 :       break;
     933           3 :     case Intrinsic::exp2:
     934           3 :       ISDs.push_back(ISD::FEXP2);
     935           3 :       break;
     936          22 :     case Intrinsic::log:
     937          22 :       ISDs.push_back(ISD::FLOG);
     938          22 :       break;
     939          11 :     case Intrinsic::log10:
     940          11 :       ISDs.push_back(ISD::FLOG10);
     941          11 :       break;
     942           0 :     case Intrinsic::log2:
     943           0 :       ISDs.push_back(ISD::FLOG2);
     944           0 :       break;
     945         169 :     case Intrinsic::fabs:
     946         169 :       ISDs.push_back(ISD::FABS);
     947         169 :       break;
     948           0 :     case Intrinsic::minnum:
     949           0 :       ISDs.push_back(ISD::FMINNUM);
     950           0 :       if (FMF.noNaNs())
     951           0 :         ISDs.push_back(ISD::FMINNAN);
     952             :       break;
     953           0 :     case Intrinsic::maxnum:
     954           0 :       ISDs.push_back(ISD::FMAXNUM);
     955           0 :       if (FMF.noNaNs())
     956           0 :         ISDs.push_back(ISD::FMAXNAN);
     957             :       break;
     958         138 :     case Intrinsic::copysign:
     959         138 :       ISDs.push_back(ISD::FCOPYSIGN);
     960         138 :       break;
     961         197 :     case Intrinsic::floor:
     962         197 :       ISDs.push_back(ISD::FFLOOR);
     963         197 :       break;
     964         176 :     case Intrinsic::ceil:
     965         176 :       ISDs.push_back(ISD::FCEIL);
     966         176 :       break;
     967         162 :     case Intrinsic::trunc:
     968         162 :       ISDs.push_back(ISD::FTRUNC);
     969         162 :       break;
     970         165 :     case Intrinsic::nearbyint:
     971         165 :       ISDs.push_back(ISD::FNEARBYINT);
     972         165 :       break;
     973         162 :     case Intrinsic::rint:
     974         162 :       ISDs.push_back(ISD::FRINT);
     975         162 :       break;
     976           0 :     case Intrinsic::round:
     977           0 :       ISDs.push_back(ISD::FROUND);
     978           0 :       break;
     979          25 :     case Intrinsic::pow:
     980          25 :       ISDs.push_back(ISD::FPOW);
     981          25 :       break;
     982         344 :     case Intrinsic::fma:
     983         344 :       ISDs.push_back(ISD::FMA);
     984         344 :       break;
     985           2 :     case Intrinsic::fmuladd:
     986           2 :       ISDs.push_back(ISD::FMA);
     987           2 :       break;
     988             :     // FIXME: We should return 0 whenever getIntrinsicCost == TCC_Free.
     989             :     case Intrinsic::lifetime_start:
     990             :     case Intrinsic::lifetime_end:
     991             :       return 0;
     992           9 :     case Intrinsic::masked_store:
     993             :       return static_cast<T *>(this)
     994           9 :           ->getMaskedMemoryOpCost(Instruction::Store, Tys[0], 0, 0);
     995          15 :     case Intrinsic::masked_load:
     996             :       return static_cast<T *>(this)
     997          15 :           ->getMaskedMemoryOpCost(Instruction::Load, RetTy, 0, 0);
     998          88 :     case Intrinsic::ctpop:
     999          88 :       ISDs.push_back(ISD::CTPOP);
    1000             :       // In case of legalization use TCC_Expensive. This is cheaper than a
    1001             :       // library call but still not a cheap instruction.
    1002          88 :       SingleCallCost = TargetTransformInfo::TCC_Expensive;
    1003          88 :       break;
    1004             :     // FIXME: ctlz, cttz, ...
    1005             :     }
    1006             : 
    1007        1764 :     const TargetLoweringBase *TLI = getTLI();
    1008        3528 :     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
    1009             : 
    1010        1764 :     SmallVector<unsigned, 2> LegalCost;
    1011        3528 :     SmallVector<unsigned, 2> CustomCost;
    1012        7041 :     for (unsigned ISD : ISDs) {
    1013        1764 :       if (TLI->isOperationLegalOrPromote(ISD, LT.second)) {
    1014         561 :         if (IID == Intrinsic::fabs && TLI->isFAbsFree(LT.second)) {
    1015             :           return 0;
    1016             :         }
    1017             : 
    1018             :         // The operation is legal. Assume it costs 1.
    1019             :         // If the type is split to multiple registers, assume that there is some
    1020             :         // overhead to this.
    1021             :         // TODO: Once we have extract/insert subvector cost we need to use them.
    1022         529 :         if (LT.first > 1)
    1023           7 :           LegalCost.push_back(LT.first * 2);
    1024             :         else
    1025         522 :           LegalCost.push_back(LT.first * 1);
    1026        2154 :       } else if (!TLI->isOperationExpand(ISD, LT.second)) {
    1027             :         // If the operation is custom lowered then assume
    1028             :         // that the code is twice as expensive.
    1029         286 :         CustomCost.push_back(LT.first * 2);
    1030             :       }
    1031             :     }
    1032             : 
    1033        5247 :     auto MinLegalCostI = std::min_element(LegalCost.begin(), LegalCost.end());
    1034        1749 :     if (MinLegalCostI != LegalCost.end())
    1035         529 :       return *MinLegalCostI;
    1036             : 
    1037        3660 :     auto MinCustomCostI = std::min_element(CustomCost.begin(), CustomCost.end());
    1038        1220 :     if (MinCustomCostI != CustomCost.end())
    1039         286 :       return *MinCustomCostI;
    1040             : 
    1041             :     // If we can't lower fmuladd into an FMA estimate the cost as a floating
    1042             :     // point mul followed by an add.
    1043         934 :     if (IID == Intrinsic::fmuladd)
    1044             :       return static_cast<T *>(this)
    1045           4 :                  ->getArithmeticInstrCost(BinaryOperator::FMul, RetTy) +
    1046             :              static_cast<T *>(this)
    1047           2 :                  ->getArithmeticInstrCost(BinaryOperator::FAdd, RetTy);
    1048             : 
    1049             :     // Else, assume that we need to scalarize this intrinsic. For math builtins
    1050             :     // this will emit a costly libcall, adding call overhead and spills. Make it
    1051             :     // very expensive.
    1052         932 :     if (RetTy->isVectorTy()) {
    1053         334 :       unsigned ScalarizationCost = ((ScalarizationCostPassed != UINT_MAX) ?
    1054             :          ScalarizationCostPassed : getScalarizationOverhead(RetTy, true, false));
    1055         334 :       unsigned ScalarCalls = RetTy->getVectorNumElements();
    1056         668 :       SmallVector<Type *, 4> ScalarTys;
    1057         855 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
    1058        1042 :         Type *Ty = Tys[i];
    1059        1042 :         if (Ty->isVectorTy())
    1060        1042 :           Ty = Ty->getScalarType();
    1061         521 :         ScalarTys.push_back(Ty);
    1062             :       }
    1063         672 :       unsigned ScalarCost = static_cast<T *>(this)->getIntrinsicInstrCost(
    1064             :           IID, RetTy->getScalarType(), ScalarTys, FMF);
    1065         855 :       for (unsigned i = 0, ie = Tys.size(); i != ie; ++i) {
    1066        1563 :         if (Tys[i]->isVectorTy()) {
    1067         521 :           if (ScalarizationCostPassed == UINT_MAX)
    1068           0 :             ScalarizationCost += getScalarizationOverhead(Tys[i], false, true);
    1069        1563 :           ScalarCalls = std::max(ScalarCalls, Tys[i]->getVectorNumElements());
    1070             :         }
    1071             :       }
    1072             : 
    1073         334 :       return ScalarCalls * ScalarCost + ScalarizationCost;
    1074             :     }
    1075             : 
    1076             :     // This is going to be turned into a library call, make it expensive.
    1077             :     return SingleCallCost;
    1078             :   }
    1079             : 
    1080             :   /// \brief Compute a cost of the given call instruction.
    1081             :   ///
    1082             :   /// Compute the cost of calling function F with return type RetTy and
    1083             :   /// argument types Tys. F might be nullptr, in this case the cost of an
    1084             :   /// arbitrary call with the specified signature will be returned.
    1085             :   /// This is used, for instance,  when we estimate call of a vector
    1086             :   /// counterpart of the given function.
    1087             :   /// \param F Called function, might be nullptr.
    1088             :   /// \param RetTy Return value types.
    1089             :   /// \param Tys Argument types.
    1090             :   /// \returns The cost of Call instruction.
    1091             :   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
    1092             :     return 10;
    1093             :   }
    1094             : 
    1095             :   unsigned getNumberOfParts(Type *Tp) {
    1096       26064 :     std::pair<unsigned, MVT> LT = getTLI()->getTypeLegalizationCost(DL, Tp);
    1097             :     return LT.first;
    1098             :   }
    1099             : 
    1100             :   unsigned getAddressComputationCost(Type *Ty, ScalarEvolution *,
    1101             :                                      const SCEV *) {
    1102             :     return 0;
    1103             :   }
    1104             : 
    1105             :   /// Try to calculate arithmetic and shuffle op costs for reduction operations.
    1106             :   /// We're assuming that reduction operation are performing the following way:
    1107             :   /// 1. Non-pairwise reduction
    1108             :   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
    1109             :   /// <n x i32> <i32 n/2, i32 n/2 + 1, ..., i32 n, i32 undef, ..., i32 undef>
    1110             :   ///            \----------------v-------------/  \----------v------------/
    1111             :   ///                            n/2 elements               n/2 elements
    1112             :   /// %red1 = op <n x t> %val, <n x t> val1
    1113             :   /// After this operation we have a vector %red1 where only the first n/2
    1114             :   /// elements are meaningful, the second n/2 elements are undefined and can be
    1115             :   /// dropped. All other operations are actually working with the vector of
    1116             :   /// length n/2, not n, though the real vector length is still n.
    1117             :   /// %val2 = shufflevector<n x t> %red1, <n x t> %undef,
    1118             :   /// <n x i32> <i32 n/4, i32 n/4 + 1, ..., i32 n/2, i32 undef, ..., i32 undef>
    1119             :   ///            \----------------v-------------/  \----------v------------/
    1120             :   ///                            n/4 elements               3*n/4 elements
    1121             :   /// %red2 = op <n x t> %red1, <n x t> val2  - working with the vector of
    1122             :   /// length n/2, the resulting vector has length n/4 etc.
    1123             :   /// 2. Pairwise reduction:
    1124             :   /// Everything is the same except for an additional shuffle operation which
    1125             :   /// is used to produce operands for pairwise kind of reductions.
    1126             :   /// %val1 = shufflevector<n x t> %val, <n x t> %undef,
    1127             :   /// <n x i32> <i32 0, i32 2, ..., i32 n-2, i32 undef, ..., i32 undef>
    1128             :   ///            \-------------v----------/  \----------v------------/
    1129             :   ///                   n/2 elements               n/2 elements
    1130             :   /// %val2 = shufflevector<n x t> %val, <n x t> %undef,
    1131             :   /// <n x i32> <i32 1, i32 3, ..., i32 n-1, i32 undef, ..., i32 undef>
    1132             :   ///            \-------------v----------/  \----------v------------/
    1133             :   ///                   n/2 elements               n/2 elements
    1134             :   /// %red1 = op <n x t> %val1, <n x t> val2
    1135             :   /// Again, the operation is performed on <n x t> vector, but the resulting
    1136             :   /// vector %red1 is <n/2 x t> vector.
    1137             :   ///
    1138             :   /// The cost model should take into account that the actual length of the
    1139             :   /// vector is reduced on each iteration.
    1140          45 :   unsigned getArithmeticReductionCost(unsigned Opcode, Type *Ty,
    1141             :                                       bool IsPairwise) {
    1142             :     assert(Ty->isVectorTy() && "Expect a vector type");
    1143          90 :     Type *ScalarTy = Ty->getVectorElementType();
    1144          45 :     unsigned NumVecElts = Ty->getVectorNumElements();
    1145          45 :     unsigned NumReduxLevels = Log2_32(NumVecElts);
    1146          45 :     unsigned ArithCost = 0;
    1147          45 :     unsigned ShuffleCost = 0;
    1148          45 :     auto *ConcreteTTI = static_cast<T *>(this);
    1149          90 :     std::pair<unsigned, MVT> LT =
    1150          45 :         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
    1151          45 :     unsigned LongVectorCount = 0;
    1152          45 :     unsigned MVTLen =
    1153          45 :         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
    1154          87 :     while (NumVecElts > MVTLen) {
    1155          21 :       NumVecElts /= 2;
    1156             :       // Assume the pairwise shuffles add a cost.
    1157          21 :       ShuffleCost += (IsPairwise + 1) *
    1158             :                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1159             :                                                  NumVecElts, Ty);
    1160          21 :       ArithCost += ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
    1161          21 :       Ty = VectorType::get(ScalarTy, NumVecElts);
    1162          21 :       ++LongVectorCount;
    1163             :     }
    1164             :     // The minimal length of the vector is limited by the real length of vector
    1165             :     // operations performed on the current platform. That's why several final
    1166             :     // reduction operations are performed on the vectors with the same
    1167             :     // architecture-dependent length.
    1168          45 :     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
    1169             :                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1170             :                                                NumVecElts, Ty);
    1171          45 :     ArithCost += (NumReduxLevels - LongVectorCount) *
    1172             :                  ConcreteTTI->getArithmeticInstrCost(Opcode, Ty);
    1173          45 :     return ShuffleCost + ArithCost + getScalarizationOverhead(Ty, false, true);
    1174             :   }
    1175             : 
    1176             :   /// Try to calculate op costs for min/max reduction operations.
    1177             :   /// \param CondTy Conditional type for the Select instruction.
    1178        1028 :   unsigned getMinMaxReductionCost(Type *Ty, Type *CondTy, bool IsPairwise,
    1179             :                                   bool) {
    1180             :     assert(Ty->isVectorTy() && "Expect a vector type");
    1181        2056 :     Type *ScalarTy = Ty->getVectorElementType();
    1182        2056 :     Type *ScalarCondTy = CondTy->getVectorElementType();
    1183        1028 :     unsigned NumVecElts = Ty->getVectorNumElements();
    1184        1028 :     unsigned NumReduxLevels = Log2_32(NumVecElts);
    1185             :     unsigned CmpOpcode;
    1186         254 :     if (Ty->isFPOrFPVectorTy()) {
    1187             :       CmpOpcode = Instruction::FCmp;
    1188             :     } else {
    1189             :       assert(Ty->isIntOrIntVectorTy() &&
    1190             :              "expecting floating point or integer type for min/max reduction");
    1191             :       CmpOpcode = Instruction::ICmp;
    1192             :     }
    1193        1028 :     unsigned MinMaxCost = 0;
    1194        1028 :     unsigned ShuffleCost = 0;
    1195        1028 :     auto *ConcreteTTI = static_cast<T *>(this);
    1196        2056 :     std::pair<unsigned, MVT> LT =
    1197        1028 :         ConcreteTTI->getTLI()->getTypeLegalizationCost(DL, Ty);
    1198        1028 :     unsigned LongVectorCount = 0;
    1199        1028 :     unsigned MVTLen =
    1200        1028 :         LT.second.isVector() ? LT.second.getVectorNumElements() : 1;
    1201        2912 :     while (NumVecElts > MVTLen) {
    1202         942 :       NumVecElts /= 2;
    1203             :       // Assume the pairwise shuffles add a cost.
    1204         942 :       ShuffleCost += (IsPairwise + 1) *
    1205             :                      ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1206             :                                                  NumVecElts, Ty);
    1207         942 :       MinMaxCost +=
    1208         942 :           ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
    1209             :           ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
    1210             :                                           nullptr);
    1211         942 :       Ty = VectorType::get(ScalarTy, NumVecElts);
    1212         942 :       CondTy = VectorType::get(ScalarCondTy, NumVecElts);
    1213         942 :       ++LongVectorCount;
    1214             :     }
    1215             :     // The minimal length of the vector is limited by the real length of vector
    1216             :     // operations performed on the current platform. That's why several final
    1217             :     // reduction opertions are perfomed on the vectors with the same
    1218             :     // architecture-dependent length.
    1219        1028 :     ShuffleCost += (NumReduxLevels - LongVectorCount) * (IsPairwise + 1) *
    1220             :                    ConcreteTTI->getShuffleCost(TTI::SK_ExtractSubvector, Ty,
    1221             :                                                NumVecElts, Ty);
    1222        1028 :     MinMaxCost +=
    1223        1028 :         (NumReduxLevels - LongVectorCount) *
    1224        1028 :         (ConcreteTTI->getCmpSelInstrCost(CmpOpcode, Ty, CondTy, nullptr) +
    1225             :          ConcreteTTI->getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
    1226             :                                          nullptr));
    1227             :     // Need 3 extractelement instructions for scalarization + an additional
    1228             :     // scalar select instruction.
    1229        2056 :     return ShuffleCost + MinMaxCost +
    1230        1028 :            3 * getScalarizationOverhead(Ty, /*Insert=*/false,
    1231        1028 :                                         /*Extract=*/true) +
    1232             :            ConcreteTTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
    1233        1028 :                                            ScalarCondTy, nullptr);
    1234             :   }
    1235             : 
    1236             :   unsigned getVectorSplitCost() { return 1; }
    1237             : 
    1238             :   /// @}
    1239             : };
    1240             : 
    1241             : /// \brief Concrete BasicTTIImpl that can be used if no further customization
    1242             : /// is needed.
    1243      258588 : class BasicTTIImpl : public BasicTTIImplBase<BasicTTIImpl> {
    1244             :   typedef BasicTTIImplBase<BasicTTIImpl> BaseT;
    1245             :   friend class BasicTTIImplBase<BasicTTIImpl>;
    1246             : 
    1247             :   const TargetSubtargetInfo *ST;
    1248             :   const TargetLoweringBase *TLI;
    1249             : 
    1250             :   const TargetSubtargetInfo *getST() const { return ST; }
    1251             :   const TargetLoweringBase *getTLI() const { return TLI; }
    1252             : 
    1253             : public:
    1254             :   explicit BasicTTIImpl(const TargetMachine *ST, const Function &F);
    1255             : };
    1256             : 
    1257             : }
    1258             : 
    1259             : #endif

Generated by: LCOV version 1.13