BasicTTIImpl.h 29 KB

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