VectorUtils.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  1. //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines vectorizer utilities.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/VectorUtils.h"
  13. #include "llvm/ADT/EquivalenceClasses.h"
  14. #include "llvm/Analysis/DemandedBits.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/LoopIterator.h"
  17. #include "llvm/Analysis/ScalarEvolution.h"
  18. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/GetElementPtrTypeIterator.h"
  23. #include "llvm/IR/IRBuilder.h"
  24. #include "llvm/IR/PatternMatch.h"
  25. #include "llvm/IR/Value.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #define DEBUG_TYPE "vectorutils"
  28. using namespace llvm;
  29. using namespace llvm::PatternMatch;
  30. /// Maximum factor for an interleaved memory access.
  31. static cl::opt<unsigned> MaxInterleaveGroupFactor(
  32. "max-interleave-group-factor", cl::Hidden,
  33. cl::desc("Maximum factor for an interleaved access group (default = 8)"),
  34. cl::init(8));
  35. /// Return true if all of the intrinsic's arguments and return type are scalars
  36. /// for the scalar form of the intrinsic, and vectors for the vector form of the
  37. /// intrinsic (except operands that are marked as always being scalar by
  38. /// hasVectorInstrinsicScalarOpd).
  39. bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
  40. switch (ID) {
  41. case Intrinsic::abs: // Begin integer bit-manipulation.
  42. case Intrinsic::bswap:
  43. case Intrinsic::bitreverse:
  44. case Intrinsic::ctpop:
  45. case Intrinsic::ctlz:
  46. case Intrinsic::cttz:
  47. case Intrinsic::fshl:
  48. case Intrinsic::fshr:
  49. case Intrinsic::smax:
  50. case Intrinsic::smin:
  51. case Intrinsic::umax:
  52. case Intrinsic::umin:
  53. case Intrinsic::sadd_sat:
  54. case Intrinsic::ssub_sat:
  55. case Intrinsic::uadd_sat:
  56. case Intrinsic::usub_sat:
  57. case Intrinsic::smul_fix:
  58. case Intrinsic::smul_fix_sat:
  59. case Intrinsic::umul_fix:
  60. case Intrinsic::umul_fix_sat:
  61. case Intrinsic::sqrt: // Begin floating-point.
  62. case Intrinsic::sin:
  63. case Intrinsic::cos:
  64. case Intrinsic::exp:
  65. case Intrinsic::exp2:
  66. case Intrinsic::log:
  67. case Intrinsic::log10:
  68. case Intrinsic::log2:
  69. case Intrinsic::fabs:
  70. case Intrinsic::minnum:
  71. case Intrinsic::maxnum:
  72. case Intrinsic::minimum:
  73. case Intrinsic::maximum:
  74. case Intrinsic::copysign:
  75. case Intrinsic::floor:
  76. case Intrinsic::ceil:
  77. case Intrinsic::trunc:
  78. case Intrinsic::rint:
  79. case Intrinsic::nearbyint:
  80. case Intrinsic::round:
  81. case Intrinsic::roundeven:
  82. case Intrinsic::pow:
  83. case Intrinsic::fma:
  84. case Intrinsic::fmuladd:
  85. case Intrinsic::powi:
  86. case Intrinsic::canonicalize:
  87. return true;
  88. default:
  89. return false;
  90. }
  91. }
  92. /// Identifies if the vector form of the intrinsic has a scalar operand.
  93. bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
  94. unsigned ScalarOpdIdx) {
  95. switch (ID) {
  96. case Intrinsic::abs:
  97. case Intrinsic::ctlz:
  98. case Intrinsic::cttz:
  99. case Intrinsic::powi:
  100. return (ScalarOpdIdx == 1);
  101. case Intrinsic::smul_fix:
  102. case Intrinsic::smul_fix_sat:
  103. case Intrinsic::umul_fix:
  104. case Intrinsic::umul_fix_sat:
  105. return (ScalarOpdIdx == 2);
  106. default:
  107. return false;
  108. }
  109. }
  110. bool llvm::hasVectorInstrinsicOverloadedScalarOpd(Intrinsic::ID ID,
  111. unsigned ScalarOpdIdx) {
  112. switch (ID) {
  113. case Intrinsic::powi:
  114. return (ScalarOpdIdx == 1);
  115. default:
  116. return false;
  117. }
  118. }
  119. /// Returns intrinsic ID for call.
  120. /// For the input call instruction it finds mapping intrinsic and returns
  121. /// its ID, in case it does not found it return not_intrinsic.
  122. Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
  123. const TargetLibraryInfo *TLI) {
  124. Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
  125. if (ID == Intrinsic::not_intrinsic)
  126. return Intrinsic::not_intrinsic;
  127. if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
  128. ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
  129. ID == Intrinsic::experimental_noalias_scope_decl ||
  130. ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
  131. return ID;
  132. return Intrinsic::not_intrinsic;
  133. }
  134. /// Find the operand of the GEP that should be checked for consecutive
  135. /// stores. This ignores trailing indices that have no effect on the final
  136. /// pointer.
  137. unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
  138. const DataLayout &DL = Gep->getModule()->getDataLayout();
  139. unsigned LastOperand = Gep->getNumOperands() - 1;
  140. TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
  141. // Walk backwards and try to peel off zeros.
  142. while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
  143. // Find the type we're currently indexing into.
  144. gep_type_iterator GEPTI = gep_type_begin(Gep);
  145. std::advance(GEPTI, LastOperand - 2);
  146. // If it's a type with the same allocation size as the result of the GEP we
  147. // can peel off the zero index.
  148. if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
  149. break;
  150. --LastOperand;
  151. }
  152. return LastOperand;
  153. }
  154. /// If the argument is a GEP, then returns the operand identified by
  155. /// getGEPInductionOperand. However, if there is some other non-loop-invariant
  156. /// operand, it returns that instead.
  157. Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  158. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  159. if (!GEP)
  160. return Ptr;
  161. unsigned InductionOperand = getGEPInductionOperand(GEP);
  162. // Check that all of the gep indices are uniform except for our induction
  163. // operand.
  164. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
  165. if (i != InductionOperand &&
  166. !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
  167. return Ptr;
  168. return GEP->getOperand(InductionOperand);
  169. }
  170. /// If a value has only one user that is a CastInst, return it.
  171. Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
  172. Value *UniqueCast = nullptr;
  173. for (User *U : Ptr->users()) {
  174. CastInst *CI = dyn_cast<CastInst>(U);
  175. if (CI && CI->getType() == Ty) {
  176. if (!UniqueCast)
  177. UniqueCast = CI;
  178. else
  179. return nullptr;
  180. }
  181. }
  182. return UniqueCast;
  183. }
  184. /// Get the stride of a pointer access in a loop. Looks for symbolic
  185. /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
  186. Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  187. auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  188. if (!PtrTy || PtrTy->isAggregateType())
  189. return nullptr;
  190. // Try to remove a gep instruction to make the pointer (actually index at this
  191. // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
  192. // pointer, otherwise, we are analyzing the index.
  193. Value *OrigPtr = Ptr;
  194. // The size of the pointer access.
  195. int64_t PtrAccessSize = 1;
  196. Ptr = stripGetElementPtr(Ptr, SE, Lp);
  197. const SCEV *V = SE->getSCEV(Ptr);
  198. if (Ptr != OrigPtr)
  199. // Strip off casts.
  200. while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
  201. V = C->getOperand();
  202. const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
  203. if (!S)
  204. return nullptr;
  205. V = S->getStepRecurrence(*SE);
  206. if (!V)
  207. return nullptr;
  208. // Strip off the size of access multiplication if we are still analyzing the
  209. // pointer.
  210. if (OrigPtr == Ptr) {
  211. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
  212. if (M->getOperand(0)->getSCEVType() != scConstant)
  213. return nullptr;
  214. const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
  215. // Huge step value - give up.
  216. if (APStepVal.getBitWidth() > 64)
  217. return nullptr;
  218. int64_t StepVal = APStepVal.getSExtValue();
  219. if (PtrAccessSize != StepVal)
  220. return nullptr;
  221. V = M->getOperand(1);
  222. }
  223. }
  224. // Strip off casts.
  225. Type *StripedOffRecurrenceCast = nullptr;
  226. if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) {
  227. StripedOffRecurrenceCast = C->getType();
  228. V = C->getOperand();
  229. }
  230. // Look for the loop invariant symbolic value.
  231. const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
  232. if (!U)
  233. return nullptr;
  234. Value *Stride = U->getValue();
  235. if (!Lp->isLoopInvariant(Stride))
  236. return nullptr;
  237. // If we have stripped off the recurrence cast we have to make sure that we
  238. // return the value that is used in this loop so that we can replace it later.
  239. if (StripedOffRecurrenceCast)
  240. Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
  241. return Stride;
  242. }
  243. /// Given a vector and an element number, see if the scalar value is
  244. /// already around as a register, for example if it were inserted then extracted
  245. /// from the vector.
  246. Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
  247. assert(V->getType()->isVectorTy() && "Not looking at a vector?");
  248. VectorType *VTy = cast<VectorType>(V->getType());
  249. // For fixed-length vector, return undef for out of range access.
  250. if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
  251. unsigned Width = FVTy->getNumElements();
  252. if (EltNo >= Width)
  253. return UndefValue::get(FVTy->getElementType());
  254. }
  255. if (Constant *C = dyn_cast<Constant>(V))
  256. return C->getAggregateElement(EltNo);
  257. if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
  258. // If this is an insert to a variable element, we don't know what it is.
  259. if (!isa<ConstantInt>(III->getOperand(2)))
  260. return nullptr;
  261. unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
  262. // If this is an insert to the element we are looking for, return the
  263. // inserted value.
  264. if (EltNo == IIElt)
  265. return III->getOperand(1);
  266. // Guard against infinite loop on malformed, unreachable IR.
  267. if (III == III->getOperand(0))
  268. return nullptr;
  269. // Otherwise, the insertelement doesn't modify the value, recurse on its
  270. // vector input.
  271. return findScalarElement(III->getOperand(0), EltNo);
  272. }
  273. ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
  274. // Restrict the following transformation to fixed-length vector.
  275. if (SVI && isa<FixedVectorType>(SVI->getType())) {
  276. unsigned LHSWidth =
  277. cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
  278. int InEl = SVI->getMaskValue(EltNo);
  279. if (InEl < 0)
  280. return UndefValue::get(VTy->getElementType());
  281. if (InEl < (int)LHSWidth)
  282. return findScalarElement(SVI->getOperand(0), InEl);
  283. return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
  284. }
  285. // Extract a value from a vector add operation with a constant zero.
  286. // TODO: Use getBinOpIdentity() to generalize this.
  287. Value *Val; Constant *C;
  288. if (match(V, m_Add(m_Value(Val), m_Constant(C))))
  289. if (Constant *Elt = C->getAggregateElement(EltNo))
  290. if (Elt->isNullValue())
  291. return findScalarElement(Val, EltNo);
  292. // If the vector is a splat then we can trivially find the scalar element.
  293. if (isa<ScalableVectorType>(VTy))
  294. if (Value *Splat = getSplatValue(V))
  295. if (EltNo < VTy->getElementCount().getKnownMinValue())
  296. return Splat;
  297. // Otherwise, we don't know.
  298. return nullptr;
  299. }
  300. int llvm::getSplatIndex(ArrayRef<int> Mask) {
  301. int SplatIndex = -1;
  302. for (int M : Mask) {
  303. // Ignore invalid (undefined) mask elements.
  304. if (M < 0)
  305. continue;
  306. // There can be only 1 non-negative mask element value if this is a splat.
  307. if (SplatIndex != -1 && SplatIndex != M)
  308. return -1;
  309. // Initialize the splat index to the 1st non-negative mask element.
  310. SplatIndex = M;
  311. }
  312. assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
  313. return SplatIndex;
  314. }
  315. /// Get splat value if the input is a splat vector or return nullptr.
  316. /// This function is not fully general. It checks only 2 cases:
  317. /// the input value is (1) a splat constant vector or (2) a sequence
  318. /// of instructions that broadcasts a scalar at element 0.
  319. Value *llvm::getSplatValue(const Value *V) {
  320. if (isa<VectorType>(V->getType()))
  321. if (auto *C = dyn_cast<Constant>(V))
  322. return C->getSplatValue();
  323. // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
  324. Value *Splat;
  325. if (match(V,
  326. m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
  327. m_Value(), m_ZeroMask())))
  328. return Splat;
  329. return nullptr;
  330. }
  331. bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
  332. assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
  333. if (isa<VectorType>(V->getType())) {
  334. if (isa<UndefValue>(V))
  335. return true;
  336. // FIXME: We can allow undefs, but if Index was specified, we may want to
  337. // check that the constant is defined at that index.
  338. if (auto *C = dyn_cast<Constant>(V))
  339. return C->getSplatValue() != nullptr;
  340. }
  341. if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
  342. // FIXME: We can safely allow undefs here. If Index was specified, we will
  343. // check that the mask elt is defined at the required index.
  344. if (!is_splat(Shuf->getShuffleMask()))
  345. return false;
  346. // Match any index.
  347. if (Index == -1)
  348. return true;
  349. // Match a specific element. The mask should be defined at and match the
  350. // specified index.
  351. return Shuf->getMaskValue(Index) == Index;
  352. }
  353. // The remaining tests are all recursive, so bail out if we hit the limit.
  354. if (Depth++ == MaxAnalysisRecursionDepth)
  355. return false;
  356. // If both operands of a binop are splats, the result is a splat.
  357. Value *X, *Y, *Z;
  358. if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
  359. return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
  360. // If all operands of a select are splats, the result is a splat.
  361. if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
  362. return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
  363. isSplatValue(Z, Index, Depth);
  364. // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
  365. return false;
  366. }
  367. void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  368. SmallVectorImpl<int> &ScaledMask) {
  369. assert(Scale > 0 && "Unexpected scaling factor");
  370. // Fast-path: if no scaling, then it is just a copy.
  371. if (Scale == 1) {
  372. ScaledMask.assign(Mask.begin(), Mask.end());
  373. return;
  374. }
  375. ScaledMask.clear();
  376. for (int MaskElt : Mask) {
  377. if (MaskElt >= 0) {
  378. assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
  379. "Overflowed 32-bits");
  380. }
  381. for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
  382. ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
  383. }
  384. }
  385. bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
  386. SmallVectorImpl<int> &ScaledMask) {
  387. assert(Scale > 0 && "Unexpected scaling factor");
  388. // Fast-path: if no scaling, then it is just a copy.
  389. if (Scale == 1) {
  390. ScaledMask.assign(Mask.begin(), Mask.end());
  391. return true;
  392. }
  393. // We must map the original elements down evenly to a type with less elements.
  394. int NumElts = Mask.size();
  395. if (NumElts % Scale != 0)
  396. return false;
  397. ScaledMask.clear();
  398. ScaledMask.reserve(NumElts / Scale);
  399. // Step through the input mask by splitting into Scale-sized slices.
  400. do {
  401. ArrayRef<int> MaskSlice = Mask.take_front(Scale);
  402. assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
  403. // The first element of the slice determines how we evaluate this slice.
  404. int SliceFront = MaskSlice.front();
  405. if (SliceFront < 0) {
  406. // Negative values (undef or other "sentinel" values) must be equal across
  407. // the entire slice.
  408. if (!is_splat(MaskSlice))
  409. return false;
  410. ScaledMask.push_back(SliceFront);
  411. } else {
  412. // A positive mask element must be cleanly divisible.
  413. if (SliceFront % Scale != 0)
  414. return false;
  415. // Elements of the slice must be consecutive.
  416. for (int i = 1; i < Scale; ++i)
  417. if (MaskSlice[i] != SliceFront + i)
  418. return false;
  419. ScaledMask.push_back(SliceFront / Scale);
  420. }
  421. Mask = Mask.drop_front(Scale);
  422. } while (!Mask.empty());
  423. assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
  424. // All elements of the original mask can be scaled down to map to the elements
  425. // of a mask with wider elements.
  426. return true;
  427. }
  428. MapVector<Instruction *, uint64_t>
  429. llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
  430. const TargetTransformInfo *TTI) {
  431. // DemandedBits will give us every value's live-out bits. But we want
  432. // to ensure no extra casts would need to be inserted, so every DAG
  433. // of connected values must have the same minimum bitwidth.
  434. EquivalenceClasses<Value *> ECs;
  435. SmallVector<Value *, 16> Worklist;
  436. SmallPtrSet<Value *, 4> Roots;
  437. SmallPtrSet<Value *, 16> Visited;
  438. DenseMap<Value *, uint64_t> DBits;
  439. SmallPtrSet<Instruction *, 4> InstructionSet;
  440. MapVector<Instruction *, uint64_t> MinBWs;
  441. // Determine the roots. We work bottom-up, from truncs or icmps.
  442. bool SeenExtFromIllegalType = false;
  443. for (auto *BB : Blocks)
  444. for (auto &I : *BB) {
  445. InstructionSet.insert(&I);
  446. if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
  447. !TTI->isTypeLegal(I.getOperand(0)->getType()))
  448. SeenExtFromIllegalType = true;
  449. // Only deal with non-vector integers up to 64-bits wide.
  450. if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
  451. !I.getType()->isVectorTy() &&
  452. I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
  453. // Don't make work for ourselves. If we know the loaded type is legal,
  454. // don't add it to the worklist.
  455. if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
  456. continue;
  457. Worklist.push_back(&I);
  458. Roots.insert(&I);
  459. }
  460. }
  461. // Early exit.
  462. if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
  463. return MinBWs;
  464. // Now proceed breadth-first, unioning values together.
  465. while (!Worklist.empty()) {
  466. Value *Val = Worklist.pop_back_val();
  467. Value *Leader = ECs.getOrInsertLeaderValue(Val);
  468. if (Visited.count(Val))
  469. continue;
  470. Visited.insert(Val);
  471. // Non-instructions terminate a chain successfully.
  472. if (!isa<Instruction>(Val))
  473. continue;
  474. Instruction *I = cast<Instruction>(Val);
  475. // If we encounter a type that is larger than 64 bits, we can't represent
  476. // it so bail out.
  477. if (DB.getDemandedBits(I).getBitWidth() > 64)
  478. return MapVector<Instruction *, uint64_t>();
  479. uint64_t V = DB.getDemandedBits(I).getZExtValue();
  480. DBits[Leader] |= V;
  481. DBits[I] = V;
  482. // Casts, loads and instructions outside of our range terminate a chain
  483. // successfully.
  484. if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
  485. !InstructionSet.count(I))
  486. continue;
  487. // Unsafe casts terminate a chain unsuccessfully. We can't do anything
  488. // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
  489. // transform anything that relies on them.
  490. if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
  491. !I->getType()->isIntegerTy()) {
  492. DBits[Leader] |= ~0ULL;
  493. continue;
  494. }
  495. // We don't modify the types of PHIs. Reductions will already have been
  496. // truncated if possible, and inductions' sizes will have been chosen by
  497. // indvars.
  498. if (isa<PHINode>(I))
  499. continue;
  500. if (DBits[Leader] == ~0ULL)
  501. // All bits demanded, no point continuing.
  502. continue;
  503. for (Value *O : cast<User>(I)->operands()) {
  504. ECs.unionSets(Leader, O);
  505. Worklist.push_back(O);
  506. }
  507. }
  508. // Now we've discovered all values, walk them to see if there are
  509. // any users we didn't see. If there are, we can't optimize that
  510. // chain.
  511. for (auto &I : DBits)
  512. for (auto *U : I.first->users())
  513. if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
  514. DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
  515. for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
  516. uint64_t LeaderDemandedBits = 0;
  517. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
  518. LeaderDemandedBits |= DBits[M];
  519. uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
  520. llvm::countLeadingZeros(LeaderDemandedBits);
  521. // Round up to a power of 2
  522. if (!isPowerOf2_64((uint64_t)MinBW))
  523. MinBW = NextPowerOf2(MinBW);
  524. // We don't modify the types of PHIs. Reductions will already have been
  525. // truncated if possible, and inductions' sizes will have been chosen by
  526. // indvars.
  527. // If we are required to shrink a PHI, abandon this entire equivalence class.
  528. bool Abort = false;
  529. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
  530. if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
  531. Abort = true;
  532. break;
  533. }
  534. if (Abort)
  535. continue;
  536. for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
  537. if (!isa<Instruction>(M))
  538. continue;
  539. Type *Ty = M->getType();
  540. if (Roots.count(M))
  541. Ty = cast<Instruction>(M)->getOperand(0)->getType();
  542. if (MinBW < Ty->getScalarSizeInBits())
  543. MinBWs[cast<Instruction>(M)] = MinBW;
  544. }
  545. }
  546. return MinBWs;
  547. }
  548. /// Add all access groups in @p AccGroups to @p List.
  549. template <typename ListT>
  550. static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
  551. // Interpret an access group as a list containing itself.
  552. if (AccGroups->getNumOperands() == 0) {
  553. assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
  554. List.insert(AccGroups);
  555. return;
  556. }
  557. for (auto &AccGroupListOp : AccGroups->operands()) {
  558. auto *Item = cast<MDNode>(AccGroupListOp.get());
  559. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  560. List.insert(Item);
  561. }
  562. }
  563. MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
  564. if (!AccGroups1)
  565. return AccGroups2;
  566. if (!AccGroups2)
  567. return AccGroups1;
  568. if (AccGroups1 == AccGroups2)
  569. return AccGroups1;
  570. SmallSetVector<Metadata *, 4> Union;
  571. addToAccessGroupList(Union, AccGroups1);
  572. addToAccessGroupList(Union, AccGroups2);
  573. if (Union.size() == 0)
  574. return nullptr;
  575. if (Union.size() == 1)
  576. return cast<MDNode>(Union.front());
  577. LLVMContext &Ctx = AccGroups1->getContext();
  578. return MDNode::get(Ctx, Union.getArrayRef());
  579. }
  580. MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
  581. const Instruction *Inst2) {
  582. bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
  583. bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
  584. if (!MayAccessMem1 && !MayAccessMem2)
  585. return nullptr;
  586. if (!MayAccessMem1)
  587. return Inst2->getMetadata(LLVMContext::MD_access_group);
  588. if (!MayAccessMem2)
  589. return Inst1->getMetadata(LLVMContext::MD_access_group);
  590. MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
  591. MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
  592. if (!MD1 || !MD2)
  593. return nullptr;
  594. if (MD1 == MD2)
  595. return MD1;
  596. // Use set for scalable 'contains' check.
  597. SmallPtrSet<Metadata *, 4> AccGroupSet2;
  598. addToAccessGroupList(AccGroupSet2, MD2);
  599. SmallVector<Metadata *, 4> Intersection;
  600. if (MD1->getNumOperands() == 0) {
  601. assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
  602. if (AccGroupSet2.count(MD1))
  603. Intersection.push_back(MD1);
  604. } else {
  605. for (const MDOperand &Node : MD1->operands()) {
  606. auto *Item = cast<MDNode>(Node.get());
  607. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  608. if (AccGroupSet2.count(Item))
  609. Intersection.push_back(Item);
  610. }
  611. }
  612. if (Intersection.size() == 0)
  613. return nullptr;
  614. if (Intersection.size() == 1)
  615. return cast<MDNode>(Intersection.front());
  616. LLVMContext &Ctx = Inst1->getContext();
  617. return MDNode::get(Ctx, Intersection);
  618. }
  619. /// \returns \p I after propagating metadata from \p VL.
  620. Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
  621. if (VL.empty())
  622. return Inst;
  623. Instruction *I0 = cast<Instruction>(VL[0]);
  624. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  625. I0->getAllMetadataOtherThanDebugLoc(Metadata);
  626. for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  627. LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
  628. LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
  629. LLVMContext::MD_access_group}) {
  630. MDNode *MD = I0->getMetadata(Kind);
  631. for (int J = 1, E = VL.size(); MD && J != E; ++J) {
  632. const Instruction *IJ = cast<Instruction>(VL[J]);
  633. MDNode *IMD = IJ->getMetadata(Kind);
  634. switch (Kind) {
  635. case LLVMContext::MD_tbaa:
  636. MD = MDNode::getMostGenericTBAA(MD, IMD);
  637. break;
  638. case LLVMContext::MD_alias_scope:
  639. MD = MDNode::getMostGenericAliasScope(MD, IMD);
  640. break;
  641. case LLVMContext::MD_fpmath:
  642. MD = MDNode::getMostGenericFPMath(MD, IMD);
  643. break;
  644. case LLVMContext::MD_noalias:
  645. case LLVMContext::MD_nontemporal:
  646. case LLVMContext::MD_invariant_load:
  647. MD = MDNode::intersect(MD, IMD);
  648. break;
  649. case LLVMContext::MD_access_group:
  650. MD = intersectAccessGroups(Inst, IJ);
  651. break;
  652. default:
  653. llvm_unreachable("unhandled metadata");
  654. }
  655. }
  656. Inst->setMetadata(Kind, MD);
  657. }
  658. return Inst;
  659. }
  660. Constant *
  661. llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
  662. const InterleaveGroup<Instruction> &Group) {
  663. // All 1's means mask is not needed.
  664. if (Group.getNumMembers() == Group.getFactor())
  665. return nullptr;
  666. // TODO: support reversed access.
  667. assert(!Group.isReverse() && "Reversed group not supported.");
  668. SmallVector<Constant *, 16> Mask;
  669. for (unsigned i = 0; i < VF; i++)
  670. for (unsigned j = 0; j < Group.getFactor(); ++j) {
  671. unsigned HasMember = Group.getMember(j) ? 1 : 0;
  672. Mask.push_back(Builder.getInt1(HasMember));
  673. }
  674. return ConstantVector::get(Mask);
  675. }
  676. llvm::SmallVector<int, 16>
  677. llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
  678. SmallVector<int, 16> MaskVec;
  679. for (unsigned i = 0; i < VF; i++)
  680. for (unsigned j = 0; j < ReplicationFactor; j++)
  681. MaskVec.push_back(i);
  682. return MaskVec;
  683. }
  684. llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
  685. unsigned NumVecs) {
  686. SmallVector<int, 16> Mask;
  687. for (unsigned i = 0; i < VF; i++)
  688. for (unsigned j = 0; j < NumVecs; j++)
  689. Mask.push_back(j * VF + i);
  690. return Mask;
  691. }
  692. llvm::SmallVector<int, 16>
  693. llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
  694. SmallVector<int, 16> Mask;
  695. for (unsigned i = 0; i < VF; i++)
  696. Mask.push_back(Start + i * Stride);
  697. return Mask;
  698. }
  699. llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
  700. unsigned NumInts,
  701. unsigned NumUndefs) {
  702. SmallVector<int, 16> Mask;
  703. for (unsigned i = 0; i < NumInts; i++)
  704. Mask.push_back(Start + i);
  705. for (unsigned i = 0; i < NumUndefs; i++)
  706. Mask.push_back(-1);
  707. return Mask;
  708. }
  709. llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
  710. unsigned NumElts) {
  711. // Avoid casts in the loop and make sure we have a reasonable number.
  712. int NumEltsSigned = NumElts;
  713. assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
  714. // If the mask chooses an element from operand 1, reduce it to choose from the
  715. // corresponding element of operand 0. Undef mask elements are unchanged.
  716. SmallVector<int, 16> UnaryMask;
  717. for (int MaskElt : Mask) {
  718. assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
  719. int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
  720. UnaryMask.push_back(UnaryElt);
  721. }
  722. return UnaryMask;
  723. }
  724. /// A helper function for concatenating vectors. This function concatenates two
  725. /// vectors having the same element type. If the second vector has fewer
  726. /// elements than the first, it is padded with undefs.
  727. static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
  728. Value *V2) {
  729. VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
  730. VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
  731. assert(VecTy1 && VecTy2 &&
  732. VecTy1->getScalarType() == VecTy2->getScalarType() &&
  733. "Expect two vectors with the same element type");
  734. unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
  735. unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
  736. assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
  737. if (NumElts1 > NumElts2) {
  738. // Extend with UNDEFs.
  739. V2 = Builder.CreateShuffleVector(
  740. V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
  741. }
  742. return Builder.CreateShuffleVector(
  743. V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
  744. }
  745. Value *llvm::concatenateVectors(IRBuilderBase &Builder,
  746. ArrayRef<Value *> Vecs) {
  747. unsigned NumVecs = Vecs.size();
  748. assert(NumVecs > 1 && "Should be at least two vectors");
  749. SmallVector<Value *, 8> ResList;
  750. ResList.append(Vecs.begin(), Vecs.end());
  751. do {
  752. SmallVector<Value *, 8> TmpList;
  753. for (unsigned i = 0; i < NumVecs - 1; i += 2) {
  754. Value *V0 = ResList[i], *V1 = ResList[i + 1];
  755. assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
  756. "Only the last vector may have a different type");
  757. TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
  758. }
  759. // Push the last vector if the total number of vectors is odd.
  760. if (NumVecs % 2 != 0)
  761. TmpList.push_back(ResList[NumVecs - 1]);
  762. ResList = TmpList;
  763. NumVecs = ResList.size();
  764. } while (NumVecs > 1);
  765. return ResList[0];
  766. }
  767. bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
  768. assert(isa<VectorType>(Mask->getType()) &&
  769. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  770. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  771. 1 &&
  772. "Mask must be a vector of i1");
  773. auto *ConstMask = dyn_cast<Constant>(Mask);
  774. if (!ConstMask)
  775. return false;
  776. if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
  777. return true;
  778. if (isa<ScalableVectorType>(ConstMask->getType()))
  779. return false;
  780. for (unsigned
  781. I = 0,
  782. E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
  783. I != E; ++I) {
  784. if (auto *MaskElt = ConstMask->getAggregateElement(I))
  785. if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
  786. continue;
  787. return false;
  788. }
  789. return true;
  790. }
  791. bool llvm::maskIsAllOneOrUndef(Value *Mask) {
  792. assert(isa<VectorType>(Mask->getType()) &&
  793. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  794. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  795. 1 &&
  796. "Mask must be a vector of i1");
  797. auto *ConstMask = dyn_cast<Constant>(Mask);
  798. if (!ConstMask)
  799. return false;
  800. if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
  801. return true;
  802. if (isa<ScalableVectorType>(ConstMask->getType()))
  803. return false;
  804. for (unsigned
  805. I = 0,
  806. E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
  807. I != E; ++I) {
  808. if (auto *MaskElt = ConstMask->getAggregateElement(I))
  809. if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
  810. continue;
  811. return false;
  812. }
  813. return true;
  814. }
  815. /// TODO: This is a lot like known bits, but for
  816. /// vectors. Is there something we can common this with?
  817. APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
  818. assert(isa<FixedVectorType>(Mask->getType()) &&
  819. isa<IntegerType>(Mask->getType()->getScalarType()) &&
  820. cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
  821. 1 &&
  822. "Mask must be a fixed width vector of i1");
  823. const unsigned VWidth =
  824. cast<FixedVectorType>(Mask->getType())->getNumElements();
  825. APInt DemandedElts = APInt::getAllOnes(VWidth);
  826. if (auto *CV = dyn_cast<ConstantVector>(Mask))
  827. for (unsigned i = 0; i < VWidth; i++)
  828. if (CV->getAggregateElement(i)->isNullValue())
  829. DemandedElts.clearBit(i);
  830. return DemandedElts;
  831. }
  832. bool InterleavedAccessInfo::isStrided(int Stride) {
  833. unsigned Factor = std::abs(Stride);
  834. return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
  835. }
  836. void InterleavedAccessInfo::collectConstStrideAccesses(
  837. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  838. const ValueToValueMap &Strides) {
  839. auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
  840. // Since it's desired that the load/store instructions be maintained in
  841. // "program order" for the interleaved access analysis, we have to visit the
  842. // blocks in the loop in reverse postorder (i.e., in a topological order).
  843. // Such an ordering will ensure that any load/store that may be executed
  844. // before a second load/store will precede the second load/store in
  845. // AccessStrideInfo.
  846. LoopBlocksDFS DFS(TheLoop);
  847. DFS.perform(LI);
  848. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
  849. for (auto &I : *BB) {
  850. Value *Ptr = getLoadStorePointerOperand(&I);
  851. if (!Ptr)
  852. continue;
  853. Type *ElementTy = getLoadStoreType(&I);
  854. // We don't check wrapping here because we don't know yet if Ptr will be
  855. // part of a full group or a group with gaps. Checking wrapping for all
  856. // pointers (even those that end up in groups with no gaps) will be overly
  857. // conservative. For full groups, wrapping should be ok since if we would
  858. // wrap around the address space we would do a memory access at nullptr
  859. // even without the transformation. The wrapping checks are therefore
  860. // deferred until after we've formed the interleaved groups.
  861. int64_t Stride = getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
  862. /*Assume=*/true, /*ShouldCheckWrap=*/false);
  863. const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
  864. uint64_t Size = DL.getTypeAllocSize(ElementTy);
  865. AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
  866. getLoadStoreAlignment(&I));
  867. }
  868. }
  869. // Analyze interleaved accesses and collect them into interleaved load and
  870. // store groups.
  871. //
  872. // When generating code for an interleaved load group, we effectively hoist all
  873. // loads in the group to the location of the first load in program order. When
  874. // generating code for an interleaved store group, we sink all stores to the
  875. // location of the last store. This code motion can change the order of load
  876. // and store instructions and may break dependences.
  877. //
  878. // The code generation strategy mentioned above ensures that we won't violate
  879. // any write-after-read (WAR) dependences.
  880. //
  881. // E.g., for the WAR dependence: a = A[i]; // (1)
  882. // A[i] = b; // (2)
  883. //
  884. // The store group of (2) is always inserted at or below (2), and the load
  885. // group of (1) is always inserted at or above (1). Thus, the instructions will
  886. // never be reordered. All other dependences are checked to ensure the
  887. // correctness of the instruction reordering.
  888. //
  889. // The algorithm visits all memory accesses in the loop in bottom-up program
  890. // order. Program order is established by traversing the blocks in the loop in
  891. // reverse postorder when collecting the accesses.
  892. //
  893. // We visit the memory accesses in bottom-up order because it can simplify the
  894. // construction of store groups in the presence of write-after-write (WAW)
  895. // dependences.
  896. //
  897. // E.g., for the WAW dependence: A[i] = a; // (1)
  898. // A[i] = b; // (2)
  899. // A[i + 1] = c; // (3)
  900. //
  901. // We will first create a store group with (3) and (2). (1) can't be added to
  902. // this group because it and (2) are dependent. However, (1) can be grouped
  903. // with other accesses that may precede it in program order. Note that a
  904. // bottom-up order does not imply that WAW dependences should not be checked.
  905. void InterleavedAccessInfo::analyzeInterleaving(
  906. bool EnablePredicatedInterleavedMemAccesses) {
  907. LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
  908. const ValueToValueMap &Strides = LAI->getSymbolicStrides();
  909. // Holds all accesses with a constant stride.
  910. MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
  911. collectConstStrideAccesses(AccessStrideInfo, Strides);
  912. if (AccessStrideInfo.empty())
  913. return;
  914. // Collect the dependences in the loop.
  915. collectDependences();
  916. // Holds all interleaved store groups temporarily.
  917. SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
  918. // Holds all interleaved load groups temporarily.
  919. SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
  920. // Search in bottom-up program order for pairs of accesses (A and B) that can
  921. // form interleaved load or store groups. In the algorithm below, access A
  922. // precedes access B in program order. We initialize a group for B in the
  923. // outer loop of the algorithm, and then in the inner loop, we attempt to
  924. // insert each A into B's group if:
  925. //
  926. // 1. A and B have the same stride,
  927. // 2. A and B have the same memory object size, and
  928. // 3. A belongs in B's group according to its distance from B.
  929. //
  930. // Special care is taken to ensure group formation will not break any
  931. // dependences.
  932. for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
  933. BI != E; ++BI) {
  934. Instruction *B = BI->first;
  935. StrideDescriptor DesB = BI->second;
  936. // Initialize a group for B if it has an allowable stride. Even if we don't
  937. // create a group for B, we continue with the bottom-up algorithm to ensure
  938. // we don't break any of B's dependences.
  939. InterleaveGroup<Instruction> *Group = nullptr;
  940. if (isStrided(DesB.Stride) &&
  941. (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
  942. Group = getInterleaveGroup(B);
  943. if (!Group) {
  944. LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
  945. << '\n');
  946. Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
  947. }
  948. if (B->mayWriteToMemory())
  949. StoreGroups.insert(Group);
  950. else
  951. LoadGroups.insert(Group);
  952. }
  953. for (auto AI = std::next(BI); AI != E; ++AI) {
  954. Instruction *A = AI->first;
  955. StrideDescriptor DesA = AI->second;
  956. // Our code motion strategy implies that we can't have dependences
  957. // between accesses in an interleaved group and other accesses located
  958. // between the first and last member of the group. Note that this also
  959. // means that a group can't have more than one member at a given offset.
  960. // The accesses in a group can have dependences with other accesses, but
  961. // we must ensure we don't extend the boundaries of the group such that
  962. // we encompass those dependent accesses.
  963. //
  964. // For example, assume we have the sequence of accesses shown below in a
  965. // stride-2 loop:
  966. //
  967. // (1, 2) is a group | A[i] = a; // (1)
  968. // | A[i-1] = b; // (2) |
  969. // A[i-3] = c; // (3)
  970. // A[i] = d; // (4) | (2, 4) is not a group
  971. //
  972. // Because accesses (2) and (3) are dependent, we can group (2) with (1)
  973. // but not with (4). If we did, the dependent access (3) would be within
  974. // the boundaries of the (2, 4) group.
  975. if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
  976. // If a dependence exists and A is already in a group, we know that A
  977. // must be a store since A precedes B and WAR dependences are allowed.
  978. // Thus, A would be sunk below B. We release A's group to prevent this
  979. // illegal code motion. A will then be free to form another group with
  980. // instructions that precede it.
  981. if (isInterleaved(A)) {
  982. InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
  983. LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
  984. "dependence between " << *A << " and "<< *B << '\n');
  985. StoreGroups.remove(StoreGroup);
  986. releaseGroup(StoreGroup);
  987. }
  988. // If a dependence exists and A is not already in a group (or it was
  989. // and we just released it), B might be hoisted above A (if B is a
  990. // load) or another store might be sunk below A (if B is a store). In
  991. // either case, we can't add additional instructions to B's group. B
  992. // will only form a group with instructions that it precedes.
  993. break;
  994. }
  995. // At this point, we've checked for illegal code motion. If either A or B
  996. // isn't strided, there's nothing left to do.
  997. if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
  998. continue;
  999. // Ignore A if it's already in a group or isn't the same kind of memory
  1000. // operation as B.
  1001. // Note that mayReadFromMemory() isn't mutually exclusive to
  1002. // mayWriteToMemory in the case of atomic loads. We shouldn't see those
  1003. // here, canVectorizeMemory() should have returned false - except for the
  1004. // case we asked for optimization remarks.
  1005. if (isInterleaved(A) ||
  1006. (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
  1007. (A->mayWriteToMemory() != B->mayWriteToMemory()))
  1008. continue;
  1009. // Check rules 1 and 2. Ignore A if its stride or size is different from
  1010. // that of B.
  1011. if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
  1012. continue;
  1013. // Ignore A if the memory object of A and B don't belong to the same
  1014. // address space
  1015. if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
  1016. continue;
  1017. // Calculate the distance from A to B.
  1018. const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
  1019. PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
  1020. if (!DistToB)
  1021. continue;
  1022. int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
  1023. // Check rule 3. Ignore A if its distance to B is not a multiple of the
  1024. // size.
  1025. if (DistanceToB % static_cast<int64_t>(DesB.Size))
  1026. continue;
  1027. // All members of a predicated interleave-group must have the same predicate,
  1028. // and currently must reside in the same BB.
  1029. BasicBlock *BlockA = A->getParent();
  1030. BasicBlock *BlockB = B->getParent();
  1031. if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
  1032. (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
  1033. continue;
  1034. // The index of A is the index of B plus A's distance to B in multiples
  1035. // of the size.
  1036. int IndexA =
  1037. Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
  1038. // Try to insert A into B's group.
  1039. if (Group->insertMember(A, IndexA, DesA.Alignment)) {
  1040. LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
  1041. << " into the interleave group with" << *B
  1042. << '\n');
  1043. InterleaveGroupMap[A] = Group;
  1044. // Set the first load in program order as the insert position.
  1045. if (A->mayReadFromMemory())
  1046. Group->setInsertPos(A);
  1047. }
  1048. } // Iteration over A accesses.
  1049. } // Iteration over B accesses.
  1050. auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
  1051. int Index,
  1052. std::string FirstOrLast) -> bool {
  1053. Instruction *Member = Group->getMember(Index);
  1054. assert(Member && "Group member does not exist");
  1055. Value *MemberPtr = getLoadStorePointerOperand(Member);
  1056. Type *AccessTy = getLoadStoreType(Member);
  1057. if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
  1058. /*Assume=*/false, /*ShouldCheckWrap=*/true))
  1059. return false;
  1060. LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
  1061. << FirstOrLast
  1062. << " group member potentially pointer-wrapping.\n");
  1063. releaseGroup(Group);
  1064. return true;
  1065. };
  1066. // Remove interleaved groups with gaps whose memory
  1067. // accesses may wrap around. We have to revisit the getPtrStride analysis,
  1068. // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
  1069. // not check wrapping (see documentation there).
  1070. // FORNOW we use Assume=false;
  1071. // TODO: Change to Assume=true but making sure we don't exceed the threshold
  1072. // of runtime SCEV assumptions checks (thereby potentially failing to
  1073. // vectorize altogether).
  1074. // Additional optional optimizations:
  1075. // TODO: If we are peeling the loop and we know that the first pointer doesn't
  1076. // wrap then we can deduce that all pointers in the group don't wrap.
  1077. // This means that we can forcefully peel the loop in order to only have to
  1078. // check the first pointer for no-wrap. When we'll change to use Assume=true
  1079. // we'll only need at most one runtime check per interleaved group.
  1080. for (auto *Group : LoadGroups) {
  1081. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  1082. // load would wrap around the address space we would do a memory access at
  1083. // nullptr even without the transformation.
  1084. if (Group->getNumMembers() == Group->getFactor())
  1085. continue;
  1086. // Case 2: If first and last members of the group don't wrap this implies
  1087. // that all the pointers in the group don't wrap.
  1088. // So we check only group member 0 (which is always guaranteed to exist),
  1089. // and group member Factor - 1; If the latter doesn't exist we rely on
  1090. // peeling (if it is a non-reversed accsess -- see Case 3).
  1091. if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
  1092. continue;
  1093. if (Group->getMember(Group->getFactor() - 1))
  1094. InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
  1095. std::string("last"));
  1096. else {
  1097. // Case 3: A non-reversed interleaved load group with gaps: We need
  1098. // to execute at least one scalar epilogue iteration. This will ensure
  1099. // we don't speculatively access memory out-of-bounds. We only need
  1100. // to look for a member at index factor - 1, since every group must have
  1101. // a member at index zero.
  1102. if (Group->isReverse()) {
  1103. LLVM_DEBUG(
  1104. dbgs() << "LV: Invalidate candidate interleaved group due to "
  1105. "a reverse access with gaps.\n");
  1106. releaseGroup(Group);
  1107. continue;
  1108. }
  1109. LLVM_DEBUG(
  1110. dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
  1111. RequiresScalarEpilogue = true;
  1112. }
  1113. }
  1114. for (auto *Group : StoreGroups) {
  1115. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  1116. // store would wrap around the address space we would do a memory access at
  1117. // nullptr even without the transformation.
  1118. if (Group->getNumMembers() == Group->getFactor())
  1119. continue;
  1120. // Interleave-store-group with gaps is implemented using masked wide store.
  1121. // Remove interleaved store groups with gaps if
  1122. // masked-interleaved-accesses are not enabled by the target.
  1123. if (!EnablePredicatedInterleavedMemAccesses) {
  1124. LLVM_DEBUG(
  1125. dbgs() << "LV: Invalidate candidate interleaved store group due "
  1126. "to gaps.\n");
  1127. releaseGroup(Group);
  1128. continue;
  1129. }
  1130. // Case 2: If first and last members of the group don't wrap this implies
  1131. // that all the pointers in the group don't wrap.
  1132. // So we check only group member 0 (which is always guaranteed to exist),
  1133. // and the last group member. Case 3 (scalar epilog) is not relevant for
  1134. // stores with gaps, which are implemented with masked-store (rather than
  1135. // speculative access, as in loads).
  1136. if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
  1137. continue;
  1138. for (int Index = Group->getFactor() - 1; Index > 0; Index--)
  1139. if (Group->getMember(Index)) {
  1140. InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
  1141. break;
  1142. }
  1143. }
  1144. }
  1145. void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
  1146. // If no group had triggered the requirement to create an epilogue loop,
  1147. // there is nothing to do.
  1148. if (!requiresScalarEpilogue())
  1149. return;
  1150. bool ReleasedGroup = false;
  1151. // Release groups requiring scalar epilogues. Note that this also removes them
  1152. // from InterleaveGroups.
  1153. for (auto *Group : make_early_inc_range(InterleaveGroups)) {
  1154. if (!Group->requiresScalarEpilogue())
  1155. continue;
  1156. LLVM_DEBUG(
  1157. dbgs()
  1158. << "LV: Invalidate candidate interleaved group due to gaps that "
  1159. "require a scalar epilogue (not allowed under optsize) and cannot "
  1160. "be masked (not enabled). \n");
  1161. releaseGroup(Group);
  1162. ReleasedGroup = true;
  1163. }
  1164. assert(ReleasedGroup && "At least one group must be invalidated, as a "
  1165. "scalar epilogue was required");
  1166. (void)ReleasedGroup;
  1167. RequiresScalarEpilogue = false;
  1168. }
  1169. template <typename InstT>
  1170. void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
  1171. llvm_unreachable("addMetadata can only be used for Instruction");
  1172. }
  1173. namespace llvm {
  1174. template <>
  1175. void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
  1176. SmallVector<Value *, 4> VL;
  1177. std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
  1178. [](std::pair<int, Instruction *> p) { return p.second; });
  1179. propagateMetadata(NewInst, VL);
  1180. }
  1181. }
  1182. std::string VFABI::mangleTLIVectorName(StringRef VectorName,
  1183. StringRef ScalarName, unsigned numArgs,
  1184. ElementCount VF) {
  1185. SmallString<256> Buffer;
  1186. llvm::raw_svector_ostream Out(Buffer);
  1187. Out << "_ZGV" << VFABI::_LLVM_ << "N";
  1188. if (VF.isScalable())
  1189. Out << 'x';
  1190. else
  1191. Out << VF.getFixedValue();
  1192. for (unsigned I = 0; I < numArgs; ++I)
  1193. Out << "v";
  1194. Out << "_" << ScalarName << "(" << VectorName << ")";
  1195. return std::string(Out.str());
  1196. }
  1197. void VFABI::getVectorVariantNames(
  1198. const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
  1199. const StringRef S = CI.getFnAttr(VFABI::MappingsAttrName).getValueAsString();
  1200. if (S.empty())
  1201. return;
  1202. SmallVector<StringRef, 8> ListAttr;
  1203. S.split(ListAttr, ",");
  1204. for (auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
  1205. #ifndef NDEBUG
  1206. LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
  1207. Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
  1208. assert(Info.hasValue() && "Invalid name for a VFABI variant.");
  1209. assert(CI.getModule()->getFunction(Info.getValue().VectorName) &&
  1210. "Vector function is missing.");
  1211. #endif
  1212. VariantMappings.push_back(std::string(S));
  1213. }
  1214. }
  1215. bool VFShape::hasValidParameterList() const {
  1216. for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
  1217. ++Pos) {
  1218. assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
  1219. switch (Parameters[Pos].ParamKind) {
  1220. default: // Nothing to check.
  1221. break;
  1222. case VFParamKind::OMP_Linear:
  1223. case VFParamKind::OMP_LinearRef:
  1224. case VFParamKind::OMP_LinearVal:
  1225. case VFParamKind::OMP_LinearUVal:
  1226. // Compile time linear steps must be non-zero.
  1227. if (Parameters[Pos].LinearStepOrPos == 0)
  1228. return false;
  1229. break;
  1230. case VFParamKind::OMP_LinearPos:
  1231. case VFParamKind::OMP_LinearRefPos:
  1232. case VFParamKind::OMP_LinearValPos:
  1233. case VFParamKind::OMP_LinearUValPos:
  1234. // The runtime linear step must be referring to some other
  1235. // parameters in the signature.
  1236. if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
  1237. return false;
  1238. // The linear step parameter must be marked as uniform.
  1239. if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
  1240. VFParamKind::OMP_Uniform)
  1241. return false;
  1242. // The linear step parameter can't point at itself.
  1243. if (Parameters[Pos].LinearStepOrPos == int(Pos))
  1244. return false;
  1245. break;
  1246. case VFParamKind::GlobalPredicate:
  1247. // The global predicate must be the unique. Can be placed anywhere in the
  1248. // signature.
  1249. for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
  1250. if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
  1251. return false;
  1252. break;
  1253. }
  1254. }
  1255. return true;
  1256. }