LoopRerollPass.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===//
  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 pass implements a simple loop reroller.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/MapVector.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallBitVector.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/AliasSetTracker.h"
  21. #include "llvm/Analysis/LoopPass.h"
  22. #include "llvm/Analysis/ScalarEvolution.h"
  23. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  24. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. #include "llvm/Transforms/Utils/LoopUtils.h"
  36. using namespace llvm;
  37. #define DEBUG_TYPE "loop-reroll"
  38. STATISTIC(NumRerolledLoops, "Number of rerolled loops");
  39. static cl::opt<unsigned>
  40. MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
  41. cl::desc("The maximum increment for loop rerolling"));
  42. static cl::opt<unsigned>
  43. NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
  44. cl::Hidden,
  45. cl::desc("The maximum number of failures to tolerate"
  46. " during fuzzy matching. (default: 400)"));
  47. // This loop re-rolling transformation aims to transform loops like this:
  48. //
  49. // int foo(int a);
  50. // void bar(int *x) {
  51. // for (int i = 0; i < 500; i += 3) {
  52. // foo(i);
  53. // foo(i+1);
  54. // foo(i+2);
  55. // }
  56. // }
  57. //
  58. // into a loop like this:
  59. //
  60. // void bar(int *x) {
  61. // for (int i = 0; i < 500; ++i)
  62. // foo(i);
  63. // }
  64. //
  65. // It does this by looking for loops that, besides the latch code, are composed
  66. // of isomorphic DAGs of instructions, with each DAG rooted at some increment
  67. // to the induction variable, and where each DAG is isomorphic to the DAG
  68. // rooted at the induction variable (excepting the sub-DAGs which root the
  69. // other induction-variable increments). In other words, we're looking for loop
  70. // bodies of the form:
  71. //
  72. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  73. // f(%iv)
  74. // %iv.1 = add %iv, 1 <-- a root increment
  75. // f(%iv.1)
  76. // %iv.2 = add %iv, 2 <-- a root increment
  77. // f(%iv.2)
  78. // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
  79. // f(%iv.scale_m_1)
  80. // ...
  81. // %iv.next = add %iv, scale
  82. // %cmp = icmp(%iv, ...)
  83. // br %cmp, header, exit
  84. //
  85. // where each f(i) is a set of instructions that, collectively, are a function
  86. // only of i (and other loop-invariant values).
  87. //
  88. // As a special case, we can also reroll loops like this:
  89. //
  90. // int foo(int);
  91. // void bar(int *x) {
  92. // for (int i = 0; i < 500; ++i) {
  93. // x[3*i] = foo(0);
  94. // x[3*i+1] = foo(0);
  95. // x[3*i+2] = foo(0);
  96. // }
  97. // }
  98. //
  99. // into this:
  100. //
  101. // void bar(int *x) {
  102. // for (int i = 0; i < 1500; ++i)
  103. // x[i] = foo(0);
  104. // }
  105. //
  106. // in which case, we're looking for inputs like this:
  107. //
  108. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  109. // %scaled.iv = mul %iv, scale
  110. // f(%scaled.iv)
  111. // %scaled.iv.1 = add %scaled.iv, 1
  112. // f(%scaled.iv.1)
  113. // %scaled.iv.2 = add %scaled.iv, 2
  114. // f(%scaled.iv.2)
  115. // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
  116. // f(%scaled.iv.scale_m_1)
  117. // ...
  118. // %iv.next = add %iv, 1
  119. // %cmp = icmp(%iv, ...)
  120. // br %cmp, header, exit
  121. namespace {
  122. enum IterationLimits {
  123. /// The maximum number of iterations that we'll try and reroll. This
  124. /// has to be less than 25 in order to fit into a SmallBitVector.
  125. IL_MaxRerollIterations = 16,
  126. /// The bitvector index used by loop induction variables and other
  127. /// instructions that belong to all iterations.
  128. IL_All,
  129. IL_End
  130. };
  131. class LoopReroll : public LoopPass {
  132. public:
  133. static char ID; // Pass ID, replacement for typeid
  134. LoopReroll() : LoopPass(ID) {
  135. initializeLoopRerollPass(*PassRegistry::getPassRegistry());
  136. }
  137. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  138. void getAnalysisUsage(AnalysisUsage &AU) const override {
  139. AU.addRequired<AliasAnalysis>();
  140. AU.addRequired<LoopInfoWrapperPass>();
  141. AU.addPreserved<LoopInfoWrapperPass>();
  142. AU.addRequired<DominatorTreeWrapperPass>();
  143. AU.addPreserved<DominatorTreeWrapperPass>();
  144. AU.addRequired<ScalarEvolution>();
  145. AU.addRequired<TargetLibraryInfoWrapperPass>();
  146. }
  147. protected:
  148. AliasAnalysis *AA;
  149. LoopInfo *LI;
  150. ScalarEvolution *SE;
  151. TargetLibraryInfo *TLI;
  152. DominatorTree *DT;
  153. typedef SmallVector<Instruction *, 16> SmallInstructionVector;
  154. typedef SmallSet<Instruction *, 16> SmallInstructionSet;
  155. // A chain of isomorphic instructions, indentified by a single-use PHI,
  156. // representing a reduction. Only the last value may be used outside the
  157. // loop.
  158. struct SimpleLoopReduction {
  159. SimpleLoopReduction(Instruction *P, Loop *L)
  160. : Valid(false), Instructions(1, P) {
  161. assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
  162. add(L);
  163. }
  164. bool valid() const {
  165. return Valid;
  166. }
  167. Instruction *getPHI() const {
  168. assert(Valid && "Using invalid reduction");
  169. return Instructions.front();
  170. }
  171. Instruction *getReducedValue() const {
  172. assert(Valid && "Using invalid reduction");
  173. return Instructions.back();
  174. }
  175. Instruction *get(size_t i) const {
  176. assert(Valid && "Using invalid reduction");
  177. return Instructions[i+1];
  178. }
  179. Instruction *operator [] (size_t i) const { return get(i); }
  180. // The size, ignoring the initial PHI.
  181. size_t size() const {
  182. assert(Valid && "Using invalid reduction");
  183. return Instructions.size()-1;
  184. }
  185. typedef SmallInstructionVector::iterator iterator;
  186. typedef SmallInstructionVector::const_iterator const_iterator;
  187. iterator begin() {
  188. assert(Valid && "Using invalid reduction");
  189. return std::next(Instructions.begin());
  190. }
  191. const_iterator begin() const {
  192. assert(Valid && "Using invalid reduction");
  193. return std::next(Instructions.begin());
  194. }
  195. iterator end() { return Instructions.end(); }
  196. const_iterator end() const { return Instructions.end(); }
  197. protected:
  198. bool Valid;
  199. SmallInstructionVector Instructions;
  200. void add(Loop *L);
  201. };
  202. // The set of all reductions, and state tracking of possible reductions
  203. // during loop instruction processing.
  204. struct ReductionTracker {
  205. typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
  206. // Add a new possible reduction.
  207. void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
  208. // Setup to track possible reductions corresponding to the provided
  209. // rerolling scale. Only reductions with a number of non-PHI instructions
  210. // that is divisible by the scale are considered. Three instructions sets
  211. // are filled in:
  212. // - A set of all possible instructions in eligible reductions.
  213. // - A set of all PHIs in eligible reductions
  214. // - A set of all reduced values (last instructions) in eligible
  215. // reductions.
  216. void restrictToScale(uint64_t Scale,
  217. SmallInstructionSet &PossibleRedSet,
  218. SmallInstructionSet &PossibleRedPHISet,
  219. SmallInstructionSet &PossibleRedLastSet) {
  220. PossibleRedIdx.clear();
  221. PossibleRedIter.clear();
  222. Reds.clear();
  223. for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
  224. if (PossibleReds[i].size() % Scale == 0) {
  225. PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
  226. PossibleRedPHISet.insert(PossibleReds[i].getPHI());
  227. PossibleRedSet.insert(PossibleReds[i].getPHI());
  228. PossibleRedIdx[PossibleReds[i].getPHI()] = i;
  229. for (Instruction *J : PossibleReds[i]) {
  230. PossibleRedSet.insert(J);
  231. PossibleRedIdx[J] = i;
  232. }
  233. }
  234. }
  235. // The functions below are used while processing the loop instructions.
  236. // Are the two instructions both from reductions, and furthermore, from
  237. // the same reduction?
  238. bool isPairInSame(Instruction *J1, Instruction *J2) {
  239. DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
  240. if (J1I != PossibleRedIdx.end()) {
  241. DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
  242. if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
  243. return true;
  244. }
  245. return false;
  246. }
  247. // The two provided instructions, the first from the base iteration, and
  248. // the second from iteration i, form a matched pair. If these are part of
  249. // a reduction, record that fact.
  250. void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
  251. if (PossibleRedIdx.count(J1)) {
  252. assert(PossibleRedIdx.count(J2) &&
  253. "Recording reduction vs. non-reduction instruction?");
  254. PossibleRedIter[J1] = 0;
  255. PossibleRedIter[J2] = i;
  256. int Idx = PossibleRedIdx[J1];
  257. assert(Idx == PossibleRedIdx[J2] &&
  258. "Recording pair from different reductions?");
  259. Reds.insert(Idx);
  260. }
  261. }
  262. // The functions below can be called after we've finished processing all
  263. // instructions in the loop, and we know which reductions were selected.
  264. // Is the provided instruction the PHI of a reduction selected for
  265. // rerolling?
  266. bool isSelectedPHI(Instruction *J) {
  267. if (!isa<PHINode>(J))
  268. return false;
  269. for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
  270. RI != RIE; ++RI) {
  271. int i = *RI;
  272. if (cast<Instruction>(J) == PossibleReds[i].getPHI())
  273. return true;
  274. }
  275. return false;
  276. }
  277. bool validateSelected();
  278. void replaceSelected();
  279. protected:
  280. // The vector of all possible reductions (for any scale).
  281. SmallReductionVector PossibleReds;
  282. DenseMap<Instruction *, int> PossibleRedIdx;
  283. DenseMap<Instruction *, int> PossibleRedIter;
  284. DenseSet<int> Reds;
  285. };
  286. // A DAGRootSet models an induction variable being used in a rerollable
  287. // loop. For example,
  288. //
  289. // x[i*3+0] = y1
  290. // x[i*3+1] = y2
  291. // x[i*3+2] = y3
  292. //
  293. // Base instruction -> i*3
  294. // +---+----+
  295. // / | \
  296. // ST[y1] +1 +2 <-- Roots
  297. // | |
  298. // ST[y2] ST[y3]
  299. //
  300. // There may be multiple DAGRoots, for example:
  301. //
  302. // x[i*2+0] = ... (1)
  303. // x[i*2+1] = ... (1)
  304. // x[i*2+4] = ... (2)
  305. // x[i*2+5] = ... (2)
  306. // x[(i+1234)*2+5678] = ... (3)
  307. // x[(i+1234)*2+5679] = ... (3)
  308. //
  309. // The loop will be rerolled by adding a new loop induction variable,
  310. // one for the Base instruction in each DAGRootSet.
  311. //
  312. struct DAGRootSet {
  313. Instruction *BaseInst;
  314. SmallInstructionVector Roots;
  315. // The instructions between IV and BaseInst (but not including BaseInst).
  316. SmallInstructionSet SubsumedInsts;
  317. };
  318. // The set of all DAG roots, and state tracking of all roots
  319. // for a particular induction variable.
  320. struct DAGRootTracker {
  321. DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
  322. ScalarEvolution *SE, AliasAnalysis *AA,
  323. TargetLibraryInfo *TLI)
  324. : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV) {}
  325. /// Stage 1: Find all the DAG roots for the induction variable.
  326. bool findRoots();
  327. /// Stage 2: Validate if the found roots are valid.
  328. bool validate(ReductionTracker &Reductions);
  329. /// Stage 3: Assuming validate() returned true, perform the
  330. /// replacement.
  331. /// @param IterCount The maximum iteration count of L.
  332. void replace(const SCEV *IterCount);
  333. protected:
  334. typedef MapVector<Instruction*, SmallBitVector> UsesTy;
  335. bool findRootsRecursive(Instruction *IVU,
  336. SmallInstructionSet SubsumedInsts);
  337. bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
  338. bool collectPossibleRoots(Instruction *Base,
  339. std::map<int64_t,Instruction*> &Roots);
  340. bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
  341. void collectInLoopUserSet(const SmallInstructionVector &Roots,
  342. const SmallInstructionSet &Exclude,
  343. const SmallInstructionSet &Final,
  344. DenseSet<Instruction *> &Users);
  345. void collectInLoopUserSet(Instruction *Root,
  346. const SmallInstructionSet &Exclude,
  347. const SmallInstructionSet &Final,
  348. DenseSet<Instruction *> &Users);
  349. UsesTy::iterator nextInstr(int Val, UsesTy &In,
  350. const SmallInstructionSet &Exclude,
  351. UsesTy::iterator *StartI=nullptr);
  352. bool isBaseInst(Instruction *I);
  353. bool isRootInst(Instruction *I);
  354. bool instrDependsOn(Instruction *I,
  355. UsesTy::iterator Start,
  356. UsesTy::iterator End);
  357. LoopReroll *Parent;
  358. // Members of Parent, replicated here for brevity.
  359. Loop *L;
  360. ScalarEvolution *SE;
  361. AliasAnalysis *AA;
  362. TargetLibraryInfo *TLI;
  363. // The loop induction variable.
  364. Instruction *IV;
  365. // Loop step amount.
  366. uint64_t Inc;
  367. // Loop reroll count; if Inc == 1, this records the scaling applied
  368. // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
  369. // If Inc is not 1, Scale = Inc.
  370. uint64_t Scale;
  371. // The roots themselves.
  372. SmallVector<DAGRootSet,16> RootSets;
  373. // All increment instructions for IV.
  374. SmallInstructionVector LoopIncs;
  375. // Map of all instructions in the loop (in order) to the iterations
  376. // they are used in (or specially, IL_All for instructions
  377. // used in the loop increment mechanism).
  378. UsesTy Uses;
  379. };
  380. void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
  381. void collectPossibleReductions(Loop *L,
  382. ReductionTracker &Reductions);
  383. bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
  384. ReductionTracker &Reductions);
  385. };
  386. }
  387. char LoopReroll::ID = 0;
  388. INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
  389. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  390. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  391. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  392. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  393. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  394. INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
  395. Pass *llvm::createLoopRerollPass() {
  396. return new LoopReroll;
  397. }
  398. // Returns true if the provided instruction is used outside the given loop.
  399. // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
  400. // non-loop blocks to be outside the loop.
  401. static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
  402. for (User *U : I->users()) {
  403. if (!L->contains(cast<Instruction>(U)))
  404. return true;
  405. }
  406. return false;
  407. }
  408. // Collect the list of loop induction variables with respect to which it might
  409. // be possible to reroll the loop.
  410. void LoopReroll::collectPossibleIVs(Loop *L,
  411. SmallInstructionVector &PossibleIVs) {
  412. BasicBlock *Header = L->getHeader();
  413. for (BasicBlock::iterator I = Header->begin(),
  414. IE = Header->getFirstInsertionPt(); I != IE; ++I) {
  415. if (!isa<PHINode>(I))
  416. continue;
  417. if (!I->getType()->isIntegerTy())
  418. continue;
  419. if (const SCEVAddRecExpr *PHISCEV =
  420. dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
  421. if (PHISCEV->getLoop() != L)
  422. continue;
  423. if (!PHISCEV->isAffine())
  424. continue;
  425. if (const SCEVConstant *IncSCEV =
  426. dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
  427. if (!IncSCEV->getValue()->getValue().isStrictlyPositive())
  428. continue;
  429. if (IncSCEV->getValue()->uge(MaxInc))
  430. continue;
  431. DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " <<
  432. *PHISCEV << "\n");
  433. PossibleIVs.push_back(I);
  434. }
  435. }
  436. }
  437. }
  438. // Add the remainder of the reduction-variable chain to the instruction vector
  439. // (the initial PHINode has already been added). If successful, the object is
  440. // marked as valid.
  441. void LoopReroll::SimpleLoopReduction::add(Loop *L) {
  442. assert(!Valid && "Cannot add to an already-valid chain");
  443. // The reduction variable must be a chain of single-use instructions
  444. // (including the PHI), except for the last value (which is used by the PHI
  445. // and also outside the loop).
  446. Instruction *C = Instructions.front();
  447. if (C->user_empty())
  448. return;
  449. do {
  450. C = cast<Instruction>(*C->user_begin());
  451. if (C->hasOneUse()) {
  452. if (!C->isBinaryOp())
  453. return;
  454. if (!(isa<PHINode>(Instructions.back()) ||
  455. C->isSameOperationAs(Instructions.back())))
  456. return;
  457. Instructions.push_back(C);
  458. }
  459. } while (C->hasOneUse());
  460. if (Instructions.size() < 2 ||
  461. !C->isSameOperationAs(Instructions.back()) ||
  462. C->use_empty())
  463. return;
  464. // C is now the (potential) last instruction in the reduction chain.
  465. for (User *U : C->users()) {
  466. // The only in-loop user can be the initial PHI.
  467. if (L->contains(cast<Instruction>(U)))
  468. if (cast<Instruction>(U) != Instructions.front())
  469. return;
  470. }
  471. Instructions.push_back(C);
  472. Valid = true;
  473. }
  474. // Collect the vector of possible reduction variables.
  475. void LoopReroll::collectPossibleReductions(Loop *L,
  476. ReductionTracker &Reductions) {
  477. BasicBlock *Header = L->getHeader();
  478. for (BasicBlock::iterator I = Header->begin(),
  479. IE = Header->getFirstInsertionPt(); I != IE; ++I) {
  480. if (!isa<PHINode>(I))
  481. continue;
  482. if (!I->getType()->isSingleValueType())
  483. continue;
  484. SimpleLoopReduction SLR(I, L);
  485. if (!SLR.valid())
  486. continue;
  487. DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
  488. SLR.size() << " chained instructions)\n");
  489. Reductions.addSLR(SLR);
  490. }
  491. }
  492. // Collect the set of all users of the provided root instruction. This set of
  493. // users contains not only the direct users of the root instruction, but also
  494. // all users of those users, and so on. There are two exceptions:
  495. //
  496. // 1. Instructions in the set of excluded instructions are never added to the
  497. // use set (even if they are users). This is used, for example, to exclude
  498. // including root increments in the use set of the primary IV.
  499. //
  500. // 2. Instructions in the set of final instructions are added to the use set
  501. // if they are users, but their users are not added. This is used, for
  502. // example, to prevent a reduction update from forcing all later reduction
  503. // updates into the use set.
  504. void LoopReroll::DAGRootTracker::collectInLoopUserSet(
  505. Instruction *Root, const SmallInstructionSet &Exclude,
  506. const SmallInstructionSet &Final,
  507. DenseSet<Instruction *> &Users) {
  508. SmallInstructionVector Queue(1, Root);
  509. while (!Queue.empty()) {
  510. Instruction *I = Queue.pop_back_val();
  511. if (!Users.insert(I).second)
  512. continue;
  513. if (!Final.count(I))
  514. for (Use &U : I->uses()) {
  515. Instruction *User = cast<Instruction>(U.getUser());
  516. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  517. // Ignore "wrap-around" uses to PHIs of this loop's header.
  518. if (PN->getIncomingBlock(U) == L->getHeader())
  519. continue;
  520. }
  521. if (L->contains(User) && !Exclude.count(User)) {
  522. Queue.push_back(User);
  523. }
  524. }
  525. // We also want to collect single-user "feeder" values.
  526. for (User::op_iterator OI = I->op_begin(),
  527. OIE = I->op_end(); OI != OIE; ++OI) {
  528. if (Instruction *Op = dyn_cast<Instruction>(*OI))
  529. if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
  530. !Final.count(Op))
  531. Queue.push_back(Op);
  532. }
  533. }
  534. }
  535. // Collect all of the users of all of the provided root instructions (combined
  536. // into a single set).
  537. void LoopReroll::DAGRootTracker::collectInLoopUserSet(
  538. const SmallInstructionVector &Roots,
  539. const SmallInstructionSet &Exclude,
  540. const SmallInstructionSet &Final,
  541. DenseSet<Instruction *> &Users) {
  542. for (SmallInstructionVector::const_iterator I = Roots.begin(),
  543. IE = Roots.end(); I != IE; ++I)
  544. collectInLoopUserSet(*I, Exclude, Final, Users);
  545. }
  546. static bool isSimpleLoadStore(Instruction *I) {
  547. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  548. return LI->isSimple();
  549. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  550. return SI->isSimple();
  551. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  552. return !MI->isVolatile();
  553. return false;
  554. }
  555. /// Return true if IVU is a "simple" arithmetic operation.
  556. /// This is used for narrowing the search space for DAGRoots; only arithmetic
  557. /// and GEPs can be part of a DAGRoot.
  558. static bool isSimpleArithmeticOp(User *IVU) {
  559. if (Instruction *I = dyn_cast<Instruction>(IVU)) {
  560. switch (I->getOpcode()) {
  561. default: return false;
  562. case Instruction::Add:
  563. case Instruction::Sub:
  564. case Instruction::Mul:
  565. case Instruction::Shl:
  566. case Instruction::AShr:
  567. case Instruction::LShr:
  568. case Instruction::GetElementPtr:
  569. case Instruction::Trunc:
  570. case Instruction::ZExt:
  571. case Instruction::SExt:
  572. return true;
  573. }
  574. }
  575. return false;
  576. }
  577. static bool isLoopIncrement(User *U, Instruction *IV) {
  578. BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
  579. if (!BO || BO->getOpcode() != Instruction::Add)
  580. return false;
  581. for (auto *UU : BO->users()) {
  582. PHINode *PN = dyn_cast<PHINode>(UU);
  583. if (PN && PN == IV)
  584. return true;
  585. }
  586. return false;
  587. }
  588. bool LoopReroll::DAGRootTracker::
  589. collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
  590. SmallInstructionVector BaseUsers;
  591. for (auto *I : Base->users()) {
  592. ConstantInt *CI = nullptr;
  593. if (isLoopIncrement(I, IV)) {
  594. LoopIncs.push_back(cast<Instruction>(I));
  595. continue;
  596. }
  597. // The root nodes must be either GEPs, ORs or ADDs.
  598. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  599. if (BO->getOpcode() == Instruction::Add ||
  600. BO->getOpcode() == Instruction::Or)
  601. CI = dyn_cast<ConstantInt>(BO->getOperand(1));
  602. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  603. Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
  604. CI = dyn_cast<ConstantInt>(LastOperand);
  605. }
  606. if (!CI) {
  607. if (Instruction *II = dyn_cast<Instruction>(I)) {
  608. BaseUsers.push_back(II);
  609. continue;
  610. } else {
  611. DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
  612. return false;
  613. }
  614. }
  615. int64_t V = CI->getValue().getSExtValue();
  616. if (Roots.find(V) != Roots.end())
  617. // No duplicates, please.
  618. return false;
  619. // FIXME: Add support for negative values.
  620. if (V < 0) {
  621. DEBUG(dbgs() << "LRR: Aborting due to negative value: " << V << "\n");
  622. return false;
  623. }
  624. Roots[V] = cast<Instruction>(I);
  625. }
  626. if (Roots.empty())
  627. return false;
  628. // If we found non-loop-inc, non-root users of Base, assume they are
  629. // for the zeroth root index. This is because "add %a, 0" gets optimized
  630. // away.
  631. if (BaseUsers.size()) {
  632. if (Roots.find(0) != Roots.end()) {
  633. DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
  634. return false;
  635. }
  636. Roots[0] = Base;
  637. }
  638. // Calculate the number of users of the base, or lowest indexed, iteration.
  639. unsigned NumBaseUses = BaseUsers.size();
  640. if (NumBaseUses == 0)
  641. NumBaseUses = Roots.begin()->second->getNumUses();
  642. // Check that every node has the same number of users.
  643. for (auto &KV : Roots) {
  644. if (KV.first == 0)
  645. continue;
  646. if (KV.second->getNumUses() != NumBaseUses) {
  647. DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
  648. << "#Base=" << NumBaseUses << ", #Root=" <<
  649. KV.second->getNumUses() << "\n");
  650. return false;
  651. }
  652. }
  653. return true;
  654. }
  655. bool LoopReroll::DAGRootTracker::
  656. findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
  657. // Does the user look like it could be part of a root set?
  658. // All its users must be simple arithmetic ops.
  659. if (I->getNumUses() > IL_MaxRerollIterations)
  660. return false;
  661. if ((I->getOpcode() == Instruction::Mul ||
  662. I->getOpcode() == Instruction::PHI) &&
  663. I != IV &&
  664. findRootsBase(I, SubsumedInsts))
  665. return true;
  666. SubsumedInsts.insert(I);
  667. for (User *V : I->users()) {
  668. Instruction *I = dyn_cast<Instruction>(V);
  669. if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
  670. continue;
  671. if (!I || !isSimpleArithmeticOp(I) ||
  672. !findRootsRecursive(I, SubsumedInsts))
  673. return false;
  674. }
  675. return true;
  676. }
  677. bool LoopReroll::DAGRootTracker::
  678. findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
  679. // The base instruction needs to be a multiply so
  680. // that we can erase it.
  681. if (IVU->getOpcode() != Instruction::Mul &&
  682. IVU->getOpcode() != Instruction::PHI)
  683. return false;
  684. std::map<int64_t, Instruction*> V;
  685. if (!collectPossibleRoots(IVU, V))
  686. return false;
  687. // If we didn't get a root for index zero, then IVU must be
  688. // subsumed.
  689. if (V.find(0) == V.end())
  690. SubsumedInsts.insert(IVU);
  691. // Partition the vector into monotonically increasing indexes.
  692. DAGRootSet DRS;
  693. DRS.BaseInst = nullptr;
  694. for (auto &KV : V) {
  695. if (!DRS.BaseInst) {
  696. DRS.BaseInst = KV.second;
  697. DRS.SubsumedInsts = SubsumedInsts;
  698. } else if (DRS.Roots.empty()) {
  699. DRS.Roots.push_back(KV.second);
  700. } else if (V.find(KV.first - 1) != V.end()) {
  701. DRS.Roots.push_back(KV.second);
  702. } else {
  703. // Linear sequence terminated.
  704. RootSets.push_back(DRS);
  705. DRS.BaseInst = KV.second;
  706. DRS.SubsumedInsts = SubsumedInsts;
  707. DRS.Roots.clear();
  708. }
  709. }
  710. RootSets.push_back(DRS);
  711. return true;
  712. }
  713. bool LoopReroll::DAGRootTracker::findRoots() {
  714. const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(IV));
  715. Inc = cast<SCEVConstant>(RealIVSCEV->getOperand(1))->
  716. getValue()->getZExtValue();
  717. assert(RootSets.empty() && "Unclean state!");
  718. if (Inc == 1) {
  719. for (auto *IVU : IV->users()) {
  720. if (isLoopIncrement(IVU, IV))
  721. LoopIncs.push_back(cast<Instruction>(IVU));
  722. }
  723. if (!findRootsRecursive(IV, SmallInstructionSet()))
  724. return false;
  725. LoopIncs.push_back(IV);
  726. } else {
  727. if (!findRootsBase(IV, SmallInstructionSet()))
  728. return false;
  729. }
  730. // Ensure all sets have the same size.
  731. if (RootSets.empty()) {
  732. DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
  733. return false;
  734. }
  735. for (auto &V : RootSets) {
  736. if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
  737. DEBUG(dbgs()
  738. << "LRR: Aborting because not all root sets have the same size\n");
  739. return false;
  740. }
  741. }
  742. // And ensure all loop iterations are consecutive. We rely on std::map
  743. // providing ordered traversal.
  744. for (auto &V : RootSets) {
  745. const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
  746. if (!ADR)
  747. return false;
  748. // Consider a DAGRootSet with N-1 roots (so N different values including
  749. // BaseInst).
  750. // Define d = Roots[0] - BaseInst, which should be the same as
  751. // Roots[I] - Roots[I-1] for all I in [1..N).
  752. // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
  753. // loop iteration J.
  754. //
  755. // Now, For the loop iterations to be consecutive:
  756. // D = d * N
  757. unsigned N = V.Roots.size() + 1;
  758. const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
  759. const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
  760. if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
  761. DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
  762. return false;
  763. }
  764. }
  765. Scale = RootSets[0].Roots.size() + 1;
  766. if (Scale > IL_MaxRerollIterations) {
  767. DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
  768. << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
  769. << "\n");
  770. return false;
  771. }
  772. DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
  773. return true;
  774. }
  775. bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
  776. // Populate the MapVector with all instructions in the block, in order first,
  777. // so we can iterate over the contents later in perfect order.
  778. for (auto &I : *L->getHeader()) {
  779. Uses[&I].resize(IL_End);
  780. }
  781. SmallInstructionSet Exclude;
  782. for (auto &DRS : RootSets) {
  783. Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
  784. Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
  785. Exclude.insert(DRS.BaseInst);
  786. }
  787. Exclude.insert(LoopIncs.begin(), LoopIncs.end());
  788. for (auto &DRS : RootSets) {
  789. DenseSet<Instruction*> VBase;
  790. collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
  791. for (auto *I : VBase) {
  792. Uses[I].set(0);
  793. }
  794. unsigned Idx = 1;
  795. for (auto *Root : DRS.Roots) {
  796. DenseSet<Instruction*> V;
  797. collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
  798. // While we're here, check the use sets are the same size.
  799. if (V.size() != VBase.size()) {
  800. DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
  801. return false;
  802. }
  803. for (auto *I : V) {
  804. Uses[I].set(Idx);
  805. }
  806. ++Idx;
  807. }
  808. // Make sure our subsumed instructions are remembered too.
  809. for (auto *I : DRS.SubsumedInsts) {
  810. Uses[I].set(IL_All);
  811. }
  812. }
  813. // Make sure the loop increments are also accounted for.
  814. Exclude.clear();
  815. for (auto &DRS : RootSets) {
  816. Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
  817. Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
  818. Exclude.insert(DRS.BaseInst);
  819. }
  820. DenseSet<Instruction*> V;
  821. collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
  822. for (auto *I : V) {
  823. Uses[I].set(IL_All);
  824. }
  825. return true;
  826. }
  827. /// Get the next instruction in "In" that is a member of set Val.
  828. /// Start searching from StartI, and do not return anything in Exclude.
  829. /// If StartI is not given, start from In.begin().
  830. LoopReroll::DAGRootTracker::UsesTy::iterator
  831. LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
  832. const SmallInstructionSet &Exclude,
  833. UsesTy::iterator *StartI) {
  834. UsesTy::iterator I = StartI ? *StartI : In.begin();
  835. while (I != In.end() && (I->second.test(Val) == 0 ||
  836. Exclude.count(I->first) != 0))
  837. ++I;
  838. return I;
  839. }
  840. bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
  841. for (auto &DRS : RootSets) {
  842. if (DRS.BaseInst == I)
  843. return true;
  844. }
  845. return false;
  846. }
  847. bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
  848. for (auto &DRS : RootSets) {
  849. if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
  850. return true;
  851. }
  852. return false;
  853. }
  854. /// Return true if instruction I depends on any instruction between
  855. /// Start and End.
  856. bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
  857. UsesTy::iterator Start,
  858. UsesTy::iterator End) {
  859. for (auto *U : I->users()) {
  860. for (auto It = Start; It != End; ++It)
  861. if (U == It->first)
  862. return true;
  863. }
  864. return false;
  865. }
  866. bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
  867. // We now need to check for equivalence of the use graph of each root with
  868. // that of the primary induction variable (excluding the roots). Our goal
  869. // here is not to solve the full graph isomorphism problem, but rather to
  870. // catch common cases without a lot of work. As a result, we will assume
  871. // that the relative order of the instructions in each unrolled iteration
  872. // is the same (although we will not make an assumption about how the
  873. // different iterations are intermixed). Note that while the order must be
  874. // the same, the instructions may not be in the same basic block.
  875. // An array of just the possible reductions for this scale factor. When we
  876. // collect the set of all users of some root instructions, these reduction
  877. // instructions are treated as 'final' (their uses are not considered).
  878. // This is important because we don't want the root use set to search down
  879. // the reduction chain.
  880. SmallInstructionSet PossibleRedSet;
  881. SmallInstructionSet PossibleRedLastSet;
  882. SmallInstructionSet PossibleRedPHISet;
  883. Reductions.restrictToScale(Scale, PossibleRedSet,
  884. PossibleRedPHISet, PossibleRedLastSet);
  885. // Populate "Uses" with where each instruction is used.
  886. if (!collectUsedInstructions(PossibleRedSet))
  887. return false;
  888. // Make sure we mark the reduction PHIs as used in all iterations.
  889. for (auto *I : PossibleRedPHISet) {
  890. Uses[I].set(IL_All);
  891. }
  892. // Make sure all instructions in the loop are in one and only one
  893. // set.
  894. for (auto &KV : Uses) {
  895. if (KV.second.count() != 1) {
  896. DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
  897. << *KV.first << " (#uses=" << KV.second.count() << ")\n");
  898. return false;
  899. }
  900. }
  901. DEBUG(
  902. for (auto &KV : Uses) {
  903. dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
  904. }
  905. );
  906. for (unsigned Iter = 1; Iter < Scale; ++Iter) {
  907. // In addition to regular aliasing information, we need to look for
  908. // instructions from later (future) iterations that have side effects
  909. // preventing us from reordering them past other instructions with side
  910. // effects.
  911. bool FutureSideEffects = false;
  912. AliasSetTracker AST(*AA);
  913. // The map between instructions in f(%iv.(i+1)) and f(%iv).
  914. DenseMap<Value *, Value *> BaseMap;
  915. // Compare iteration Iter to the base.
  916. SmallInstructionSet Visited;
  917. auto BaseIt = nextInstr(0, Uses, Visited);
  918. auto RootIt = nextInstr(Iter, Uses, Visited);
  919. auto LastRootIt = Uses.begin();
  920. while (BaseIt != Uses.end() && RootIt != Uses.end()) {
  921. Instruction *BaseInst = BaseIt->first;
  922. Instruction *RootInst = RootIt->first;
  923. // Skip over the IV or root instructions; only match their users.
  924. bool Continue = false;
  925. if (isBaseInst(BaseInst)) {
  926. Visited.insert(BaseInst);
  927. BaseIt = nextInstr(0, Uses, Visited);
  928. Continue = true;
  929. }
  930. if (isRootInst(RootInst)) {
  931. LastRootIt = RootIt;
  932. Visited.insert(RootInst);
  933. RootIt = nextInstr(Iter, Uses, Visited);
  934. Continue = true;
  935. }
  936. if (Continue) continue;
  937. if (!BaseInst->isSameOperationAs(RootInst)) {
  938. // Last chance saloon. We don't try and solve the full isomorphism
  939. // problem, but try and at least catch the case where two instructions
  940. // *of different types* are round the wrong way. We won't be able to
  941. // efficiently tell, given two ADD instructions, which way around we
  942. // should match them, but given an ADD and a SUB, we can at least infer
  943. // which one is which.
  944. //
  945. // This should allow us to deal with a greater subset of the isomorphism
  946. // problem. It does however change a linear algorithm into a quadratic
  947. // one, so limit the number of probes we do.
  948. auto TryIt = RootIt;
  949. unsigned N = NumToleratedFailedMatches;
  950. while (TryIt != Uses.end() &&
  951. !BaseInst->isSameOperationAs(TryIt->first) &&
  952. N--) {
  953. ++TryIt;
  954. TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
  955. }
  956. if (TryIt == Uses.end() || TryIt == RootIt ||
  957. instrDependsOn(TryIt->first, RootIt, TryIt)) {
  958. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
  959. " vs. " << *RootInst << "\n");
  960. return false;
  961. }
  962. RootIt = TryIt;
  963. RootInst = TryIt->first;
  964. }
  965. // All instructions between the last root and this root
  966. // may belong to some other iteration. If they belong to a
  967. // future iteration, then they're dangerous to alias with.
  968. //
  969. // Note that because we allow a limited amount of flexibility in the order
  970. // that we visit nodes, LastRootIt might be *before* RootIt, in which
  971. // case we've already checked this set of instructions so we shouldn't
  972. // do anything.
  973. for (; LastRootIt < RootIt; ++LastRootIt) {
  974. Instruction *I = LastRootIt->first;
  975. if (LastRootIt->second.find_first() < (int)Iter)
  976. continue;
  977. if (I->mayWriteToMemory())
  978. AST.add(I);
  979. // Note: This is specifically guarded by a check on isa<PHINode>,
  980. // which while a valid (somewhat arbitrary) micro-optimization, is
  981. // needed because otherwise isSafeToSpeculativelyExecute returns
  982. // false on PHI nodes.
  983. if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
  984. !isSafeToSpeculativelyExecute(I))
  985. // Intervening instructions cause side effects.
  986. FutureSideEffects = true;
  987. }
  988. // Make sure that this instruction, which is in the use set of this
  989. // root instruction, does not also belong to the base set or the set of
  990. // some other root instruction.
  991. if (RootIt->second.count() > 1) {
  992. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
  993. " vs. " << *RootInst << " (prev. case overlap)\n");
  994. return false;
  995. }
  996. // Make sure that we don't alias with any instruction in the alias set
  997. // tracker. If we do, then we depend on a future iteration, and we
  998. // can't reroll.
  999. if (RootInst->mayReadFromMemory())
  1000. for (auto &K : AST) {
  1001. if (K.aliasesUnknownInst(RootInst, *AA)) {
  1002. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
  1003. " vs. " << *RootInst << " (depends on future store)\n");
  1004. return false;
  1005. }
  1006. }
  1007. // If we've past an instruction from a future iteration that may have
  1008. // side effects, and this instruction might also, then we can't reorder
  1009. // them, and this matching fails. As an exception, we allow the alias
  1010. // set tracker to handle regular (simple) load/store dependencies.
  1011. if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
  1012. !isSafeToSpeculativelyExecute(BaseInst)) ||
  1013. (!isSimpleLoadStore(RootInst) &&
  1014. !isSafeToSpeculativelyExecute(RootInst)))) {
  1015. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
  1016. " vs. " << *RootInst <<
  1017. " (side effects prevent reordering)\n");
  1018. return false;
  1019. }
  1020. // For instructions that are part of a reduction, if the operation is
  1021. // associative, then don't bother matching the operands (because we
  1022. // already know that the instructions are isomorphic, and the order
  1023. // within the iteration does not matter). For non-associative reductions,
  1024. // we do need to match the operands, because we need to reject
  1025. // out-of-order instructions within an iteration!
  1026. // For example (assume floating-point addition), we need to reject this:
  1027. // x += a[i]; x += b[i];
  1028. // x += a[i+1]; x += b[i+1];
  1029. // x += b[i+2]; x += a[i+2];
  1030. bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
  1031. if (!(InReduction && BaseInst->isAssociative())) {
  1032. bool Swapped = false, SomeOpMatched = false;
  1033. for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
  1034. Value *Op2 = RootInst->getOperand(j);
  1035. // If this is part of a reduction (and the operation is not
  1036. // associatve), then we match all operands, but not those that are
  1037. // part of the reduction.
  1038. if (InReduction)
  1039. if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
  1040. if (Reductions.isPairInSame(RootInst, Op2I))
  1041. continue;
  1042. DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
  1043. if (BMI != BaseMap.end()) {
  1044. Op2 = BMI->second;
  1045. } else {
  1046. for (auto &DRS : RootSets) {
  1047. if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
  1048. Op2 = DRS.BaseInst;
  1049. break;
  1050. }
  1051. }
  1052. }
  1053. if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
  1054. // If we've not already decided to swap the matched operands, and
  1055. // we've not already matched our first operand (note that we could
  1056. // have skipped matching the first operand because it is part of a
  1057. // reduction above), and the instruction is commutative, then try
  1058. // the swapped match.
  1059. if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
  1060. BaseInst->getOperand(!j) == Op2) {
  1061. Swapped = true;
  1062. } else {
  1063. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
  1064. << " vs. " << *RootInst << " (operand " << j << ")\n");
  1065. return false;
  1066. }
  1067. }
  1068. SomeOpMatched = true;
  1069. }
  1070. }
  1071. if ((!PossibleRedLastSet.count(BaseInst) &&
  1072. hasUsesOutsideLoop(BaseInst, L)) ||
  1073. (!PossibleRedLastSet.count(RootInst) &&
  1074. hasUsesOutsideLoop(RootInst, L))) {
  1075. DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
  1076. " vs. " << *RootInst << " (uses outside loop)\n");
  1077. return false;
  1078. }
  1079. Reductions.recordPair(BaseInst, RootInst, Iter);
  1080. BaseMap.insert(std::make_pair(RootInst, BaseInst));
  1081. LastRootIt = RootIt;
  1082. Visited.insert(BaseInst);
  1083. Visited.insert(RootInst);
  1084. BaseIt = nextInstr(0, Uses, Visited);
  1085. RootIt = nextInstr(Iter, Uses, Visited);
  1086. }
  1087. assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
  1088. "Mismatched set sizes!");
  1089. }
  1090. DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
  1091. *IV << "\n");
  1092. return true;
  1093. }
  1094. void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
  1095. BasicBlock *Header = L->getHeader();
  1096. // Remove instructions associated with non-base iterations.
  1097. for (BasicBlock::reverse_iterator J = Header->rbegin();
  1098. J != Header->rend();) {
  1099. unsigned I = Uses[&*J].find_first();
  1100. if (I > 0 && I < IL_All) {
  1101. Instruction *D = &*J;
  1102. DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
  1103. D->eraseFromParent();
  1104. continue;
  1105. }
  1106. ++J;
  1107. }
  1108. const DataLayout &DL = Header->getModule()->getDataLayout();
  1109. // We need to create a new induction variable for each different BaseInst.
  1110. for (auto &DRS : RootSets) {
  1111. // Insert the new induction variable.
  1112. const SCEVAddRecExpr *RealIVSCEV =
  1113. cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
  1114. const SCEV *Start = RealIVSCEV->getStart();
  1115. const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>
  1116. (SE->getAddRecExpr(Start,
  1117. SE->getConstant(RealIVSCEV->getType(), 1),
  1118. L, SCEV::FlagAnyWrap));
  1119. { // Limit the lifetime of SCEVExpander.
  1120. SCEVExpander Expander(*SE, DL, "reroll");
  1121. Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
  1122. for (auto &KV : Uses) {
  1123. if (KV.second.find_first() == 0)
  1124. KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
  1125. }
  1126. if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
  1127. // FIXME: Why do we need this check?
  1128. if (Uses[BI].find_first() == IL_All) {
  1129. const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
  1130. // Iteration count SCEV minus 1
  1131. const SCEV *ICMinus1SCEV =
  1132. SE->getMinusSCEV(ICSCEV, SE->getConstant(ICSCEV->getType(), 1));
  1133. Value *ICMinus1; // Iteration count minus 1
  1134. if (isa<SCEVConstant>(ICMinus1SCEV)) {
  1135. ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
  1136. } else {
  1137. BasicBlock *Preheader = L->getLoopPreheader();
  1138. if (!Preheader)
  1139. Preheader = InsertPreheaderForLoop(L, Parent);
  1140. ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
  1141. Preheader->getTerminator());
  1142. }
  1143. Value *Cond =
  1144. new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
  1145. BI->setCondition(Cond);
  1146. if (BI->getSuccessor(1) != Header)
  1147. BI->swapSuccessors();
  1148. }
  1149. }
  1150. }
  1151. }
  1152. SimplifyInstructionsInBlock(Header, TLI);
  1153. DeleteDeadPHIs(Header, TLI);
  1154. }
  1155. // Validate the selected reductions. All iterations must have an isomorphic
  1156. // part of the reduction chain and, for non-associative reductions, the chain
  1157. // entries must appear in order.
  1158. bool LoopReroll::ReductionTracker::validateSelected() {
  1159. // For a non-associative reduction, the chain entries must appear in order.
  1160. for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
  1161. RI != RIE; ++RI) {
  1162. int i = *RI;
  1163. int PrevIter = 0, BaseCount = 0, Count = 0;
  1164. for (Instruction *J : PossibleReds[i]) {
  1165. // Note that all instructions in the chain must have been found because
  1166. // all instructions in the function must have been assigned to some
  1167. // iteration.
  1168. int Iter = PossibleRedIter[J];
  1169. if (Iter != PrevIter && Iter != PrevIter + 1 &&
  1170. !PossibleReds[i].getReducedValue()->isAssociative()) {
  1171. DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
  1172. J << "\n");
  1173. return false;
  1174. }
  1175. if (Iter != PrevIter) {
  1176. if (Count != BaseCount) {
  1177. DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
  1178. " reduction use count " << Count <<
  1179. " is not equal to the base use count " <<
  1180. BaseCount << "\n");
  1181. return false;
  1182. }
  1183. Count = 0;
  1184. }
  1185. ++Count;
  1186. if (Iter == 0)
  1187. ++BaseCount;
  1188. PrevIter = Iter;
  1189. }
  1190. }
  1191. return true;
  1192. }
  1193. // For all selected reductions, remove all parts except those in the first
  1194. // iteration (and the PHI). Replace outside uses of the reduced value with uses
  1195. // of the first-iteration reduced value (in other words, reroll the selected
  1196. // reductions).
  1197. void LoopReroll::ReductionTracker::replaceSelected() {
  1198. // Fixup reductions to refer to the last instruction associated with the
  1199. // first iteration (not the last).
  1200. for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
  1201. RI != RIE; ++RI) {
  1202. int i = *RI;
  1203. int j = 0;
  1204. for (int e = PossibleReds[i].size(); j != e; ++j)
  1205. if (PossibleRedIter[PossibleReds[i][j]] != 0) {
  1206. --j;
  1207. break;
  1208. }
  1209. // Replace users with the new end-of-chain value.
  1210. SmallInstructionVector Users;
  1211. for (User *U : PossibleReds[i].getReducedValue()->users()) {
  1212. Users.push_back(cast<Instruction>(U));
  1213. }
  1214. for (SmallInstructionVector::iterator J = Users.begin(),
  1215. JE = Users.end(); J != JE; ++J)
  1216. (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
  1217. PossibleReds[i][j]);
  1218. }
  1219. }
  1220. // Reroll the provided loop with respect to the provided induction variable.
  1221. // Generally, we're looking for a loop like this:
  1222. //
  1223. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  1224. // f(%iv)
  1225. // %iv.1 = add %iv, 1 <-- a root increment
  1226. // f(%iv.1)
  1227. // %iv.2 = add %iv, 2 <-- a root increment
  1228. // f(%iv.2)
  1229. // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
  1230. // f(%iv.scale_m_1)
  1231. // ...
  1232. // %iv.next = add %iv, scale
  1233. // %cmp = icmp(%iv, ...)
  1234. // br %cmp, header, exit
  1235. //
  1236. // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
  1237. // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
  1238. // be intermixed with eachother. The restriction imposed by this algorithm is
  1239. // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
  1240. // etc. be the same.
  1241. //
  1242. // First, we collect the use set of %iv, excluding the other increment roots.
  1243. // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
  1244. // times, having collected the use set of f(%iv.(i+1)), during which we:
  1245. // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
  1246. // the next unmatched instruction in f(%iv.(i+1)).
  1247. // - Ensure that both matched instructions don't have any external users
  1248. // (with the exception of last-in-chain reduction instructions).
  1249. // - Track the (aliasing) write set, and other side effects, of all
  1250. // instructions that belong to future iterations that come before the matched
  1251. // instructions. If the matched instructions read from that write set, then
  1252. // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
  1253. // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
  1254. // if any of these future instructions had side effects (could not be
  1255. // speculatively executed), and so do the matched instructions, when we
  1256. // cannot reorder those side-effect-producing instructions, and rerolling
  1257. // fails.
  1258. //
  1259. // Finally, we make sure that all loop instructions are either loop increment
  1260. // roots, belong to simple latch code, parts of validated reductions, part of
  1261. // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
  1262. // have been validated), then we reroll the loop.
  1263. bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
  1264. const SCEV *IterCount,
  1265. ReductionTracker &Reductions) {
  1266. DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI);
  1267. if (!DAGRoots.findRoots())
  1268. return false;
  1269. DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
  1270. *IV << "\n");
  1271. if (!DAGRoots.validate(Reductions))
  1272. return false;
  1273. if (!Reductions.validateSelected())
  1274. return false;
  1275. // At this point, we've validated the rerolling, and we're committed to
  1276. // making changes!
  1277. Reductions.replaceSelected();
  1278. DAGRoots.replace(IterCount);
  1279. ++NumRerolledLoops;
  1280. return true;
  1281. }
  1282. bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
  1283. if (skipOptnoneFunction(L))
  1284. return false;
  1285. AA = &getAnalysis<AliasAnalysis>();
  1286. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1287. SE = &getAnalysis<ScalarEvolution>();
  1288. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  1289. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1290. BasicBlock *Header = L->getHeader();
  1291. DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
  1292. "] Loop %" << Header->getName() << " (" <<
  1293. L->getNumBlocks() << " block(s))\n");
  1294. bool Changed = false;
  1295. // For now, we'll handle only single BB loops.
  1296. if (L->getNumBlocks() > 1)
  1297. return Changed;
  1298. if (!SE->hasLoopInvariantBackedgeTakenCount(L))
  1299. return Changed;
  1300. const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
  1301. const SCEV *IterCount =
  1302. SE->getAddExpr(LIBETC, SE->getConstant(LIBETC->getType(), 1));
  1303. DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
  1304. // First, we need to find the induction variable with respect to which we can
  1305. // reroll (there may be several possible options).
  1306. SmallInstructionVector PossibleIVs;
  1307. collectPossibleIVs(L, PossibleIVs);
  1308. if (PossibleIVs.empty()) {
  1309. DEBUG(dbgs() << "LRR: No possible IVs found\n");
  1310. return Changed;
  1311. }
  1312. ReductionTracker Reductions;
  1313. collectPossibleReductions(L, Reductions);
  1314. // For each possible IV, collect the associated possible set of 'root' nodes
  1315. // (i+1, i+2, etc.).
  1316. for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
  1317. IE = PossibleIVs.end(); I != IE; ++I)
  1318. if (reroll(*I, L, Header, IterCount, Reductions)) {
  1319. Changed = true;
  1320. break;
  1321. }
  1322. return Changed;
  1323. }