TargetTransformInfo.h 126 KB

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