Home | History | Annotate | Download | only in Analysis
      1 //===- TargetTransformInfoImpl.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 helpers for the implementation of
     11 /// a TargetTransformInfo-conforming class.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
     16 #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H
     17 
     18 #include "llvm/Analysis/TargetTransformInfo.h"
     19 #include "llvm/IR/CallSite.h"
     20 #include "llvm/IR/DataLayout.h"
     21 #include "llvm/IR/Function.h"
     22 #include "llvm/IR/GetElementPtrTypeIterator.h"
     23 #include "llvm/IR/Operator.h"
     24 #include "llvm/IR/Type.h"
     25 #include "llvm/Analysis/VectorUtils.h"
     26 
     27 namespace llvm {
     28 
     29 /// \brief Base class for use as a mix-in that aids implementing
     30 /// a TargetTransformInfo-compatible class.
     31 class TargetTransformInfoImplBase {
     32 protected:
     33   typedef TargetTransformInfo TTI;
     34 
     35   const DataLayout &DL;
     36 
     37   explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {}
     38 
     39 public:
     40   // Provide value semantics. MSVC requires that we spell all of these out.
     41   TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg)
     42       : DL(Arg.DL) {}
     43   TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {}
     44 
     45   const DataLayout &getDataLayout() const { return DL; }
     46 
     47   unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) {
     48     switch (Opcode) {
     49     default:
     50       // By default, just classify everything as 'basic'.
     51       return TTI::TCC_Basic;
     52 
     53     case Instruction::GetElementPtr:
     54       llvm_unreachable("Use getGEPCost for GEP operations!");
     55 
     56     case Instruction::BitCast:
     57       assert(OpTy && "Cast instructions must provide the operand type");
     58       if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy()))
     59         // Identity and pointer-to-pointer casts are free.
     60         return TTI::TCC_Free;
     61 
     62       // Otherwise, the default basic cost is used.
     63       return TTI::TCC_Basic;
     64 
     65     case Instruction::FDiv:
     66     case Instruction::FRem:
     67     case Instruction::SDiv:
     68     case Instruction::SRem:
     69     case Instruction::UDiv:
     70     case Instruction::URem:
     71       return TTI::TCC_Expensive;
     72 
     73     case Instruction::IntToPtr: {
     74       // An inttoptr cast is free so long as the input is a legal integer type
     75       // which doesn't contain values outside the range of a pointer.
     76       unsigned OpSize = OpTy->getScalarSizeInBits();
     77       if (DL.isLegalInteger(OpSize) &&
     78           OpSize <= DL.getPointerTypeSizeInBits(Ty))
     79         return TTI::TCC_Free;
     80 
     81       // Otherwise it's not a no-op.
     82       return TTI::TCC_Basic;
     83     }
     84     case Instruction::PtrToInt: {
     85       // A ptrtoint cast is free so long as the result is large enough to store
     86       // the pointer, and a legal integer type.
     87       unsigned DestSize = Ty->getScalarSizeInBits();
     88       if (DL.isLegalInteger(DestSize) &&
     89           DestSize >= DL.getPointerTypeSizeInBits(OpTy))
     90         return TTI::TCC_Free;
     91 
     92       // Otherwise it's not a no-op.
     93       return TTI::TCC_Basic;
     94     }
     95     case Instruction::Trunc:
     96       // trunc to a native type is free (assuming the target has compare and
     97       // shift-right of the same width).
     98       if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty)))
     99         return TTI::TCC_Free;
    100 
    101       return TTI::TCC_Basic;
    102     }
    103   }
    104 
    105   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
    106                       ArrayRef<const Value *> Operands) {
    107     // In the basic model, we just assume that all-constant GEPs will be folded
    108     // into their uses via addressing modes.
    109     for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx)
    110       if (!isa<Constant>(Operands[Idx]))
    111         return TTI::TCC_Basic;
    112 
    113     return TTI::TCC_Free;
    114   }
    115 
    116   unsigned getCallCost(FunctionType *FTy, int NumArgs) {
    117     assert(FTy && "FunctionType must be provided to this routine.");
    118 
    119     // The target-independent implementation just measures the size of the
    120     // function by approximating that each argument will take on average one
    121     // instruction to prepare.
    122 
    123     if (NumArgs < 0)
    124       // Set the argument number to the number of explicit arguments in the
    125       // function.
    126       NumArgs = FTy->getNumParams();
    127 
    128     return TTI::TCC_Basic * (NumArgs + 1);
    129   }
    130 
    131   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
    132                             ArrayRef<Type *> ParamTys) {
    133     switch (IID) {
    134     default:
    135       // Intrinsics rarely (if ever) have normal argument setup constraints.
    136       // Model them as having a basic instruction cost.
    137       // FIXME: This is wrong for libc intrinsics.
    138       return TTI::TCC_Basic;
    139 
    140     case Intrinsic::annotation:
    141     case Intrinsic::assume:
    142     case Intrinsic::dbg_declare:
    143     case Intrinsic::dbg_value:
    144     case Intrinsic::invariant_start:
    145     case Intrinsic::invariant_end:
    146     case Intrinsic::lifetime_start:
    147     case Intrinsic::lifetime_end:
    148     case Intrinsic::objectsize:
    149     case Intrinsic::ptr_annotation:
    150     case Intrinsic::var_annotation:
    151     case Intrinsic::experimental_gc_result_int:
    152     case Intrinsic::experimental_gc_result_float:
    153     case Intrinsic::experimental_gc_result_ptr:
    154     case Intrinsic::experimental_gc_result:
    155     case Intrinsic::experimental_gc_relocate:
    156       // These intrinsics don't actually represent code after lowering.
    157       return TTI::TCC_Free;
    158     }
    159   }
    160 
    161   bool hasBranchDivergence() { return false; }
    162 
    163   bool isSourceOfDivergence(const Value *V) { return false; }
    164 
    165   bool isLoweredToCall(const Function *F) {
    166     // FIXME: These should almost certainly not be handled here, and instead
    167     // handled with the help of TLI or the target itself. This was largely
    168     // ported from existing analysis heuristics here so that such refactorings
    169     // can take place in the future.
    170 
    171     if (F->isIntrinsic())
    172       return false;
    173 
    174     if (F->hasLocalLinkage() || !F->hasName())
    175       return true;
    176 
    177     StringRef Name = F->getName();
    178 
    179     // These will all likely lower to a single selection DAG node.
    180     if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" ||
    181         Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" ||
    182         Name == "fmin" || Name == "fminf" || Name == "fminl" ||
    183         Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" ||
    184         Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" ||
    185         Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl")
    186       return false;
    187 
    188     // These are all likely to be optimized into something smaller.
    189     if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" ||
    190         Name == "exp2l" || Name == "exp2f" || Name == "floor" ||
    191         Name == "floorf" || Name == "ceil" || Name == "round" ||
    192         Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" ||
    193         Name == "llabs")
    194       return false;
    195 
    196     return true;
    197   }
    198 
    199   void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {}
    200 
    201   bool isLegalAddImmediate(int64_t Imm) { return false; }
    202 
    203   bool isLegalICmpImmediate(int64_t Imm) { return false; }
    204 
    205   bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
    206                              bool HasBaseReg, int64_t Scale,
    207                              unsigned AddrSpace) {
    208     // Guess that only reg and reg+reg addressing is allowed. This heuristic is
    209     // taken from the implementation of LSR.
    210     return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1);
    211   }
    212 
    213   bool isLegalMaskedStore(Type *DataType) { return false; }
    214 
    215   bool isLegalMaskedLoad(Type *DataType) { return false; }
    216 
    217   bool isLegalMaskedScatter(Type *DataType) { return false; }
    218 
    219   bool isLegalMaskedGather(Type *DataType) { return false; }
    220 
    221   int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
    222                            bool HasBaseReg, int64_t Scale, unsigned AddrSpace) {
    223     // Guess that all legal addressing mode are free.
    224     if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
    225                               Scale, AddrSpace))
    226       return 0;
    227     return -1;
    228   }
    229 
    230   bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; }
    231 
    232   bool isProfitableToHoist(Instruction *I) { return true; }
    233 
    234   bool isTypeLegal(Type *Ty) { return false; }
    235 
    236   unsigned getJumpBufAlignment() { return 0; }
    237 
    238   unsigned getJumpBufSize() { return 0; }
    239 
    240   bool shouldBuildLookupTables() { return true; }
    241 
    242   bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; }
    243 
    244   bool enableInterleavedAccessVectorization() { return false; }
    245 
    246   TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) {
    247     return TTI::PSK_Software;
    248   }
    249 
    250   bool haveFastSqrt(Type *Ty) { return false; }
    251 
    252   unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; }
    253 
    254   unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; }
    255 
    256   unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
    257                          Type *Ty) {
    258     return TTI::TCC_Free;
    259   }
    260 
    261   unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
    262                          Type *Ty) {
    263     return TTI::TCC_Free;
    264   }
    265 
    266   unsigned getNumberOfRegisters(bool Vector) { return 8; }
    267 
    268   unsigned getRegisterBitWidth(bool Vector) { return 32; }
    269 
    270   unsigned getMaxInterleaveFactor(unsigned VF) { return 1; }
    271 
    272   unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty,
    273                                   TTI::OperandValueKind Opd1Info,
    274                                   TTI::OperandValueKind Opd2Info,
    275                                   TTI::OperandValueProperties Opd1PropInfo,
    276                                   TTI::OperandValueProperties Opd2PropInfo) {
    277     return 1;
    278   }
    279 
    280   unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index,
    281                           Type *SubTp) {
    282     return 1;
    283   }
    284 
    285   unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) { return 1; }
    286 
    287   unsigned getCFInstrCost(unsigned Opcode) { return 1; }
    288 
    289   unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
    290     return 1;
    291   }
    292 
    293   unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
    294     return 1;
    295   }
    296 
    297   unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
    298                            unsigned AddressSpace) {
    299     return 1;
    300   }
    301 
    302   unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
    303                                  unsigned AddressSpace) {
    304     return 1;
    305   }
    306 
    307   unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy,
    308                                       unsigned Factor,
    309                                       ArrayRef<unsigned> Indices,
    310                                       unsigned Alignment,
    311                                       unsigned AddressSpace) {
    312     return 1;
    313   }
    314 
    315   unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy,
    316                                  ArrayRef<Type *> Tys) {
    317     return 1;
    318   }
    319 
    320   unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) {
    321     return 1;
    322   }
    323 
    324   unsigned getNumberOfParts(Type *Tp) { return 0; }
    325 
    326   unsigned getAddressComputationCost(Type *Tp, bool) { return 0; }
    327 
    328   unsigned getReductionCost(unsigned, Type *, bool) { return 1; }
    329 
    330   unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; }
    331 
    332   bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) {
    333     return false;
    334   }
    335 
    336   Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
    337                                            Type *ExpectedType) {
    338     return nullptr;
    339   }
    340 
    341   bool areInlineCompatible(const Function *Caller,
    342                            const Function *Callee) const {
    343     return (Caller->getFnAttribute("target-cpu") ==
    344             Callee->getFnAttribute("target-cpu")) &&
    345            (Caller->getFnAttribute("target-features") ==
    346             Callee->getFnAttribute("target-features"));
    347   }
    348 };
    349 
    350 /// \brief CRTP base class for use as a mix-in that aids implementing
    351 /// a TargetTransformInfo-compatible class.
    352 template <typename T>
    353 class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase {
    354 private:
    355   typedef TargetTransformInfoImplBase BaseT;
    356 
    357 protected:
    358   explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {}
    359 
    360 public:
    361   // Provide value semantics. MSVC requires that we spell all of these out.
    362   TargetTransformInfoImplCRTPBase(const TargetTransformInfoImplCRTPBase &Arg)
    363       : BaseT(static_cast<const BaseT &>(Arg)) {}
    364   TargetTransformInfoImplCRTPBase(TargetTransformInfoImplCRTPBase &&Arg)
    365       : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
    366 
    367   using BaseT::getCallCost;
    368 
    369   unsigned getCallCost(const Function *F, int NumArgs) {
    370     assert(F && "A concrete function must be provided to this routine.");
    371 
    372     if (NumArgs < 0)
    373       // Set the argument number to the number of explicit arguments in the
    374       // function.
    375       NumArgs = F->arg_size();
    376 
    377     if (Intrinsic::ID IID = F->getIntrinsicID()) {
    378       FunctionType *FTy = F->getFunctionType();
    379       SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end());
    380       return static_cast<T *>(this)
    381           ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys);
    382     }
    383 
    384     if (!static_cast<T *>(this)->isLoweredToCall(F))
    385       return TTI::TCC_Basic; // Give a basic cost if it will be lowered
    386                              // directly.
    387 
    388     return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs);
    389   }
    390 
    391   unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) {
    392     // Simply delegate to generic handling of the call.
    393     // FIXME: We should use instsimplify or something else to catch calls which
    394     // will constant fold with these arguments.
    395     return static_cast<T *>(this)->getCallCost(F, Arguments.size());
    396   }
    397 
    398   using BaseT::getGEPCost;
    399 
    400   unsigned getGEPCost(Type *PointeeType, const Value *Ptr,
    401                       ArrayRef<const Value *> Operands) {
    402     const GlobalValue *BaseGV = nullptr;
    403     if (Ptr != nullptr) {
    404       // TODO: will remove this when pointers have an opaque type.
    405       assert(Ptr->getType()->getScalarType()->getPointerElementType() ==
    406                  PointeeType &&
    407              "explicit pointee type doesn't match operand's pointee type");
    408       BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts());
    409     }
    410     bool HasBaseReg = (BaseGV == nullptr);
    411     int64_t BaseOffset = 0;
    412     int64_t Scale = 0;
    413 
    414     // Assumes the address space is 0 when Ptr is nullptr.
    415     unsigned AS =
    416         (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace());
    417     auto GTI = gep_type_begin(PointerType::get(PointeeType, AS), Operands);
    418     for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) {
    419       // We assume that the cost of Scalar GEP with constant index and the
    420       // cost of Vector GEP with splat constant index are the same.
    421       const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I);
    422       if (!ConstIdx)
    423         if (auto Splat = getSplatValue(*I))
    424           ConstIdx = dyn_cast<ConstantInt>(Splat);
    425       if (isa<SequentialType>(*GTI)) {
    426         int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType());
    427         if (ConstIdx)
    428           BaseOffset += ConstIdx->getSExtValue() * ElementSize;
    429         else {
    430           // Needs scale register.
    431           if (Scale != 0)
    432             // No addressing mode takes two scale registers.
    433             return TTI::TCC_Basic;
    434           Scale = ElementSize;
    435         }
    436       } else {
    437         StructType *STy = cast<StructType>(*GTI);
    438         // For structures the index is always splat or scalar constant
    439         assert(ConstIdx && "Unexpected GEP index");
    440         uint64_t Field = ConstIdx->getZExtValue();
    441         BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field);
    442       }
    443     }
    444 
    445     if (static_cast<T *>(this)->isLegalAddressingMode(
    446             PointerType::get(*GTI, AS), const_cast<GlobalValue *>(BaseGV),
    447             BaseOffset, HasBaseReg, Scale, AS)) {
    448       return TTI::TCC_Free;
    449     }
    450     return TTI::TCC_Basic;
    451   }
    452 
    453   using BaseT::getIntrinsicCost;
    454 
    455   unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy,
    456                             ArrayRef<const Value *> Arguments) {
    457     // Delegate to the generic intrinsic handling code. This mostly provides an
    458     // opportunity for targets to (for example) special case the cost of
    459     // certain intrinsics based on constants used as arguments.
    460     SmallVector<Type *, 8> ParamTys;
    461     ParamTys.reserve(Arguments.size());
    462     for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
    463       ParamTys.push_back(Arguments[Idx]->getType());
    464     return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys);
    465   }
    466 
    467   unsigned getUserCost(const User *U) {
    468     if (isa<PHINode>(U))
    469       return TTI::TCC_Free; // Model all PHI nodes as free.
    470 
    471     if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
    472       SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end());
    473       return static_cast<T *>(this)->getGEPCost(
    474           GEP->getSourceElementType(), GEP->getPointerOperand(), Indices);
    475     }
    476 
    477     if (auto CS = ImmutableCallSite(U)) {
    478       const Function *F = CS.getCalledFunction();
    479       if (!F) {
    480         // Just use the called value type.
    481         Type *FTy = CS.getCalledValue()->getType()->getPointerElementType();
    482         return static_cast<T *>(this)
    483             ->getCallCost(cast<FunctionType>(FTy), CS.arg_size());
    484       }
    485 
    486       SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end());
    487       return static_cast<T *>(this)->getCallCost(F, Arguments);
    488     }
    489 
    490     if (const CastInst *CI = dyn_cast<CastInst>(U)) {
    491       // Result of a cmp instruction is often extended (to be used by other
    492       // cmp instructions, logical or return instructions). These are usually
    493       // nop on most sane targets.
    494       if (isa<CmpInst>(CI->getOperand(0)))
    495         return TTI::TCC_Free;
    496     }
    497 
    498     return static_cast<T *>(this)->getOperationCost(
    499         Operator::getOpcode(U), U->getType(),
    500         U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr);
    501   }
    502 };
    503 }
    504 
    505 #endif
    506