TargetTransformInfo.h 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- TargetTransformInfo.h ------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. /// This pass exposes codegen information to IR-level passes. Every
  15. /// transformation that uses codegen information is broken into three parts:
  16. /// 1. The IR-level analysis pass.
  17. /// 2. The IR-level transformation interface which provides the needed
  18. /// information.
  19. /// 3. Codegen-level implementation which uses target-specific hooks.
  20. ///
  21. /// This file defines #2, which is the interface that IR-level transformations
  22. /// use for querying the codegen.
  23. ///
  24. //===----------------------------------------------------------------------===//
  25. #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
  26. #define LLVM_ANALYSIS_TARGETTRANSFORMINFO_H
  27. #include "llvm/IR/InstrTypes.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/PassManager.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/AtomicOrdering.h"
  32. #include "llvm/Support/BranchProbability.h"
  33. #include "llvm/Support/DataTypes.h"
  34. #include "llvm/Support/InstructionCost.h"
  35. #include <functional>
  36. #include <utility>
  37. namespace llvm {
  38. namespace Intrinsic {
  39. typedef unsigned ID;
  40. }
  41. class AssumptionCache;
  42. class BlockFrequencyInfo;
  43. class DominatorTree;
  44. class BranchInst;
  45. class CallBase;
  46. class Function;
  47. class GlobalValue;
  48. class InstCombiner;
  49. class OptimizationRemarkEmitter;
  50. class IntrinsicInst;
  51. class LoadInst;
  52. class LoopAccessInfo;
  53. class Loop;
  54. class LoopInfo;
  55. class ProfileSummaryInfo;
  56. class RecurrenceDescriptor;
  57. class SCEV;
  58. class ScalarEvolution;
  59. class StoreInst;
  60. class SwitchInst;
  61. class TargetLibraryInfo;
  62. class Type;
  63. class User;
  64. class Value;
  65. class VPIntrinsic;
  66. struct KnownBits;
  67. template <typename T> class Optional;
  68. /// Information about a load/store intrinsic defined by the target.
  69. struct MemIntrinsicInfo {
  70. /// This is the pointer that the intrinsic is loading from or storing to.
  71. /// If this is non-null, then analysis/optimization passes can assume that
  72. /// this intrinsic is functionally equivalent to a load/store from this
  73. /// pointer.
  74. Value *PtrVal = nullptr;
  75. // Ordering for atomic operations.
  76. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  77. // Same Id is set by the target for corresponding load/store intrinsics.
  78. unsigned short MatchingId = 0;
  79. bool ReadMem = false;
  80. bool WriteMem = false;
  81. bool IsVolatile = false;
  82. bool isUnordered() const {
  83. return (Ordering == AtomicOrdering::NotAtomic ||
  84. Ordering == AtomicOrdering::Unordered) &&
  85. !IsVolatile;
  86. }
  87. };
  88. /// Attributes of a target dependent hardware loop.
  89. struct HardwareLoopInfo {
  90. HardwareLoopInfo() = delete;
  91. HardwareLoopInfo(Loop *L) : L(L) {}
  92. Loop *L = nullptr;
  93. BasicBlock *ExitBlock = nullptr;
  94. BranchInst *ExitBranch = nullptr;
  95. const SCEV *ExitCount = nullptr;
  96. IntegerType *CountType = nullptr;
  97. Value *LoopDecrement = nullptr; // Decrement the loop counter by this
  98. // value in every iteration.
  99. bool IsNestingLegal = false; // Can a hardware loop be a parent to
  100. // another hardware loop?
  101. bool CounterInReg = false; // Should loop counter be updated in
  102. // the loop via a phi?
  103. bool PerformEntryTest = false; // Generate the intrinsic which also performs
  104. // icmp ne zero on the loop counter value and
  105. // produces an i1 to guard the loop entry.
  106. bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI,
  107. DominatorTree &DT, bool ForceNestedLoop = false,
  108. bool ForceHardwareLoopPHI = false);
  109. bool canAnalyze(LoopInfo &LI);
  110. };
  111. class IntrinsicCostAttributes {
  112. const IntrinsicInst *II = nullptr;
  113. Type *RetTy = nullptr;
  114. Intrinsic::ID IID;
  115. SmallVector<Type *, 4> ParamTys;
  116. SmallVector<const Value *, 4> Arguments;
  117. FastMathFlags FMF;
  118. // If ScalarizationCost is UINT_MAX, the cost of scalarizing the
  119. // arguments and the return value will be computed based on types.
  120. InstructionCost ScalarizationCost = InstructionCost::getInvalid();
  121. public:
  122. IntrinsicCostAttributes(
  123. Intrinsic::ID Id, const CallBase &CI,
  124. InstructionCost ScalarCost = InstructionCost::getInvalid());
  125. IntrinsicCostAttributes(
  126. Intrinsic::ID Id, Type *RTy, ArrayRef<Type *> Tys,
  127. FastMathFlags Flags = FastMathFlags(), const IntrinsicInst *I = nullptr,
  128. InstructionCost ScalarCost = InstructionCost::getInvalid());
  129. IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
  130. ArrayRef<const Value *> Args);
  131. IntrinsicCostAttributes(
  132. Intrinsic::ID Id, Type *RTy, ArrayRef<const Value *> Args,
  133. ArrayRef<Type *> Tys, FastMathFlags Flags = FastMathFlags(),
  134. const IntrinsicInst *I = nullptr,
  135. InstructionCost ScalarCost = InstructionCost::getInvalid());
  136. Intrinsic::ID getID() const { return IID; }
  137. const IntrinsicInst *getInst() const { return II; }
  138. Type *getReturnType() const { return RetTy; }
  139. FastMathFlags getFlags() const { return FMF; }
  140. InstructionCost getScalarizationCost() const { return ScalarizationCost; }
  141. const SmallVectorImpl<const Value *> &getArgs() const { return Arguments; }
  142. const SmallVectorImpl<Type *> &getArgTypes() const { return ParamTys; }
  143. bool isTypeBasedOnly() const {
  144. return Arguments.empty();
  145. }
  146. bool skipScalarizationCost() const { return ScalarizationCost.isValid(); }
  147. };
  148. class TargetTransformInfo;
  149. typedef TargetTransformInfo TTI;
  150. /// This pass provides access to the codegen interfaces that are needed
  151. /// for IR-level transformations.
  152. class TargetTransformInfo {
  153. public:
  154. /// Construct a TTI object using a type implementing the \c Concept
  155. /// API below.
  156. ///
  157. /// This is used by targets to construct a TTI wrapping their target-specific
  158. /// implementation that encodes appropriate costs for their target.
  159. template <typename T> TargetTransformInfo(T Impl);
  160. /// Construct a baseline TTI object using a minimal implementation of
  161. /// the \c Concept API below.
  162. ///
  163. /// The TTI implementation will reflect the information in the DataLayout
  164. /// provided if non-null.
  165. explicit TargetTransformInfo(const DataLayout &DL);
  166. // Provide move semantics.
  167. TargetTransformInfo(TargetTransformInfo &&Arg);
  168. TargetTransformInfo &operator=(TargetTransformInfo &&RHS);
  169. // We need to define the destructor out-of-line to define our sub-classes
  170. // out-of-line.
  171. ~TargetTransformInfo();
  172. /// Handle the invalidation of this information.
  173. ///
  174. /// When used as a result of \c TargetIRAnalysis this method will be called
  175. /// when the function this was computed for changes. When it returns false,
  176. /// the information is preserved across those changes.
  177. bool invalidate(Function &, const PreservedAnalyses &,
  178. FunctionAnalysisManager::Invalidator &) {
  179. // FIXME: We should probably in some way ensure that the subtarget
  180. // information for a function hasn't changed.
  181. return false;
  182. }
  183. /// \name Generic Target Information
  184. /// @{
  185. /// The kind of cost model.
  186. ///
  187. /// There are several different cost models that can be customized by the
  188. /// target. The normalization of each cost model may be target specific.
  189. enum TargetCostKind {
  190. TCK_RecipThroughput, ///< Reciprocal throughput.
  191. TCK_Latency, ///< The latency of instruction.
  192. TCK_CodeSize, ///< Instruction code size.
  193. TCK_SizeAndLatency ///< The weighted sum of size and latency.
  194. };
  195. /// Query the cost of a specified instruction.
  196. ///
  197. /// Clients should use this interface to query the cost of an existing
  198. /// instruction. The instruction must have a valid parent (basic block).
  199. ///
  200. /// Note, this method does not cache the cost calculation and it
  201. /// can be expensive in some cases.
  202. InstructionCost getInstructionCost(const Instruction *I,
  203. enum TargetCostKind kind) const {
  204. InstructionCost Cost;
  205. switch (kind) {
  206. case TCK_RecipThroughput:
  207. Cost = getInstructionThroughput(I);
  208. break;
  209. case TCK_Latency:
  210. Cost = getInstructionLatency(I);
  211. break;
  212. case TCK_CodeSize:
  213. case TCK_SizeAndLatency:
  214. Cost = getUserCost(I, kind);
  215. break;
  216. }
  217. return Cost;
  218. }
  219. /// Underlying constants for 'cost' values in this interface.
  220. ///
  221. /// Many APIs in this interface return a cost. This enum defines the
  222. /// fundamental values that should be used to interpret (and produce) those
  223. /// costs. The costs are returned as an int rather than a member of this
  224. /// enumeration because it is expected that the cost of one IR instruction
  225. /// may have a multiplicative factor to it or otherwise won't fit directly
  226. /// into the enum. Moreover, it is common to sum or average costs which works
  227. /// better as simple integral values. Thus this enum only provides constants.
  228. /// Also note that the returned costs are signed integers to make it natural
  229. /// to add, subtract, and test with zero (a common boundary condition). It is
  230. /// not expected that 2^32 is a realistic cost to be modeling at any point.
  231. ///
  232. /// Note that these costs should usually reflect the intersection of code-size
  233. /// cost and execution cost. A free instruction is typically one that folds
  234. /// into another instruction. For example, reg-to-reg moves can often be
  235. /// skipped by renaming the registers in the CPU, but they still are encoded
  236. /// and thus wouldn't be considered 'free' here.
  237. enum TargetCostConstants {
  238. TCC_Free = 0, ///< Expected to fold away in lowering.
  239. TCC_Basic = 1, ///< The cost of a typical 'add' instruction.
  240. TCC_Expensive = 4 ///< The cost of a 'div' instruction on x86.
  241. };
  242. /// Estimate the cost of a GEP operation when lowered.
  243. InstructionCost
  244. getGEPCost(Type *PointeeType, const Value *Ptr,
  245. ArrayRef<const Value *> Operands,
  246. TargetCostKind CostKind = TCK_SizeAndLatency) const;
  247. /// \returns A value by which our inlining threshold should be multiplied.
  248. /// This is primarily used to bump up the inlining threshold wholesale on
  249. /// targets where calls are unusually expensive.
  250. ///
  251. /// TODO: This is a rather blunt instrument. Perhaps altering the costs of
  252. /// individual classes of instructions would be better.
  253. unsigned getInliningThresholdMultiplier() const;
  254. /// \returns A value to be added to the inlining threshold.
  255. unsigned adjustInliningThreshold(const CallBase *CB) const;
  256. /// \returns Vector bonus in percent.
  257. ///
  258. /// Vector bonuses: We want to more aggressively inline vector-dense kernels
  259. /// and apply this bonus based on the percentage of vector instructions. A
  260. /// bonus is applied if the vector instructions exceed 50% and half that
  261. /// amount is applied if it exceeds 10%. Note that these bonuses are some what
  262. /// arbitrary and evolved over time by accident as much as because they are
  263. /// principled bonuses.
  264. /// FIXME: It would be nice to base the bonus values on something more
  265. /// scientific. A target may has no bonus on vector instructions.
  266. int getInlinerVectorBonusPercent() const;
  267. /// \return the expected cost of a memcpy, which could e.g. depend on the
  268. /// source/destination type and alignment and the number of bytes copied.
  269. InstructionCost getMemcpyCost(const Instruction *I) const;
  270. /// \return The estimated number of case clusters when lowering \p 'SI'.
  271. /// \p JTSize Set a jump table size only when \p SI is suitable for a jump
  272. /// table.
  273. unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
  274. unsigned &JTSize,
  275. ProfileSummaryInfo *PSI,
  276. BlockFrequencyInfo *BFI) const;
  277. /// Estimate the cost of a given IR user when lowered.
  278. ///
  279. /// This can estimate the cost of either a ConstantExpr or Instruction when
  280. /// lowered.
  281. ///
  282. /// \p Operands is a list of operands which can be a result of transformations
  283. /// of the current operands. The number of the operands on the list must equal
  284. /// to the number of the current operands the IR user has. Their order on the
  285. /// list must be the same as the order of the current operands the IR user
  286. /// has.
  287. ///
  288. /// The returned cost is defined in terms of \c TargetCostConstants, see its
  289. /// comments for a detailed explanation of the cost values.
  290. InstructionCost getUserCost(const User *U, ArrayRef<const Value *> Operands,
  291. TargetCostKind CostKind) const;
  292. /// This is a helper function which calls the two-argument getUserCost
  293. /// with \p Operands which are the current operands U has.
  294. InstructionCost getUserCost(const User *U, TargetCostKind CostKind) const {
  295. SmallVector<const Value *, 4> Operands(U->operand_values());
  296. return getUserCost(U, Operands, CostKind);
  297. }
  298. /// If a branch or a select condition is skewed in one direction by more than
  299. /// this factor, it is very likely to be predicted correctly.
  300. BranchProbability getPredictableBranchThreshold() const;
  301. /// Return true if branch divergence exists.
  302. ///
  303. /// Branch divergence has a significantly negative impact on GPU performance
  304. /// when threads in the same wavefront take different paths due to conditional
  305. /// branches.
  306. bool hasBranchDivergence() const;
  307. /// Return true if the target prefers to use GPU divergence analysis to
  308. /// replace the legacy version.
  309. bool useGPUDivergenceAnalysis() const;
  310. /// Returns whether V is a source of divergence.
  311. ///
  312. /// This function provides the target-dependent information for
  313. /// the target-independent LegacyDivergenceAnalysis. LegacyDivergenceAnalysis
  314. /// first builds the dependency graph, and then runs the reachability
  315. /// algorithm starting with the sources of divergence.
  316. bool isSourceOfDivergence(const Value *V) const;
  317. // Returns true for the target specific
  318. // set of operations which produce uniform result
  319. // even taking non-uniform arguments
  320. bool isAlwaysUniform(const Value *V) const;
  321. /// Returns the address space ID for a target's 'flat' address space. Note
  322. /// this is not necessarily the same as addrspace(0), which LLVM sometimes
  323. /// refers to as the generic address space. The flat address space is a
  324. /// generic address space that can be used access multiple segments of memory
  325. /// with different address spaces. Access of a memory location through a
  326. /// pointer with this address space is expected to be legal but slower
  327. /// compared to the same memory location accessed through a pointer with a
  328. /// different address space.
  329. //
  330. /// This is for targets with different pointer representations which can
  331. /// be converted with the addrspacecast instruction. If a pointer is converted
  332. /// to this address space, optimizations should attempt to replace the access
  333. /// with the source address space.
  334. ///
  335. /// \returns ~0u if the target does not have such a flat address space to
  336. /// optimize away.
  337. unsigned getFlatAddressSpace() const;
  338. /// Return any intrinsic address operand indexes which may be rewritten if
  339. /// they use a flat address space pointer.
  340. ///
  341. /// \returns true if the intrinsic was handled.
  342. bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
  343. Intrinsic::ID IID) const;
  344. bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const;
  345. /// Return true if globals in this address space can have initializers other
  346. /// than `undef`.
  347. bool canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const;
  348. unsigned getAssumedAddrSpace(const Value *V) const;
  349. std::pair<const Value *, unsigned>
  350. getPredicatedAddrSpace(const Value *V) const;
  351. /// Rewrite intrinsic call \p II such that \p OldV will be replaced with \p
  352. /// NewV, which has a different address space. This should happen for every
  353. /// operand index that collectFlatAddressOperands returned for the intrinsic.
  354. /// \returns nullptr if the intrinsic was not handled. Otherwise, returns the
  355. /// new value (which may be the original \p II with modified operands).
  356. Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
  357. Value *NewV) const;
  358. /// Test whether calls to a function lower to actual program function
  359. /// calls.
  360. ///
  361. /// The idea is to test whether the program is likely to require a 'call'
  362. /// instruction or equivalent in order to call the given function.
  363. ///
  364. /// FIXME: It's not clear that this is a good or useful query API. Client's
  365. /// should probably move to simpler cost metrics using the above.
  366. /// Alternatively, we could split the cost interface into distinct code-size
  367. /// and execution-speed costs. This would allow modelling the core of this
  368. /// query more accurately as a call is a single small instruction, but
  369. /// incurs significant execution cost.
  370. bool isLoweredToCall(const Function *F) const;
  371. struct LSRCost {
  372. /// TODO: Some of these could be merged. Also, a lexical ordering
  373. /// isn't always optimal.
  374. unsigned Insns;
  375. unsigned NumRegs;
  376. unsigned AddRecCost;
  377. unsigned NumIVMuls;
  378. unsigned NumBaseAdds;
  379. unsigned ImmCost;
  380. unsigned SetupCost;
  381. unsigned ScaleCost;
  382. };
  383. /// Parameters that control the generic loop unrolling transformation.
  384. struct UnrollingPreferences {
  385. /// The cost threshold for the unrolled loop. Should be relative to the
  386. /// getUserCost values returned by this API, and the expectation is that
  387. /// the unrolled loop's instructions when run through that interface should
  388. /// not exceed this cost. However, this is only an estimate. Also, specific
  389. /// loops may be unrolled even with a cost above this threshold if deemed
  390. /// profitable. Set this to UINT_MAX to disable the loop body cost
  391. /// restriction.
  392. unsigned Threshold;
  393. /// If complete unrolling will reduce the cost of the loop, we will boost
  394. /// the Threshold by a certain percent to allow more aggressive complete
  395. /// unrolling. This value provides the maximum boost percentage that we
  396. /// can apply to Threshold (The value should be no less than 100).
  397. /// BoostedThreshold = Threshold * min(RolledCost / UnrolledCost,
  398. /// MaxPercentThresholdBoost / 100)
  399. /// E.g. if complete unrolling reduces the loop execution time by 50%
  400. /// then we boost the threshold by the factor of 2x. If unrolling is not
  401. /// expected to reduce the running time, then we do not increase the
  402. /// threshold.
  403. unsigned MaxPercentThresholdBoost;
  404. /// The cost threshold for the unrolled loop when optimizing for size (set
  405. /// to UINT_MAX to disable).
  406. unsigned OptSizeThreshold;
  407. /// The cost threshold for the unrolled loop, like Threshold, but used
  408. /// for partial/runtime unrolling (set to UINT_MAX to disable).
  409. unsigned PartialThreshold;
  410. /// The cost threshold for the unrolled loop when optimizing for size, like
  411. /// OptSizeThreshold, but used for partial/runtime unrolling (set to
  412. /// UINT_MAX to disable).
  413. unsigned PartialOptSizeThreshold;
  414. /// A forced unrolling factor (the number of concatenated bodies of the
  415. /// original loop in the unrolled loop body). When set to 0, the unrolling
  416. /// transformation will select an unrolling factor based on the current cost
  417. /// threshold and other factors.
  418. unsigned Count;
  419. /// Default unroll count for loops with run-time trip count.
  420. unsigned DefaultUnrollRuntimeCount;
  421. // Set the maximum unrolling factor. The unrolling factor may be selected
  422. // using the appropriate cost threshold, but may not exceed this number
  423. // (set to UINT_MAX to disable). This does not apply in cases where the
  424. // loop is being fully unrolled.
  425. unsigned MaxCount;
  426. /// Set the maximum unrolling factor for full unrolling. Like MaxCount, but
  427. /// applies even if full unrolling is selected. This allows a target to fall
  428. /// back to Partial unrolling if full unrolling is above FullUnrollMaxCount.
  429. unsigned FullUnrollMaxCount;
  430. // Represents number of instructions optimized when "back edge"
  431. // becomes "fall through" in unrolled loop.
  432. // For now we count a conditional branch on a backedge and a comparison
  433. // feeding it.
  434. unsigned BEInsns;
  435. /// Allow partial unrolling (unrolling of loops to expand the size of the
  436. /// loop body, not only to eliminate small constant-trip-count loops).
  437. bool Partial;
  438. /// Allow runtime unrolling (unrolling of loops to expand the size of the
  439. /// loop body even when the number of loop iterations is not known at
  440. /// compile time).
  441. bool Runtime;
  442. /// Allow generation of a loop remainder (extra iterations after unroll).
  443. bool AllowRemainder;
  444. /// Allow emitting expensive instructions (such as divisions) when computing
  445. /// the trip count of a loop for runtime unrolling.
  446. bool AllowExpensiveTripCount;
  447. /// Apply loop unroll on any kind of loop
  448. /// (mainly to loops that fail runtime unrolling).
  449. bool Force;
  450. /// Allow using trip count upper bound to unroll loops.
  451. bool UpperBound;
  452. /// Allow unrolling of all the iterations of the runtime loop remainder.
  453. bool UnrollRemainder;
  454. /// Allow unroll and jam. Used to enable unroll and jam for the target.
  455. bool UnrollAndJam;
  456. /// Threshold for unroll and jam, for inner loop size. The 'Threshold'
  457. /// value above is used during unroll and jam for the outer loop size.
  458. /// This value is used in the same manner to limit the size of the inner
  459. /// loop.
  460. unsigned UnrollAndJamInnerLoopThreshold;
  461. /// Don't allow loop unrolling to simulate more than this number of
  462. /// iterations when checking full unroll profitability
  463. unsigned MaxIterationsCountToAnalyze;
  464. };
  465. /// Get target-customized preferences for the generic loop unrolling
  466. /// transformation. The caller will initialize UP with the current
  467. /// target-independent defaults.
  468. void getUnrollingPreferences(Loop *L, ScalarEvolution &,
  469. UnrollingPreferences &UP,
  470. OptimizationRemarkEmitter *ORE) const;
  471. /// Query the target whether it would be profitable to convert the given loop
  472. /// into a hardware loop.
  473. bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
  474. AssumptionCache &AC, TargetLibraryInfo *LibInfo,
  475. HardwareLoopInfo &HWLoopInfo) const;
  476. /// Query the target whether it would be prefered to create a predicated
  477. /// vector loop, which can avoid the need to emit a scalar epilogue loop.
  478. bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
  479. AssumptionCache &AC, TargetLibraryInfo *TLI,
  480. DominatorTree *DT,
  481. const LoopAccessInfo *LAI) const;
  482. /// Query the target whether lowering of the llvm.get.active.lane.mask
  483. /// intrinsic is supported.
  484. bool emitGetActiveLaneMask() const;
  485. // Parameters that control the loop peeling transformation
  486. struct PeelingPreferences {
  487. /// A forced peeling factor (the number of bodied of the original loop
  488. /// that should be peeled off before the loop body). When set to 0, the
  489. /// a peeling factor based on profile information and other factors.
  490. unsigned PeelCount;
  491. /// Allow peeling off loop iterations.
  492. bool AllowPeeling;
  493. /// Allow peeling off loop iterations for loop nests.
  494. bool AllowLoopNestsPeeling;
  495. /// Allow peeling basing on profile. Uses to enable peeling off all
  496. /// iterations basing on provided profile.
  497. /// If the value is true the peeling cost model can decide to peel only
  498. /// some iterations and in this case it will set this to false.
  499. bool PeelProfiledIterations;
  500. };
  501. /// Get target-customized preferences for the generic loop peeling
  502. /// transformation. The caller will initialize \p PP with the current
  503. /// target-independent defaults with information from \p L and \p SE.
  504. void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
  505. PeelingPreferences &PP) const;
  506. /// Targets can implement their own combinations for target-specific
  507. /// intrinsics. This function will be called from the InstCombine pass every
  508. /// time a target-specific intrinsic is encountered.
  509. ///
  510. /// \returns None to not do anything target specific or a value that will be
  511. /// returned from the InstCombiner. It is possible to return null and stop
  512. /// further processing of the intrinsic by returning nullptr.
  513. Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
  514. IntrinsicInst &II) const;
  515. /// Can be used to implement target-specific instruction combining.
  516. /// \see instCombineIntrinsic
  517. Optional<Value *>
  518. simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
  519. APInt DemandedMask, KnownBits &Known,
  520. bool &KnownBitsComputed) const;
  521. /// Can be used to implement target-specific instruction combining.
  522. /// \see instCombineIntrinsic
  523. Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
  524. InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
  525. APInt &UndefElts2, APInt &UndefElts3,
  526. std::function<void(Instruction *, unsigned, APInt, APInt &)>
  527. SimplifyAndSetOp) const;
  528. /// @}
  529. /// \name Scalar Target Information
  530. /// @{
  531. /// Flags indicating the kind of support for population count.
  532. ///
  533. /// Compared to the SW implementation, HW support is supposed to
  534. /// significantly boost the performance when the population is dense, and it
  535. /// may or may not degrade performance if the population is sparse. A HW
  536. /// support is considered as "Fast" if it can outperform, or is on a par
  537. /// with, SW implementation when the population is sparse; otherwise, it is
  538. /// considered as "Slow".
  539. enum PopcntSupportKind { PSK_Software, PSK_SlowHardware, PSK_FastHardware };
  540. /// Return true if the specified immediate is legal add immediate, that
  541. /// is the target has add instructions which can add a register with the
  542. /// immediate without having to materialize the immediate into a register.
  543. bool isLegalAddImmediate(int64_t Imm) const;
  544. /// Return true if the specified immediate is legal icmp immediate,
  545. /// that is the target has icmp instructions which can compare a register
  546. /// against the immediate without having to materialize the immediate into a
  547. /// register.
  548. bool isLegalICmpImmediate(int64_t Imm) const;
  549. /// Return true if the addressing mode represented by AM is legal for
  550. /// this target, for a load/store of the specified type.
  551. /// The type may be VoidTy, in which case only return true if the addressing
  552. /// mode is legal for a load/store of any legal type.
  553. /// If target returns true in LSRWithInstrQueries(), I may be valid.
  554. /// TODO: Handle pre/postinc as well.
  555. bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
  556. bool HasBaseReg, int64_t Scale,
  557. unsigned AddrSpace = 0,
  558. Instruction *I = nullptr) const;
  559. /// Return true if LSR cost of C1 is lower than C1.
  560. bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
  561. TargetTransformInfo::LSRCost &C2) const;
  562. /// Return true if LSR major cost is number of registers. Targets which
  563. /// implement their own isLSRCostLess and unset number of registers as major
  564. /// cost should return false, otherwise return true.
  565. bool isNumRegsMajorCostOfLSR() const;
  566. /// \returns true if LSR should not optimize a chain that includes \p I.
  567. bool isProfitableLSRChainElement(Instruction *I) const;
  568. /// Return true if the target can fuse a compare and branch.
  569. /// Loop-strength-reduction (LSR) uses that knowledge to adjust its cost
  570. /// calculation for the instructions in a loop.
  571. bool canMacroFuseCmp() const;
  572. /// Return true if the target can save a compare for loop count, for example
  573. /// hardware loop saves a compare.
  574. bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
  575. DominatorTree *DT, AssumptionCache *AC,
  576. TargetLibraryInfo *LibInfo) const;
  577. enum AddressingModeKind {
  578. AMK_PreIndexed,
  579. AMK_PostIndexed,
  580. AMK_None
  581. };
  582. /// Return the preferred addressing mode LSR should make efforts to generate.
  583. AddressingModeKind getPreferredAddressingMode(const Loop *L,
  584. ScalarEvolution *SE) const;
  585. /// Return true if the target supports masked store.
  586. bool isLegalMaskedStore(Type *DataType, Align Alignment) const;
  587. /// Return true if the target supports masked load.
  588. bool isLegalMaskedLoad(Type *DataType, Align Alignment) const;
  589. /// Return true if the target supports nontemporal store.
  590. bool isLegalNTStore(Type *DataType, Align Alignment) const;
  591. /// Return true if the target supports nontemporal load.
  592. bool isLegalNTLoad(Type *DataType, Align Alignment) const;
  593. /// Return true if the target supports masked scatter.
  594. bool isLegalMaskedScatter(Type *DataType, Align Alignment) const;
  595. /// Return true if the target supports masked gather.
  596. bool isLegalMaskedGather(Type *DataType, Align Alignment) const;
  597. /// Return true if the target forces scalarizing of llvm.masked.gather
  598. /// intrinsics.
  599. bool forceScalarizeMaskedGather(VectorType *Type, Align Alignment) const;
  600. /// Return true if the target forces scalarizing of llvm.masked.scatter
  601. /// intrinsics.
  602. bool forceScalarizeMaskedScatter(VectorType *Type, Align Alignment) const;
  603. /// Return true if the target supports masked compress store.
  604. bool isLegalMaskedCompressStore(Type *DataType) const;
  605. /// Return true if the target supports masked expand load.
  606. bool isLegalMaskedExpandLoad(Type *DataType) const;
  607. /// Return true if we should be enabling ordered reductions for the target.
  608. bool enableOrderedReductions() const;
  609. /// Return true if the target has a unified operation to calculate division
  610. /// and remainder. If so, the additional implicit multiplication and
  611. /// subtraction required to calculate a remainder from division are free. This
  612. /// can enable more aggressive transformations for division and remainder than
  613. /// would typically be allowed using throughput or size cost models.
  614. bool hasDivRemOp(Type *DataType, bool IsSigned) const;
  615. /// Return true if the given instruction (assumed to be a memory access
  616. /// instruction) has a volatile variant. If that's the case then we can avoid
  617. /// addrspacecast to generic AS for volatile loads/stores. Default
  618. /// implementation returns false, which prevents address space inference for
  619. /// volatile loads/stores.
  620. bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) const;
  621. /// Return true if target doesn't mind addresses in vectors.
  622. bool prefersVectorizedAddressing() const;
  623. /// Return the cost of the scaling factor used in the addressing
  624. /// mode represented by AM for this target, for a load/store
  625. /// of the specified type.
  626. /// If the AM is supported, the return value must be >= 0.
  627. /// If the AM is not supported, it returns a negative value.
  628. /// TODO: Handle pre/postinc as well.
  629. InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
  630. int64_t BaseOffset, bool HasBaseReg,
  631. int64_t Scale,
  632. unsigned AddrSpace = 0) const;
  633. /// Return true if the loop strength reduce pass should make
  634. /// Instruction* based TTI queries to isLegalAddressingMode(). This is
  635. /// needed on SystemZ, where e.g. a memcpy can only have a 12 bit unsigned
  636. /// immediate offset and no index register.
  637. bool LSRWithInstrQueries() const;
  638. /// Return true if it's free to truncate a value of type Ty1 to type
  639. /// Ty2. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
  640. /// by referencing its sub-register AX.
  641. bool isTruncateFree(Type *Ty1, Type *Ty2) const;
  642. /// Return true if it is profitable to hoist instruction in the
  643. /// then/else to before if.
  644. bool isProfitableToHoist(Instruction *I) const;
  645. bool useAA() const;
  646. /// Return true if this type is legal.
  647. bool isTypeLegal(Type *Ty) const;
  648. /// Returns the estimated number of registers required to represent \p Ty.
  649. InstructionCost getRegUsageForType(Type *Ty) const;
  650. /// Return true if switches should be turned into lookup tables for the
  651. /// target.
  652. bool shouldBuildLookupTables() const;
  653. /// Return true if switches should be turned into lookup tables
  654. /// containing this constant value for the target.
  655. bool shouldBuildLookupTablesForConstant(Constant *C) const;
  656. /// Return true if lookup tables should be turned into relative lookup tables.
  657. bool shouldBuildRelLookupTables() const;
  658. /// Return true if the input function which is cold at all call sites,
  659. /// should use coldcc calling convention.
  660. bool useColdCCForColdCall(Function &F) const;
  661. /// Estimate the overhead of scalarizing an instruction. Insert and Extract
  662. /// are set if the demanded result elements need to be inserted and/or
  663. /// extracted from vectors.
  664. InstructionCost getScalarizationOverhead(VectorType *Ty,
  665. const APInt &DemandedElts,
  666. bool Insert, bool Extract) const;
  667. /// Estimate the overhead of scalarizing an instructions unique
  668. /// non-constant operands. The (potentially vector) types to use for each of
  669. /// argument are passes via Tys.
  670. InstructionCost getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
  671. ArrayRef<Type *> Tys) const;
  672. /// If target has efficient vector element load/store instructions, it can
  673. /// return true here so that insertion/extraction costs are not added to
  674. /// the scalarization cost of a load/store.
  675. bool supportsEfficientVectorElementLoadStore() const;
  676. /// Don't restrict interleaved unrolling to small loops.
  677. bool enableAggressiveInterleaving(bool LoopHasReductions) const;
  678. /// Returns options for expansion of memcmp. IsZeroCmp is
  679. // true if this is the expansion of memcmp(p1, p2, s) == 0.
  680. struct MemCmpExpansionOptions {
  681. // Return true if memcmp expansion is enabled.
  682. operator bool() const { return MaxNumLoads > 0; }
  683. // Maximum number of load operations.
  684. unsigned MaxNumLoads = 0;
  685. // The list of available load sizes (in bytes), sorted in decreasing order.
  686. SmallVector<unsigned, 8> LoadSizes;
  687. // For memcmp expansion when the memcmp result is only compared equal or
  688. // not-equal to 0, allow up to this number of load pairs per block. As an
  689. // example, this may allow 'memcmp(a, b, 3) == 0' in a single block:
  690. // a0 = load2bytes &a[0]
  691. // b0 = load2bytes &b[0]
  692. // a2 = load1byte &a[2]
  693. // b2 = load1byte &b[2]
  694. // r = cmp eq (a0 ^ b0 | a2 ^ b2), 0
  695. unsigned NumLoadsPerBlock = 1;
  696. // Set to true to allow overlapping loads. For example, 7-byte compares can
  697. // be done with two 4-byte compares instead of 4+2+1-byte compares. This
  698. // requires all loads in LoadSizes to be doable in an unaligned way.
  699. bool AllowOverlappingLoads = false;
  700. };
  701. MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
  702. bool IsZeroCmp) const;
  703. /// Enable matching of interleaved access groups.
  704. bool enableInterleavedAccessVectorization() const;
  705. /// Enable matching of interleaved access groups that contain predicated
  706. /// accesses or gaps and therefore vectorized using masked
  707. /// vector loads/stores.
  708. bool enableMaskedInterleavedAccessVectorization() const;
  709. /// Indicate that it is potentially unsafe to automatically vectorize
  710. /// floating-point operations because the semantics of vector and scalar
  711. /// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
  712. /// does not support IEEE-754 denormal numbers, while depending on the
  713. /// platform, scalar floating-point math does.
  714. /// This applies to floating-point math operations and calls, not memory
  715. /// operations, shuffles, or casts.
  716. bool isFPVectorizationPotentiallyUnsafe() const;
  717. /// Determine if the target supports unaligned memory accesses.
  718. bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
  719. unsigned AddressSpace = 0,
  720. Align Alignment = Align(1),
  721. bool *Fast = nullptr) const;
  722. /// Return hardware support for population count.
  723. PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) const;
  724. /// Return true if the hardware has a fast square-root instruction.
  725. bool haveFastSqrt(Type *Ty) const;
  726. /// Return true if it is faster to check if a floating-point value is NaN
  727. /// (or not-NaN) versus a comparison against a constant FP zero value.
  728. /// Targets should override this if materializing a 0.0 for comparison is
  729. /// generally as cheap as checking for ordered/unordered.
  730. bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) const;
  731. /// Return the expected cost of supporting the floating point operation
  732. /// of the specified type.
  733. InstructionCost getFPOpCost(Type *Ty) const;
  734. /// Return the expected cost of materializing for the given integer
  735. /// immediate of the specified type.
  736. InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
  737. TargetCostKind CostKind) const;
  738. /// Return the expected cost of materialization for the given integer
  739. /// immediate of the specified type for a given instruction. The cost can be
  740. /// zero if the immediate can be folded into the specified instruction.
  741. InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
  742. const APInt &Imm, Type *Ty,
  743. TargetCostKind CostKind,
  744. Instruction *Inst = nullptr) const;
  745. InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
  746. const APInt &Imm, Type *Ty,
  747. TargetCostKind CostKind) const;
  748. /// Return the expected cost for the given integer when optimising
  749. /// for size. This is different than the other integer immediate cost
  750. /// functions in that it is subtarget agnostic. This is useful when you e.g.
  751. /// target one ISA such as Aarch32 but smaller encodings could be possible
  752. /// with another such as Thumb. This return value is used as a penalty when
  753. /// the total costs for a constant is calculated (the bigger the cost, the
  754. /// more beneficial constant hoisting is).
  755. InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
  756. const APInt &Imm, Type *Ty) const;
  757. /// @}
  758. /// \name Vector Target Information
  759. /// @{
  760. /// The various kinds of shuffle patterns for vector queries.
  761. enum ShuffleKind {
  762. SK_Broadcast, ///< Broadcast element 0 to all other elements.
  763. SK_Reverse, ///< Reverse the order of the vector.
  764. SK_Select, ///< Selects elements from the corresponding lane of
  765. ///< either source operand. This is equivalent to a
  766. ///< vector select with a constant condition operand.
  767. SK_Transpose, ///< Transpose two vectors.
  768. SK_InsertSubvector, ///< InsertSubvector. Index indicates start offset.
  769. SK_ExtractSubvector, ///< ExtractSubvector Index indicates start offset.
  770. SK_PermuteTwoSrc, ///< Merge elements from two source vectors into one
  771. ///< with any shuffle mask.
  772. SK_PermuteSingleSrc, ///< Shuffle elements of single source vector with any
  773. ///< shuffle mask.
  774. SK_Splice ///< Concatenates elements from the first input vector
  775. ///< with elements of the second input vector. Returning
  776. ///< a vector of the same type as the input vectors.
  777. };
  778. /// Additional information about an operand's possible values.
  779. enum OperandValueKind {
  780. OK_AnyValue, // Operand can have any value.
  781. OK_UniformValue, // Operand is uniform (splat of a value).
  782. OK_UniformConstantValue, // Operand is uniform constant.
  783. OK_NonUniformConstantValue // Operand is a non uniform constant value.
  784. };
  785. /// Additional properties of an operand's values.
  786. enum OperandValueProperties { OP_None = 0, OP_PowerOf2 = 1 };
  787. /// \return the number of registers in the target-provided register class.
  788. unsigned getNumberOfRegisters(unsigned ClassID) const;
  789. /// \return the target-provided register class ID for the provided type,
  790. /// accounting for type promotion and other type-legalization techniques that
  791. /// the target might apply. However, it specifically does not account for the
  792. /// scalarization or splitting of vector types. Should a vector type require
  793. /// scalarization or splitting into multiple underlying vector registers, that
  794. /// type should be mapped to a register class containing no registers.
  795. /// Specifically, this is designed to provide a simple, high-level view of the
  796. /// register allocation later performed by the backend. These register classes
  797. /// don't necessarily map onto the register classes used by the backend.
  798. /// FIXME: It's not currently possible to determine how many registers
  799. /// are used by the provided type.
  800. unsigned getRegisterClassForType(bool Vector, Type *Ty = nullptr) const;
  801. /// \return the target-provided register class name
  802. const char *getRegisterClassName(unsigned ClassID) const;
  803. enum RegisterKind { RGK_Scalar, RGK_FixedWidthVector, RGK_ScalableVector };
  804. /// \return The width of the largest scalar or vector register type.
  805. TypeSize getRegisterBitWidth(RegisterKind K) const;
  806. /// \return The width of the smallest vector register type.
  807. unsigned getMinVectorRegisterBitWidth() const;
  808. /// \return The maximum value of vscale if the target specifies an
  809. /// architectural maximum vector length, and None otherwise.
  810. Optional<unsigned> getMaxVScale() const;
  811. /// \return the value of vscale to tune the cost model for.
  812. Optional<unsigned> getVScaleForTuning() const;
  813. /// \return True if the vectorization factor should be chosen to
  814. /// make the vector of the smallest element type match the size of a
  815. /// vector register. For wider element types, this could result in
  816. /// creating vectors that span multiple vector registers.
  817. /// If false, the vectorization factor will be chosen based on the
  818. /// size of the widest element type.
  819. bool shouldMaximizeVectorBandwidth() const;
  820. /// \return The minimum vectorization factor for types of given element
  821. /// bit width, or 0 if there is no minimum VF. The returned value only
  822. /// applies when shouldMaximizeVectorBandwidth returns true.
  823. /// If IsScalable is true, the returned ElementCount must be a scalable VF.
  824. ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const;
  825. /// \return The maximum vectorization factor for types of given element
  826. /// bit width and opcode, or 0 if there is no maximum VF.
  827. /// Currently only used by the SLP vectorizer.
  828. unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const;
  829. /// \return True if it should be considered for address type promotion.
  830. /// \p AllowPromotionWithoutCommonHeader Set true if promoting \p I is
  831. /// profitable without finding other extensions fed by the same input.
  832. bool shouldConsiderAddressTypePromotion(
  833. const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const;
  834. /// \return The size of a cache line in bytes.
  835. unsigned getCacheLineSize() const;
  836. /// The possible cache levels
  837. enum class CacheLevel {
  838. L1D, // The L1 data cache
  839. L2D, // The L2 data cache
  840. // We currently do not model L3 caches, as their sizes differ widely between
  841. // microarchitectures. Also, we currently do not have a use for L3 cache
  842. // size modeling yet.
  843. };
  844. /// \return The size of the cache level in bytes, if available.
  845. Optional<unsigned> getCacheSize(CacheLevel Level) const;
  846. /// \return The associativity of the cache level, if available.
  847. Optional<unsigned> getCacheAssociativity(CacheLevel Level) const;
  848. /// \return How much before a load we should place the prefetch
  849. /// instruction. This is currently measured in number of
  850. /// instructions.
  851. unsigned getPrefetchDistance() const;
  852. /// Some HW prefetchers can handle accesses up to a certain constant stride.
  853. /// Sometimes prefetching is beneficial even below the HW prefetcher limit,
  854. /// and the arguments provided are meant to serve as a basis for deciding this
  855. /// for a particular loop.
  856. ///
  857. /// \param NumMemAccesses Number of memory accesses in the loop.
  858. /// \param NumStridedMemAccesses Number of the memory accesses that
  859. /// ScalarEvolution could find a known stride
  860. /// for.
  861. /// \param NumPrefetches Number of software prefetches that will be
  862. /// emitted as determined by the addresses
  863. /// involved and the cache line size.
  864. /// \param HasCall True if the loop contains a call.
  865. ///
  866. /// \return This is the minimum stride in bytes where it makes sense to start
  867. /// adding SW prefetches. The default is 1, i.e. prefetch with any
  868. /// stride.
  869. unsigned getMinPrefetchStride(unsigned NumMemAccesses,
  870. unsigned NumStridedMemAccesses,
  871. unsigned NumPrefetches, bool HasCall) const;
  872. /// \return The maximum number of iterations to prefetch ahead. If
  873. /// the required number of iterations is more than this number, no
  874. /// prefetching is performed.
  875. unsigned getMaxPrefetchIterationsAhead() const;
  876. /// \return True if prefetching should also be done for writes.
  877. bool enableWritePrefetching() const;
  878. /// \return The maximum interleave factor that any transform should try to
  879. /// perform for this target. This number depends on the level of parallelism
  880. /// and the number of execution units in the CPU.
  881. unsigned getMaxInterleaveFactor(unsigned VF) const;
  882. /// Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
  883. static OperandValueKind getOperandInfo(const Value *V,
  884. OperandValueProperties &OpProps);
  885. /// This is an approximation of reciprocal throughput of a math/logic op.
  886. /// A higher cost indicates less expected throughput.
  887. /// From Agner Fog's guides, reciprocal throughput is "the average number of
  888. /// clock cycles per instruction when the instructions are not part of a
  889. /// limiting dependency chain."
  890. /// Therefore, costs should be scaled to account for multiple execution units
  891. /// on the target that can process this type of instruction. For example, if
  892. /// there are 5 scalar integer units and 2 vector integer units that can
  893. /// calculate an 'add' in a single cycle, this model should indicate that the
  894. /// cost of the vector add instruction is 2.5 times the cost of the scalar
  895. /// add instruction.
  896. /// \p Args is an optional argument which holds the instruction operands
  897. /// values so the TTI can analyze those values searching for special
  898. /// cases or optimizations based on those values.
  899. /// \p CxtI is the optional original context instruction, if one exists, to
  900. /// provide even more information.
  901. InstructionCost getArithmeticInstrCost(
  902. unsigned Opcode, Type *Ty,
  903. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  904. OperandValueKind Opd1Info = OK_AnyValue,
  905. OperandValueKind Opd2Info = OK_AnyValue,
  906. OperandValueProperties Opd1PropInfo = OP_None,
  907. OperandValueProperties Opd2PropInfo = OP_None,
  908. ArrayRef<const Value *> Args = ArrayRef<const Value *>(),
  909. const Instruction *CxtI = nullptr) const;
  910. /// \return The cost of a shuffle instruction of kind Kind and of type Tp.
  911. /// The exact mask may be passed as Mask, or else the array will be empty.
  912. /// The index and subtype parameters are used by the subvector insertion and
  913. /// extraction shuffle kinds to show the insert/extract point and the type of
  914. /// the subvector being inserted/extracted.
  915. /// NOTE: For subvector extractions Tp represents the source type.
  916. InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
  917. ArrayRef<int> Mask = None, int Index = 0,
  918. VectorType *SubTp = nullptr) const;
  919. /// Represents a hint about the context in which a cast is used.
  920. ///
  921. /// For zext/sext, the context of the cast is the operand, which must be a
  922. /// load of some kind. For trunc, the context is of the cast is the single
  923. /// user of the instruction, which must be a store of some kind.
  924. ///
  925. /// This enum allows the vectorizer to give getCastInstrCost an idea of the
  926. /// type of cast it's dealing with, as not every cast is equal. For instance,
  927. /// the zext of a load may be free, but the zext of an interleaving load can
  928. //// be (very) expensive!
  929. ///
  930. /// See \c getCastContextHint to compute a CastContextHint from a cast
  931. /// Instruction*. Callers can use it if they don't need to override the
  932. /// context and just want it to be calculated from the instruction.
  933. ///
  934. /// FIXME: This handles the types of load/store that the vectorizer can
  935. /// produce, which are the cases where the context instruction is most
  936. /// likely to be incorrect. There are other situations where that can happen
  937. /// too, which might be handled here but in the long run a more general
  938. /// solution of costing multiple instructions at the same times may be better.
  939. enum class CastContextHint : uint8_t {
  940. None, ///< The cast is not used with a load/store of any kind.
  941. Normal, ///< The cast is used with a normal load/store.
  942. Masked, ///< The cast is used with a masked load/store.
  943. GatherScatter, ///< The cast is used with a gather/scatter.
  944. Interleave, ///< The cast is used with an interleaved load/store.
  945. Reversed, ///< The cast is used with a reversed load/store.
  946. };
  947. /// Calculates a CastContextHint from \p I.
  948. /// This should be used by callers of getCastInstrCost if they wish to
  949. /// determine the context from some instruction.
  950. /// \returns the CastContextHint for ZExt/SExt/Trunc, None if \p I is nullptr,
  951. /// or if it's another type of cast.
  952. static CastContextHint getCastContextHint(const Instruction *I);
  953. /// \return The expected cost of cast instructions, such as bitcast, trunc,
  954. /// zext, etc. If there is an existing instruction that holds Opcode, it
  955. /// may be passed in the 'I' parameter.
  956. InstructionCost
  957. getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
  958. TTI::CastContextHint CCH,
  959. TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency,
  960. const Instruction *I = nullptr) const;
  961. /// \return The expected cost of a sign- or zero-extended vector extract. Use
  962. /// -1 to indicate that there is no information about the index value.
  963. InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
  964. VectorType *VecTy,
  965. unsigned Index = -1) const;
  966. /// \return The expected cost of control-flow related instructions such as
  967. /// Phi, Ret, Br, Switch.
  968. InstructionCost
  969. getCFInstrCost(unsigned Opcode,
  970. TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency,
  971. const Instruction *I = nullptr) const;
  972. /// \returns The expected cost of compare and select instructions. If there
  973. /// is an existing instruction that holds Opcode, it may be passed in the
  974. /// 'I' parameter. The \p VecPred parameter can be used to indicate the select
  975. /// is using a compare with the specified predicate as condition. When vector
  976. /// types are passed, \p VecPred must be used for all lanes.
  977. InstructionCost
  978. getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
  979. CmpInst::Predicate VecPred,
  980. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  981. const Instruction *I = nullptr) const;
  982. /// \return The expected cost of vector Insert and Extract.
  983. /// Use -1 to indicate that there is no information on the index value.
  984. InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
  985. unsigned Index = -1) const;
  986. /// \return The cost of replication shuffle of \p VF elements typed \p EltTy
  987. /// \p ReplicationFactor times.
  988. ///
  989. /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
  990. /// <0,0,0,1,1,1,2,2,2,3,3,3>
  991. InstructionCost getReplicationShuffleCost(Type *EltTy, int ReplicationFactor,
  992. int VF,
  993. const APInt &DemandedDstElts,
  994. TTI::TargetCostKind CostKind);
  995. /// \return The cost of Load and Store instructions.
  996. InstructionCost
  997. getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
  998. unsigned AddressSpace,
  999. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  1000. const Instruction *I = nullptr) const;
  1001. /// \return The cost of VP Load and Store instructions.
  1002. InstructionCost
  1003. getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
  1004. unsigned AddressSpace,
  1005. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  1006. const Instruction *I = nullptr) const;
  1007. /// \return The cost of masked Load and Store instructions.
  1008. InstructionCost getMaskedMemoryOpCost(
  1009. unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
  1010. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
  1011. /// \return The cost of Gather or Scatter operation
  1012. /// \p Opcode - is a type of memory access Load or Store
  1013. /// \p DataTy - a vector type of the data to be loaded or stored
  1014. /// \p Ptr - pointer [or vector of pointers] - address[es] in memory
  1015. /// \p VariableMask - true when the memory access is predicated with a mask
  1016. /// that is not a compile-time constant
  1017. /// \p Alignment - alignment of single element
  1018. /// \p I - the optional original context instruction, if one exists, e.g. the
  1019. /// load/store to transform or the call to the gather/scatter intrinsic
  1020. InstructionCost getGatherScatterOpCost(
  1021. unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
  1022. Align Alignment, TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  1023. const Instruction *I = nullptr) const;
  1024. /// \return The cost of the interleaved memory operation.
  1025. /// \p Opcode is the memory operation code
  1026. /// \p VecTy is the vector type of the interleaved access.
  1027. /// \p Factor is the interleave factor
  1028. /// \p Indices is the indices for interleaved load members (as interleaved
  1029. /// load allows gaps)
  1030. /// \p Alignment is the alignment of the memory operation
  1031. /// \p AddressSpace is address space of the pointer.
  1032. /// \p UseMaskForCond indicates if the memory access is predicated.
  1033. /// \p UseMaskForGaps indicates if gaps should be masked.
  1034. InstructionCost getInterleavedMemoryOpCost(
  1035. unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
  1036. Align Alignment, unsigned AddressSpace,
  1037. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput,
  1038. bool UseMaskForCond = false, bool UseMaskForGaps = false) const;
  1039. /// A helper function to determine the type of reduction algorithm used
  1040. /// for a given \p Opcode and set of FastMathFlags \p FMF.
  1041. static bool requiresOrderedReduction(Optional<FastMathFlags> FMF) {
  1042. return FMF != None && !(*FMF).allowReassoc();
  1043. }
  1044. /// Calculate the cost of vector reduction intrinsics.
  1045. ///
  1046. /// This is the cost of reducing the vector value of type \p Ty to a scalar
  1047. /// value using the operation denoted by \p Opcode. The FastMathFlags
  1048. /// parameter \p FMF indicates what type of reduction we are performing:
  1049. /// 1. Tree-wise. This is the typical 'fast' reduction performed that
  1050. /// involves successively splitting a vector into half and doing the
  1051. /// operation on the pair of halves until you have a scalar value. For
  1052. /// example:
  1053. /// (v0, v1, v2, v3)
  1054. /// ((v0+v2), (v1+v3), undef, undef)
  1055. /// ((v0+v2+v1+v3), undef, undef, undef)
  1056. /// This is the default behaviour for integer operations, whereas for
  1057. /// floating point we only do this if \p FMF indicates that
  1058. /// reassociation is allowed.
  1059. /// 2. Ordered. For a vector with N elements this involves performing N
  1060. /// operations in lane order, starting with an initial scalar value, i.e.
  1061. /// result = InitVal + v0
  1062. /// result = result + v1
  1063. /// result = result + v2
  1064. /// result = result + v3
  1065. /// This is only the case for FP operations and when reassociation is not
  1066. /// allowed.
  1067. ///
  1068. InstructionCost getArithmeticReductionCost(
  1069. unsigned Opcode, VectorType *Ty, Optional<FastMathFlags> FMF,
  1070. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
  1071. InstructionCost getMinMaxReductionCost(
  1072. VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
  1073. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
  1074. /// Calculate the cost of an extended reduction pattern, similar to
  1075. /// getArithmeticReductionCost of an Add reduction with an extension and
  1076. /// optional multiply. This is the cost of as:
  1077. /// ResTy vecreduce.add(ext(Ty A)), or if IsMLA flag is set then:
  1078. /// ResTy vecreduce.add(mul(ext(Ty A), ext(Ty B)). The reduction happens
  1079. /// on a VectorType with ResTy elements and Ty lanes.
  1080. InstructionCost getExtendedAddReductionCost(
  1081. bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty,
  1082. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) const;
  1083. /// \returns The cost of Intrinsic instructions. Analyses the real arguments.
  1084. /// Three cases are handled: 1. scalar instruction 2. vector instruction
  1085. /// 3. scalar instruction which is to be vectorized.
  1086. InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  1087. TTI::TargetCostKind CostKind) const;
  1088. /// \returns The cost of Call instructions.
  1089. InstructionCost getCallInstrCost(
  1090. Function *F, Type *RetTy, ArrayRef<Type *> Tys,
  1091. TTI::TargetCostKind CostKind = TTI::TCK_SizeAndLatency) const;
  1092. /// \returns The number of pieces into which the provided type must be
  1093. /// split during legalization. Zero is returned when the answer is unknown.
  1094. unsigned getNumberOfParts(Type *Tp) const;
  1095. /// \returns The cost of the address computation. For most targets this can be
  1096. /// merged into the instruction indexing mode. Some targets might want to
  1097. /// distinguish between address computation for memory operations on vector
  1098. /// types and scalar types. Such targets should override this function.
  1099. /// The 'SE' parameter holds pointer for the scalar evolution object which
  1100. /// is used in order to get the Ptr step value in case of constant stride.
  1101. /// The 'Ptr' parameter holds SCEV of the access pointer.
  1102. InstructionCost getAddressComputationCost(Type *Ty,
  1103. ScalarEvolution *SE = nullptr,
  1104. const SCEV *Ptr = nullptr) const;
  1105. /// \returns The cost, if any, of keeping values of the given types alive
  1106. /// over a callsite.
  1107. ///
  1108. /// Some types may require the use of register classes that do not have
  1109. /// any callee-saved registers, so would require a spill and fill.
  1110. InstructionCost getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const;
  1111. /// \returns True if the intrinsic is a supported memory intrinsic. Info
  1112. /// will contain additional information - whether the intrinsic may write
  1113. /// or read to memory, volatility and the pointer. Info is undefined
  1114. /// if false is returned.
  1115. bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) const;
  1116. /// \returns The maximum element size, in bytes, for an element
  1117. /// unordered-atomic memory intrinsic.
  1118. unsigned getAtomicMemIntrinsicMaxElementSize() const;
  1119. /// \returns A value which is the result of the given memory intrinsic. New
  1120. /// instructions may be created to extract the result from the given intrinsic
  1121. /// memory operation. Returns nullptr if the target cannot create a result
  1122. /// from the given intrinsic.
  1123. Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
  1124. Type *ExpectedType) const;
  1125. /// \returns The type to use in a loop expansion of a memcpy call.
  1126. Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
  1127. unsigned SrcAddrSpace, unsigned DestAddrSpace,
  1128. unsigned SrcAlign, unsigned DestAlign) const;
  1129. /// \param[out] OpsOut The operand types to copy RemainingBytes of memory.
  1130. /// \param RemainingBytes The number of bytes to copy.
  1131. ///
  1132. /// Calculates the operand types to use when copying \p RemainingBytes of
  1133. /// memory, where source and destination alignments are \p SrcAlign and
  1134. /// \p DestAlign respectively.
  1135. void getMemcpyLoopResidualLoweringType(
  1136. SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
  1137. unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
  1138. unsigned SrcAlign, unsigned DestAlign) const;
  1139. /// \returns True if the two functions have compatible attributes for inlining
  1140. /// purposes.
  1141. bool areInlineCompatible(const Function *Caller,
  1142. const Function *Callee) const;
  1143. /// \returns True if the caller and callee agree on how \p Types will be
  1144. /// passed to or returned from the callee.
  1145. /// to the callee.
  1146. /// \param Types List of types to check.
  1147. bool areTypesABICompatible(const Function *Caller, const Function *Callee,
  1148. const ArrayRef<Type *> &Types) const;
  1149. /// The type of load/store indexing.
  1150. enum MemIndexedMode {
  1151. MIM_Unindexed, ///< No indexing.
  1152. MIM_PreInc, ///< Pre-incrementing.
  1153. MIM_PreDec, ///< Pre-decrementing.
  1154. MIM_PostInc, ///< Post-incrementing.
  1155. MIM_PostDec ///< Post-decrementing.
  1156. };
  1157. /// \returns True if the specified indexed load for the given type is legal.
  1158. bool isIndexedLoadLegal(enum MemIndexedMode Mode, Type *Ty) const;
  1159. /// \returns True if the specified indexed store for the given type is legal.
  1160. bool isIndexedStoreLegal(enum MemIndexedMode Mode, Type *Ty) const;
  1161. /// \returns The bitwidth of the largest vector type that should be used to
  1162. /// load/store in the given address space.
  1163. unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const;
  1164. /// \returns True if the load instruction is legal to vectorize.
  1165. bool isLegalToVectorizeLoad(LoadInst *LI) const;
  1166. /// \returns True if the store instruction is legal to vectorize.
  1167. bool isLegalToVectorizeStore(StoreInst *SI) const;
  1168. /// \returns True if it is legal to vectorize the given load chain.
  1169. bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
  1170. unsigned AddrSpace) const;
  1171. /// \returns True if it is legal to vectorize the given store chain.
  1172. bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
  1173. unsigned AddrSpace) const;
  1174. /// \returns True if it is legal to vectorize the given reduction kind.
  1175. bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
  1176. ElementCount VF) const;
  1177. /// \returns True if the given type is supported for scalable vectors
  1178. bool isElementTypeLegalForScalableVector(Type *Ty) const;
  1179. /// \returns The new vector factor value if the target doesn't support \p
  1180. /// SizeInBytes loads or has a better vector factor.
  1181. unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
  1182. unsigned ChainSizeInBytes,
  1183. VectorType *VecTy) const;
  1184. /// \returns The new vector factor value if the target doesn't support \p
  1185. /// SizeInBytes stores or has a better vector factor.
  1186. unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
  1187. unsigned ChainSizeInBytes,
  1188. VectorType *VecTy) const;
  1189. /// Flags describing the kind of vector reduction.
  1190. struct ReductionFlags {
  1191. ReductionFlags() = default;
  1192. bool IsMaxOp =
  1193. false; ///< If the op a min/max kind, true if it's a max operation.
  1194. bool IsSigned = false; ///< Whether the operation is a signed int reduction.
  1195. bool NoNaN =
  1196. false; ///< If op is an fp min/max, whether NaNs may be present.
  1197. };
  1198. /// \returns True if the target prefers reductions in loop.
  1199. bool preferInLoopReduction(unsigned Opcode, Type *Ty,
  1200. ReductionFlags Flags) const;
  1201. /// \returns True if the target prefers reductions select kept in the loop
  1202. /// when tail folding. i.e.
  1203. /// loop:
  1204. /// p = phi (0, s)
  1205. /// a = add (p, x)
  1206. /// s = select (mask, a, p)
  1207. /// vecreduce.add(s)
  1208. ///
  1209. /// As opposed to the normal scheme of p = phi (0, a) which allows the select
  1210. /// to be pulled out of the loop. If the select(.., add, ..) can be predicated
  1211. /// by the target, this can lead to cleaner code generation.
  1212. bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
  1213. ReductionFlags Flags) const;
  1214. /// \returns True if the target wants to expand the given reduction intrinsic
  1215. /// into a shuffle sequence.
  1216. bool shouldExpandReduction(const IntrinsicInst *II) const;
  1217. /// \returns the size cost of rematerializing a GlobalValue address relative
  1218. /// to a stack reload.
  1219. unsigned getGISelRematGlobalCost() const;
  1220. /// \returns True if the target supports scalable vectors.
  1221. bool supportsScalableVectors() const;
  1222. /// \return true when scalable vectorization is preferred.
  1223. bool enableScalableVectorization() const;
  1224. /// \name Vector Predication Information
  1225. /// @{
  1226. /// Whether the target supports the %evl parameter of VP intrinsic efficiently
  1227. /// in hardware, for the given opcode and type/alignment. (see LLVM Language
  1228. /// Reference - "Vector Predication Intrinsics").
  1229. /// Use of %evl is discouraged when that is not the case.
  1230. bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
  1231. Align Alignment) const;
  1232. struct VPLegalization {
  1233. enum VPTransform {
  1234. // keep the predicating parameter
  1235. Legal = 0,
  1236. // where legal, discard the predicate parameter
  1237. Discard = 1,
  1238. // transform into something else that is also predicating
  1239. Convert = 2
  1240. };
  1241. // How to transform the EVL parameter.
  1242. // Legal: keep the EVL parameter as it is.
  1243. // Discard: Ignore the EVL parameter where it is safe to do so.
  1244. // Convert: Fold the EVL into the mask parameter.
  1245. VPTransform EVLParamStrategy;
  1246. // How to transform the operator.
  1247. // Legal: The target supports this operator.
  1248. // Convert: Convert this to a non-VP operation.
  1249. // The 'Discard' strategy is invalid.
  1250. VPTransform OpStrategy;
  1251. bool shouldDoNothing() const {
  1252. return (EVLParamStrategy == Legal) && (OpStrategy == Legal);
  1253. }
  1254. VPLegalization(VPTransform EVLParamStrategy, VPTransform OpStrategy)
  1255. : EVLParamStrategy(EVLParamStrategy), OpStrategy(OpStrategy) {}
  1256. };
  1257. /// \returns How the target needs this vector-predicated operation to be
  1258. /// transformed.
  1259. VPLegalization getVPLegalizationStrategy(const VPIntrinsic &PI) const;
  1260. /// @}
  1261. /// @}
  1262. private:
  1263. /// Estimate the latency of specified instruction.
  1264. /// Returns 1 as the default value.
  1265. InstructionCost getInstructionLatency(const Instruction *I) const;
  1266. /// Returns the expected throughput cost of the instruction.
  1267. /// Returns -1 if the cost is unknown.
  1268. InstructionCost getInstructionThroughput(const Instruction *I) const;
  1269. /// The abstract base class used to type erase specific TTI
  1270. /// implementations.
  1271. class Concept;
  1272. /// The template model for the base class which wraps a concrete
  1273. /// implementation in a type erased interface.
  1274. template <typename T> class Model;
  1275. std::unique_ptr<Concept> TTIImpl;
  1276. };
  1277. class TargetTransformInfo::Concept {
  1278. public:
  1279. virtual ~Concept() = 0;
  1280. virtual const DataLayout &getDataLayout() const = 0;
  1281. virtual InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr,
  1282. ArrayRef<const Value *> Operands,
  1283. TTI::TargetCostKind CostKind) = 0;
  1284. virtual unsigned getInliningThresholdMultiplier() = 0;
  1285. virtual unsigned adjustInliningThreshold(const CallBase *CB) = 0;
  1286. virtual int getInlinerVectorBonusPercent() = 0;
  1287. virtual InstructionCost getMemcpyCost(const Instruction *I) = 0;
  1288. virtual unsigned
  1289. getEstimatedNumberOfCaseClusters(const SwitchInst &SI, unsigned &JTSize,
  1290. ProfileSummaryInfo *PSI,
  1291. BlockFrequencyInfo *BFI) = 0;
  1292. virtual InstructionCost getUserCost(const User *U,
  1293. ArrayRef<const Value *> Operands,
  1294. TargetCostKind CostKind) = 0;
  1295. virtual BranchProbability getPredictableBranchThreshold() = 0;
  1296. virtual bool hasBranchDivergence() = 0;
  1297. virtual bool useGPUDivergenceAnalysis() = 0;
  1298. virtual bool isSourceOfDivergence(const Value *V) = 0;
  1299. virtual bool isAlwaysUniform(const Value *V) = 0;
  1300. virtual unsigned getFlatAddressSpace() = 0;
  1301. virtual bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
  1302. Intrinsic::ID IID) const = 0;
  1303. virtual bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const = 0;
  1304. virtual bool
  1305. canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const = 0;
  1306. virtual unsigned getAssumedAddrSpace(const Value *V) const = 0;
  1307. virtual std::pair<const Value *, unsigned>
  1308. getPredicatedAddrSpace(const Value *V) const = 0;
  1309. virtual Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
  1310. Value *OldV,
  1311. Value *NewV) const = 0;
  1312. virtual bool isLoweredToCall(const Function *F) = 0;
  1313. virtual void getUnrollingPreferences(Loop *L, ScalarEvolution &,
  1314. UnrollingPreferences &UP,
  1315. OptimizationRemarkEmitter *ORE) = 0;
  1316. virtual void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
  1317. PeelingPreferences &PP) = 0;
  1318. virtual bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
  1319. AssumptionCache &AC,
  1320. TargetLibraryInfo *LibInfo,
  1321. HardwareLoopInfo &HWLoopInfo) = 0;
  1322. virtual bool
  1323. preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
  1324. AssumptionCache &AC, TargetLibraryInfo *TLI,
  1325. DominatorTree *DT, const LoopAccessInfo *LAI) = 0;
  1326. virtual bool emitGetActiveLaneMask() = 0;
  1327. virtual Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
  1328. IntrinsicInst &II) = 0;
  1329. virtual Optional<Value *>
  1330. simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
  1331. APInt DemandedMask, KnownBits &Known,
  1332. bool &KnownBitsComputed) = 0;
  1333. virtual Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
  1334. InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
  1335. APInt &UndefElts2, APInt &UndefElts3,
  1336. std::function<void(Instruction *, unsigned, APInt, APInt &)>
  1337. SimplifyAndSetOp) = 0;
  1338. virtual bool isLegalAddImmediate(int64_t Imm) = 0;
  1339. virtual bool isLegalICmpImmediate(int64_t Imm) = 0;
  1340. virtual bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
  1341. int64_t BaseOffset, bool HasBaseReg,
  1342. int64_t Scale, unsigned AddrSpace,
  1343. Instruction *I) = 0;
  1344. virtual bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
  1345. TargetTransformInfo::LSRCost &C2) = 0;
  1346. virtual bool isNumRegsMajorCostOfLSR() = 0;
  1347. virtual bool isProfitableLSRChainElement(Instruction *I) = 0;
  1348. virtual bool canMacroFuseCmp() = 0;
  1349. virtual bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE,
  1350. LoopInfo *LI, DominatorTree *DT, AssumptionCache *AC,
  1351. TargetLibraryInfo *LibInfo) = 0;
  1352. virtual AddressingModeKind
  1353. getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const = 0;
  1354. virtual bool isLegalMaskedStore(Type *DataType, Align Alignment) = 0;
  1355. virtual bool isLegalMaskedLoad(Type *DataType, Align Alignment) = 0;
  1356. virtual bool isLegalNTStore(Type *DataType, Align Alignment) = 0;
  1357. virtual bool isLegalNTLoad(Type *DataType, Align Alignment) = 0;
  1358. virtual bool isLegalMaskedScatter(Type *DataType, Align Alignment) = 0;
  1359. virtual bool isLegalMaskedGather(Type *DataType, Align Alignment) = 0;
  1360. virtual bool forceScalarizeMaskedGather(VectorType *DataType,
  1361. Align Alignment) = 0;
  1362. virtual bool forceScalarizeMaskedScatter(VectorType *DataType,
  1363. Align Alignment) = 0;
  1364. virtual bool isLegalMaskedCompressStore(Type *DataType) = 0;
  1365. virtual bool isLegalMaskedExpandLoad(Type *DataType) = 0;
  1366. virtual bool enableOrderedReductions() = 0;
  1367. virtual bool hasDivRemOp(Type *DataType, bool IsSigned) = 0;
  1368. virtual bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) = 0;
  1369. virtual bool prefersVectorizedAddressing() = 0;
  1370. virtual InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
  1371. int64_t BaseOffset,
  1372. bool HasBaseReg, int64_t Scale,
  1373. unsigned AddrSpace) = 0;
  1374. virtual bool LSRWithInstrQueries() = 0;
  1375. virtual bool isTruncateFree(Type *Ty1, Type *Ty2) = 0;
  1376. virtual bool isProfitableToHoist(Instruction *I) = 0;
  1377. virtual bool useAA() = 0;
  1378. virtual bool isTypeLegal(Type *Ty) = 0;
  1379. virtual InstructionCost getRegUsageForType(Type *Ty) = 0;
  1380. virtual bool shouldBuildLookupTables() = 0;
  1381. virtual bool shouldBuildLookupTablesForConstant(Constant *C) = 0;
  1382. virtual bool shouldBuildRelLookupTables() = 0;
  1383. virtual bool useColdCCForColdCall(Function &F) = 0;
  1384. virtual InstructionCost getScalarizationOverhead(VectorType *Ty,
  1385. const APInt &DemandedElts,
  1386. bool Insert,
  1387. bool Extract) = 0;
  1388. virtual InstructionCost
  1389. getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
  1390. ArrayRef<Type *> Tys) = 0;
  1391. virtual bool supportsEfficientVectorElementLoadStore() = 0;
  1392. virtual bool enableAggressiveInterleaving(bool LoopHasReductions) = 0;
  1393. virtual MemCmpExpansionOptions
  1394. enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const = 0;
  1395. virtual bool enableInterleavedAccessVectorization() = 0;
  1396. virtual bool enableMaskedInterleavedAccessVectorization() = 0;
  1397. virtual bool isFPVectorizationPotentiallyUnsafe() = 0;
  1398. virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
  1399. unsigned BitWidth,
  1400. unsigned AddressSpace,
  1401. Align Alignment,
  1402. bool *Fast) = 0;
  1403. virtual PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) = 0;
  1404. virtual bool haveFastSqrt(Type *Ty) = 0;
  1405. virtual bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) = 0;
  1406. virtual InstructionCost getFPOpCost(Type *Ty) = 0;
  1407. virtual InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
  1408. const APInt &Imm, Type *Ty) = 0;
  1409. virtual InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
  1410. TargetCostKind CostKind) = 0;
  1411. virtual InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
  1412. const APInt &Imm, Type *Ty,
  1413. TargetCostKind CostKind,
  1414. Instruction *Inst = nullptr) = 0;
  1415. virtual InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
  1416. const APInt &Imm, Type *Ty,
  1417. TargetCostKind CostKind) = 0;
  1418. virtual unsigned getNumberOfRegisters(unsigned ClassID) const = 0;
  1419. virtual unsigned getRegisterClassForType(bool Vector,
  1420. Type *Ty = nullptr) const = 0;
  1421. virtual const char *getRegisterClassName(unsigned ClassID) const = 0;
  1422. virtual TypeSize getRegisterBitWidth(RegisterKind K) const = 0;
  1423. virtual unsigned getMinVectorRegisterBitWidth() const = 0;
  1424. virtual Optional<unsigned> getMaxVScale() const = 0;
  1425. virtual Optional<unsigned> getVScaleForTuning() const = 0;
  1426. virtual bool shouldMaximizeVectorBandwidth() const = 0;
  1427. virtual ElementCount getMinimumVF(unsigned ElemWidth,
  1428. bool IsScalable) const = 0;
  1429. virtual unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const = 0;
  1430. virtual bool shouldConsiderAddressTypePromotion(
  1431. const Instruction &I, bool &AllowPromotionWithoutCommonHeader) = 0;
  1432. virtual unsigned getCacheLineSize() const = 0;
  1433. virtual Optional<unsigned> getCacheSize(CacheLevel Level) const = 0;
  1434. virtual Optional<unsigned> getCacheAssociativity(CacheLevel Level) const = 0;
  1435. /// \return How much before a load we should place the prefetch
  1436. /// instruction. This is currently measured in number of
  1437. /// instructions.
  1438. virtual unsigned getPrefetchDistance() const = 0;
  1439. /// \return Some HW prefetchers can handle accesses up to a certain
  1440. /// constant stride. This is the minimum stride in bytes where it
  1441. /// makes sense to start adding SW prefetches. The default is 1,
  1442. /// i.e. prefetch with any stride. Sometimes prefetching is beneficial
  1443. /// even below the HW prefetcher limit, and the arguments provided are
  1444. /// meant to serve as a basis for deciding this for a particular loop.
  1445. virtual unsigned getMinPrefetchStride(unsigned NumMemAccesses,
  1446. unsigned NumStridedMemAccesses,
  1447. unsigned NumPrefetches,
  1448. bool HasCall) const = 0;
  1449. /// \return The maximum number of iterations to prefetch ahead. If
  1450. /// the required number of iterations is more than this number, no
  1451. /// prefetching is performed.
  1452. virtual unsigned getMaxPrefetchIterationsAhead() const = 0;
  1453. /// \return True if prefetching should also be done for writes.
  1454. virtual bool enableWritePrefetching() const = 0;
  1455. virtual unsigned getMaxInterleaveFactor(unsigned VF) = 0;
  1456. virtual InstructionCost getArithmeticInstrCost(
  1457. unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
  1458. OperandValueKind Opd1Info, OperandValueKind Opd2Info,
  1459. OperandValueProperties Opd1PropInfo, OperandValueProperties Opd2PropInfo,
  1460. ArrayRef<const Value *> Args, const Instruction *CxtI = nullptr) = 0;
  1461. virtual InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
  1462. ArrayRef<int> Mask, int Index,
  1463. VectorType *SubTp) = 0;
  1464. virtual InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst,
  1465. Type *Src, CastContextHint CCH,
  1466. TTI::TargetCostKind CostKind,
  1467. const Instruction *I) = 0;
  1468. virtual InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
  1469. VectorType *VecTy,
  1470. unsigned Index) = 0;
  1471. virtual InstructionCost getCFInstrCost(unsigned Opcode,
  1472. TTI::TargetCostKind CostKind,
  1473. const Instruction *I = nullptr) = 0;
  1474. virtual InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
  1475. Type *CondTy,
  1476. CmpInst::Predicate VecPred,
  1477. TTI::TargetCostKind CostKind,
  1478. const Instruction *I) = 0;
  1479. virtual InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
  1480. unsigned Index) = 0;
  1481. virtual InstructionCost
  1482. getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
  1483. const APInt &DemandedDstElts,
  1484. TTI::TargetCostKind CostKind) = 0;
  1485. virtual InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src,
  1486. Align Alignment,
  1487. unsigned AddressSpace,
  1488. TTI::TargetCostKind CostKind,
  1489. const Instruction *I) = 0;
  1490. virtual InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src,
  1491. Align Alignment,
  1492. unsigned AddressSpace,
  1493. TTI::TargetCostKind CostKind,
  1494. const Instruction *I) = 0;
  1495. virtual InstructionCost
  1496. getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
  1497. unsigned AddressSpace,
  1498. TTI::TargetCostKind CostKind) = 0;
  1499. virtual InstructionCost
  1500. getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
  1501. bool VariableMask, Align Alignment,
  1502. TTI::TargetCostKind CostKind,
  1503. const Instruction *I = nullptr) = 0;
  1504. virtual InstructionCost getInterleavedMemoryOpCost(
  1505. unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
  1506. Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
  1507. bool UseMaskForCond = false, bool UseMaskForGaps = false) = 0;
  1508. virtual InstructionCost
  1509. getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
  1510. Optional<FastMathFlags> FMF,
  1511. TTI::TargetCostKind CostKind) = 0;
  1512. virtual InstructionCost
  1513. getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
  1514. TTI::TargetCostKind CostKind) = 0;
  1515. virtual InstructionCost getExtendedAddReductionCost(
  1516. bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty,
  1517. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) = 0;
  1518. virtual InstructionCost
  1519. getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  1520. TTI::TargetCostKind CostKind) = 0;
  1521. virtual InstructionCost getCallInstrCost(Function *F, Type *RetTy,
  1522. ArrayRef<Type *> Tys,
  1523. TTI::TargetCostKind CostKind) = 0;
  1524. virtual unsigned getNumberOfParts(Type *Tp) = 0;
  1525. virtual InstructionCost
  1526. getAddressComputationCost(Type *Ty, ScalarEvolution *SE, const SCEV *Ptr) = 0;
  1527. virtual InstructionCost
  1528. getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) = 0;
  1529. virtual bool getTgtMemIntrinsic(IntrinsicInst *Inst,
  1530. MemIntrinsicInfo &Info) = 0;
  1531. virtual unsigned getAtomicMemIntrinsicMaxElementSize() const = 0;
  1532. virtual Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
  1533. Type *ExpectedType) = 0;
  1534. virtual Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
  1535. unsigned SrcAddrSpace,
  1536. unsigned DestAddrSpace,
  1537. unsigned SrcAlign,
  1538. unsigned DestAlign) const = 0;
  1539. virtual void getMemcpyLoopResidualLoweringType(
  1540. SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
  1541. unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
  1542. unsigned SrcAlign, unsigned DestAlign) const = 0;
  1543. virtual bool areInlineCompatible(const Function *Caller,
  1544. const Function *Callee) const = 0;
  1545. virtual bool areTypesABICompatible(const Function *Caller,
  1546. const Function *Callee,
  1547. const ArrayRef<Type *> &Types) const = 0;
  1548. virtual bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const = 0;
  1549. virtual bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const = 0;
  1550. virtual unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const = 0;
  1551. virtual bool isLegalToVectorizeLoad(LoadInst *LI) const = 0;
  1552. virtual bool isLegalToVectorizeStore(StoreInst *SI) const = 0;
  1553. virtual bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
  1554. Align Alignment,
  1555. unsigned AddrSpace) const = 0;
  1556. virtual bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
  1557. Align Alignment,
  1558. unsigned AddrSpace) const = 0;
  1559. virtual bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
  1560. ElementCount VF) const = 0;
  1561. virtual bool isElementTypeLegalForScalableVector(Type *Ty) const = 0;
  1562. virtual unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
  1563. unsigned ChainSizeInBytes,
  1564. VectorType *VecTy) const = 0;
  1565. virtual unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
  1566. unsigned ChainSizeInBytes,
  1567. VectorType *VecTy) const = 0;
  1568. virtual bool preferInLoopReduction(unsigned Opcode, Type *Ty,
  1569. ReductionFlags) const = 0;
  1570. virtual bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
  1571. ReductionFlags) const = 0;
  1572. virtual bool shouldExpandReduction(const IntrinsicInst *II) const = 0;
  1573. virtual unsigned getGISelRematGlobalCost() const = 0;
  1574. virtual bool enableScalableVectorization() const = 0;
  1575. virtual bool supportsScalableVectors() const = 0;
  1576. virtual bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
  1577. Align Alignment) const = 0;
  1578. virtual InstructionCost getInstructionLatency(const Instruction *I) = 0;
  1579. virtual VPLegalization
  1580. getVPLegalizationStrategy(const VPIntrinsic &PI) const = 0;
  1581. };
  1582. template <typename T>
  1583. class TargetTransformInfo::Model final : public TargetTransformInfo::Concept {
  1584. T Impl;
  1585. public:
  1586. Model(T Impl) : Impl(std::move(Impl)) {}
  1587. ~Model() override = default;
  1588. const DataLayout &getDataLayout() const override {
  1589. return Impl.getDataLayout();
  1590. }
  1591. InstructionCost
  1592. getGEPCost(Type *PointeeType, const Value *Ptr,
  1593. ArrayRef<const Value *> Operands,
  1594. TargetTransformInfo::TargetCostKind CostKind) override {
  1595. return Impl.getGEPCost(PointeeType, Ptr, Operands, CostKind);
  1596. }
  1597. unsigned getInliningThresholdMultiplier() override {
  1598. return Impl.getInliningThresholdMultiplier();
  1599. }
  1600. unsigned adjustInliningThreshold(const CallBase *CB) override {
  1601. return Impl.adjustInliningThreshold(CB);
  1602. }
  1603. int getInlinerVectorBonusPercent() override {
  1604. return Impl.getInlinerVectorBonusPercent();
  1605. }
  1606. InstructionCost getMemcpyCost(const Instruction *I) override {
  1607. return Impl.getMemcpyCost(I);
  1608. }
  1609. InstructionCost getUserCost(const User *U, ArrayRef<const Value *> Operands,
  1610. TargetCostKind CostKind) override {
  1611. return Impl.getUserCost(U, Operands, CostKind);
  1612. }
  1613. BranchProbability getPredictableBranchThreshold() override {
  1614. return Impl.getPredictableBranchThreshold();
  1615. }
  1616. bool hasBranchDivergence() override { return Impl.hasBranchDivergence(); }
  1617. bool useGPUDivergenceAnalysis() override {
  1618. return Impl.useGPUDivergenceAnalysis();
  1619. }
  1620. bool isSourceOfDivergence(const Value *V) override {
  1621. return Impl.isSourceOfDivergence(V);
  1622. }
  1623. bool isAlwaysUniform(const Value *V) override {
  1624. return Impl.isAlwaysUniform(V);
  1625. }
  1626. unsigned getFlatAddressSpace() override { return Impl.getFlatAddressSpace(); }
  1627. bool collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
  1628. Intrinsic::ID IID) const override {
  1629. return Impl.collectFlatAddressOperands(OpIndexes, IID);
  1630. }
  1631. bool isNoopAddrSpaceCast(unsigned FromAS, unsigned ToAS) const override {
  1632. return Impl.isNoopAddrSpaceCast(FromAS, ToAS);
  1633. }
  1634. bool
  1635. canHaveNonUndefGlobalInitializerInAddressSpace(unsigned AS) const override {
  1636. return Impl.canHaveNonUndefGlobalInitializerInAddressSpace(AS);
  1637. }
  1638. unsigned getAssumedAddrSpace(const Value *V) const override {
  1639. return Impl.getAssumedAddrSpace(V);
  1640. }
  1641. std::pair<const Value *, unsigned>
  1642. getPredicatedAddrSpace(const Value *V) const override {
  1643. return Impl.getPredicatedAddrSpace(V);
  1644. }
  1645. Value *rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, Value *OldV,
  1646. Value *NewV) const override {
  1647. return Impl.rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
  1648. }
  1649. bool isLoweredToCall(const Function *F) override {
  1650. return Impl.isLoweredToCall(F);
  1651. }
  1652. void getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
  1653. UnrollingPreferences &UP,
  1654. OptimizationRemarkEmitter *ORE) override {
  1655. return Impl.getUnrollingPreferences(L, SE, UP, ORE);
  1656. }
  1657. void getPeelingPreferences(Loop *L, ScalarEvolution &SE,
  1658. PeelingPreferences &PP) override {
  1659. return Impl.getPeelingPreferences(L, SE, PP);
  1660. }
  1661. bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
  1662. AssumptionCache &AC, TargetLibraryInfo *LibInfo,
  1663. HardwareLoopInfo &HWLoopInfo) override {
  1664. return Impl.isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
  1665. }
  1666. bool preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
  1667. AssumptionCache &AC, TargetLibraryInfo *TLI,
  1668. DominatorTree *DT,
  1669. const LoopAccessInfo *LAI) override {
  1670. return Impl.preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LAI);
  1671. }
  1672. bool emitGetActiveLaneMask() override {
  1673. return Impl.emitGetActiveLaneMask();
  1674. }
  1675. Optional<Instruction *> instCombineIntrinsic(InstCombiner &IC,
  1676. IntrinsicInst &II) override {
  1677. return Impl.instCombineIntrinsic(IC, II);
  1678. }
  1679. Optional<Value *>
  1680. simplifyDemandedUseBitsIntrinsic(InstCombiner &IC, IntrinsicInst &II,
  1681. APInt DemandedMask, KnownBits &Known,
  1682. bool &KnownBitsComputed) override {
  1683. return Impl.simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
  1684. KnownBitsComputed);
  1685. }
  1686. Optional<Value *> simplifyDemandedVectorEltsIntrinsic(
  1687. InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
  1688. APInt &UndefElts2, APInt &UndefElts3,
  1689. std::function<void(Instruction *, unsigned, APInt, APInt &)>
  1690. SimplifyAndSetOp) override {
  1691. return Impl.simplifyDemandedVectorEltsIntrinsic(
  1692. IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
  1693. SimplifyAndSetOp);
  1694. }
  1695. bool isLegalAddImmediate(int64_t Imm) override {
  1696. return Impl.isLegalAddImmediate(Imm);
  1697. }
  1698. bool isLegalICmpImmediate(int64_t Imm) override {
  1699. return Impl.isLegalICmpImmediate(Imm);
  1700. }
  1701. bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset,
  1702. bool HasBaseReg, int64_t Scale, unsigned AddrSpace,
  1703. Instruction *I) override {
  1704. return Impl.isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
  1705. AddrSpace, I);
  1706. }
  1707. bool isLSRCostLess(TargetTransformInfo::LSRCost &C1,
  1708. TargetTransformInfo::LSRCost &C2) override {
  1709. return Impl.isLSRCostLess(C1, C2);
  1710. }
  1711. bool isNumRegsMajorCostOfLSR() override {
  1712. return Impl.isNumRegsMajorCostOfLSR();
  1713. }
  1714. bool isProfitableLSRChainElement(Instruction *I) override {
  1715. return Impl.isProfitableLSRChainElement(I);
  1716. }
  1717. bool canMacroFuseCmp() override { return Impl.canMacroFuseCmp(); }
  1718. bool canSaveCmp(Loop *L, BranchInst **BI, ScalarEvolution *SE, LoopInfo *LI,
  1719. DominatorTree *DT, AssumptionCache *AC,
  1720. TargetLibraryInfo *LibInfo) override {
  1721. return Impl.canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo);
  1722. }
  1723. AddressingModeKind
  1724. getPreferredAddressingMode(const Loop *L,
  1725. ScalarEvolution *SE) const override {
  1726. return Impl.getPreferredAddressingMode(L, SE);
  1727. }
  1728. bool isLegalMaskedStore(Type *DataType, Align Alignment) override {
  1729. return Impl.isLegalMaskedStore(DataType, Alignment);
  1730. }
  1731. bool isLegalMaskedLoad(Type *DataType, Align Alignment) override {
  1732. return Impl.isLegalMaskedLoad(DataType, Alignment);
  1733. }
  1734. bool isLegalNTStore(Type *DataType, Align Alignment) override {
  1735. return Impl.isLegalNTStore(DataType, Alignment);
  1736. }
  1737. bool isLegalNTLoad(Type *DataType, Align Alignment) override {
  1738. return Impl.isLegalNTLoad(DataType, Alignment);
  1739. }
  1740. bool isLegalMaskedScatter(Type *DataType, Align Alignment) override {
  1741. return Impl.isLegalMaskedScatter(DataType, Alignment);
  1742. }
  1743. bool isLegalMaskedGather(Type *DataType, Align Alignment) override {
  1744. return Impl.isLegalMaskedGather(DataType, Alignment);
  1745. }
  1746. bool forceScalarizeMaskedGather(VectorType *DataType,
  1747. Align Alignment) override {
  1748. return Impl.forceScalarizeMaskedGather(DataType, Alignment);
  1749. }
  1750. bool forceScalarizeMaskedScatter(VectorType *DataType,
  1751. Align Alignment) override {
  1752. return Impl.forceScalarizeMaskedScatter(DataType, Alignment);
  1753. }
  1754. bool isLegalMaskedCompressStore(Type *DataType) override {
  1755. return Impl.isLegalMaskedCompressStore(DataType);
  1756. }
  1757. bool isLegalMaskedExpandLoad(Type *DataType) override {
  1758. return Impl.isLegalMaskedExpandLoad(DataType);
  1759. }
  1760. bool enableOrderedReductions() override {
  1761. return Impl.enableOrderedReductions();
  1762. }
  1763. bool hasDivRemOp(Type *DataType, bool IsSigned) override {
  1764. return Impl.hasDivRemOp(DataType, IsSigned);
  1765. }
  1766. bool hasVolatileVariant(Instruction *I, unsigned AddrSpace) override {
  1767. return Impl.hasVolatileVariant(I, AddrSpace);
  1768. }
  1769. bool prefersVectorizedAddressing() override {
  1770. return Impl.prefersVectorizedAddressing();
  1771. }
  1772. InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
  1773. int64_t BaseOffset, bool HasBaseReg,
  1774. int64_t Scale,
  1775. unsigned AddrSpace) override {
  1776. return Impl.getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg, Scale,
  1777. AddrSpace);
  1778. }
  1779. bool LSRWithInstrQueries() override { return Impl.LSRWithInstrQueries(); }
  1780. bool isTruncateFree(Type *Ty1, Type *Ty2) override {
  1781. return Impl.isTruncateFree(Ty1, Ty2);
  1782. }
  1783. bool isProfitableToHoist(Instruction *I) override {
  1784. return Impl.isProfitableToHoist(I);
  1785. }
  1786. bool useAA() override { return Impl.useAA(); }
  1787. bool isTypeLegal(Type *Ty) override { return Impl.isTypeLegal(Ty); }
  1788. InstructionCost getRegUsageForType(Type *Ty) override {
  1789. return Impl.getRegUsageForType(Ty);
  1790. }
  1791. bool shouldBuildLookupTables() override {
  1792. return Impl.shouldBuildLookupTables();
  1793. }
  1794. bool shouldBuildLookupTablesForConstant(Constant *C) override {
  1795. return Impl.shouldBuildLookupTablesForConstant(C);
  1796. }
  1797. bool shouldBuildRelLookupTables() override {
  1798. return Impl.shouldBuildRelLookupTables();
  1799. }
  1800. bool useColdCCForColdCall(Function &F) override {
  1801. return Impl.useColdCCForColdCall(F);
  1802. }
  1803. InstructionCost getScalarizationOverhead(VectorType *Ty,
  1804. const APInt &DemandedElts,
  1805. bool Insert, bool Extract) override {
  1806. return Impl.getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
  1807. }
  1808. InstructionCost
  1809. getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
  1810. ArrayRef<Type *> Tys) override {
  1811. return Impl.getOperandsScalarizationOverhead(Args, Tys);
  1812. }
  1813. bool supportsEfficientVectorElementLoadStore() override {
  1814. return Impl.supportsEfficientVectorElementLoadStore();
  1815. }
  1816. bool enableAggressiveInterleaving(bool LoopHasReductions) override {
  1817. return Impl.enableAggressiveInterleaving(LoopHasReductions);
  1818. }
  1819. MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize,
  1820. bool IsZeroCmp) const override {
  1821. return Impl.enableMemCmpExpansion(OptSize, IsZeroCmp);
  1822. }
  1823. bool enableInterleavedAccessVectorization() override {
  1824. return Impl.enableInterleavedAccessVectorization();
  1825. }
  1826. bool enableMaskedInterleavedAccessVectorization() override {
  1827. return Impl.enableMaskedInterleavedAccessVectorization();
  1828. }
  1829. bool isFPVectorizationPotentiallyUnsafe() override {
  1830. return Impl.isFPVectorizationPotentiallyUnsafe();
  1831. }
  1832. bool allowsMisalignedMemoryAccesses(LLVMContext &Context, unsigned BitWidth,
  1833. unsigned AddressSpace, Align Alignment,
  1834. bool *Fast) override {
  1835. return Impl.allowsMisalignedMemoryAccesses(Context, BitWidth, AddressSpace,
  1836. Alignment, Fast);
  1837. }
  1838. PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) override {
  1839. return Impl.getPopcntSupport(IntTyWidthInBit);
  1840. }
  1841. bool haveFastSqrt(Type *Ty) override { return Impl.haveFastSqrt(Ty); }
  1842. bool isFCmpOrdCheaperThanFCmpZero(Type *Ty) override {
  1843. return Impl.isFCmpOrdCheaperThanFCmpZero(Ty);
  1844. }
  1845. InstructionCost getFPOpCost(Type *Ty) override {
  1846. return Impl.getFPOpCost(Ty);
  1847. }
  1848. InstructionCost getIntImmCodeSizeCost(unsigned Opc, unsigned Idx,
  1849. const APInt &Imm, Type *Ty) override {
  1850. return Impl.getIntImmCodeSizeCost(Opc, Idx, Imm, Ty);
  1851. }
  1852. InstructionCost getIntImmCost(const APInt &Imm, Type *Ty,
  1853. TargetCostKind CostKind) override {
  1854. return Impl.getIntImmCost(Imm, Ty, CostKind);
  1855. }
  1856. InstructionCost getIntImmCostInst(unsigned Opc, unsigned Idx,
  1857. const APInt &Imm, Type *Ty,
  1858. TargetCostKind CostKind,
  1859. Instruction *Inst = nullptr) override {
  1860. return Impl.getIntImmCostInst(Opc, Idx, Imm, Ty, CostKind, Inst);
  1861. }
  1862. InstructionCost getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
  1863. const APInt &Imm, Type *Ty,
  1864. TargetCostKind CostKind) override {
  1865. return Impl.getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
  1866. }
  1867. unsigned getNumberOfRegisters(unsigned ClassID) const override {
  1868. return Impl.getNumberOfRegisters(ClassID);
  1869. }
  1870. unsigned getRegisterClassForType(bool Vector,
  1871. Type *Ty = nullptr) const override {
  1872. return Impl.getRegisterClassForType(Vector, Ty);
  1873. }
  1874. const char *getRegisterClassName(unsigned ClassID) const override {
  1875. return Impl.getRegisterClassName(ClassID);
  1876. }
  1877. TypeSize getRegisterBitWidth(RegisterKind K) const override {
  1878. return Impl.getRegisterBitWidth(K);
  1879. }
  1880. unsigned getMinVectorRegisterBitWidth() const override {
  1881. return Impl.getMinVectorRegisterBitWidth();
  1882. }
  1883. Optional<unsigned> getMaxVScale() const override {
  1884. return Impl.getMaxVScale();
  1885. }
  1886. Optional<unsigned> getVScaleForTuning() const override {
  1887. return Impl.getVScaleForTuning();
  1888. }
  1889. bool shouldMaximizeVectorBandwidth() const override {
  1890. return Impl.shouldMaximizeVectorBandwidth();
  1891. }
  1892. ElementCount getMinimumVF(unsigned ElemWidth,
  1893. bool IsScalable) const override {
  1894. return Impl.getMinimumVF(ElemWidth, IsScalable);
  1895. }
  1896. unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const override {
  1897. return Impl.getMaximumVF(ElemWidth, Opcode);
  1898. }
  1899. bool shouldConsiderAddressTypePromotion(
  1900. const Instruction &I, bool &AllowPromotionWithoutCommonHeader) override {
  1901. return Impl.shouldConsiderAddressTypePromotion(
  1902. I, AllowPromotionWithoutCommonHeader);
  1903. }
  1904. unsigned getCacheLineSize() const override { return Impl.getCacheLineSize(); }
  1905. Optional<unsigned> getCacheSize(CacheLevel Level) const override {
  1906. return Impl.getCacheSize(Level);
  1907. }
  1908. Optional<unsigned> getCacheAssociativity(CacheLevel Level) const override {
  1909. return Impl.getCacheAssociativity(Level);
  1910. }
  1911. /// Return the preferred prefetch distance in terms of instructions.
  1912. ///
  1913. unsigned getPrefetchDistance() const override {
  1914. return Impl.getPrefetchDistance();
  1915. }
  1916. /// Return the minimum stride necessary to trigger software
  1917. /// prefetching.
  1918. ///
  1919. unsigned getMinPrefetchStride(unsigned NumMemAccesses,
  1920. unsigned NumStridedMemAccesses,
  1921. unsigned NumPrefetches,
  1922. bool HasCall) const override {
  1923. return Impl.getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
  1924. NumPrefetches, HasCall);
  1925. }
  1926. /// Return the maximum prefetch distance in terms of loop
  1927. /// iterations.
  1928. ///
  1929. unsigned getMaxPrefetchIterationsAhead() const override {
  1930. return Impl.getMaxPrefetchIterationsAhead();
  1931. }
  1932. /// \return True if prefetching should also be done for writes.
  1933. bool enableWritePrefetching() const override {
  1934. return Impl.enableWritePrefetching();
  1935. }
  1936. unsigned getMaxInterleaveFactor(unsigned VF) override {
  1937. return Impl.getMaxInterleaveFactor(VF);
  1938. }
  1939. unsigned getEstimatedNumberOfCaseClusters(const SwitchInst &SI,
  1940. unsigned &JTSize,
  1941. ProfileSummaryInfo *PSI,
  1942. BlockFrequencyInfo *BFI) override {
  1943. return Impl.getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI);
  1944. }
  1945. InstructionCost getArithmeticInstrCost(
  1946. unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
  1947. OperandValueKind Opd1Info, OperandValueKind Opd2Info,
  1948. OperandValueProperties Opd1PropInfo, OperandValueProperties Opd2PropInfo,
  1949. ArrayRef<const Value *> Args,
  1950. const Instruction *CxtI = nullptr) override {
  1951. return Impl.getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
  1952. Opd1PropInfo, Opd2PropInfo, Args, CxtI);
  1953. }
  1954. InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp,
  1955. ArrayRef<int> Mask, int Index,
  1956. VectorType *SubTp) override {
  1957. return Impl.getShuffleCost(Kind, Tp, Mask, Index, SubTp);
  1958. }
  1959. InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
  1960. CastContextHint CCH,
  1961. TTI::TargetCostKind CostKind,
  1962. const Instruction *I) override {
  1963. return Impl.getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
  1964. }
  1965. InstructionCost getExtractWithExtendCost(unsigned Opcode, Type *Dst,
  1966. VectorType *VecTy,
  1967. unsigned Index) override {
  1968. return Impl.getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
  1969. }
  1970. InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind,
  1971. const Instruction *I = nullptr) override {
  1972. return Impl.getCFInstrCost(Opcode, CostKind, I);
  1973. }
  1974. InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
  1975. CmpInst::Predicate VecPred,
  1976. TTI::TargetCostKind CostKind,
  1977. const Instruction *I) override {
  1978. return Impl.getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
  1979. }
  1980. InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val,
  1981. unsigned Index) override {
  1982. return Impl.getVectorInstrCost(Opcode, Val, Index);
  1983. }
  1984. InstructionCost
  1985. getReplicationShuffleCost(Type *EltTy, int ReplicationFactor, int VF,
  1986. const APInt &DemandedDstElts,
  1987. TTI::TargetCostKind CostKind) override {
  1988. return Impl.getReplicationShuffleCost(EltTy, ReplicationFactor, VF,
  1989. DemandedDstElts, CostKind);
  1990. }
  1991. InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
  1992. unsigned AddressSpace,
  1993. TTI::TargetCostKind CostKind,
  1994. const Instruction *I) override {
  1995. return Impl.getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  1996. CostKind, I);
  1997. }
  1998. InstructionCost getVPMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
  1999. unsigned AddressSpace,
  2000. TTI::TargetCostKind CostKind,
  2001. const Instruction *I) override {
  2002. return Impl.getVPMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  2003. CostKind, I);
  2004. }
  2005. InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
  2006. Align Alignment, unsigned AddressSpace,
  2007. TTI::TargetCostKind CostKind) override {
  2008. return Impl.getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
  2009. CostKind);
  2010. }
  2011. InstructionCost
  2012. getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr,
  2013. bool VariableMask, Align Alignment,
  2014. TTI::TargetCostKind CostKind,
  2015. const Instruction *I = nullptr) override {
  2016. return Impl.getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
  2017. Alignment, CostKind, I);
  2018. }
  2019. InstructionCost getInterleavedMemoryOpCost(
  2020. unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
  2021. Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
  2022. bool UseMaskForCond, bool UseMaskForGaps) override {
  2023. return Impl.getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
  2024. Alignment, AddressSpace, CostKind,
  2025. UseMaskForCond, UseMaskForGaps);
  2026. }
  2027. InstructionCost
  2028. getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
  2029. Optional<FastMathFlags> FMF,
  2030. TTI::TargetCostKind CostKind) override {
  2031. return Impl.getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
  2032. }
  2033. InstructionCost
  2034. getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, bool IsUnsigned,
  2035. TTI::TargetCostKind CostKind) override {
  2036. return Impl.getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
  2037. }
  2038. InstructionCost getExtendedAddReductionCost(
  2039. bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty,
  2040. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput) override {
  2041. return Impl.getExtendedAddReductionCost(IsMLA, IsUnsigned, ResTy, Ty,
  2042. CostKind);
  2043. }
  2044. InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
  2045. TTI::TargetCostKind CostKind) override {
  2046. return Impl.getIntrinsicInstrCost(ICA, CostKind);
  2047. }
  2048. InstructionCost getCallInstrCost(Function *F, Type *RetTy,
  2049. ArrayRef<Type *> Tys,
  2050. TTI::TargetCostKind CostKind) override {
  2051. return Impl.getCallInstrCost(F, RetTy, Tys, CostKind);
  2052. }
  2053. unsigned getNumberOfParts(Type *Tp) override {
  2054. return Impl.getNumberOfParts(Tp);
  2055. }
  2056. InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
  2057. const SCEV *Ptr) override {
  2058. return Impl.getAddressComputationCost(Ty, SE, Ptr);
  2059. }
  2060. InstructionCost getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) override {
  2061. return Impl.getCostOfKeepingLiveOverCall(Tys);
  2062. }
  2063. bool getTgtMemIntrinsic(IntrinsicInst *Inst,
  2064. MemIntrinsicInfo &Info) override {
  2065. return Impl.getTgtMemIntrinsic(Inst, Info);
  2066. }
  2067. unsigned getAtomicMemIntrinsicMaxElementSize() const override {
  2068. return Impl.getAtomicMemIntrinsicMaxElementSize();
  2069. }
  2070. Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
  2071. Type *ExpectedType) override {
  2072. return Impl.getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
  2073. }
  2074. Type *getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
  2075. unsigned SrcAddrSpace, unsigned DestAddrSpace,
  2076. unsigned SrcAlign,
  2077. unsigned DestAlign) const override {
  2078. return Impl.getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
  2079. DestAddrSpace, SrcAlign, DestAlign);
  2080. }
  2081. void getMemcpyLoopResidualLoweringType(
  2082. SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
  2083. unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
  2084. unsigned SrcAlign, unsigned DestAlign) const override {
  2085. Impl.getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
  2086. SrcAddrSpace, DestAddrSpace,
  2087. SrcAlign, DestAlign);
  2088. }
  2089. bool areInlineCompatible(const Function *Caller,
  2090. const Function *Callee) const override {
  2091. return Impl.areInlineCompatible(Caller, Callee);
  2092. }
  2093. bool areTypesABICompatible(const Function *Caller, const Function *Callee,
  2094. const ArrayRef<Type *> &Types) const override {
  2095. return Impl.areTypesABICompatible(Caller, Callee, Types);
  2096. }
  2097. bool isIndexedLoadLegal(MemIndexedMode Mode, Type *Ty) const override {
  2098. return Impl.isIndexedLoadLegal(Mode, Ty, getDataLayout());
  2099. }
  2100. bool isIndexedStoreLegal(MemIndexedMode Mode, Type *Ty) const override {
  2101. return Impl.isIndexedStoreLegal(Mode, Ty, getDataLayout());
  2102. }
  2103. unsigned getLoadStoreVecRegBitWidth(unsigned AddrSpace) const override {
  2104. return Impl.getLoadStoreVecRegBitWidth(AddrSpace);
  2105. }
  2106. bool isLegalToVectorizeLoad(LoadInst *LI) const override {
  2107. return Impl.isLegalToVectorizeLoad(LI);
  2108. }
  2109. bool isLegalToVectorizeStore(StoreInst *SI) const override {
  2110. return Impl.isLegalToVectorizeStore(SI);
  2111. }
  2112. bool isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, Align Alignment,
  2113. unsigned AddrSpace) const override {
  2114. return Impl.isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
  2115. AddrSpace);
  2116. }
  2117. bool isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, Align Alignment,
  2118. unsigned AddrSpace) const override {
  2119. return Impl.isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
  2120. AddrSpace);
  2121. }
  2122. bool isLegalToVectorizeReduction(const RecurrenceDescriptor &RdxDesc,
  2123. ElementCount VF) const override {
  2124. return Impl.isLegalToVectorizeReduction(RdxDesc, VF);
  2125. }
  2126. bool isElementTypeLegalForScalableVector(Type *Ty) const override {
  2127. return Impl.isElementTypeLegalForScalableVector(Ty);
  2128. }
  2129. unsigned getLoadVectorFactor(unsigned VF, unsigned LoadSize,
  2130. unsigned ChainSizeInBytes,
  2131. VectorType *VecTy) const override {
  2132. return Impl.getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
  2133. }
  2134. unsigned getStoreVectorFactor(unsigned VF, unsigned StoreSize,
  2135. unsigned ChainSizeInBytes,
  2136. VectorType *VecTy) const override {
  2137. return Impl.getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
  2138. }
  2139. bool preferInLoopReduction(unsigned Opcode, Type *Ty,
  2140. ReductionFlags Flags) const override {
  2141. return Impl.preferInLoopReduction(Opcode, Ty, Flags);
  2142. }
  2143. bool preferPredicatedReductionSelect(unsigned Opcode, Type *Ty,
  2144. ReductionFlags Flags) const override {
  2145. return Impl.preferPredicatedReductionSelect(Opcode, Ty, Flags);
  2146. }
  2147. bool shouldExpandReduction(const IntrinsicInst *II) const override {
  2148. return Impl.shouldExpandReduction(II);
  2149. }
  2150. unsigned getGISelRematGlobalCost() const override {
  2151. return Impl.getGISelRematGlobalCost();
  2152. }
  2153. bool supportsScalableVectors() const override {
  2154. return Impl.supportsScalableVectors();
  2155. }
  2156. bool enableScalableVectorization() const override {
  2157. return Impl.enableScalableVectorization();
  2158. }
  2159. bool hasActiveVectorLength(unsigned Opcode, Type *DataType,
  2160. Align Alignment) const override {
  2161. return Impl.hasActiveVectorLength(Opcode, DataType, Alignment);
  2162. }
  2163. InstructionCost getInstructionLatency(const Instruction *I) override {
  2164. return Impl.getInstructionLatency(I);
  2165. }
  2166. VPLegalization
  2167. getVPLegalizationStrategy(const VPIntrinsic &PI) const override {
  2168. return Impl.getVPLegalizationStrategy(PI);
  2169. }
  2170. };
  2171. template <typename T>
  2172. TargetTransformInfo::TargetTransformInfo(T Impl)
  2173. : TTIImpl(new Model<T>(Impl)) {}
  2174. /// Analysis pass providing the \c TargetTransformInfo.
  2175. ///
  2176. /// The core idea of the TargetIRAnalysis is to expose an interface through
  2177. /// which LLVM targets can analyze and provide information about the middle
  2178. /// end's target-independent IR. This supports use cases such as target-aware
  2179. /// cost modeling of IR constructs.
  2180. ///
  2181. /// This is a function analysis because much of the cost modeling for targets
  2182. /// is done in a subtarget specific way and LLVM supports compiling different
  2183. /// functions targeting different subtargets in order to support runtime
  2184. /// dispatch according to the observed subtarget.
  2185. class TargetIRAnalysis : public AnalysisInfoMixin<TargetIRAnalysis> {
  2186. public:
  2187. typedef TargetTransformInfo Result;
  2188. /// Default construct a target IR analysis.
  2189. ///
  2190. /// This will use the module's datalayout to construct a baseline
  2191. /// conservative TTI result.
  2192. TargetIRAnalysis();
  2193. /// Construct an IR analysis pass around a target-provide callback.
  2194. ///
  2195. /// The callback will be called with a particular function for which the TTI
  2196. /// is needed and must return a TTI object for that function.
  2197. TargetIRAnalysis(std::function<Result(const Function &)> TTICallback);
  2198. // Value semantics. We spell out the constructors for MSVC.
  2199. TargetIRAnalysis(const TargetIRAnalysis &Arg)
  2200. : TTICallback(Arg.TTICallback) {}
  2201. TargetIRAnalysis(TargetIRAnalysis &&Arg)
  2202. : TTICallback(std::move(Arg.TTICallback)) {}
  2203. TargetIRAnalysis &operator=(const TargetIRAnalysis &RHS) {
  2204. TTICallback = RHS.TTICallback;
  2205. return *this;
  2206. }
  2207. TargetIRAnalysis &operator=(TargetIRAnalysis &&RHS) {
  2208. TTICallback = std::move(RHS.TTICallback);
  2209. return *this;
  2210. }
  2211. Result run(const Function &F, FunctionAnalysisManager &);
  2212. private:
  2213. friend AnalysisInfoMixin<TargetIRAnalysis>;
  2214. static AnalysisKey Key;
  2215. /// The callback used to produce a result.
  2216. ///
  2217. /// We use a completely opaque callback so that targets can provide whatever
  2218. /// mechanism they desire for constructing the TTI for a given function.
  2219. ///
  2220. /// FIXME: Should we really use std::function? It's relatively inefficient.
  2221. /// It might be possible to arrange for even stateful callbacks to outlive
  2222. /// the analysis and thus use a function_ref which would be lighter weight.
  2223. /// This may also be less error prone as the callback is likely to reference
  2224. /// the external TargetMachine, and that reference needs to never dangle.
  2225. std::function<Result(const Function &)> TTICallback;
  2226. /// Helper function used as the callback in the default constructor.
  2227. static Result getDefaultTTI(const Function &F);
  2228. };
  2229. /// Wrapper pass for TargetTransformInfo.
  2230. ///
  2231. /// This pass can be constructed from a TTI object which it stores internally
  2232. /// and is queried by passes.
  2233. class TargetTransformInfoWrapperPass : public ImmutablePass {
  2234. TargetIRAnalysis TIRA;
  2235. Optional<TargetTransformInfo> TTI;
  2236. virtual void anchor();
  2237. public:
  2238. static char ID;
  2239. /// We must provide a default constructor for the pass but it should
  2240. /// never be used.
  2241. ///
  2242. /// Use the constructor below or call one of the creation routines.
  2243. TargetTransformInfoWrapperPass();
  2244. explicit TargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
  2245. TargetTransformInfo &getTTI(const Function &F);
  2246. };
  2247. /// Create an analysis pass wrapper around a TTI object.
  2248. ///
  2249. /// This analysis pass just holds the TTI instance and makes it available to
  2250. /// clients.
  2251. ImmutablePass *createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA);
  2252. } // namespace llvm
  2253. #endif
  2254. #ifdef __GNUC__
  2255. #pragma GCC diagnostic pop
  2256. #endif