LoopRerollPass.cpp 52 KB

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