IVDescriptors.cpp 56 KB

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