IVDescriptors.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
  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 "describes" induction and recurrence variables.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/IVDescriptors.h"
  13. #include "llvm/Analysis/DemandedBits.h"
  14. #include "llvm/Analysis/LoopInfo.h"
  15. #include "llvm/Analysis/ScalarEvolution.h"
  16. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  17. #include "llvm/Analysis/ValueTracking.h"
  18. #include "llvm/IR/Dominators.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IR/PatternMatch.h"
  22. #include "llvm/IR/ValueHandle.h"
  23. #include "llvm/Support/Debug.h"
  24. #include "llvm/Support/KnownBits.h"
  25. #include <set>
  26. using namespace llvm;
  27. using namespace llvm::PatternMatch;
  28. #define DEBUG_TYPE "iv-descriptors"
  29. bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
  30. SmallPtrSetImpl<Instruction *> &Set) {
  31. for (const Use &Use : I->operands())
  32. if (!Set.count(dyn_cast<Instruction>(Use)))
  33. return false;
  34. return true;
  35. }
  36. bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind) {
  37. switch (Kind) {
  38. default:
  39. break;
  40. case RecurKind::Add:
  41. case RecurKind::Mul:
  42. case RecurKind::Or:
  43. case RecurKind::And:
  44. case RecurKind::Xor:
  45. case RecurKind::SMax:
  46. case RecurKind::SMin:
  47. case RecurKind::UMax:
  48. case RecurKind::UMin:
  49. case RecurKind::SelectICmp:
  50. case RecurKind::SelectFCmp:
  51. return true;
  52. }
  53. return false;
  54. }
  55. bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind) {
  56. return (Kind != RecurKind::None) && !isIntegerRecurrenceKind(Kind);
  57. }
  58. /// Determines if Phi may have been type-promoted. If Phi has a single user
  59. /// that ANDs the Phi with a type mask, return the user. RT is updated to
  60. /// account for the narrower bit width represented by the mask, and the AND
  61. /// instruction is added to CI.
  62. static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
  63. SmallPtrSetImpl<Instruction *> &Visited,
  64. SmallPtrSetImpl<Instruction *> &CI) {
  65. if (!Phi->hasOneUse())
  66. return Phi;
  67. const APInt *M = nullptr;
  68. Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
  69. // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
  70. // with a new integer type of the corresponding bit width.
  71. if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
  72. int32_t Bits = (*M + 1).exactLogBase2();
  73. if (Bits > 0) {
  74. RT = IntegerType::get(Phi->getContext(), Bits);
  75. Visited.insert(Phi);
  76. CI.insert(J);
  77. return J;
  78. }
  79. }
  80. return Phi;
  81. }
  82. /// Compute the minimal bit width needed to represent a reduction whose exit
  83. /// instruction is given by Exit.
  84. static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
  85. DemandedBits *DB,
  86. AssumptionCache *AC,
  87. DominatorTree *DT) {
  88. bool IsSigned = false;
  89. const DataLayout &DL = Exit->getModule()->getDataLayout();
  90. uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
  91. if (DB) {
  92. // Use the demanded bits analysis to determine the bits that are live out
  93. // of the exit instruction, rounding up to the nearest power of two. If the
  94. // use of demanded bits results in a smaller bit width, we know the value
  95. // must be positive (i.e., IsSigned = false), because if this were not the
  96. // case, the sign bit would have been demanded.
  97. auto Mask = DB->getDemandedBits(Exit);
  98. MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
  99. }
  100. if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
  101. // If demanded bits wasn't able to limit the bit width, we can try to use
  102. // value tracking instead. This can be the case, for example, if the value
  103. // may be negative.
  104. auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
  105. auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
  106. MaxBitWidth = NumTypeBits - NumSignBits;
  107. KnownBits Bits = computeKnownBits(Exit, DL);
  108. if (!Bits.isNonNegative()) {
  109. // If the value is not known to be non-negative, we set IsSigned to true,
  110. // meaning that we will use sext instructions instead of zext
  111. // instructions to restore the original type.
  112. IsSigned = true;
  113. // Make sure at at least one sign bit is included in the result, so it
  114. // will get properly sign-extended.
  115. ++MaxBitWidth;
  116. }
  117. }
  118. if (!isPowerOf2_64(MaxBitWidth))
  119. MaxBitWidth = NextPowerOf2(MaxBitWidth);
  120. return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
  121. IsSigned);
  122. }
  123. /// Collect cast instructions that can be ignored in the vectorizer's cost
  124. /// model, given a reduction exit value and the minimal type in which the
  125. // reduction can be represented. Also search casts to the recurrence type
  126. // to find the minimum width used by the recurrence.
  127. static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
  128. Type *RecurrenceType,
  129. SmallPtrSetImpl<Instruction *> &Casts,
  130. unsigned &MinWidthCastToRecurTy) {
  131. SmallVector<Instruction *, 8> Worklist;
  132. SmallPtrSet<Instruction *, 8> Visited;
  133. Worklist.push_back(Exit);
  134. MinWidthCastToRecurTy = -1U;
  135. while (!Worklist.empty()) {
  136. Instruction *Val = Worklist.pop_back_val();
  137. Visited.insert(Val);
  138. if (auto *Cast = dyn_cast<CastInst>(Val)) {
  139. if (Cast->getSrcTy() == RecurrenceType) {
  140. // If the source type of a cast instruction is equal to the recurrence
  141. // type, it will be eliminated, and should be ignored in the vectorizer
  142. // cost model.
  143. Casts.insert(Cast);
  144. continue;
  145. }
  146. if (Cast->getDestTy() == RecurrenceType) {
  147. // The minimum width used by the recurrence is found by checking for
  148. // casts on its operands. The minimum width is used by the vectorizer
  149. // when finding the widest type for in-loop reductions without any
  150. // loads/stores.
  151. MinWidthCastToRecurTy = std::min<unsigned>(
  152. MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits());
  153. continue;
  154. }
  155. }
  156. // Add all operands to the work list if they are loop-varying values that
  157. // we haven't yet visited.
  158. for (Value *O : cast<User>(Val)->operands())
  159. if (auto *I = dyn_cast<Instruction>(O))
  160. if (TheLoop->contains(I) && !Visited.count(I))
  161. Worklist.push_back(I);
  162. }
  163. }
  164. // Check if a given Phi node can be recognized as an ordered reduction for
  165. // vectorizing floating point operations without unsafe math.
  166. static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
  167. Instruction *Exit, PHINode *Phi) {
  168. // Currently only FAdd and FMulAdd are supported.
  169. if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
  170. return false;
  171. if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
  172. return false;
  173. if (Kind == RecurKind::FMulAdd &&
  174. !RecurrenceDescriptor::isFMulAddIntrinsic(Exit))
  175. return false;
  176. // Ensure the exit instruction has only one user other than the reduction PHI
  177. if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
  178. return false;
  179. // The only pattern accepted is the one in which the reduction PHI
  180. // is used as one of the operands of the exit instruction
  181. auto *Op0 = Exit->getOperand(0);
  182. auto *Op1 = Exit->getOperand(1);
  183. if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
  184. return false;
  185. if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
  186. return false;
  187. LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
  188. << ", ExitInst: " << *Exit << "\n");
  189. return true;
  190. }
  191. bool RecurrenceDescriptor::AddReductionVar(
  192. PHINode *Phi, RecurKind Kind, Loop *TheLoop, FastMathFlags FuncFMF,
  193. RecurrenceDescriptor &RedDes, DemandedBits *DB, AssumptionCache *AC,
  194. DominatorTree *DT, ScalarEvolution *SE) {
  195. if (Phi->getNumIncomingValues() != 2)
  196. return false;
  197. // Reduction variables are only found in the loop header block.
  198. if (Phi->getParent() != TheLoop->getHeader())
  199. return false;
  200. // Obtain the reduction start value from the value that comes from the loop
  201. // preheader.
  202. Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
  203. // ExitInstruction is the single value which is used outside the loop.
  204. // We only allow for a single reduction value to be used outside the loop.
  205. // This includes users of the reduction, variables (which form a cycle
  206. // which ends in the phi node).
  207. Instruction *ExitInstruction = nullptr;
  208. // Variable to keep last visited store instruction. By the end of the
  209. // algorithm this variable will be either empty or having intermediate
  210. // reduction value stored in invariant address.
  211. StoreInst *IntermediateStore = nullptr;
  212. // Indicates that we found a reduction operation in our scan.
  213. bool FoundReduxOp = false;
  214. // We start with the PHI node and scan for all of the users of this
  215. // instruction. All users must be instructions that can be used as reduction
  216. // variables (such as ADD). We must have a single out-of-block user. The cycle
  217. // must include the original PHI.
  218. bool FoundStartPHI = false;
  219. // To recognize min/max patterns formed by a icmp select sequence, we store
  220. // the number of instruction we saw from the recognized min/max pattern,
  221. // to make sure we only see exactly the two instructions.
  222. unsigned NumCmpSelectPatternInst = 0;
  223. InstDesc ReduxDesc(false, nullptr);
  224. // Data used for determining if the recurrence has been type-promoted.
  225. Type *RecurrenceType = Phi->getType();
  226. SmallPtrSet<Instruction *, 4> CastInsts;
  227. unsigned MinWidthCastToRecurrenceType;
  228. Instruction *Start = Phi;
  229. bool IsSigned = false;
  230. SmallPtrSet<Instruction *, 8> VisitedInsts;
  231. SmallVector<Instruction *, 8> Worklist;
  232. // Return early if the recurrence kind does not match the type of Phi. If the
  233. // recurrence kind is arithmetic, we attempt to look through AND operations
  234. // resulting from the type promotion performed by InstCombine. Vector
  235. // operations are not limited to the legal integer widths, so we may be able
  236. // to evaluate the reduction in the narrower width.
  237. if (RecurrenceType->isFloatingPointTy()) {
  238. if (!isFloatingPointRecurrenceKind(Kind))
  239. return false;
  240. } else if (RecurrenceType->isIntegerTy()) {
  241. if (!isIntegerRecurrenceKind(Kind))
  242. return false;
  243. if (!isMinMaxRecurrenceKind(Kind))
  244. Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
  245. } else {
  246. // Pointer min/max may exist, but it is not supported as a reduction op.
  247. return false;
  248. }
  249. Worklist.push_back(Start);
  250. VisitedInsts.insert(Start);
  251. // Start with all flags set because we will intersect this with the reduction
  252. // flags from all the reduction operations.
  253. FastMathFlags FMF = FastMathFlags::getFast();
  254. // The first instruction in the use-def chain of the Phi node that requires
  255. // exact floating point operations.
  256. Instruction *ExactFPMathInst = nullptr;
  257. // A value in the reduction can be used:
  258. // - By the reduction:
  259. // - Reduction operation:
  260. // - One use of reduction value (safe).
  261. // - Multiple use of reduction value (not safe).
  262. // - PHI:
  263. // - All uses of the PHI must be the reduction (safe).
  264. // - Otherwise, not safe.
  265. // - By instructions outside of the loop (safe).
  266. // * One value may have several outside users, but all outside
  267. // uses must be of the same value.
  268. // - By store instructions with a loop invariant address (safe with
  269. // the following restrictions):
  270. // * If there are several stores, all must have the same address.
  271. // * Final value should be stored in that loop invariant address.
  272. // - By an instruction that is not part of the reduction (not safe).
  273. // This is either:
  274. // * An instruction type other than PHI or the reduction operation.
  275. // * A PHI in the header other than the initial PHI.
  276. while (!Worklist.empty()) {
  277. Instruction *Cur = Worklist.pop_back_val();
  278. // Store instructions are allowed iff it is the store of the reduction
  279. // value to the same loop invariant memory location.
  280. if (auto *SI = dyn_cast<StoreInst>(Cur)) {
  281. if (!SE) {
  282. LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
  283. << "Scalar Evolution Analysis\n");
  284. return false;
  285. }
  286. const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
  287. // Check it is the same address as previous stores
  288. if (IntermediateStore) {
  289. const SCEV *OtherScev =
  290. SE->getSCEV(IntermediateStore->getPointerOperand());
  291. if (OtherScev != PtrScev) {
  292. LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
  293. << "inside the loop: " << *SI->getPointerOperand()
  294. << " and "
  295. << *IntermediateStore->getPointerOperand() << '\n');
  296. return false;
  297. }
  298. }
  299. // Check the pointer is loop invariant
  300. if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
  301. LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
  302. << "inside the loop: " << *SI->getPointerOperand()
  303. << '\n');
  304. return false;
  305. }
  306. // IntermediateStore is always the last store in the loop.
  307. IntermediateStore = SI;
  308. continue;
  309. }
  310. // No Users.
  311. // If the instruction has no users then this is a broken chain and can't be
  312. // a reduction variable.
  313. if (Cur->use_empty())
  314. return false;
  315. bool IsAPhi = isa<PHINode>(Cur);
  316. // A header PHI use other than the original PHI.
  317. if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
  318. return false;
  319. // Reductions of instructions such as Div, and Sub is only possible if the
  320. // LHS is the reduction variable.
  321. if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
  322. !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
  323. !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
  324. return false;
  325. // Any reduction instruction must be of one of the allowed kinds. We ignore
  326. // the starting value (the Phi or an AND instruction if the Phi has been
  327. // type-promoted).
  328. if (Cur != Start) {
  329. ReduxDesc =
  330. isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, FuncFMF);
  331. ExactFPMathInst = ExactFPMathInst == nullptr
  332. ? ReduxDesc.getExactFPMathInst()
  333. : ExactFPMathInst;
  334. if (!ReduxDesc.isRecurrence())
  335. return false;
  336. // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
  337. if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi) {
  338. FastMathFlags CurFMF = ReduxDesc.getPatternInst()->getFastMathFlags();
  339. if (auto *Sel = dyn_cast<SelectInst>(ReduxDesc.getPatternInst())) {
  340. // Accept FMF on either fcmp or select of a min/max idiom.
  341. // TODO: This is a hack to work-around the fact that FMF may not be
  342. // assigned/propagated correctly. If that problem is fixed or we
  343. // standardize on fmin/fmax via intrinsics, this can be removed.
  344. if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
  345. CurFMF |= FCmp->getFastMathFlags();
  346. }
  347. FMF &= CurFMF;
  348. }
  349. // Update this reduction kind if we matched a new instruction.
  350. // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
  351. // state accurate while processing the worklist?
  352. if (ReduxDesc.getRecKind() != RecurKind::None)
  353. Kind = ReduxDesc.getRecKind();
  354. }
  355. bool IsASelect = isa<SelectInst>(Cur);
  356. // A conditional reduction operation must only have 2 or less uses in
  357. // VisitedInsts.
  358. if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
  359. hasMultipleUsesOf(Cur, VisitedInsts, 2))
  360. return false;
  361. // A reduction operation must only have one use of the reduction value.
  362. if (!IsAPhi && !IsASelect && !isMinMaxRecurrenceKind(Kind) &&
  363. !isSelectCmpRecurrenceKind(Kind) &&
  364. hasMultipleUsesOf(Cur, VisitedInsts, 1))
  365. return false;
  366. // All inputs to a PHI node must be a reduction value.
  367. if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
  368. return false;
  369. if ((isIntMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectICmp) &&
  370. (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
  371. ++NumCmpSelectPatternInst;
  372. if ((isFPMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectFCmp) &&
  373. (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
  374. ++NumCmpSelectPatternInst;
  375. // Check whether we found a reduction operator.
  376. FoundReduxOp |= !IsAPhi && Cur != Start;
  377. // Process users of current instruction. Push non-PHI nodes after PHI nodes
  378. // onto the stack. This way we are going to have seen all inputs to PHI
  379. // nodes once we get to them.
  380. SmallVector<Instruction *, 8> NonPHIs;
  381. SmallVector<Instruction *, 8> PHIs;
  382. for (User *U : Cur->users()) {
  383. Instruction *UI = cast<Instruction>(U);
  384. // If the user is a call to llvm.fmuladd then the instruction can only be
  385. // the final operand.
  386. if (isFMulAddIntrinsic(UI))
  387. if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
  388. return false;
  389. // Check if we found the exit user.
  390. BasicBlock *Parent = UI->getParent();
  391. if (!TheLoop->contains(Parent)) {
  392. // If we already know this instruction is used externally, move on to
  393. // the next user.
  394. if (ExitInstruction == Cur)
  395. continue;
  396. // Exit if you find multiple values used outside or if the header phi
  397. // node is being used. In this case the user uses the value of the
  398. // previous iteration, in which case we would loose "VF-1" iterations of
  399. // the reduction operation if we vectorize.
  400. if (ExitInstruction != nullptr || Cur == Phi)
  401. return false;
  402. // The instruction used by an outside user must be the last instruction
  403. // before we feed back to the reduction phi. Otherwise, we loose VF-1
  404. // operations on the value.
  405. if (!is_contained(Phi->operands(), Cur))
  406. return false;
  407. ExitInstruction = Cur;
  408. continue;
  409. }
  410. // Process instructions only once (termination). Each reduction cycle
  411. // value must only be used once, except by phi nodes and min/max
  412. // reductions which are represented as a cmp followed by a select.
  413. InstDesc IgnoredVal(false, nullptr);
  414. if (VisitedInsts.insert(UI).second) {
  415. if (isa<PHINode>(UI)) {
  416. PHIs.push_back(UI);
  417. } else {
  418. StoreInst *SI = dyn_cast<StoreInst>(UI);
  419. if (SI && SI->getPointerOperand() == Cur) {
  420. // Reduction variable chain can only be stored somewhere but it
  421. // can't be used as an address.
  422. return false;
  423. }
  424. NonPHIs.push_back(UI);
  425. }
  426. } else if (!isa<PHINode>(UI) &&
  427. ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
  428. !isa<SelectInst>(UI)) ||
  429. (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
  430. !isSelectCmpPattern(TheLoop, Phi, UI, IgnoredVal)
  431. .isRecurrence() &&
  432. !isMinMaxPattern(UI, Kind, IgnoredVal).isRecurrence())))
  433. return false;
  434. // Remember that we completed the cycle.
  435. if (UI == Phi)
  436. FoundStartPHI = true;
  437. }
  438. Worklist.append(PHIs.begin(), PHIs.end());
  439. Worklist.append(NonPHIs.begin(), NonPHIs.end());
  440. }
  441. // This means we have seen one but not the other instruction of the
  442. // pattern or more than just a select and cmp. Zero implies that we saw a
  443. // llvm.min/max intrinsic, which is always OK.
  444. if (isMinMaxRecurrenceKind(Kind) && NumCmpSelectPatternInst != 2 &&
  445. NumCmpSelectPatternInst != 0)
  446. return false;
  447. if (isSelectCmpRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1)
  448. return false;
  449. if (IntermediateStore) {
  450. // Check that stored value goes to the phi node again. This way we make sure
  451. // that the value stored in IntermediateStore is indeed the final reduction
  452. // value.
  453. if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
  454. LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
  455. << *IntermediateStore << '\n');
  456. return false;
  457. }
  458. // If there is an exit instruction it's value should be stored in
  459. // IntermediateStore
  460. if (ExitInstruction &&
  461. IntermediateStore->getValueOperand() != ExitInstruction) {
  462. LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
  463. "store last calculated value of the reduction: "
  464. << *IntermediateStore << '\n');
  465. return false;
  466. }
  467. // If all uses are inside the loop (intermediate stores), then the
  468. // reduction value after the loop will be the one used in the last store.
  469. if (!ExitInstruction)
  470. ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
  471. }
  472. if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
  473. return false;
  474. const bool IsOrdered =
  475. checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
  476. if (Start != Phi) {
  477. // If the starting value is not the same as the phi node, we speculatively
  478. // looked through an 'and' instruction when evaluating a potential
  479. // arithmetic reduction to determine if it may have been type-promoted.
  480. //
  481. // We now compute the minimal bit width that is required to represent the
  482. // reduction. If this is the same width that was indicated by the 'and', we
  483. // can represent the reduction in the smaller type. The 'and' instruction
  484. // will be eliminated since it will essentially be a cast instruction that
  485. // can be ignore in the cost model. If we compute a different type than we
  486. // did when evaluating the 'and', the 'and' will not be eliminated, and we
  487. // will end up with different kinds of operations in the recurrence
  488. // expression (e.g., IntegerAND, IntegerADD). We give up if this is
  489. // the case.
  490. //
  491. // The vectorizer relies on InstCombine to perform the actual
  492. // type-shrinking. It does this by inserting instructions to truncate the
  493. // exit value of the reduction to the width indicated by RecurrenceType and
  494. // then extend this value back to the original width. If IsSigned is false,
  495. // a 'zext' instruction will be generated; otherwise, a 'sext' will be
  496. // used.
  497. //
  498. // TODO: We should not rely on InstCombine to rewrite the reduction in the
  499. // smaller type. We should just generate a correctly typed expression
  500. // to begin with.
  501. Type *ComputedType;
  502. std::tie(ComputedType, IsSigned) =
  503. computeRecurrenceType(ExitInstruction, DB, AC, DT);
  504. if (ComputedType != RecurrenceType)
  505. return false;
  506. }
  507. // Collect cast instructions and the minimum width used by the recurrence.
  508. // If the starting value is not the same as the phi node and the computed
  509. // recurrence type is equal to the recurrence type, the recurrence expression
  510. // will be represented in a narrower or wider type. If there are any cast
  511. // instructions that will be unnecessary, collect them in CastsFromRecurTy.
  512. // Note that the 'and' instruction was already included in this list.
  513. //
  514. // TODO: A better way to represent this may be to tag in some way all the
  515. // instructions that are a part of the reduction. The vectorizer cost
  516. // model could then apply the recurrence type to these instructions,
  517. // without needing a white list of instructions to ignore.
  518. // This may also be useful for the inloop reductions, if it can be
  519. // kept simple enough.
  520. collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
  521. MinWidthCastToRecurrenceType);
  522. // We found a reduction var if we have reached the original phi node and we
  523. // only have a single instruction with out-of-loop users.
  524. // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
  525. // is saved as part of the RecurrenceDescriptor.
  526. // Save the description of this reduction variable.
  527. RecurrenceDescriptor RD(RdxStart, ExitInstruction, IntermediateStore, Kind,
  528. FMF, ExactFPMathInst, RecurrenceType, IsSigned,
  529. IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
  530. RedDes = RD;
  531. return true;
  532. }
  533. // We are looking for loops that do something like this:
  534. // int r = 0;
  535. // for (int i = 0; i < n; i++) {
  536. // if (src[i] > 3)
  537. // r = 3;
  538. // }
  539. // where the reduction value (r) only has two states, in this example 0 or 3.
  540. // The generated LLVM IR for this type of loop will be like this:
  541. // for.body:
  542. // %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
  543. // ...
  544. // %cmp = icmp sgt i32 %5, 3
  545. // %spec.select = select i1 %cmp, i32 3, i32 %r
  546. // ...
  547. // In general we can support vectorization of loops where 'r' flips between
  548. // any two non-constants, provided they are loop invariant. The only thing
  549. // we actually care about at the end of the loop is whether or not any lane
  550. // in the selected vector is different from the start value. The final
  551. // across-vector reduction after the loop simply involves choosing the start
  552. // value if nothing changed (0 in the example above) or the other selected
  553. // value (3 in the example above).
  554. RecurrenceDescriptor::InstDesc
  555. RecurrenceDescriptor::isSelectCmpPattern(Loop *Loop, PHINode *OrigPhi,
  556. Instruction *I, InstDesc &Prev) {
  557. // We must handle the select(cmp(),x,y) as a single instruction. Advance to
  558. // the select.
  559. CmpInst::Predicate Pred;
  560. if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
  561. if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
  562. return InstDesc(Select, Prev.getRecKind());
  563. }
  564. // Only match select with single use cmp condition.
  565. if (!match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
  566. m_Value())))
  567. return InstDesc(false, I);
  568. SelectInst *SI = cast<SelectInst>(I);
  569. Value *NonPhi = nullptr;
  570. if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
  571. NonPhi = SI->getFalseValue();
  572. else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
  573. NonPhi = SI->getTrueValue();
  574. else
  575. return InstDesc(false, I);
  576. // We are looking for selects of the form:
  577. // select(cmp(), phi, loop_invariant) or
  578. // select(cmp(), loop_invariant, phi)
  579. if (!Loop->isLoopInvariant(NonPhi))
  580. return InstDesc(false, I);
  581. return InstDesc(I, isa<ICmpInst>(I->getOperand(0)) ? RecurKind::SelectICmp
  582. : RecurKind::SelectFCmp);
  583. }
  584. RecurrenceDescriptor::InstDesc
  585. RecurrenceDescriptor::isMinMaxPattern(Instruction *I, RecurKind Kind,
  586. const InstDesc &Prev) {
  587. assert((isa<CmpInst>(I) || isa<SelectInst>(I) || isa<CallInst>(I)) &&
  588. "Expected a cmp or select or call instruction");
  589. if (!isMinMaxRecurrenceKind(Kind))
  590. return InstDesc(false, I);
  591. // We must handle the select(cmp()) as a single instruction. Advance to the
  592. // select.
  593. CmpInst::Predicate Pred;
  594. if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
  595. if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
  596. return InstDesc(Select, Prev.getRecKind());
  597. }
  598. // Only match select with single use cmp condition, or a min/max intrinsic.
  599. if (!isa<IntrinsicInst>(I) &&
  600. !match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
  601. m_Value())))
  602. return InstDesc(false, I);
  603. // Look for a min/max pattern.
  604. if (match(I, m_UMin(m_Value(), m_Value())))
  605. return InstDesc(Kind == RecurKind::UMin, I);
  606. if (match(I, m_UMax(m_Value(), m_Value())))
  607. return InstDesc(Kind == RecurKind::UMax, I);
  608. if (match(I, m_SMax(m_Value(), m_Value())))
  609. return InstDesc(Kind == RecurKind::SMax, I);
  610. if (match(I, m_SMin(m_Value(), m_Value())))
  611. return InstDesc(Kind == RecurKind::SMin, I);
  612. if (match(I, m_OrdFMin(m_Value(), m_Value())))
  613. return InstDesc(Kind == RecurKind::FMin, I);
  614. if (match(I, m_OrdFMax(m_Value(), m_Value())))
  615. return InstDesc(Kind == RecurKind::FMax, I);
  616. if (match(I, m_UnordFMin(m_Value(), m_Value())))
  617. return InstDesc(Kind == RecurKind::FMin, I);
  618. if (match(I, m_UnordFMax(m_Value(), m_Value())))
  619. return InstDesc(Kind == RecurKind::FMax, I);
  620. if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
  621. return InstDesc(Kind == RecurKind::FMin, I);
  622. if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
  623. return InstDesc(Kind == RecurKind::FMax, I);
  624. return InstDesc(false, I);
  625. }
  626. /// Returns true if the select instruction has users in the compare-and-add
  627. /// reduction pattern below. The select instruction argument is the last one
  628. /// in the sequence.
  629. ///
  630. /// %sum.1 = phi ...
  631. /// ...
  632. /// %cmp = fcmp pred %0, %CFP
  633. /// %add = fadd %0, %sum.1
  634. /// %sum.2 = select %cmp, %add, %sum.1
  635. RecurrenceDescriptor::InstDesc
  636. RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind, Instruction *I) {
  637. SelectInst *SI = dyn_cast<SelectInst>(I);
  638. if (!SI)
  639. return InstDesc(false, I);
  640. CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
  641. // Only handle single use cases for now.
  642. if (!CI || !CI->hasOneUse())
  643. return InstDesc(false, I);
  644. Value *TrueVal = SI->getTrueValue();
  645. Value *FalseVal = SI->getFalseValue();
  646. // Handle only when either of operands of select instruction is a PHI
  647. // node for now.
  648. if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
  649. (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
  650. return InstDesc(false, I);
  651. Instruction *I1 =
  652. isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
  653. : dyn_cast<Instruction>(TrueVal);
  654. if (!I1 || !I1->isBinaryOp())
  655. return InstDesc(false, I);
  656. Value *Op1, *Op2;
  657. if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1) ||
  658. m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
  659. I1->isFast())
  660. return InstDesc(Kind == RecurKind::FAdd, SI);
  661. if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
  662. return InstDesc(Kind == RecurKind::FMul, SI);
  663. return InstDesc(false, I);
  664. }
  665. RecurrenceDescriptor::InstDesc
  666. RecurrenceDescriptor::isRecurrenceInstr(Loop *L, PHINode *OrigPhi,
  667. Instruction *I, RecurKind Kind,
  668. InstDesc &Prev, FastMathFlags FuncFMF) {
  669. assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
  670. switch (I->getOpcode()) {
  671. default:
  672. return InstDesc(false, I);
  673. case Instruction::PHI:
  674. return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
  675. case Instruction::Sub:
  676. case Instruction::Add:
  677. return InstDesc(Kind == RecurKind::Add, I);
  678. case Instruction::Mul:
  679. return InstDesc(Kind == RecurKind::Mul, I);
  680. case Instruction::And:
  681. return InstDesc(Kind == RecurKind::And, I);
  682. case Instruction::Or:
  683. return InstDesc(Kind == RecurKind::Or, I);
  684. case Instruction::Xor:
  685. return InstDesc(Kind == RecurKind::Xor, I);
  686. case Instruction::FDiv:
  687. case Instruction::FMul:
  688. return InstDesc(Kind == RecurKind::FMul, I,
  689. I->hasAllowReassoc() ? nullptr : I);
  690. case Instruction::FSub:
  691. case Instruction::FAdd:
  692. return InstDesc(Kind == RecurKind::FAdd, I,
  693. I->hasAllowReassoc() ? nullptr : I);
  694. case Instruction::Select:
  695. if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul)
  696. return isConditionalRdxPattern(Kind, I);
  697. [[fallthrough]];
  698. case Instruction::FCmp:
  699. case Instruction::ICmp:
  700. case Instruction::Call:
  701. if (isSelectCmpRecurrenceKind(Kind))
  702. return isSelectCmpPattern(L, OrigPhi, I, Prev);
  703. if (isIntMinMaxRecurrenceKind(Kind) ||
  704. (((FuncFMF.noNaNs() && FuncFMF.noSignedZeros()) ||
  705. (isa<FPMathOperator>(I) && I->hasNoNaNs() &&
  706. I->hasNoSignedZeros())) &&
  707. isFPMinMaxRecurrenceKind(Kind)))
  708. return isMinMaxPattern(I, Kind, Prev);
  709. else if (isFMulAddIntrinsic(I))
  710. return InstDesc(Kind == RecurKind::FMulAdd, I,
  711. I->hasAllowReassoc() ? nullptr : I);
  712. return InstDesc(false, I);
  713. }
  714. }
  715. bool RecurrenceDescriptor::hasMultipleUsesOf(
  716. Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
  717. unsigned MaxNumUses) {
  718. unsigned NumUses = 0;
  719. for (const Use &U : I->operands()) {
  720. if (Insts.count(dyn_cast<Instruction>(U)))
  721. ++NumUses;
  722. if (NumUses > MaxNumUses)
  723. return true;
  724. }
  725. return false;
  726. }
  727. bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
  728. RecurrenceDescriptor &RedDes,
  729. DemandedBits *DB, AssumptionCache *AC,
  730. DominatorTree *DT,
  731. ScalarEvolution *SE) {
  732. BasicBlock *Header = TheLoop->getHeader();
  733. Function &F = *Header->getParent();
  734. FastMathFlags FMF;
  735. FMF.setNoNaNs(
  736. F.getFnAttribute("no-nans-fp-math").getValueAsBool());
  737. FMF.setNoSignedZeros(
  738. F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool());
  739. if (AddReductionVar(Phi, RecurKind::Add, TheLoop, FMF, RedDes, DB, AC, DT,
  740. SE)) {
  741. LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
  742. return true;
  743. }
  744. if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, FMF, RedDes, DB, AC, DT,
  745. SE)) {
  746. LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
  747. return true;
  748. }
  749. if (AddReductionVar(Phi, RecurKind::Or, TheLoop, FMF, RedDes, DB, AC, DT,
  750. SE)) {
  751. LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
  752. return true;
  753. }
  754. if (AddReductionVar(Phi, RecurKind::And, TheLoop, FMF, RedDes, DB, AC, DT,
  755. SE)) {
  756. LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
  757. return true;
  758. }
  759. if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, FMF, RedDes, DB, AC, DT,
  760. SE)) {
  761. LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
  762. return true;
  763. }
  764. if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, FMF, RedDes, DB, AC, DT,
  765. SE)) {
  766. LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n");
  767. return true;
  768. }
  769. if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, FMF, RedDes, DB, AC, DT,
  770. SE)) {
  771. LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n");
  772. return true;
  773. }
  774. if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, FMF, RedDes, DB, AC, DT,
  775. SE)) {
  776. LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n");
  777. return true;
  778. }
  779. if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, FMF, RedDes, DB, AC, DT,
  780. SE)) {
  781. LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n");
  782. return true;
  783. }
  784. if (AddReductionVar(Phi, RecurKind::SelectICmp, TheLoop, FMF, RedDes, DB, AC,
  785. DT, SE)) {
  786. LLVM_DEBUG(dbgs() << "Found an integer conditional select reduction PHI."
  787. << *Phi << "\n");
  788. return true;
  789. }
  790. if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, FMF, RedDes, DB, AC, DT,
  791. SE)) {
  792. LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
  793. return true;
  794. }
  795. if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, FMF, RedDes, DB, AC, DT,
  796. SE)) {
  797. LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
  798. return true;
  799. }
  800. if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, FMF, RedDes, DB, AC, DT,
  801. SE)) {
  802. LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n");
  803. return true;
  804. }
  805. if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, FMF, RedDes, DB, AC, DT,
  806. SE)) {
  807. LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n");
  808. return true;
  809. }
  810. if (AddReductionVar(Phi, RecurKind::SelectFCmp, TheLoop, FMF, RedDes, DB, AC,
  811. DT, SE)) {
  812. LLVM_DEBUG(dbgs() << "Found a float conditional select reduction PHI."
  813. << " PHI." << *Phi << "\n");
  814. return true;
  815. }
  816. if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, FMF, RedDes, DB, AC, DT,
  817. SE)) {
  818. LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
  819. return true;
  820. }
  821. // Not a reduction of known type.
  822. return false;
  823. }
  824. bool RecurrenceDescriptor::isFixedOrderRecurrence(
  825. PHINode *Phi, Loop *TheLoop,
  826. MapVector<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
  827. // Ensure the phi node is in the loop header and has two incoming values.
  828. if (Phi->getParent() != TheLoop->getHeader() ||
  829. Phi->getNumIncomingValues() != 2)
  830. return false;
  831. // Ensure the loop has a preheader and a single latch block. The loop
  832. // vectorizer will need the latch to set up the next iteration of the loop.
  833. auto *Preheader = TheLoop->getLoopPreheader();
  834. auto *Latch = TheLoop->getLoopLatch();
  835. if (!Preheader || !Latch)
  836. return false;
  837. // Ensure the phi node's incoming blocks are the loop preheader and latch.
  838. if (Phi->getBasicBlockIndex(Preheader) < 0 ||
  839. Phi->getBasicBlockIndex(Latch) < 0)
  840. return false;
  841. // Get the previous value. The previous value comes from the latch edge while
  842. // the initial value comes from the preheader edge.
  843. auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
  844. // If Previous is a phi in the header, go through incoming values from the
  845. // latch until we find a non-phi value. Use this as the new Previous, all uses
  846. // in the header will be dominated by the original phi, but need to be moved
  847. // after the non-phi previous value.
  848. SmallPtrSet<PHINode *, 4> SeenPhis;
  849. while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
  850. if (PrevPhi->getParent() != Phi->getParent())
  851. return false;
  852. if (!SeenPhis.insert(PrevPhi).second)
  853. return false;
  854. Previous = dyn_cast<Instruction>(PrevPhi->getIncomingValueForBlock(Latch));
  855. }
  856. if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
  857. SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
  858. return false;
  859. // Ensure every user of the phi node (recursively) is dominated by the
  860. // previous value. The dominance requirement ensures the loop vectorizer will
  861. // not need to vectorize the initial value prior to the first iteration of the
  862. // loop.
  863. // TODO: Consider extending this sinking to handle memory instructions.
  864. // We optimistically assume we can sink all users after Previous. Keep a set
  865. // of instructions to sink after Previous ordered by dominance in the common
  866. // basic block. It will be applied to SinkAfter if all users can be sunk.
  867. auto CompareByComesBefore = [](const Instruction *A, const Instruction *B) {
  868. return A->comesBefore(B);
  869. };
  870. std::set<Instruction *, decltype(CompareByComesBefore)> InstrsToSink(
  871. CompareByComesBefore);
  872. BasicBlock *PhiBB = Phi->getParent();
  873. SmallVector<Instruction *, 8> WorkList;
  874. auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
  875. // Already sunk SinkCandidate.
  876. if (SinkCandidate->getParent() == PhiBB &&
  877. InstrsToSink.find(SinkCandidate) != InstrsToSink.end())
  878. return true;
  879. // Cyclic dependence.
  880. if (Previous == SinkCandidate)
  881. return false;
  882. if (DT->dominates(Previous,
  883. SinkCandidate)) // We already are good w/o sinking.
  884. return true;
  885. if (SinkCandidate->getParent() != PhiBB ||
  886. SinkCandidate->mayHaveSideEffects() ||
  887. SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
  888. return false;
  889. // Avoid sinking an instruction multiple times (if multiple operands are
  890. // fixed order recurrences) by sinking once - after the latest 'previous'
  891. // instruction.
  892. auto It = SinkAfter.find(SinkCandidate);
  893. if (It != SinkAfter.end()) {
  894. auto *OtherPrev = It->second;
  895. // Find the earliest entry in the 'sink-after' chain. The last entry in
  896. // the chain is the original 'Previous' for a recurrence handled earlier.
  897. auto EarlierIt = SinkAfter.find(OtherPrev);
  898. while (EarlierIt != SinkAfter.end()) {
  899. Instruction *EarlierInst = EarlierIt->second;
  900. EarlierIt = SinkAfter.find(EarlierInst);
  901. // Bail out if order has not been preserved.
  902. if (EarlierIt != SinkAfter.end() &&
  903. !DT->dominates(EarlierInst, OtherPrev))
  904. return false;
  905. OtherPrev = EarlierInst;
  906. }
  907. // Bail out if order has not been preserved.
  908. if (OtherPrev != It->second && !DT->dominates(It->second, OtherPrev))
  909. return false;
  910. // SinkCandidate is already being sunk after an instruction after
  911. // Previous. Nothing left to do.
  912. if (DT->dominates(Previous, OtherPrev) || Previous == OtherPrev)
  913. return true;
  914. // If there are other instructions to be sunk after SinkCandidate, remove
  915. // and re-insert SinkCandidate can break those instructions. Bail out for
  916. // simplicity.
  917. if (any_of(SinkAfter,
  918. [SinkCandidate](const std::pair<Instruction *, Instruction *> &P) {
  919. return P.second == SinkCandidate;
  920. }))
  921. return false;
  922. // Otherwise, Previous comes after OtherPrev and SinkCandidate needs to be
  923. // re-sunk to Previous, instead of sinking to OtherPrev. Remove
  924. // SinkCandidate from SinkAfter to ensure it's insert position is updated.
  925. SinkAfter.erase(SinkCandidate);
  926. }
  927. // If we reach a PHI node that is not dominated by Previous, we reached a
  928. // header PHI. No need for sinking.
  929. if (isa<PHINode>(SinkCandidate))
  930. return true;
  931. // Sink User tentatively and check its users
  932. InstrsToSink.insert(SinkCandidate);
  933. WorkList.push_back(SinkCandidate);
  934. return true;
  935. };
  936. WorkList.push_back(Phi);
  937. // Try to recursively sink instructions and their users after Previous.
  938. while (!WorkList.empty()) {
  939. Instruction *Current = WorkList.pop_back_val();
  940. for (User *User : Current->users()) {
  941. if (!TryToPushSinkCandidate(cast<Instruction>(User)))
  942. return false;
  943. }
  944. }
  945. // We can sink all users of Phi. Update the mapping.
  946. for (Instruction *I : InstrsToSink) {
  947. SinkAfter[I] = Previous;
  948. Previous = I;
  949. }
  950. return true;
  951. }
  952. /// This function returns the identity element (or neutral element) for
  953. /// the operation K.
  954. Value *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp,
  955. FastMathFlags FMF) const {
  956. switch (K) {
  957. case RecurKind::Xor:
  958. case RecurKind::Add:
  959. case RecurKind::Or:
  960. // Adding, Xoring, Oring zero to a number does not change it.
  961. return ConstantInt::get(Tp, 0);
  962. case RecurKind::Mul:
  963. // Multiplying a number by 1 does not change it.
  964. return ConstantInt::get(Tp, 1);
  965. case RecurKind::And:
  966. // AND-ing a number with an all-1 value does not change it.
  967. return ConstantInt::get(Tp, -1, true);
  968. case RecurKind::FMul:
  969. // Multiplying a number by 1 does not change it.
  970. return ConstantFP::get(Tp, 1.0L);
  971. case RecurKind::FMulAdd:
  972. case RecurKind::FAdd:
  973. // Adding zero to a number does not change it.
  974. // FIXME: Ideally we should not need to check FMF for FAdd and should always
  975. // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0.
  976. // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI
  977. // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would
  978. // mean we can then remove the check for noSignedZeros() below (see D98963).
  979. if (FMF.noSignedZeros())
  980. return ConstantFP::get(Tp, 0.0L);
  981. return ConstantFP::get(Tp, -0.0L);
  982. case RecurKind::UMin:
  983. return ConstantInt::get(Tp, -1);
  984. case RecurKind::UMax:
  985. return ConstantInt::get(Tp, 0);
  986. case RecurKind::SMin:
  987. return ConstantInt::get(Tp,
  988. APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
  989. case RecurKind::SMax:
  990. return ConstantInt::get(Tp,
  991. APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
  992. case RecurKind::FMin:
  993. assert((FMF.noNaNs() && FMF.noSignedZeros()) &&
  994. "nnan, nsz is expected to be set for FP min reduction.");
  995. return ConstantFP::getInfinity(Tp, false /*Negative*/);
  996. case RecurKind::FMax:
  997. assert((FMF.noNaNs() && FMF.noSignedZeros()) &&
  998. "nnan, nsz is expected to be set for FP max reduction.");
  999. return ConstantFP::getInfinity(Tp, true /*Negative*/);
  1000. case RecurKind::SelectICmp:
  1001. case RecurKind::SelectFCmp:
  1002. return getRecurrenceStartValue();
  1003. break;
  1004. default:
  1005. llvm_unreachable("Unknown recurrence kind");
  1006. }
  1007. }
  1008. unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) {
  1009. switch (Kind) {
  1010. case RecurKind::Add:
  1011. return Instruction::Add;
  1012. case RecurKind::Mul:
  1013. return Instruction::Mul;
  1014. case RecurKind::Or:
  1015. return Instruction::Or;
  1016. case RecurKind::And:
  1017. return Instruction::And;
  1018. case RecurKind::Xor:
  1019. return Instruction::Xor;
  1020. case RecurKind::FMul:
  1021. return Instruction::FMul;
  1022. case RecurKind::FMulAdd:
  1023. case RecurKind::FAdd:
  1024. return Instruction::FAdd;
  1025. case RecurKind::SMax:
  1026. case RecurKind::SMin:
  1027. case RecurKind::UMax:
  1028. case RecurKind::UMin:
  1029. case RecurKind::SelectICmp:
  1030. return Instruction::ICmp;
  1031. case RecurKind::FMax:
  1032. case RecurKind::FMin:
  1033. case RecurKind::SelectFCmp:
  1034. return Instruction::FCmp;
  1035. default:
  1036. llvm_unreachable("Unknown recurrence operation");
  1037. }
  1038. }
  1039. SmallVector<Instruction *, 4>
  1040. RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
  1041. SmallVector<Instruction *, 4> ReductionOperations;
  1042. unsigned RedOp = getOpcode(Kind);
  1043. // Search down from the Phi to the LoopExitInstr, looking for instructions
  1044. // with a single user of the correct type for the reduction.
  1045. // Note that we check that the type of the operand is correct for each item in
  1046. // the chain, including the last (the loop exit value). This can come up from
  1047. // sub, which would otherwise be treated as an add reduction. MinMax also need
  1048. // to check for a pair of icmp/select, for which we use getNextInstruction and
  1049. // isCorrectOpcode functions to step the right number of instruction, and
  1050. // check the icmp/select pair.
  1051. // FIXME: We also do not attempt to look through Select's yet, which might
  1052. // be part of the reduction chain, or attempt to looks through And's to find a
  1053. // smaller bitwidth. Subs are also currently not allowed (which are usually
  1054. // treated as part of a add reduction) as they are expected to generally be
  1055. // more expensive than out-of-loop reductions, and need to be costed more
  1056. // carefully.
  1057. unsigned ExpectedUses = 1;
  1058. if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
  1059. ExpectedUses = 2;
  1060. auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
  1061. for (auto *User : Cur->users()) {
  1062. Instruction *UI = cast<Instruction>(User);
  1063. if (isa<PHINode>(UI))
  1064. continue;
  1065. if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
  1066. // We are expecting a icmp/select pair, which we go to the next select
  1067. // instruction if we can. We already know that Cur has 2 uses.
  1068. if (isa<SelectInst>(UI))
  1069. return UI;
  1070. continue;
  1071. }
  1072. return UI;
  1073. }
  1074. return nullptr;
  1075. };
  1076. auto isCorrectOpcode = [&](Instruction *Cur) {
  1077. if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
  1078. Value *LHS, *RHS;
  1079. return SelectPatternResult::isMinOrMax(
  1080. matchSelectPattern(Cur, LHS, RHS).Flavor);
  1081. }
  1082. // Recognize a call to the llvm.fmuladd intrinsic.
  1083. if (isFMulAddIntrinsic(Cur))
  1084. return true;
  1085. return Cur->getOpcode() == RedOp;
  1086. };
  1087. // Attempt to look through Phis which are part of the reduction chain
  1088. unsigned ExtraPhiUses = 0;
  1089. Instruction *RdxInstr = LoopExitInstr;
  1090. if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
  1091. if (ExitPhi->getNumIncomingValues() != 2)
  1092. return {};
  1093. Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
  1094. Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
  1095. Instruction *Chain = nullptr;
  1096. if (Inc0 == Phi)
  1097. Chain = Inc1;
  1098. else if (Inc1 == Phi)
  1099. Chain = Inc0;
  1100. else
  1101. return {};
  1102. RdxInstr = Chain;
  1103. ExtraPhiUses = 1;
  1104. }
  1105. // The loop exit instruction we check first (as a quick test) but add last. We
  1106. // check the opcode is correct (and dont allow them to be Subs) and that they
  1107. // have expected to have the expected number of uses. They will have one use
  1108. // from the phi and one from a LCSSA value, no matter the type.
  1109. if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
  1110. return {};
  1111. // Check that the Phi has one (or two for min/max) uses, plus an extra use
  1112. // for conditional reductions.
  1113. if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
  1114. return {};
  1115. Instruction *Cur = getNextInstruction(Phi);
  1116. // Each other instruction in the chain should have the expected number of uses
  1117. // and be the correct opcode.
  1118. while (Cur != RdxInstr) {
  1119. if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
  1120. return {};
  1121. ReductionOperations.push_back(Cur);
  1122. Cur = getNextInstruction(Cur);
  1123. }
  1124. ReductionOperations.push_back(Cur);
  1125. return ReductionOperations;
  1126. }
  1127. InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
  1128. const SCEV *Step, BinaryOperator *BOp,
  1129. Type *ElementType,
  1130. SmallVectorImpl<Instruction *> *Casts)
  1131. : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp),
  1132. ElementType(ElementType) {
  1133. assert(IK != IK_NoInduction && "Not an induction");
  1134. // Start value type should match the induction kind and the value
  1135. // itself should not be null.
  1136. assert(StartValue && "StartValue is null");
  1137. assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
  1138. "StartValue is not a pointer for pointer induction");
  1139. assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
  1140. "StartValue is not an integer for integer induction");
  1141. // Check the Step Value. It should be non-zero integer value.
  1142. assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
  1143. "Step value is zero");
  1144. assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
  1145. "Step value should be constant for pointer induction");
  1146. assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
  1147. "StepValue is not an integer");
  1148. assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
  1149. "StepValue is not FP for FpInduction");
  1150. assert((IK != IK_FpInduction ||
  1151. (InductionBinOp &&
  1152. (InductionBinOp->getOpcode() == Instruction::FAdd ||
  1153. InductionBinOp->getOpcode() == Instruction::FSub))) &&
  1154. "Binary opcode should be specified for FP induction");
  1155. if (IK == IK_PtrInduction)
  1156. assert(ElementType && "Pointer induction must have element type");
  1157. else
  1158. assert(!ElementType && "Non-pointer induction cannot have element type");
  1159. if (Casts) {
  1160. for (auto &Inst : *Casts) {
  1161. RedundantCasts.push_back(Inst);
  1162. }
  1163. }
  1164. }
  1165. ConstantInt *InductionDescriptor::getConstIntStepValue() const {
  1166. if (isa<SCEVConstant>(Step))
  1167. return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
  1168. return nullptr;
  1169. }
  1170. bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
  1171. ScalarEvolution *SE,
  1172. InductionDescriptor &D) {
  1173. // Here we only handle FP induction variables.
  1174. assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
  1175. if (TheLoop->getHeader() != Phi->getParent())
  1176. return false;
  1177. // The loop may have multiple entrances or multiple exits; we can analyze
  1178. // this phi if it has a unique entry value and a unique backedge value.
  1179. if (Phi->getNumIncomingValues() != 2)
  1180. return false;
  1181. Value *BEValue = nullptr, *StartValue = nullptr;
  1182. if (TheLoop->contains(Phi->getIncomingBlock(0))) {
  1183. BEValue = Phi->getIncomingValue(0);
  1184. StartValue = Phi->getIncomingValue(1);
  1185. } else {
  1186. assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
  1187. "Unexpected Phi node in the loop");
  1188. BEValue = Phi->getIncomingValue(1);
  1189. StartValue = Phi->getIncomingValue(0);
  1190. }
  1191. BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
  1192. if (!BOp)
  1193. return false;
  1194. Value *Addend = nullptr;
  1195. if (BOp->getOpcode() == Instruction::FAdd) {
  1196. if (BOp->getOperand(0) == Phi)
  1197. Addend = BOp->getOperand(1);
  1198. else if (BOp->getOperand(1) == Phi)
  1199. Addend = BOp->getOperand(0);
  1200. } else if (BOp->getOpcode() == Instruction::FSub)
  1201. if (BOp->getOperand(0) == Phi)
  1202. Addend = BOp->getOperand(1);
  1203. if (!Addend)
  1204. return false;
  1205. // The addend should be loop invariant
  1206. if (auto *I = dyn_cast<Instruction>(Addend))
  1207. if (TheLoop->contains(I))
  1208. return false;
  1209. // FP Step has unknown SCEV
  1210. const SCEV *Step = SE->getUnknown(Addend);
  1211. D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
  1212. return true;
  1213. }
  1214. /// This function is called when we suspect that the update-chain of a phi node
  1215. /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
  1216. /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
  1217. /// predicate P under which the SCEV expression for the phi can be the
  1218. /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
  1219. /// cast instructions that are involved in the update-chain of this induction.
  1220. /// A caller that adds the required runtime predicate can be free to drop these
  1221. /// cast instructions, and compute the phi using \p AR (instead of some scev
  1222. /// expression with casts).
  1223. ///
  1224. /// For example, without a predicate the scev expression can take the following
  1225. /// form:
  1226. /// (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
  1227. ///
  1228. /// It corresponds to the following IR sequence:
  1229. /// %for.body:
  1230. /// %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
  1231. /// %casted_phi = "ExtTrunc i64 %x"
  1232. /// %add = add i64 %casted_phi, %step
  1233. ///
  1234. /// where %x is given in \p PN,
  1235. /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
  1236. /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
  1237. /// several forms, for example, such as:
  1238. /// ExtTrunc1: %casted_phi = and %x, 2^n-1
  1239. /// or:
  1240. /// ExtTrunc2: %t = shl %x, m
  1241. /// %casted_phi = ashr %t, m
  1242. ///
  1243. /// If we are able to find such sequence, we return the instructions
  1244. /// we found, namely %casted_phi and the instructions on its use-def chain up
  1245. /// to the phi (not including the phi).
  1246. static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
  1247. const SCEVUnknown *PhiScev,
  1248. const SCEVAddRecExpr *AR,
  1249. SmallVectorImpl<Instruction *> &CastInsts) {
  1250. assert(CastInsts.empty() && "CastInsts is expected to be empty.");
  1251. auto *PN = cast<PHINode>(PhiScev->getValue());
  1252. assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
  1253. const Loop *L = AR->getLoop();
  1254. // Find any cast instructions that participate in the def-use chain of
  1255. // PhiScev in the loop.
  1256. // FORNOW/TODO: We currently expect the def-use chain to include only
  1257. // two-operand instructions, where one of the operands is an invariant.
  1258. // createAddRecFromPHIWithCasts() currently does not support anything more
  1259. // involved than that, so we keep the search simple. This can be
  1260. // extended/generalized as needed.
  1261. auto getDef = [&](const Value *Val) -> Value * {
  1262. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
  1263. if (!BinOp)
  1264. return nullptr;
  1265. Value *Op0 = BinOp->getOperand(0);
  1266. Value *Op1 = BinOp->getOperand(1);
  1267. Value *Def = nullptr;
  1268. if (L->isLoopInvariant(Op0))
  1269. Def = Op1;
  1270. else if (L->isLoopInvariant(Op1))
  1271. Def = Op0;
  1272. return Def;
  1273. };
  1274. // Look for the instruction that defines the induction via the
  1275. // loop backedge.
  1276. BasicBlock *Latch = L->getLoopLatch();
  1277. if (!Latch)
  1278. return false;
  1279. Value *Val = PN->getIncomingValueForBlock(Latch);
  1280. if (!Val)
  1281. return false;
  1282. // Follow the def-use chain until the induction phi is reached.
  1283. // If on the way we encounter a Value that has the same SCEV Expr as the
  1284. // phi node, we can consider the instructions we visit from that point
  1285. // as part of the cast-sequence that can be ignored.
  1286. bool InCastSequence = false;
  1287. auto *Inst = dyn_cast<Instruction>(Val);
  1288. while (Val != PN) {
  1289. // If we encountered a phi node other than PN, or if we left the loop,
  1290. // we bail out.
  1291. if (!Inst || !L->contains(Inst)) {
  1292. return false;
  1293. }
  1294. auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
  1295. if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
  1296. InCastSequence = true;
  1297. if (InCastSequence) {
  1298. // Only the last instruction in the cast sequence is expected to have
  1299. // uses outside the induction def-use chain.
  1300. if (!CastInsts.empty())
  1301. if (!Inst->hasOneUse())
  1302. return false;
  1303. CastInsts.push_back(Inst);
  1304. }
  1305. Val = getDef(Val);
  1306. if (!Val)
  1307. return false;
  1308. Inst = dyn_cast<Instruction>(Val);
  1309. }
  1310. return InCastSequence;
  1311. }
  1312. bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
  1313. PredicatedScalarEvolution &PSE,
  1314. InductionDescriptor &D, bool Assume) {
  1315. Type *PhiTy = Phi->getType();
  1316. // Handle integer and pointer inductions variables.
  1317. // Now we handle also FP induction but not trying to make a
  1318. // recurrent expression from the PHI node in-place.
  1319. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
  1320. !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
  1321. return false;
  1322. if (PhiTy->isFloatingPointTy())
  1323. return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
  1324. const SCEV *PhiScev = PSE.getSCEV(Phi);
  1325. const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  1326. // We need this expression to be an AddRecExpr.
  1327. if (Assume && !AR)
  1328. AR = PSE.getAsAddRec(Phi);
  1329. if (!AR) {
  1330. LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  1331. return false;
  1332. }
  1333. // Record any Cast instructions that participate in the induction update
  1334. const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
  1335. // If we started from an UnknownSCEV, and managed to build an addRecurrence
  1336. // only after enabling Assume with PSCEV, this means we may have encountered
  1337. // cast instructions that required adding a runtime check in order to
  1338. // guarantee the correctness of the AddRecurrence respresentation of the
  1339. // induction.
  1340. if (PhiScev != AR && SymbolicPhi) {
  1341. SmallVector<Instruction *, 2> Casts;
  1342. if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
  1343. return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
  1344. }
  1345. return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
  1346. }
  1347. bool InductionDescriptor::isInductionPHI(
  1348. PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
  1349. InductionDescriptor &D, const SCEV *Expr,
  1350. SmallVectorImpl<Instruction *> *CastsToIgnore) {
  1351. Type *PhiTy = Phi->getType();
  1352. // We only handle integer and pointer inductions variables.
  1353. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
  1354. return false;
  1355. // Check that the PHI is consecutive.
  1356. const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
  1357. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  1358. if (!AR) {
  1359. LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  1360. return false;
  1361. }
  1362. if (AR->getLoop() != TheLoop) {
  1363. // FIXME: We should treat this as a uniform. Unfortunately, we
  1364. // don't currently know how to handled uniform PHIs.
  1365. LLVM_DEBUG(
  1366. dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
  1367. return false;
  1368. }
  1369. Value *StartValue =
  1370. Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
  1371. BasicBlock *Latch = AR->getLoop()->getLoopLatch();
  1372. if (!Latch)
  1373. return false;
  1374. const SCEV *Step = AR->getStepRecurrence(*SE);
  1375. // Calculate the pointer stride and check if it is consecutive.
  1376. // The stride may be a constant or a loop invariant integer value.
  1377. const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
  1378. if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
  1379. return false;
  1380. if (PhiTy->isIntegerTy()) {
  1381. BinaryOperator *BOp =
  1382. dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
  1383. D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
  1384. /* ElementType */ nullptr, CastsToIgnore);
  1385. return true;
  1386. }
  1387. assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
  1388. // Pointer induction should be a constant.
  1389. if (!ConstStep)
  1390. return false;
  1391. // Always use i8 element type for opaque pointer inductions.
  1392. PointerType *PtrTy = cast<PointerType>(PhiTy);
  1393. Type *ElementType = PtrTy->isOpaque()
  1394. ? Type::getInt8Ty(PtrTy->getContext())
  1395. : PtrTy->getNonOpaquePointerElementType();
  1396. if (!ElementType->isSized())
  1397. return false;
  1398. ConstantInt *CV = ConstStep->getValue();
  1399. const DataLayout &DL = Phi->getModule()->getDataLayout();
  1400. TypeSize TySize = DL.getTypeAllocSize(ElementType);
  1401. // TODO: We could potentially support this for scalable vectors if we can
  1402. // prove at compile time that the constant step is always a multiple of
  1403. // the scalable type.
  1404. if (TySize.isZero() || TySize.isScalable())
  1405. return false;
  1406. int64_t Size = static_cast<int64_t>(TySize.getFixedValue());
  1407. int64_t CVSize = CV->getSExtValue();
  1408. if (CVSize % Size)
  1409. return false;
  1410. auto *StepValue =
  1411. SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
  1412. D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue,
  1413. /* BinOp */ nullptr, ElementType);
  1414. return true;
  1415. }