LoopUtils.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines common loop utility functions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/LoopInfo.h"
  14. #include "llvm/IR/Instructions.h"
  15. #include "llvm/IR/PatternMatch.h"
  16. #include "llvm/IR/ValueHandle.h"
  17. #include "llvm/Support/Debug.h"
  18. #include "llvm/Analysis/ScalarEvolution.h"
  19. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/Transforms/Utils/LoopUtils.h"
  22. using namespace llvm;
  23. using namespace llvm::PatternMatch;
  24. #define DEBUG_TYPE "loop-utils"
  25. bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
  26. SmallPtrSetImpl<Instruction *> &Set) {
  27. for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
  28. if (!Set.count(dyn_cast<Instruction>(*Use)))
  29. return false;
  30. return true;
  31. }
  32. bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
  33. Loop *TheLoop, bool HasFunNoNaNAttr,
  34. RecurrenceDescriptor &RedDes) {
  35. if (Phi->getNumIncomingValues() != 2)
  36. return false;
  37. // Reduction variables are only found in the loop header block.
  38. if (Phi->getParent() != TheLoop->getHeader())
  39. return false;
  40. // Obtain the reduction start value from the value that comes from the loop
  41. // preheader.
  42. Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
  43. // ExitInstruction is the single value which is used outside the loop.
  44. // We only allow for a single reduction value to be used outside the loop.
  45. // This includes users of the reduction, variables (which form a cycle
  46. // which ends in the phi node).
  47. Instruction *ExitInstruction = nullptr;
  48. // Indicates that we found a reduction operation in our scan.
  49. bool FoundReduxOp = false;
  50. // We start with the PHI node and scan for all of the users of this
  51. // instruction. All users must be instructions that can be used as reduction
  52. // variables (such as ADD). We must have a single out-of-block user. The cycle
  53. // must include the original PHI.
  54. bool FoundStartPHI = false;
  55. // To recognize min/max patterns formed by a icmp select sequence, we store
  56. // the number of instruction we saw from the recognized min/max pattern,
  57. // to make sure we only see exactly the two instructions.
  58. unsigned NumCmpSelectPatternInst = 0;
  59. InstDesc ReduxDesc(false, nullptr);
  60. SmallPtrSet<Instruction *, 8> VisitedInsts;
  61. SmallVector<Instruction *, 8> Worklist;
  62. Worklist.push_back(Phi);
  63. VisitedInsts.insert(Phi);
  64. // A value in the reduction can be used:
  65. // - By the reduction:
  66. // - Reduction operation:
  67. // - One use of reduction value (safe).
  68. // - Multiple use of reduction value (not safe).
  69. // - PHI:
  70. // - All uses of the PHI must be the reduction (safe).
  71. // - Otherwise, not safe.
  72. // - By one instruction outside of the loop (safe).
  73. // - By further instructions outside of the loop (not safe).
  74. // - By an instruction that is not part of the reduction (not safe).
  75. // This is either:
  76. // * An instruction type other than PHI or the reduction operation.
  77. // * A PHI in the header other than the initial PHI.
  78. while (!Worklist.empty()) {
  79. Instruction *Cur = Worklist.back();
  80. Worklist.pop_back();
  81. // No Users.
  82. // If the instruction has no users then this is a broken chain and can't be
  83. // a reduction variable.
  84. if (Cur->use_empty())
  85. return false;
  86. bool IsAPhi = isa<PHINode>(Cur);
  87. // A header PHI use other than the original PHI.
  88. if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
  89. return false;
  90. // Reductions of instructions such as Div, and Sub is only possible if the
  91. // LHS is the reduction variable.
  92. if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
  93. !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
  94. !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
  95. return false;
  96. // Any reduction instruction must be of one of the allowed kinds.
  97. ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
  98. if (!ReduxDesc.isRecurrence())
  99. return false;
  100. // A reduction operation must only have one use of the reduction value.
  101. if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
  102. hasMultipleUsesOf(Cur, VisitedInsts))
  103. return false;
  104. // All inputs to a PHI node must be a reduction value.
  105. if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
  106. return false;
  107. if (Kind == RK_IntegerMinMax &&
  108. (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
  109. ++NumCmpSelectPatternInst;
  110. if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
  111. ++NumCmpSelectPatternInst;
  112. // Check whether we found a reduction operator.
  113. FoundReduxOp |= !IsAPhi;
  114. // Process users of current instruction. Push non-PHI nodes after PHI nodes
  115. // onto the stack. This way we are going to have seen all inputs to PHI
  116. // nodes once we get to them.
  117. SmallVector<Instruction *, 8> NonPHIs;
  118. SmallVector<Instruction *, 8> PHIs;
  119. for (User *U : Cur->users()) {
  120. Instruction *UI = cast<Instruction>(U);
  121. // Check if we found the exit user.
  122. BasicBlock *Parent = UI->getParent();
  123. if (!TheLoop->contains(Parent)) {
  124. // Exit if you find multiple outside users or if the header phi node is
  125. // being used. In this case the user uses the value of the previous
  126. // iteration, in which case we would loose "VF-1" iterations of the
  127. // reduction operation if we vectorize.
  128. if (ExitInstruction != nullptr || Cur == Phi)
  129. return false;
  130. // The instruction used by an outside user must be the last instruction
  131. // before we feed back to the reduction phi. Otherwise, we loose VF-1
  132. // operations on the value.
  133. if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
  134. return false;
  135. ExitInstruction = Cur;
  136. continue;
  137. }
  138. // Process instructions only once (termination). Each reduction cycle
  139. // value must only be used once, except by phi nodes and min/max
  140. // reductions which are represented as a cmp followed by a select.
  141. InstDesc IgnoredVal(false, nullptr);
  142. if (VisitedInsts.insert(UI).second) {
  143. if (isa<PHINode>(UI))
  144. PHIs.push_back(UI);
  145. else
  146. NonPHIs.push_back(UI);
  147. } else if (!isa<PHINode>(UI) &&
  148. ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
  149. !isa<SelectInst>(UI)) ||
  150. !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
  151. return false;
  152. // Remember that we completed the cycle.
  153. if (UI == Phi)
  154. FoundStartPHI = true;
  155. }
  156. Worklist.append(PHIs.begin(), PHIs.end());
  157. Worklist.append(NonPHIs.begin(), NonPHIs.end());
  158. }
  159. // This means we have seen one but not the other instruction of the
  160. // pattern or more than just a select and cmp.
  161. if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
  162. NumCmpSelectPatternInst != 2)
  163. return false;
  164. if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
  165. return false;
  166. // We found a reduction var if we have reached the original phi node and we
  167. // only have a single instruction with out-of-loop users.
  168. // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
  169. // is saved as part of the RecurrenceDescriptor.
  170. // Save the description of this reduction variable.
  171. RecurrenceDescriptor RD(RdxStart, ExitInstruction, Kind,
  172. ReduxDesc.getMinMaxKind(),
  173. ReduxDesc.getUnsafeAlgebraInst());
  174. RedDes = RD;
  175. return true;
  176. }
  177. /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
  178. /// pattern corresponding to a min(X, Y) or max(X, Y).
  179. RecurrenceDescriptor::InstDesc
  180. RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
  181. assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
  182. "Expect a select instruction");
  183. Instruction *Cmp = nullptr;
  184. SelectInst *Select = nullptr;
  185. // We must handle the select(cmp()) as a single instruction. Advance to the
  186. // select.
  187. if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
  188. if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
  189. return InstDesc(false, I);
  190. return InstDesc(Select, Prev.getMinMaxKind());
  191. }
  192. // Only handle single use cases for now.
  193. if (!(Select = dyn_cast<SelectInst>(I)))
  194. return InstDesc(false, I);
  195. if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
  196. !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
  197. return InstDesc(false, I);
  198. if (!Cmp->hasOneUse())
  199. return InstDesc(false, I);
  200. Value *CmpLeft;
  201. Value *CmpRight;
  202. // Look for a min/max pattern.
  203. if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  204. return InstDesc(Select, MRK_UIntMin);
  205. else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  206. return InstDesc(Select, MRK_UIntMax);
  207. else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  208. return InstDesc(Select, MRK_SIntMax);
  209. else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  210. return InstDesc(Select, MRK_SIntMin);
  211. else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  212. return InstDesc(Select, MRK_FloatMin);
  213. else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  214. return InstDesc(Select, MRK_FloatMax);
  215. else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  216. return InstDesc(Select, MRK_FloatMin);
  217. else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  218. return InstDesc(Select, MRK_FloatMax);
  219. return InstDesc(false, I);
  220. }
  221. RecurrenceDescriptor::InstDesc
  222. RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
  223. InstDesc &Prev, bool HasFunNoNaNAttr) {
  224. bool FP = I->getType()->isFloatingPointTy();
  225. Instruction *UAI = Prev.getUnsafeAlgebraInst();
  226. if (!UAI && FP && !I->hasUnsafeAlgebra())
  227. UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
  228. switch (I->getOpcode()) {
  229. default:
  230. return InstDesc(false, I);
  231. case Instruction::PHI:
  232. if (FP &&
  233. (Kind != RK_FloatMult && Kind != RK_FloatAdd && Kind != RK_FloatMinMax))
  234. return InstDesc(false, I);
  235. return InstDesc(I, Prev.getMinMaxKind());
  236. case Instruction::Sub:
  237. case Instruction::Add:
  238. return InstDesc(Kind == RK_IntegerAdd, I);
  239. case Instruction::Mul:
  240. return InstDesc(Kind == RK_IntegerMult, I);
  241. case Instruction::And:
  242. return InstDesc(Kind == RK_IntegerAnd, I);
  243. case Instruction::Or:
  244. return InstDesc(Kind == RK_IntegerOr, I);
  245. case Instruction::Xor:
  246. return InstDesc(Kind == RK_IntegerXor, I);
  247. case Instruction::FMul:
  248. return InstDesc(Kind == RK_FloatMult, I, UAI);
  249. case Instruction::FSub:
  250. case Instruction::FAdd:
  251. return InstDesc(Kind == RK_FloatAdd, I, UAI);
  252. case Instruction::FCmp:
  253. case Instruction::ICmp:
  254. case Instruction::Select:
  255. if (Kind != RK_IntegerMinMax &&
  256. (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
  257. return InstDesc(false, I);
  258. return isMinMaxSelectCmpPattern(I, Prev);
  259. }
  260. }
  261. bool RecurrenceDescriptor::hasMultipleUsesOf(
  262. Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
  263. unsigned NumUses = 0;
  264. for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
  265. ++Use) {
  266. if (Insts.count(dyn_cast<Instruction>(*Use)))
  267. ++NumUses;
  268. if (NumUses > 1)
  269. return true;
  270. }
  271. return false;
  272. }
  273. bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
  274. RecurrenceDescriptor &RedDes) {
  275. bool HasFunNoNaNAttr = false;
  276. BasicBlock *Header = TheLoop->getHeader();
  277. Function &F = *Header->getParent();
  278. if (F.hasFnAttribute("no-nans-fp-math"))
  279. HasFunNoNaNAttr =
  280. F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
  281. if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
  282. DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
  283. return true;
  284. }
  285. if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
  286. DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
  287. return true;
  288. }
  289. if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
  290. DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
  291. return true;
  292. }
  293. if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
  294. DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
  295. return true;
  296. }
  297. if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
  298. DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
  299. return true;
  300. }
  301. if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
  302. RedDes)) {
  303. DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
  304. return true;
  305. }
  306. if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
  307. DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
  308. return true;
  309. }
  310. if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
  311. DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
  312. return true;
  313. }
  314. if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
  315. DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
  316. return true;
  317. }
  318. // Not a reduction of known type.
  319. return false;
  320. }
  321. /// This function returns the identity element (or neutral element) for
  322. /// the operation K.
  323. Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
  324. Type *Tp) {
  325. switch (K) {
  326. case RK_IntegerXor:
  327. case RK_IntegerAdd:
  328. case RK_IntegerOr:
  329. // Adding, Xoring, Oring zero to a number does not change it.
  330. return ConstantInt::get(Tp, 0);
  331. case RK_IntegerMult:
  332. // Multiplying a number by 1 does not change it.
  333. return ConstantInt::get(Tp, 1);
  334. case RK_IntegerAnd:
  335. // AND-ing a number with an all-1 value does not change it.
  336. return ConstantInt::get(Tp, -1, true);
  337. case RK_FloatMult:
  338. // Multiplying a number by 1 does not change it.
  339. return ConstantFP::get(Tp, 1.0L);
  340. case RK_FloatAdd:
  341. // Adding zero to a number does not change it.
  342. return ConstantFP::get(Tp, 0.0L);
  343. default:
  344. llvm_unreachable("Unknown recurrence kind");
  345. }
  346. }
  347. /// This function translates the recurrence kind to an LLVM binary operator.
  348. unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
  349. switch (Kind) {
  350. case RK_IntegerAdd:
  351. return Instruction::Add;
  352. case RK_IntegerMult:
  353. return Instruction::Mul;
  354. case RK_IntegerOr:
  355. return Instruction::Or;
  356. case RK_IntegerAnd:
  357. return Instruction::And;
  358. case RK_IntegerXor:
  359. return Instruction::Xor;
  360. case RK_FloatMult:
  361. return Instruction::FMul;
  362. case RK_FloatAdd:
  363. return Instruction::FAdd;
  364. case RK_IntegerMinMax:
  365. return Instruction::ICmp;
  366. case RK_FloatMinMax:
  367. return Instruction::FCmp;
  368. default:
  369. llvm_unreachable("Unknown recurrence operation");
  370. }
  371. }
  372. Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
  373. MinMaxRecurrenceKind RK,
  374. Value *Left, Value *Right) {
  375. CmpInst::Predicate P = CmpInst::ICMP_NE;
  376. switch (RK) {
  377. default:
  378. llvm_unreachable("Unknown min/max recurrence kind");
  379. case MRK_UIntMin:
  380. P = CmpInst::ICMP_ULT;
  381. break;
  382. case MRK_UIntMax:
  383. P = CmpInst::ICMP_UGT;
  384. break;
  385. case MRK_SIntMin:
  386. P = CmpInst::ICMP_SLT;
  387. break;
  388. case MRK_SIntMax:
  389. P = CmpInst::ICMP_SGT;
  390. break;
  391. case MRK_FloatMin:
  392. P = CmpInst::FCMP_OLT;
  393. break;
  394. case MRK_FloatMax:
  395. P = CmpInst::FCMP_OGT;
  396. break;
  397. }
  398. Value *Cmp;
  399. if (RK == MRK_FloatMin || RK == MRK_FloatMax)
  400. Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
  401. else
  402. Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
  403. Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
  404. return Select;
  405. }
  406. InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
  407. ConstantInt *Step)
  408. : StartValue(Start), IK(K), StepValue(Step) {
  409. assert(IK != IK_NoInduction && "Not an induction");
  410. assert(StartValue && "StartValue is null");
  411. assert(StepValue && !StepValue->isZero() && "StepValue is zero");
  412. assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
  413. "StartValue is not a pointer for pointer induction");
  414. assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
  415. "StartValue is not an integer for integer induction");
  416. assert(StepValue->getType()->isIntegerTy() &&
  417. "StepValue is not an integer");
  418. }
  419. int InductionDescriptor::getConsecutiveDirection() const {
  420. if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
  421. return StepValue->getSExtValue();
  422. return 0;
  423. }
  424. Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
  425. switch (IK) {
  426. case IK_IntInduction:
  427. assert(Index->getType() == StartValue->getType() &&
  428. "Index type does not match StartValue type");
  429. if (StepValue->isMinusOne())
  430. return B.CreateSub(StartValue, Index);
  431. if (!StepValue->isOne())
  432. Index = B.CreateMul(Index, StepValue);
  433. return B.CreateAdd(StartValue, Index);
  434. case IK_PtrInduction:
  435. assert(Index->getType() == StepValue->getType() &&
  436. "Index type does not match StepValue type");
  437. if (StepValue->isMinusOne())
  438. Index = B.CreateNeg(Index);
  439. else if (!StepValue->isOne())
  440. Index = B.CreateMul(Index, StepValue);
  441. return B.CreateGEP(nullptr, StartValue, Index);
  442. case IK_NoInduction:
  443. return nullptr;
  444. }
  445. llvm_unreachable("invalid enum");
  446. }
  447. bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
  448. InductionDescriptor &D) {
  449. Type *PhiTy = Phi->getType();
  450. // We only handle integer and pointer inductions variables.
  451. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
  452. return false;
  453. // Check that the PHI is consecutive.
  454. const SCEV *PhiScev = SE->getSCEV(Phi);
  455. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  456. if (!AR) {
  457. DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  458. return false;
  459. }
  460. assert(AR->getLoop()->getHeader() == Phi->getParent() &&
  461. "PHI is an AddRec for a different loop?!");
  462. Value *StartValue =
  463. Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
  464. const SCEV *Step = AR->getStepRecurrence(*SE);
  465. // Calculate the pointer stride and check if it is consecutive.
  466. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  467. if (!C)
  468. return false;
  469. ConstantInt *CV = C->getValue();
  470. if (PhiTy->isIntegerTy()) {
  471. D = InductionDescriptor(StartValue, IK_IntInduction, CV);
  472. return true;
  473. }
  474. assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
  475. Type *PointerElementType = PhiTy->getPointerElementType();
  476. // The pointer stride cannot be determined if the pointer element type is not
  477. // sized.
  478. if (!PointerElementType->isSized())
  479. return false;
  480. const DataLayout &DL = Phi->getModule()->getDataLayout();
  481. int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
  482. if (!Size)
  483. return false;
  484. int64_t CVSize = CV->getSExtValue();
  485. if (CVSize % Size)
  486. return false;
  487. auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
  488. D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
  489. return true;
  490. }
  491. /// \brief Returns the instructions that use values defined in the loop.
  492. SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
  493. SmallVector<Instruction *, 8> UsedOutside;
  494. for (auto *Block : L->getBlocks())
  495. // FIXME: I believe that this could use copy_if if the Inst reference could
  496. // be adapted into a pointer.
  497. for (auto &Inst : *Block) {
  498. auto Users = Inst.users();
  499. if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
  500. auto *Use = cast<Instruction>(U);
  501. return !L->contains(Use->getParent());
  502. }))
  503. UsedOutside.push_back(&Inst);
  504. }
  505. return UsedOutside;
  506. }