VectorUtils.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/VectorUtils.h - Vector utilities -----------*- 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. //
  14. // This file defines some vectorizer utilities.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ANALYSIS_VECTORUTILS_H
  18. #define LLVM_ANALYSIS_VECTORUTILS_H
  19. #include "llvm/ADT/MapVector.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/Analysis/LoopAccessAnalysis.h"
  22. #include "llvm/Support/CheckedArithmetic.h"
  23. namespace llvm {
  24. class TargetLibraryInfo;
  25. /// Describes the type of Parameters
  26. enum class VFParamKind {
  27. Vector, // No semantic information.
  28. OMP_Linear, // declare simd linear(i)
  29. OMP_LinearRef, // declare simd linear(ref(i))
  30. OMP_LinearVal, // declare simd linear(val(i))
  31. OMP_LinearUVal, // declare simd linear(uval(i))
  32. OMP_LinearPos, // declare simd linear(i:c) uniform(c)
  33. OMP_LinearValPos, // declare simd linear(val(i:c)) uniform(c)
  34. OMP_LinearRefPos, // declare simd linear(ref(i:c)) uniform(c)
  35. OMP_LinearUValPos, // declare simd linear(uval(i:c)) uniform(c
  36. OMP_Uniform, // declare simd uniform(i)
  37. GlobalPredicate, // Global logical predicate that acts on all lanes
  38. // of the input and output mask concurrently. For
  39. // example, it is implied by the `M` token in the
  40. // Vector Function ABI mangled name.
  41. Unknown
  42. };
  43. /// Describes the type of Instruction Set Architecture
  44. enum class VFISAKind {
  45. AdvancedSIMD, // AArch64 Advanced SIMD (NEON)
  46. SVE, // AArch64 Scalable Vector Extension
  47. SSE, // x86 SSE
  48. AVX, // x86 AVX
  49. AVX2, // x86 AVX2
  50. AVX512, // x86 AVX512
  51. LLVM, // LLVM internal ISA for functions that are not
  52. // attached to an existing ABI via name mangling.
  53. Unknown // Unknown ISA
  54. };
  55. /// Encapsulates information needed to describe a parameter.
  56. ///
  57. /// The description of the parameter is not linked directly to
  58. /// OpenMP or any other vector function description. This structure
  59. /// is extendible to handle other paradigms that describe vector
  60. /// functions and their parameters.
  61. struct VFParameter {
  62. unsigned ParamPos; // Parameter Position in Scalar Function.
  63. VFParamKind ParamKind; // Kind of Parameter.
  64. int LinearStepOrPos = 0; // Step or Position of the Parameter.
  65. Align Alignment = Align(); // Optional alignment in bytes, defaulted to 1.
  66. // Comparison operator.
  67. bool operator==(const VFParameter &Other) const {
  68. return std::tie(ParamPos, ParamKind, LinearStepOrPos, Alignment) ==
  69. std::tie(Other.ParamPos, Other.ParamKind, Other.LinearStepOrPos,
  70. Other.Alignment);
  71. }
  72. };
  73. /// Contains the information about the kind of vectorization
  74. /// available.
  75. ///
  76. /// This object in independent on the paradigm used to
  77. /// represent vector functions. in particular, it is not attached to
  78. /// any target-specific ABI.
  79. struct VFShape {
  80. unsigned VF; // Vectorization factor.
  81. bool IsScalable; // True if the function is a scalable function.
  82. SmallVector<VFParameter, 8> Parameters; // List of parameter information.
  83. // Comparison operator.
  84. bool operator==(const VFShape &Other) const {
  85. return std::tie(VF, IsScalable, Parameters) ==
  86. std::tie(Other.VF, Other.IsScalable, Other.Parameters);
  87. }
  88. /// Update the parameter in position P.ParamPos to P.
  89. void updateParam(VFParameter P) {
  90. assert(P.ParamPos < Parameters.size() && "Invalid parameter position.");
  91. Parameters[P.ParamPos] = P;
  92. assert(hasValidParameterList() && "Invalid parameter list");
  93. }
  94. // Retrieve the VFShape that can be used to map a (scalar) function to itself,
  95. // with VF = 1.
  96. static VFShape getScalarShape(const CallInst &CI) {
  97. return VFShape::get(CI, ElementCount::getFixed(1),
  98. /*HasGlobalPredicate*/ false);
  99. }
  100. // Retrieve the basic vectorization shape of the function, where all
  101. // parameters are mapped to VFParamKind::Vector with \p EC
  102. // lanes. Specifies whether the function has a Global Predicate
  103. // argument via \p HasGlobalPred.
  104. static VFShape get(const CallInst &CI, ElementCount EC, bool HasGlobalPred) {
  105. SmallVector<VFParameter, 8> Parameters;
  106. for (unsigned I = 0; I < CI.arg_size(); ++I)
  107. Parameters.push_back(VFParameter({I, VFParamKind::Vector}));
  108. if (HasGlobalPred)
  109. Parameters.push_back(
  110. VFParameter({CI.arg_size(), VFParamKind::GlobalPredicate}));
  111. return {EC.getKnownMinValue(), EC.isScalable(), Parameters};
  112. }
  113. /// Sanity check on the Parameters in the VFShape.
  114. bool hasValidParameterList() const;
  115. };
  116. /// Holds the VFShape for a specific scalar to vector function mapping.
  117. struct VFInfo {
  118. VFShape Shape; /// Classification of the vector function.
  119. std::string ScalarName; /// Scalar Function Name.
  120. std::string VectorName; /// Vector Function Name associated to this VFInfo.
  121. VFISAKind ISA; /// Instruction Set Architecture.
  122. // Comparison operator.
  123. bool operator==(const VFInfo &Other) const {
  124. return std::tie(Shape, ScalarName, VectorName, ISA) ==
  125. std::tie(Shape, Other.ScalarName, Other.VectorName, Other.ISA);
  126. }
  127. };
  128. namespace VFABI {
  129. /// LLVM Internal VFABI ISA token for vector functions.
  130. static constexpr char const *_LLVM_ = "_LLVM_";
  131. /// Prefix for internal name redirection for vector function that
  132. /// tells the compiler to scalarize the call using the scalar name
  133. /// of the function. For example, a mangled name like
  134. /// `_ZGV_LLVM_N2v_foo(_LLVM_Scalarize_foo)` would tell the
  135. /// vectorizer to vectorize the scalar call `foo`, and to scalarize
  136. /// it once vectorization is done.
  137. static constexpr char const *_LLVM_Scalarize_ = "_LLVM_Scalarize_";
  138. /// Function to construct a VFInfo out of a mangled names in the
  139. /// following format:
  140. ///
  141. /// <VFABI_name>{(<redirection>)}
  142. ///
  143. /// where <VFABI_name> is the name of the vector function, mangled according
  144. /// to the rules described in the Vector Function ABI of the target vector
  145. /// extension (or <isa> from now on). The <VFABI_name> is in the following
  146. /// format:
  147. ///
  148. /// _ZGV<isa><mask><vlen><parameters>_<scalarname>[(<redirection>)]
  149. ///
  150. /// This methods support demangling rules for the following <isa>:
  151. ///
  152. /// * AArch64: https://developer.arm.com/docs/101129/latest
  153. ///
  154. /// * x86 (libmvec): https://sourceware.org/glibc/wiki/libmvec and
  155. /// https://sourceware.org/glibc/wiki/libmvec?action=AttachFile&do=view&target=VectorABI.txt
  156. ///
  157. /// \param MangledName -> input string in the format
  158. /// _ZGV<isa><mask><vlen><parameters>_<scalarname>[(<redirection>)].
  159. /// \param M -> Module used to retrieve informations about the vector
  160. /// function that are not possible to retrieve from the mangled
  161. /// name. At the moment, this parameter is needed only to retrieve the
  162. /// Vectorization Factor of scalable vector functions from their
  163. /// respective IR declarations.
  164. Optional<VFInfo> tryDemangleForVFABI(StringRef MangledName, const Module &M);
  165. /// This routine mangles the given VectorName according to the LangRef
  166. /// specification for vector-function-abi-variant attribute and is specific to
  167. /// the TLI mappings. It is the responsibility of the caller to make sure that
  168. /// this is only used if all parameters in the vector function are vector type.
  169. /// This returned string holds scalar-to-vector mapping:
  170. /// _ZGV<isa><mask><vlen><vparams>_<scalarname>(<vectorname>)
  171. ///
  172. /// where:
  173. ///
  174. /// <isa> = "_LLVM_"
  175. /// <mask> = "N". Note: TLI does not support masked interfaces.
  176. /// <vlen> = Number of concurrent lanes, stored in the `VectorizationFactor`
  177. /// field of the `VecDesc` struct.
  178. /// <vparams> = "v", as many as are the numArgs.
  179. /// <scalarname> = the name of the scalar function.
  180. /// <vectorname> = the name of the vector function.
  181. std::string mangleTLIVectorName(StringRef VectorName, StringRef ScalarName,
  182. unsigned numArgs, unsigned VF);
  183. /// Retrieve the `VFParamKind` from a string token.
  184. VFParamKind getVFParamKindFromString(const StringRef Token);
  185. // Name of the attribute where the variant mappings are stored.
  186. static constexpr char const *MappingsAttrName = "vector-function-abi-variant";
  187. /// Populates a set of strings representing the Vector Function ABI variants
  188. /// associated to the CallInst CI. If the CI does not contain the
  189. /// vector-function-abi-variant attribute, we return without populating
  190. /// VariantMappings, i.e. callers of getVectorVariantNames need not check for
  191. /// the presence of the attribute (see InjectTLIMappings).
  192. void getVectorVariantNames(const CallInst &CI,
  193. SmallVectorImpl<std::string> &VariantMappings);
  194. } // end namespace VFABI
  195. /// The Vector Function Database.
  196. ///
  197. /// Helper class used to find the vector functions associated to a
  198. /// scalar CallInst.
  199. class VFDatabase {
  200. /// The Module of the CallInst CI.
  201. const Module *M;
  202. /// The CallInst instance being queried for scalar to vector mappings.
  203. const CallInst &CI;
  204. /// List of vector functions descriptors associated to the call
  205. /// instruction.
  206. const SmallVector<VFInfo, 8> ScalarToVectorMappings;
  207. /// Retrieve the scalar-to-vector mappings associated to the rule of
  208. /// a vector Function ABI.
  209. static void getVFABIMappings(const CallInst &CI,
  210. SmallVectorImpl<VFInfo> &Mappings) {
  211. if (!CI.getCalledFunction())
  212. return;
  213. const StringRef ScalarName = CI.getCalledFunction()->getName();
  214. SmallVector<std::string, 8> ListOfStrings;
  215. // The check for the vector-function-abi-variant attribute is done when
  216. // retrieving the vector variant names here.
  217. VFABI::getVectorVariantNames(CI, ListOfStrings);
  218. if (ListOfStrings.empty())
  219. return;
  220. for (const auto &MangledName : ListOfStrings) {
  221. const Optional<VFInfo> Shape =
  222. VFABI::tryDemangleForVFABI(MangledName, *(CI.getModule()));
  223. // A match is found via scalar and vector names, and also by
  224. // ensuring that the variant described in the attribute has a
  225. // corresponding definition or declaration of the vector
  226. // function in the Module M.
  227. if (Shape.hasValue() && (Shape.getValue().ScalarName == ScalarName)) {
  228. assert(CI.getModule()->getFunction(Shape.getValue().VectorName) &&
  229. "Vector function is missing.");
  230. Mappings.push_back(Shape.getValue());
  231. }
  232. }
  233. }
  234. public:
  235. /// Retrieve all the VFInfo instances associated to the CallInst CI.
  236. static SmallVector<VFInfo, 8> getMappings(const CallInst &CI) {
  237. SmallVector<VFInfo, 8> Ret;
  238. // Get mappings from the Vector Function ABI variants.
  239. getVFABIMappings(CI, Ret);
  240. // Other non-VFABI variants should be retrieved here.
  241. return Ret;
  242. }
  243. /// Constructor, requires a CallInst instance.
  244. VFDatabase(CallInst &CI)
  245. : M(CI.getModule()), CI(CI),
  246. ScalarToVectorMappings(VFDatabase::getMappings(CI)) {}
  247. /// \defgroup VFDatabase query interface.
  248. ///
  249. /// @{
  250. /// Retrieve the Function with VFShape \p Shape.
  251. Function *getVectorizedFunction(const VFShape &Shape) const {
  252. if (Shape == VFShape::getScalarShape(CI))
  253. return CI.getCalledFunction();
  254. for (const auto &Info : ScalarToVectorMappings)
  255. if (Info.Shape == Shape)
  256. return M->getFunction(Info.VectorName);
  257. return nullptr;
  258. }
  259. /// @}
  260. };
  261. template <typename T> class ArrayRef;
  262. class DemandedBits;
  263. class GetElementPtrInst;
  264. template <typename InstTy> class InterleaveGroup;
  265. class IRBuilderBase;
  266. class Loop;
  267. class ScalarEvolution;
  268. class TargetTransformInfo;
  269. class Type;
  270. class Value;
  271. namespace Intrinsic {
  272. typedef unsigned ID;
  273. }
  274. /// A helper function for converting Scalar types to vector types. If
  275. /// the incoming type is void, we return void. If the EC represents a
  276. /// scalar, we return the scalar type.
  277. inline Type *ToVectorTy(Type *Scalar, ElementCount EC) {
  278. if (Scalar->isVoidTy() || Scalar->isMetadataTy() || EC.isScalar())
  279. return Scalar;
  280. return VectorType::get(Scalar, EC);
  281. }
  282. inline Type *ToVectorTy(Type *Scalar, unsigned VF) {
  283. return ToVectorTy(Scalar, ElementCount::getFixed(VF));
  284. }
  285. /// Identify if the intrinsic is trivially vectorizable.
  286. /// This method returns true if the intrinsic's argument types are all scalars
  287. /// for the scalar form of the intrinsic and all vectors (or scalars handled by
  288. /// hasVectorInstrinsicScalarOpd) for the vector form of the intrinsic.
  289. bool isTriviallyVectorizable(Intrinsic::ID ID);
  290. /// Identifies if the vector form of the intrinsic has a scalar operand.
  291. bool hasVectorInstrinsicScalarOpd(Intrinsic::ID ID, unsigned ScalarOpdIdx);
  292. /// Returns intrinsic ID for call.
  293. /// For the input call instruction it finds mapping intrinsic and returns
  294. /// its intrinsic ID, in case it does not found it return not_intrinsic.
  295. Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI,
  296. const TargetLibraryInfo *TLI);
  297. /// Find the operand of the GEP that should be checked for consecutive
  298. /// stores. This ignores trailing indices that have no effect on the final
  299. /// pointer.
  300. unsigned getGEPInductionOperand(const GetElementPtrInst *Gep);
  301. /// If the argument is a GEP, then returns the operand identified by
  302. /// getGEPInductionOperand. However, if there is some other non-loop-invariant
  303. /// operand, it returns that instead.
  304. Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp);
  305. /// If a value has only one user that is a CastInst, return it.
  306. Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty);
  307. /// Get the stride of a pointer access in a loop. Looks for symbolic
  308. /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
  309. Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp);
  310. /// Given a vector and an element number, see if the scalar value is
  311. /// already around as a register, for example if it were inserted then extracted
  312. /// from the vector.
  313. Value *findScalarElement(Value *V, unsigned EltNo);
  314. /// If all non-negative \p Mask elements are the same value, return that value.
  315. /// If all elements are negative (undefined) or \p Mask contains different
  316. /// non-negative values, return -1.
  317. int getSplatIndex(ArrayRef<int> Mask);
  318. /// Get splat value if the input is a splat vector or return nullptr.
  319. /// The value may be extracted from a splat constants vector or from
  320. /// a sequence of instructions that broadcast a single value into a vector.
  321. Value *getSplatValue(const Value *V);
  322. /// Return true if each element of the vector value \p V is poisoned or equal to
  323. /// every other non-poisoned element. If an index element is specified, either
  324. /// every element of the vector is poisoned or the element at that index is not
  325. /// poisoned and equal to every other non-poisoned element.
  326. /// This may be more powerful than the related getSplatValue() because it is
  327. /// not limited by finding a scalar source value to a splatted vector.
  328. bool isSplatValue(const Value *V, int Index = -1, unsigned Depth = 0);
  329. /// Replace each shuffle mask index with the scaled sequential indices for an
  330. /// equivalent mask of narrowed elements. Mask elements that are less than 0
  331. /// (sentinel values) are repeated in the output mask.
  332. ///
  333. /// Example with Scale = 4:
  334. /// <4 x i32> <3, 2, 0, -1> -->
  335. /// <16 x i8> <12, 13, 14, 15, 8, 9, 10, 11, 0, 1, 2, 3, -1, -1, -1, -1>
  336. ///
  337. /// This is the reverse process of widening shuffle mask elements, but it always
  338. /// succeeds because the indexes can always be multiplied (scaled up) to map to
  339. /// narrower vector elements.
  340. void narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  341. SmallVectorImpl<int> &ScaledMask);
  342. /// Try to transform a shuffle mask by replacing elements with the scaled index
  343. /// for an equivalent mask of widened elements. If all mask elements that would
  344. /// map to a wider element of the new mask are the same negative number
  345. /// (sentinel value), that element of the new mask is the same value. If any
  346. /// element in a given slice is negative and some other element in that slice is
  347. /// not the same value, return false (partial matches with sentinel values are
  348. /// not allowed).
  349. ///
  350. /// Example with Scale = 4:
  351. /// <16 x i8> <12, 13, 14, 15, 8, 9, 10, 11, 0, 1, 2, 3, -1, -1, -1, -1> -->
  352. /// <4 x i32> <3, 2, 0, -1>
  353. ///
  354. /// This is the reverse process of narrowing shuffle mask elements if it
  355. /// succeeds. This transform is not always possible because indexes may not
  356. /// divide evenly (scale down) to map to wider vector elements.
  357. bool widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  358. SmallVectorImpl<int> &ScaledMask);
  359. /// Compute a map of integer instructions to their minimum legal type
  360. /// size.
  361. ///
  362. /// C semantics force sub-int-sized values (e.g. i8, i16) to be promoted to int
  363. /// type (e.g. i32) whenever arithmetic is performed on them.
  364. ///
  365. /// For targets with native i8 or i16 operations, usually InstCombine can shrink
  366. /// the arithmetic type down again. However InstCombine refuses to create
  367. /// illegal types, so for targets without i8 or i16 registers, the lengthening
  368. /// and shrinking remains.
  369. ///
  370. /// Most SIMD ISAs (e.g. NEON) however support vectors of i8 or i16 even when
  371. /// their scalar equivalents do not, so during vectorization it is important to
  372. /// remove these lengthens and truncates when deciding the profitability of
  373. /// vectorization.
  374. ///
  375. /// This function analyzes the given range of instructions and determines the
  376. /// minimum type size each can be converted to. It attempts to remove or
  377. /// minimize type size changes across each def-use chain, so for example in the
  378. /// following code:
  379. ///
  380. /// %1 = load i8, i8*
  381. /// %2 = add i8 %1, 2
  382. /// %3 = load i16, i16*
  383. /// %4 = zext i8 %2 to i32
  384. /// %5 = zext i16 %3 to i32
  385. /// %6 = add i32 %4, %5
  386. /// %7 = trunc i32 %6 to i16
  387. ///
  388. /// Instruction %6 must be done at least in i16, so computeMinimumValueSizes
  389. /// will return: {%1: 16, %2: 16, %3: 16, %4: 16, %5: 16, %6: 16, %7: 16}.
  390. ///
  391. /// If the optional TargetTransformInfo is provided, this function tries harder
  392. /// to do less work by only looking at illegal types.
  393. MapVector<Instruction*, uint64_t>
  394. computeMinimumValueSizes(ArrayRef<BasicBlock*> Blocks,
  395. DemandedBits &DB,
  396. const TargetTransformInfo *TTI=nullptr);
  397. /// Compute the union of two access-group lists.
  398. ///
  399. /// If the list contains just one access group, it is returned directly. If the
  400. /// list is empty, returns nullptr.
  401. MDNode *uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2);
  402. /// Compute the access-group list of access groups that @p Inst1 and @p Inst2
  403. /// are both in. If either instruction does not access memory at all, it is
  404. /// considered to be in every list.
  405. ///
  406. /// If the list contains just one access group, it is returned directly. If the
  407. /// list is empty, returns nullptr.
  408. MDNode *intersectAccessGroups(const Instruction *Inst1,
  409. const Instruction *Inst2);
  410. /// Specifically, let Kinds = [MD_tbaa, MD_alias_scope, MD_noalias, MD_fpmath,
  411. /// MD_nontemporal, MD_access_group].
  412. /// For K in Kinds, we get the MDNode for K from each of the
  413. /// elements of VL, compute their "intersection" (i.e., the most generic
  414. /// metadata value that covers all of the individual values), and set I's
  415. /// metadata for M equal to the intersection value.
  416. ///
  417. /// This function always sets a (possibly null) value for each K in Kinds.
  418. Instruction *propagateMetadata(Instruction *I, ArrayRef<Value *> VL);
  419. /// Create a mask that filters the members of an interleave group where there
  420. /// are gaps.
  421. ///
  422. /// For example, the mask for \p Group with interleave-factor 3
  423. /// and \p VF 4, that has only its first member present is:
  424. ///
  425. /// <1,0,0,1,0,0,1,0,0,1,0,0>
  426. ///
  427. /// Note: The result is a mask of 0's and 1's, as opposed to the other
  428. /// create[*]Mask() utilities which create a shuffle mask (mask that
  429. /// consists of indices).
  430. Constant *createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
  431. const InterleaveGroup<Instruction> &Group);
  432. /// Create a mask with replicated elements.
  433. ///
  434. /// This function creates a shuffle mask for replicating each of the \p VF
  435. /// elements in a vector \p ReplicationFactor times. It can be used to
  436. /// transform a mask of \p VF elements into a mask of
  437. /// \p VF * \p ReplicationFactor elements used by a predicated
  438. /// interleaved-group of loads/stores whose Interleaved-factor ==
  439. /// \p ReplicationFactor.
  440. ///
  441. /// For example, the mask for \p ReplicationFactor=3 and \p VF=4 is:
  442. ///
  443. /// <0,0,0,1,1,1,2,2,2,3,3,3>
  444. llvm::SmallVector<int, 16> createReplicatedMask(unsigned ReplicationFactor,
  445. unsigned VF);
  446. /// Create an interleave shuffle mask.
  447. ///
  448. /// This function creates a shuffle mask for interleaving \p NumVecs vectors of
  449. /// vectorization factor \p VF into a single wide vector. The mask is of the
  450. /// form:
  451. ///
  452. /// <0, VF, VF * 2, ..., VF * (NumVecs - 1), 1, VF + 1, VF * 2 + 1, ...>
  453. ///
  454. /// For example, the mask for VF = 4 and NumVecs = 2 is:
  455. ///
  456. /// <0, 4, 1, 5, 2, 6, 3, 7>.
  457. llvm::SmallVector<int, 16> createInterleaveMask(unsigned VF, unsigned NumVecs);
  458. /// Create a stride shuffle mask.
  459. ///
  460. /// This function creates a shuffle mask whose elements begin at \p Start and
  461. /// are incremented by \p Stride. The mask can be used to deinterleave an
  462. /// interleaved vector into separate vectors of vectorization factor \p VF. The
  463. /// mask is of the form:
  464. ///
  465. /// <Start, Start + Stride, ..., Start + Stride * (VF - 1)>
  466. ///
  467. /// For example, the mask for Start = 0, Stride = 2, and VF = 4 is:
  468. ///
  469. /// <0, 2, 4, 6>
  470. llvm::SmallVector<int, 16> createStrideMask(unsigned Start, unsigned Stride,
  471. unsigned VF);
  472. /// Create a sequential shuffle mask.
  473. ///
  474. /// This function creates shuffle mask whose elements are sequential and begin
  475. /// at \p Start. The mask contains \p NumInts integers and is padded with \p
  476. /// NumUndefs undef values. The mask is of the form:
  477. ///
  478. /// <Start, Start + 1, ... Start + NumInts - 1, undef_1, ... undef_NumUndefs>
  479. ///
  480. /// For example, the mask for Start = 0, NumInsts = 4, and NumUndefs = 4 is:
  481. ///
  482. /// <0, 1, 2, 3, undef, undef, undef, undef>
  483. llvm::SmallVector<int, 16>
  484. createSequentialMask(unsigned Start, unsigned NumInts, unsigned NumUndefs);
  485. /// Concatenate a list of vectors.
  486. ///
  487. /// This function generates code that concatenate the vectors in \p Vecs into a
  488. /// single large vector. The number of vectors should be greater than one, and
  489. /// their element types should be the same. The number of elements in the
  490. /// vectors should also be the same; however, if the last vector has fewer
  491. /// elements, it will be padded with undefs.
  492. Value *concatenateVectors(IRBuilderBase &Builder, ArrayRef<Value *> Vecs);
  493. /// Given a mask vector of i1, Return true if all of the elements of this
  494. /// predicate mask are known to be false or undef. That is, return true if all
  495. /// lanes can be assumed inactive.
  496. bool maskIsAllZeroOrUndef(Value *Mask);
  497. /// Given a mask vector of i1, Return true if all of the elements of this
  498. /// predicate mask are known to be true or undef. That is, return true if all
  499. /// lanes can be assumed active.
  500. bool maskIsAllOneOrUndef(Value *Mask);
  501. /// Given a mask vector of the form <Y x i1>, return an APInt (of bitwidth Y)
  502. /// for each lane which may be active.
  503. APInt possiblyDemandedEltsInMask(Value *Mask);
  504. /// The group of interleaved loads/stores sharing the same stride and
  505. /// close to each other.
  506. ///
  507. /// Each member in this group has an index starting from 0, and the largest
  508. /// index should be less than interleaved factor, which is equal to the absolute
  509. /// value of the access's stride.
  510. ///
  511. /// E.g. An interleaved load group of factor 4:
  512. /// for (unsigned i = 0; i < 1024; i+=4) {
  513. /// a = A[i]; // Member of index 0
  514. /// b = A[i+1]; // Member of index 1
  515. /// d = A[i+3]; // Member of index 3
  516. /// ...
  517. /// }
  518. ///
  519. /// An interleaved store group of factor 4:
  520. /// for (unsigned i = 0; i < 1024; i+=4) {
  521. /// ...
  522. /// A[i] = a; // Member of index 0
  523. /// A[i+1] = b; // Member of index 1
  524. /// A[i+2] = c; // Member of index 2
  525. /// A[i+3] = d; // Member of index 3
  526. /// }
  527. ///
  528. /// Note: the interleaved load group could have gaps (missing members), but
  529. /// the interleaved store group doesn't allow gaps.
  530. template <typename InstTy> class InterleaveGroup {
  531. public:
  532. InterleaveGroup(uint32_t Factor, bool Reverse, Align Alignment)
  533. : Factor(Factor), Reverse(Reverse), Alignment(Alignment),
  534. InsertPos(nullptr) {}
  535. InterleaveGroup(InstTy *Instr, int32_t Stride, Align Alignment)
  536. : Alignment(Alignment), InsertPos(Instr) {
  537. Factor = std::abs(Stride);
  538. assert(Factor > 1 && "Invalid interleave factor");
  539. Reverse = Stride < 0;
  540. Members[0] = Instr;
  541. }
  542. bool isReverse() const { return Reverse; }
  543. uint32_t getFactor() const { return Factor; }
  544. LLVM_ATTRIBUTE_DEPRECATED(uint32_t getAlignment() const,
  545. "Use getAlign instead.") {
  546. return Alignment.value();
  547. }
  548. Align getAlign() const { return Alignment; }
  549. uint32_t getNumMembers() const { return Members.size(); }
  550. /// Try to insert a new member \p Instr with index \p Index and
  551. /// alignment \p NewAlign. The index is related to the leader and it could be
  552. /// negative if it is the new leader.
  553. ///
  554. /// \returns false if the instruction doesn't belong to the group.
  555. bool insertMember(InstTy *Instr, int32_t Index, Align NewAlign) {
  556. // Make sure the key fits in an int32_t.
  557. Optional<int32_t> MaybeKey = checkedAdd(Index, SmallestKey);
  558. if (!MaybeKey)
  559. return false;
  560. int32_t Key = *MaybeKey;
  561. // Skip if the key is used for either the tombstone or empty special values.
  562. if (DenseMapInfo<int32_t>::getTombstoneKey() == Key ||
  563. DenseMapInfo<int32_t>::getEmptyKey() == Key)
  564. return false;
  565. // Skip if there is already a member with the same index.
  566. if (Members.find(Key) != Members.end())
  567. return false;
  568. if (Key > LargestKey) {
  569. // The largest index is always less than the interleave factor.
  570. if (Index >= static_cast<int32_t>(Factor))
  571. return false;
  572. LargestKey = Key;
  573. } else if (Key < SmallestKey) {
  574. // Make sure the largest index fits in an int32_t.
  575. Optional<int32_t> MaybeLargestIndex = checkedSub(LargestKey, Key);
  576. if (!MaybeLargestIndex)
  577. return false;
  578. // The largest index is always less than the interleave factor.
  579. if (*MaybeLargestIndex >= static_cast<int64_t>(Factor))
  580. return false;
  581. SmallestKey = Key;
  582. }
  583. // It's always safe to select the minimum alignment.
  584. Alignment = std::min(Alignment, NewAlign);
  585. Members[Key] = Instr;
  586. return true;
  587. }
  588. /// Get the member with the given index \p Index
  589. ///
  590. /// \returns nullptr if contains no such member.
  591. InstTy *getMember(uint32_t Index) const {
  592. int32_t Key = SmallestKey + Index;
  593. return Members.lookup(Key);
  594. }
  595. /// Get the index for the given member. Unlike the key in the member
  596. /// map, the index starts from 0.
  597. uint32_t getIndex(const InstTy *Instr) const {
  598. for (auto I : Members) {
  599. if (I.second == Instr)
  600. return I.first - SmallestKey;
  601. }
  602. llvm_unreachable("InterleaveGroup contains no such member");
  603. }
  604. InstTy *getInsertPos() const { return InsertPos; }
  605. void setInsertPos(InstTy *Inst) { InsertPos = Inst; }
  606. /// Add metadata (e.g. alias info) from the instructions in this group to \p
  607. /// NewInst.
  608. ///
  609. /// FIXME: this function currently does not add noalias metadata a'la
  610. /// addNewMedata. To do that we need to compute the intersection of the
  611. /// noalias info from all members.
  612. void addMetadata(InstTy *NewInst) const;
  613. /// Returns true if this Group requires a scalar iteration to handle gaps.
  614. bool requiresScalarEpilogue() const {
  615. // If the last member of the Group exists, then a scalar epilog is not
  616. // needed for this group.
  617. if (getMember(getFactor() - 1))
  618. return false;
  619. // We have a group with gaps. It therefore cannot be a group of stores,
  620. // and it can't be a reversed access, because such groups get invalidated.
  621. assert(!getMember(0)->mayWriteToMemory() &&
  622. "Group should have been invalidated");
  623. assert(!isReverse() && "Group should have been invalidated");
  624. // This is a group of loads, with gaps, and without a last-member
  625. return true;
  626. }
  627. private:
  628. uint32_t Factor; // Interleave Factor.
  629. bool Reverse;
  630. Align Alignment;
  631. DenseMap<int32_t, InstTy *> Members;
  632. int32_t SmallestKey = 0;
  633. int32_t LargestKey = 0;
  634. // To avoid breaking dependences, vectorized instructions of an interleave
  635. // group should be inserted at either the first load or the last store in
  636. // program order.
  637. //
  638. // E.g. %even = load i32 // Insert Position
  639. // %add = add i32 %even // Use of %even
  640. // %odd = load i32
  641. //
  642. // store i32 %even
  643. // %odd = add i32 // Def of %odd
  644. // store i32 %odd // Insert Position
  645. InstTy *InsertPos;
  646. };
  647. /// Drive the analysis of interleaved memory accesses in the loop.
  648. ///
  649. /// Use this class to analyze interleaved accesses only when we can vectorize
  650. /// a loop. Otherwise it's meaningless to do analysis as the vectorization
  651. /// on interleaved accesses is unsafe.
  652. ///
  653. /// The analysis collects interleave groups and records the relationships
  654. /// between the member and the group in a map.
  655. class InterleavedAccessInfo {
  656. public:
  657. InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
  658. DominatorTree *DT, LoopInfo *LI,
  659. const LoopAccessInfo *LAI)
  660. : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {}
  661. ~InterleavedAccessInfo() { invalidateGroups(); }
  662. /// Analyze the interleaved accesses and collect them in interleave
  663. /// groups. Substitute symbolic strides using \p Strides.
  664. /// Consider also predicated loads/stores in the analysis if
  665. /// \p EnableMaskedInterleavedGroup is true.
  666. void analyzeInterleaving(bool EnableMaskedInterleavedGroup);
  667. /// Invalidate groups, e.g., in case all blocks in loop will be predicated
  668. /// contrary to original assumption. Although we currently prevent group
  669. /// formation for predicated accesses, we may be able to relax this limitation
  670. /// in the future once we handle more complicated blocks. Returns true if any
  671. /// groups were invalidated.
  672. bool invalidateGroups() {
  673. if (InterleaveGroups.empty()) {
  674. assert(
  675. !RequiresScalarEpilogue &&
  676. "RequiresScalarEpilog should not be set without interleave groups");
  677. return false;
  678. }
  679. InterleaveGroupMap.clear();
  680. for (auto *Ptr : InterleaveGroups)
  681. delete Ptr;
  682. InterleaveGroups.clear();
  683. RequiresScalarEpilogue = false;
  684. return true;
  685. }
  686. /// Check if \p Instr belongs to any interleave group.
  687. bool isInterleaved(Instruction *Instr) const {
  688. return InterleaveGroupMap.find(Instr) != InterleaveGroupMap.end();
  689. }
  690. /// Get the interleave group that \p Instr belongs to.
  691. ///
  692. /// \returns nullptr if doesn't have such group.
  693. InterleaveGroup<Instruction> *
  694. getInterleaveGroup(const Instruction *Instr) const {
  695. return InterleaveGroupMap.lookup(Instr);
  696. }
  697. iterator_range<SmallPtrSetIterator<llvm::InterleaveGroup<Instruction> *>>
  698. getInterleaveGroups() {
  699. return make_range(InterleaveGroups.begin(), InterleaveGroups.end());
  700. }
  701. /// Returns true if an interleaved group that may access memory
  702. /// out-of-bounds requires a scalar epilogue iteration for correctness.
  703. bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
  704. /// Invalidate groups that require a scalar epilogue (due to gaps). This can
  705. /// happen when optimizing for size forbids a scalar epilogue, and the gap
  706. /// cannot be filtered by masking the load/store.
  707. void invalidateGroupsRequiringScalarEpilogue();
  708. private:
  709. /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
  710. /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
  711. /// The interleaved access analysis can also add new predicates (for example
  712. /// by versioning strides of pointers).
  713. PredicatedScalarEvolution &PSE;
  714. Loop *TheLoop;
  715. DominatorTree *DT;
  716. LoopInfo *LI;
  717. const LoopAccessInfo *LAI;
  718. /// True if the loop may contain non-reversed interleaved groups with
  719. /// out-of-bounds accesses. We ensure we don't speculatively access memory
  720. /// out-of-bounds by executing at least one scalar epilogue iteration.
  721. bool RequiresScalarEpilogue = false;
  722. /// Holds the relationships between the members and the interleave group.
  723. DenseMap<Instruction *, InterleaveGroup<Instruction> *> InterleaveGroupMap;
  724. SmallPtrSet<InterleaveGroup<Instruction> *, 4> InterleaveGroups;
  725. /// Holds dependences among the memory accesses in the loop. It maps a source
  726. /// access to a set of dependent sink accesses.
  727. DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
  728. /// The descriptor for a strided memory access.
  729. struct StrideDescriptor {
  730. StrideDescriptor() = default;
  731. StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
  732. Align Alignment)
  733. : Stride(Stride), Scev(Scev), Size(Size), Alignment(Alignment) {}
  734. // The access's stride. It is negative for a reverse access.
  735. int64_t Stride = 0;
  736. // The scalar expression of this access.
  737. const SCEV *Scev = nullptr;
  738. // The size of the memory object.
  739. uint64_t Size = 0;
  740. // The alignment of this access.
  741. Align Alignment;
  742. };
  743. /// A type for holding instructions and their stride descriptors.
  744. using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
  745. /// Create a new interleave group with the given instruction \p Instr,
  746. /// stride \p Stride and alignment \p Align.
  747. ///
  748. /// \returns the newly created interleave group.
  749. InterleaveGroup<Instruction> *
  750. createInterleaveGroup(Instruction *Instr, int Stride, Align Alignment) {
  751. assert(!InterleaveGroupMap.count(Instr) &&
  752. "Already in an interleaved access group");
  753. InterleaveGroupMap[Instr] =
  754. new InterleaveGroup<Instruction>(Instr, Stride, Alignment);
  755. InterleaveGroups.insert(InterleaveGroupMap[Instr]);
  756. return InterleaveGroupMap[Instr];
  757. }
  758. /// Release the group and remove all the relationships.
  759. void releaseGroup(InterleaveGroup<Instruction> *Group) {
  760. for (unsigned i = 0; i < Group->getFactor(); i++)
  761. if (Instruction *Member = Group->getMember(i))
  762. InterleaveGroupMap.erase(Member);
  763. InterleaveGroups.erase(Group);
  764. delete Group;
  765. }
  766. /// Collect all the accesses with a constant stride in program order.
  767. void collectConstStrideAccesses(
  768. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  769. const ValueToValueMap &Strides);
  770. /// Returns true if \p Stride is allowed in an interleaved group.
  771. static bool isStrided(int Stride);
  772. /// Returns true if \p BB is a predicated block.
  773. bool isPredicated(BasicBlock *BB) const {
  774. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  775. }
  776. /// Returns true if LoopAccessInfo can be used for dependence queries.
  777. bool areDependencesValid() const {
  778. return LAI && LAI->getDepChecker().getDependences();
  779. }
  780. /// Returns true if memory accesses \p A and \p B can be reordered, if
  781. /// necessary, when constructing interleaved groups.
  782. ///
  783. /// \p A must precede \p B in program order. We return false if reordering is
  784. /// not necessary or is prevented because \p A and \p B may be dependent.
  785. bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
  786. StrideEntry *B) const {
  787. // Code motion for interleaved accesses can potentially hoist strided loads
  788. // and sink strided stores. The code below checks the legality of the
  789. // following two conditions:
  790. //
  791. // 1. Potentially moving a strided load (B) before any store (A) that
  792. // precedes B, or
  793. //
  794. // 2. Potentially moving a strided store (A) after any load or store (B)
  795. // that A precedes.
  796. //
  797. // It's legal to reorder A and B if we know there isn't a dependence from A
  798. // to B. Note that this determination is conservative since some
  799. // dependences could potentially be reordered safely.
  800. // A is potentially the source of a dependence.
  801. auto *Src = A->first;
  802. auto SrcDes = A->second;
  803. // B is potentially the sink of a dependence.
  804. auto *Sink = B->first;
  805. auto SinkDes = B->second;
  806. // Code motion for interleaved accesses can't violate WAR dependences.
  807. // Thus, reordering is legal if the source isn't a write.
  808. if (!Src->mayWriteToMemory())
  809. return true;
  810. // At least one of the accesses must be strided.
  811. if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
  812. return true;
  813. // If dependence information is not available from LoopAccessInfo,
  814. // conservatively assume the instructions can't be reordered.
  815. if (!areDependencesValid())
  816. return false;
  817. // If we know there is a dependence from source to sink, assume the
  818. // instructions can't be reordered. Otherwise, reordering is legal.
  819. return Dependences.find(Src) == Dependences.end() ||
  820. !Dependences.lookup(Src).count(Sink);
  821. }
  822. /// Collect the dependences from LoopAccessInfo.
  823. ///
  824. /// We process the dependences once during the interleaved access analysis to
  825. /// enable constant-time dependence queries.
  826. void collectDependences() {
  827. if (!areDependencesValid())
  828. return;
  829. auto *Deps = LAI->getDepChecker().getDependences();
  830. for (auto Dep : *Deps)
  831. Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
  832. }
  833. };
  834. } // llvm namespace
  835. #endif
  836. #ifdef __GNUC__
  837. #pragma GCC diagnostic pop
  838. #endif