ScheduleOptimizer.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. //===- ScheduleOptimizer.cpp - Calculate an optimized schedule ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass generates an entirely new schedule tree from the data dependences
  10. // and iteration domains. The new schedule tree is computed in two steps:
  11. //
  12. // 1) The isl scheduling optimizer is run
  13. //
  14. // The isl scheduling optimizer creates a new schedule tree that maximizes
  15. // parallelism and tileability and minimizes data-dependence distances. The
  16. // algorithm used is a modified version of the ``Pluto'' algorithm:
  17. //
  18. // U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
  19. // A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
  20. // In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
  21. // Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
  22. //
  23. // 2) A set of post-scheduling transformations is applied on the schedule tree.
  24. //
  25. // These optimizations include:
  26. //
  27. // - Tiling of the innermost tilable bands
  28. // - Prevectorization - The choice of a possible outer loop that is strip-mined
  29. // to the innermost level to enable inner-loop
  30. // vectorization.
  31. // - Some optimizations for spatial locality are also planned.
  32. //
  33. // For a detailed description of the schedule tree itself please see section 6
  34. // of:
  35. //
  36. // Polyhedral AST generation is more than scanning polyhedra
  37. // Tobias Grosser, Sven Verdoolaege, Albert Cohen
  38. // ACM Transactions on Programming Languages and Systems (TOPLAS),
  39. // 37(4), July 2015
  40. // http://www.grosser.es/#pub-polyhedral-AST-generation
  41. //
  42. // This publication also contains a detailed discussion of the different options
  43. // for polyhedral loop unrolling, full/partial tile separation and other uses
  44. // of the schedule tree.
  45. //
  46. //===----------------------------------------------------------------------===//
  47. #include "polly/ScheduleOptimizer.h"
  48. #include "polly/CodeGen/CodeGeneration.h"
  49. #include "polly/DependenceInfo.h"
  50. #include "polly/ManualOptimizer.h"
  51. #include "polly/MatmulOptimizer.h"
  52. #include "polly/Options.h"
  53. #include "polly/ScheduleTreeTransform.h"
  54. #include "polly/Support/ISLOStream.h"
  55. #include "polly/Support/ISLTools.h"
  56. #include "llvm/ADT/Sequence.h"
  57. #include "llvm/ADT/Statistic.h"
  58. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  59. #include "llvm/InitializePasses.h"
  60. #include "llvm/Support/CommandLine.h"
  61. #include "isl/options.h"
  62. using namespace llvm;
  63. using namespace polly;
  64. namespace llvm {
  65. class Loop;
  66. class Module;
  67. } // namespace llvm
  68. #define DEBUG_TYPE "polly-opt-isl"
  69. static cl::opt<std::string>
  70. OptimizeDeps("polly-opt-optimize-only",
  71. cl::desc("Only a certain kind of dependences (all/raw)"),
  72. cl::Hidden, cl::init("all"), cl::ZeroOrMore,
  73. cl::cat(PollyCategory));
  74. static cl::opt<std::string>
  75. SimplifyDeps("polly-opt-simplify-deps",
  76. cl::desc("Dependences should be simplified (yes/no)"),
  77. cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
  78. cl::cat(PollyCategory));
  79. static cl::opt<int> MaxConstantTerm(
  80. "polly-opt-max-constant-term",
  81. cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
  82. cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
  83. static cl::opt<int> MaxCoefficient(
  84. "polly-opt-max-coefficient",
  85. cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
  86. cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
  87. static cl::opt<std::string>
  88. MaximizeBandDepth("polly-opt-maximize-bands",
  89. cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
  90. cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
  91. static cl::opt<bool>
  92. GreedyFusion("polly-loopfusion-greedy",
  93. cl::desc("Aggressively try to fuse everything"), cl::Hidden,
  94. cl::ZeroOrMore, cl::cat(PollyCategory));
  95. static cl::opt<std::string> OuterCoincidence(
  96. "polly-opt-outer-coincidence",
  97. cl::desc("Try to construct schedules where the outer member of each band "
  98. "satisfies the coincidence constraints (yes/no)"),
  99. cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory));
  100. static cl::opt<int> PrevectorWidth(
  101. "polly-prevect-width",
  102. cl::desc(
  103. "The number of loop iterations to strip-mine for pre-vectorization"),
  104. cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
  105. static cl::opt<bool> FirstLevelTiling("polly-tiling",
  106. cl::desc("Enable loop tiling"),
  107. cl::init(true), cl::ZeroOrMore,
  108. cl::cat(PollyCategory));
  109. static cl::opt<int> FirstLevelDefaultTileSize(
  110. "polly-default-tile-size",
  111. cl::desc("The default tile size (if not enough were provided by"
  112. " --polly-tile-sizes)"),
  113. cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
  114. static cl::list<int>
  115. FirstLevelTileSizes("polly-tile-sizes",
  116. cl::desc("A tile size for each loop dimension, filled "
  117. "with --polly-default-tile-size"),
  118. cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
  119. cl::cat(PollyCategory));
  120. static cl::opt<bool>
  121. SecondLevelTiling("polly-2nd-level-tiling",
  122. cl::desc("Enable a 2nd level loop of loop tiling"),
  123. cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
  124. static cl::opt<int> SecondLevelDefaultTileSize(
  125. "polly-2nd-level-default-tile-size",
  126. cl::desc("The default 2nd-level tile size (if not enough were provided by"
  127. " --polly-2nd-level-tile-sizes)"),
  128. cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
  129. static cl::list<int>
  130. SecondLevelTileSizes("polly-2nd-level-tile-sizes",
  131. cl::desc("A tile size for each loop dimension, filled "
  132. "with --polly-default-tile-size"),
  133. cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
  134. cl::cat(PollyCategory));
  135. static cl::opt<bool> RegisterTiling("polly-register-tiling",
  136. cl::desc("Enable register tiling"),
  137. cl::init(false), cl::ZeroOrMore,
  138. cl::cat(PollyCategory));
  139. static cl::opt<int> RegisterDefaultTileSize(
  140. "polly-register-tiling-default-tile-size",
  141. cl::desc("The default register tile size (if not enough were provided by"
  142. " --polly-register-tile-sizes)"),
  143. cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
  144. static cl::list<int>
  145. RegisterTileSizes("polly-register-tile-sizes",
  146. cl::desc("A tile size for each loop dimension, filled "
  147. "with --polly-register-tile-size"),
  148. cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
  149. cl::cat(PollyCategory));
  150. static cl::opt<bool> PragmaBasedOpts(
  151. "polly-pragma-based-opts",
  152. cl::desc("Apply user-directed transformation from metadata"),
  153. cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
  154. static cl::opt<bool> EnableReschedule("polly-reschedule",
  155. cl::desc("Optimize SCoPs using ISL"),
  156. cl::init(true), cl::ZeroOrMore,
  157. cl::cat(PollyCategory));
  158. static cl::opt<bool>
  159. PMBasedOpts("polly-pattern-matching-based-opts",
  160. cl::desc("Perform optimizations based on pattern matching"),
  161. cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
  162. static cl::opt<bool>
  163. EnablePostopts("polly-postopts",
  164. cl::desc("Apply post-rescheduling optimizations such as "
  165. "tiling (requires -polly-reschedule)"),
  166. cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
  167. static cl::opt<bool> OptimizedScops(
  168. "polly-optimized-scops",
  169. cl::desc("Polly - Dump polyhedral description of Scops optimized with "
  170. "the isl scheduling optimizer and the set of post-scheduling "
  171. "transformations is applied on the schedule tree"),
  172. cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
  173. STATISTIC(ScopsProcessed, "Number of scops processed");
  174. STATISTIC(ScopsRescheduled, "Number of scops rescheduled");
  175. STATISTIC(ScopsOptimized, "Number of scops optimized");
  176. STATISTIC(NumAffineLoopsOptimized, "Number of affine loops optimized");
  177. STATISTIC(NumBoxedLoopsOptimized, "Number of boxed loops optimized");
  178. #define THREE_STATISTICS(VARNAME, DESC) \
  179. static Statistic VARNAME[3] = { \
  180. {DEBUG_TYPE, #VARNAME "0", DESC " (original)"}, \
  181. {DEBUG_TYPE, #VARNAME "1", DESC " (after scheduler)"}, \
  182. {DEBUG_TYPE, #VARNAME "2", DESC " (after optimizer)"}}
  183. THREE_STATISTICS(NumBands, "Number of bands");
  184. THREE_STATISTICS(NumBandMembers, "Number of band members");
  185. THREE_STATISTICS(NumCoincident, "Number of coincident band members");
  186. THREE_STATISTICS(NumPermutable, "Number of permutable bands");
  187. THREE_STATISTICS(NumFilters, "Number of filter nodes");
  188. THREE_STATISTICS(NumExtension, "Number of extension nodes");
  189. STATISTIC(FirstLevelTileOpts, "Number of first level tiling applied");
  190. STATISTIC(SecondLevelTileOpts, "Number of second level tiling applied");
  191. STATISTIC(RegisterTileOpts, "Number of register tiling applied");
  192. STATISTIC(PrevectOpts, "Number of strip-mining for prevectorization applied");
  193. STATISTIC(MatMulOpts,
  194. "Number of matrix multiplication patterns detected and optimized");
  195. namespace {
  196. /// Additional parameters of the schedule optimizer.
  197. ///
  198. /// Target Transform Info and the SCoP dependencies used by the schedule
  199. /// optimizer.
  200. struct OptimizerAdditionalInfoTy {
  201. const llvm::TargetTransformInfo *TTI;
  202. const Dependences *D;
  203. bool PatternOpts;
  204. bool Postopts;
  205. bool Prevect;
  206. };
  207. class ScheduleTreeOptimizer {
  208. public:
  209. /// Apply schedule tree transformations.
  210. ///
  211. /// This function takes an (possibly already optimized) schedule tree and
  212. /// applies a set of additional optimizations on the schedule tree. The
  213. /// transformations applied include:
  214. ///
  215. /// - Pattern-based optimizations
  216. /// - Tiling
  217. /// - Prevectorization
  218. ///
  219. /// @param Schedule The schedule object the transformations will be applied
  220. /// to.
  221. /// @param OAI Target Transform Info and the SCoP dependencies.
  222. /// @returns The transformed schedule.
  223. static isl::schedule
  224. optimizeSchedule(isl::schedule Schedule,
  225. const OptimizerAdditionalInfoTy *OAI = nullptr);
  226. /// Apply schedule tree transformations.
  227. ///
  228. /// This function takes a node in an (possibly already optimized) schedule
  229. /// tree and applies a set of additional optimizations on this schedule tree
  230. /// node and its descendants. The transformations applied include:
  231. ///
  232. /// - Pattern-based optimizations
  233. /// - Tiling
  234. /// - Prevectorization
  235. ///
  236. /// @param Node The schedule object post-transformations will be applied to.
  237. /// @param OAI Target Transform Info and the SCoP dependencies.
  238. /// @returns The transformed schedule.
  239. static isl::schedule_node
  240. optimizeScheduleNode(isl::schedule_node Node,
  241. const OptimizerAdditionalInfoTy *OAI = nullptr);
  242. /// Decide if the @p NewSchedule is profitable for @p S.
  243. ///
  244. /// @param S The SCoP we optimize.
  245. /// @param NewSchedule The new schedule we computed.
  246. ///
  247. /// @return True, if we believe @p NewSchedule is an improvement for @p S.
  248. static bool isProfitableSchedule(polly::Scop &S, isl::schedule NewSchedule);
  249. /// Isolate a set of partial tile prefixes.
  250. ///
  251. /// This set should ensure that it contains only partial tile prefixes that
  252. /// have exactly VectorWidth iterations.
  253. ///
  254. /// @param Node A schedule node band, which is a parent of a band node,
  255. /// that contains a vector loop.
  256. /// @return Modified isl_schedule_node.
  257. static isl::schedule_node isolateFullPartialTiles(isl::schedule_node Node,
  258. int VectorWidth);
  259. private:
  260. /// Check if this node is a band node we want to tile.
  261. ///
  262. /// We look for innermost band nodes where individual dimensions are marked as
  263. /// permutable.
  264. ///
  265. /// @param Node The node to check.
  266. static bool isTileableBandNode(isl::schedule_node Node);
  267. /// Pre-vectorizes one scheduling dimension of a schedule band.
  268. ///
  269. /// prevectSchedBand splits out the dimension DimToVectorize, tiles it and
  270. /// sinks the resulting point loop.
  271. ///
  272. /// Example (DimToVectorize=0, VectorWidth=4):
  273. ///
  274. /// | Before transformation:
  275. /// |
  276. /// | A[i,j] -> [i,j]
  277. /// |
  278. /// | for (i = 0; i < 128; i++)
  279. /// | for (j = 0; j < 128; j++)
  280. /// | A(i,j);
  281. ///
  282. /// | After transformation:
  283. /// |
  284. /// | for (it = 0; it < 32; it+=1)
  285. /// | for (j = 0; j < 128; j++)
  286. /// | for (ip = 0; ip <= 3; ip++)
  287. /// | A(4 * it + ip,j);
  288. ///
  289. /// The goal of this transformation is to create a trivially vectorizable
  290. /// loop. This means a parallel loop at the innermost level that has a
  291. /// constant number of iterations corresponding to the target vector width.
  292. ///
  293. /// This transformation creates a loop at the innermost level. The loop has
  294. /// a constant number of iterations, if the number of loop iterations at
  295. /// DimToVectorize can be divided by VectorWidth. The default VectorWidth is
  296. /// currently constant and not yet target specific. This function does not
  297. /// reason about parallelism.
  298. static isl::schedule_node prevectSchedBand(isl::schedule_node Node,
  299. unsigned DimToVectorize,
  300. int VectorWidth);
  301. /// Apply additional optimizations on the bands in the schedule tree.
  302. ///
  303. /// We are looking for an innermost band node and apply the following
  304. /// transformations:
  305. ///
  306. /// - Tile the band
  307. /// - if the band is tileable
  308. /// - if the band has more than one loop dimension
  309. ///
  310. /// - Prevectorize the schedule of the band (or the point loop in case of
  311. /// tiling).
  312. /// - if vectorization is enabled
  313. ///
  314. /// @param Node The schedule node to (possibly) optimize.
  315. /// @param User A pointer to forward some use information
  316. /// (currently unused).
  317. static isl_schedule_node *optimizeBand(isl_schedule_node *Node, void *User);
  318. /// Apply tiling optimizations on the bands in the schedule tree.
  319. ///
  320. /// @param Node The schedule node to (possibly) optimize.
  321. static isl::schedule_node applyTileBandOpt(isl::schedule_node Node);
  322. /// Apply prevectorization on the bands in the schedule tree.
  323. ///
  324. /// @param Node The schedule node to (possibly) prevectorize.
  325. static isl::schedule_node applyPrevectBandOpt(isl::schedule_node Node);
  326. };
  327. isl::schedule_node
  328. ScheduleTreeOptimizer::isolateFullPartialTiles(isl::schedule_node Node,
  329. int VectorWidth) {
  330. assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band);
  331. Node = Node.child(0).child(0);
  332. isl::union_map SchedRelUMap = Node.get_prefix_schedule_relation();
  333. isl::union_set ScheduleRangeUSet = SchedRelUMap.range();
  334. isl::set ScheduleRange{ScheduleRangeUSet};
  335. isl::set IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
  336. auto AtomicOption = getDimOptions(IsolateDomain.ctx(), "atomic");
  337. isl::union_set IsolateOption = getIsolateOptions(IsolateDomain, 1);
  338. Node = Node.parent().parent();
  339. isl::union_set Options = IsolateOption.unite(AtomicOption);
  340. isl::schedule_node_band Result =
  341. Node.as<isl::schedule_node_band>().set_ast_build_options(Options);
  342. return Result;
  343. }
  344. struct InsertSimdMarkers : public ScheduleNodeRewriter<InsertSimdMarkers> {
  345. isl::schedule_node visitBand(isl::schedule_node_band Band) {
  346. isl::schedule_node Node = visitChildren(Band);
  347. // Only add SIMD markers to innermost bands.
  348. if (!Node.first_child().isa<isl::schedule_node_leaf>())
  349. return Node;
  350. isl::id LoopMarker = isl::id::alloc(Band.ctx(), "SIMD", nullptr);
  351. return Band.insert_mark(LoopMarker);
  352. }
  353. };
  354. isl::schedule_node ScheduleTreeOptimizer::prevectSchedBand(
  355. isl::schedule_node Node, unsigned DimToVectorize, int VectorWidth) {
  356. assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band);
  357. auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
  358. unsigned ScheduleDimensions = unsignedFromIslSize(Space.dim(isl::dim::set));
  359. assert(DimToVectorize < ScheduleDimensions);
  360. if (DimToVectorize > 0) {
  361. Node = isl::manage(
  362. isl_schedule_node_band_split(Node.release(), DimToVectorize));
  363. Node = Node.child(0);
  364. }
  365. if (DimToVectorize < ScheduleDimensions - 1)
  366. Node = isl::manage(isl_schedule_node_band_split(Node.release(), 1));
  367. Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
  368. auto Sizes = isl::multi_val::zero(Space);
  369. Sizes = Sizes.set_val(0, isl::val(Node.ctx(), VectorWidth));
  370. Node =
  371. isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release()));
  372. Node = isolateFullPartialTiles(Node, VectorWidth);
  373. Node = Node.child(0);
  374. // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
  375. // we will have troubles to match it in the backend.
  376. Node = Node.as<isl::schedule_node_band>().set_ast_build_options(
  377. isl::union_set(Node.ctx(), "{ unroll[x]: 1 = 0 }"));
  378. // Sink the inner loop into the smallest possible statements to make them
  379. // represent a single vector instruction if possible.
  380. Node = isl::manage(isl_schedule_node_band_sink(Node.release()));
  381. // Add SIMD markers to those vector statements.
  382. InsertSimdMarkers SimdMarkerInserter;
  383. Node = SimdMarkerInserter.visit(Node);
  384. PrevectOpts++;
  385. return Node.parent();
  386. }
  387. static bool isSimpleInnermostBand(const isl::schedule_node &Node) {
  388. assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band);
  389. assert(isl_schedule_node_n_children(Node.get()) == 1);
  390. auto ChildType = isl_schedule_node_get_type(Node.child(0).get());
  391. if (ChildType == isl_schedule_node_leaf)
  392. return true;
  393. if (ChildType != isl_schedule_node_sequence)
  394. return false;
  395. auto Sequence = Node.child(0);
  396. for (int c = 0, nc = isl_schedule_node_n_children(Sequence.get()); c < nc;
  397. ++c) {
  398. auto Child = Sequence.child(c);
  399. if (isl_schedule_node_get_type(Child.get()) != isl_schedule_node_filter)
  400. return false;
  401. if (isl_schedule_node_get_type(Child.child(0).get()) !=
  402. isl_schedule_node_leaf)
  403. return false;
  404. }
  405. return true;
  406. }
  407. bool ScheduleTreeOptimizer::isTileableBandNode(isl::schedule_node Node) {
  408. if (isl_schedule_node_get_type(Node.get()) != isl_schedule_node_band)
  409. return false;
  410. if (isl_schedule_node_n_children(Node.get()) != 1)
  411. return false;
  412. if (!isl_schedule_node_band_get_permutable(Node.get()))
  413. return false;
  414. auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
  415. if (unsignedFromIslSize(Space.dim(isl::dim::set)) <= 1u)
  416. return false;
  417. return isSimpleInnermostBand(Node);
  418. }
  419. __isl_give isl::schedule_node
  420. ScheduleTreeOptimizer::applyTileBandOpt(isl::schedule_node Node) {
  421. if (FirstLevelTiling) {
  422. Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
  423. FirstLevelDefaultTileSize);
  424. FirstLevelTileOpts++;
  425. }
  426. if (SecondLevelTiling) {
  427. Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
  428. SecondLevelDefaultTileSize);
  429. SecondLevelTileOpts++;
  430. }
  431. if (RegisterTiling) {
  432. Node =
  433. applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
  434. RegisterTileOpts++;
  435. }
  436. return Node;
  437. }
  438. isl::schedule_node
  439. ScheduleTreeOptimizer::applyPrevectBandOpt(isl::schedule_node Node) {
  440. auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
  441. int Dims = unsignedFromIslSize(Space.dim(isl::dim::set));
  442. for (int i = Dims - 1; i >= 0; i--)
  443. if (Node.as<isl::schedule_node_band>().member_get_coincident(i)) {
  444. Node = prevectSchedBand(Node, i, PrevectorWidth);
  445. break;
  446. }
  447. return Node;
  448. }
  449. __isl_give isl_schedule_node *
  450. ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *NodeArg,
  451. void *User) {
  452. const OptimizerAdditionalInfoTy *OAI =
  453. static_cast<const OptimizerAdditionalInfoTy *>(User);
  454. assert(OAI && "Expecting optimization options");
  455. isl::schedule_node Node = isl::manage(NodeArg);
  456. if (!isTileableBandNode(Node))
  457. return Node.release();
  458. if (OAI->PatternOpts) {
  459. isl::schedule_node PatternOptimizedSchedule =
  460. tryOptimizeMatMulPattern(Node, OAI->TTI, OAI->D);
  461. if (!PatternOptimizedSchedule.is_null()) {
  462. MatMulOpts++;
  463. return PatternOptimizedSchedule.release();
  464. }
  465. }
  466. if (OAI->Postopts)
  467. Node = applyTileBandOpt(Node);
  468. if (OAI->Prevect) {
  469. // FIXME: Prevectorization requirements are different from those checked by
  470. // isTileableBandNode.
  471. Node = applyPrevectBandOpt(Node);
  472. }
  473. return Node.release();
  474. }
  475. isl::schedule
  476. ScheduleTreeOptimizer::optimizeSchedule(isl::schedule Schedule,
  477. const OptimizerAdditionalInfoTy *OAI) {
  478. auto Root = Schedule.get_root();
  479. Root = optimizeScheduleNode(Root, OAI);
  480. return Root.get_schedule();
  481. }
  482. isl::schedule_node ScheduleTreeOptimizer::optimizeScheduleNode(
  483. isl::schedule_node Node, const OptimizerAdditionalInfoTy *OAI) {
  484. Node = isl::manage(isl_schedule_node_map_descendant_bottom_up(
  485. Node.release(), optimizeBand,
  486. const_cast<void *>(static_cast<const void *>(OAI))));
  487. return Node;
  488. }
  489. bool ScheduleTreeOptimizer::isProfitableSchedule(Scop &S,
  490. isl::schedule NewSchedule) {
  491. // To understand if the schedule has been optimized we check if the schedule
  492. // has changed at all.
  493. // TODO: We can improve this by tracking if any necessarily beneficial
  494. // transformations have been performed. This can e.g. be tiling, loop
  495. // interchange, or ...) We can track this either at the place where the
  496. // transformation has been performed or, in case of automatic ILP based
  497. // optimizations, by comparing (yet to be defined) performance metrics
  498. // before/after the scheduling optimizer
  499. // (e.g., #stride-one accesses)
  500. // FIXME: A schedule tree whose union_map-conversion is identical to the
  501. // original schedule map may still allow for parallelization, i.e. can still
  502. // be profitable.
  503. auto NewScheduleMap = NewSchedule.get_map();
  504. auto OldSchedule = S.getSchedule();
  505. assert(!OldSchedule.is_null() &&
  506. "Only IslScheduleOptimizer can insert extension nodes "
  507. "that make Scop::getSchedule() return nullptr.");
  508. bool changed = !OldSchedule.is_equal(NewScheduleMap);
  509. return changed;
  510. }
  511. class IslScheduleOptimizerWrapperPass : public ScopPass {
  512. public:
  513. static char ID;
  514. explicit IslScheduleOptimizerWrapperPass() : ScopPass(ID) {}
  515. /// Optimize the schedule of the SCoP @p S.
  516. bool runOnScop(Scop &S) override;
  517. /// Print the new schedule for the SCoP @p S.
  518. void printScop(raw_ostream &OS, Scop &S) const override;
  519. /// Register all analyses and transformation required.
  520. void getAnalysisUsage(AnalysisUsage &AU) const override;
  521. /// Release the internal memory.
  522. void releaseMemory() override {
  523. LastSchedule = {};
  524. IslCtx.reset();
  525. }
  526. private:
  527. std::shared_ptr<isl_ctx> IslCtx;
  528. isl::schedule LastSchedule;
  529. };
  530. char IslScheduleOptimizerWrapperPass::ID = 0;
  531. #ifndef NDEBUG
  532. static void printSchedule(llvm::raw_ostream &OS, const isl::schedule &Schedule,
  533. StringRef Desc) {
  534. isl::ctx Ctx = Schedule.ctx();
  535. isl_printer *P = isl_printer_to_str(Ctx.get());
  536. P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
  537. P = isl_printer_print_schedule(P, Schedule.get());
  538. char *Str = isl_printer_get_str(P);
  539. OS << Desc << ": \n" << Str << "\n";
  540. free(Str);
  541. isl_printer_free(P);
  542. }
  543. #endif
  544. /// Collect statistics for the schedule tree.
  545. ///
  546. /// @param Schedule The schedule tree to analyze. If not a schedule tree it is
  547. /// ignored.
  548. /// @param Version The version of the schedule tree that is analyzed.
  549. /// 0 for the original schedule tree before any transformation.
  550. /// 1 for the schedule tree after isl's rescheduling.
  551. /// 2 for the schedule tree after optimizations are applied
  552. /// (tiling, pattern matching)
  553. static void walkScheduleTreeForStatistics(isl::schedule Schedule, int Version) {
  554. auto Root = Schedule.get_root();
  555. if (Root.is_null())
  556. return;
  557. isl_schedule_node_foreach_descendant_top_down(
  558. Root.get(),
  559. [](__isl_keep isl_schedule_node *nodeptr, void *user) -> isl_bool {
  560. isl::schedule_node Node = isl::manage_copy(nodeptr);
  561. int Version = *static_cast<int *>(user);
  562. switch (isl_schedule_node_get_type(Node.get())) {
  563. case isl_schedule_node_band: {
  564. NumBands[Version]++;
  565. if (isl_schedule_node_band_get_permutable(Node.get()) ==
  566. isl_bool_true)
  567. NumPermutable[Version]++;
  568. int CountMembers = isl_schedule_node_band_n_member(Node.get());
  569. NumBandMembers[Version] += CountMembers;
  570. for (int i = 0; i < CountMembers; i += 1) {
  571. if (Node.as<isl::schedule_node_band>().member_get_coincident(i))
  572. NumCoincident[Version]++;
  573. }
  574. break;
  575. }
  576. case isl_schedule_node_filter:
  577. NumFilters[Version]++;
  578. break;
  579. case isl_schedule_node_extension:
  580. NumExtension[Version]++;
  581. break;
  582. default:
  583. break;
  584. }
  585. return isl_bool_true;
  586. },
  587. &Version);
  588. }
  589. static bool runIslScheduleOptimizer(
  590. Scop &S,
  591. function_ref<const Dependences &(Dependences::AnalysisLevel)> GetDeps,
  592. TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE,
  593. isl::schedule &LastSchedule) {
  594. // Skip SCoPs in case they're already optimised by PPCGCodeGeneration
  595. if (S.isToBeSkipped())
  596. return false;
  597. // Skip empty SCoPs but still allow code generation as it will delete the
  598. // loops present but not needed.
  599. if (S.getSize() == 0) {
  600. S.markAsOptimized();
  601. return false;
  602. }
  603. ScopsProcessed++;
  604. // Schedule without optimizations.
  605. isl::schedule Schedule = S.getScheduleTree();
  606. walkScheduleTreeForStatistics(S.getScheduleTree(), 0);
  607. LLVM_DEBUG(printSchedule(dbgs(), Schedule, "Original schedule tree"));
  608. bool HasUserTransformation = false;
  609. if (PragmaBasedOpts) {
  610. isl::schedule ManuallyTransformed = applyManualTransformations(
  611. &S, Schedule, GetDeps(Dependences::AL_Statement), ORE);
  612. if (ManuallyTransformed.is_null()) {
  613. LLVM_DEBUG(dbgs() << "Error during manual optimization\n");
  614. return false;
  615. }
  616. if (ManuallyTransformed.get() != Schedule.get()) {
  617. // User transformations have precedence over other transformations.
  618. HasUserTransformation = true;
  619. Schedule = std::move(ManuallyTransformed);
  620. LLVM_DEBUG(
  621. printSchedule(dbgs(), Schedule, "After manual transformations"));
  622. }
  623. }
  624. // Only continue if either manual transformations have been applied or we are
  625. // allowed to apply heuristics.
  626. // TODO: Detect disabled heuristics and no user-directed transformation
  627. // metadata earlier in ScopDetection.
  628. if (!HasUserTransformation && S.hasDisableHeuristicsHint()) {
  629. LLVM_DEBUG(dbgs() << "Heuristic optimizations disabled by metadata\n");
  630. return false;
  631. }
  632. // Get dependency analysis.
  633. const Dependences &D = GetDeps(Dependences::AL_Statement);
  634. if (D.getSharedIslCtx() != S.getSharedIslCtx()) {
  635. LLVM_DEBUG(dbgs() << "DependenceInfo for another SCoP/isl_ctx\n");
  636. return false;
  637. }
  638. if (!D.hasValidDependences()) {
  639. LLVM_DEBUG(dbgs() << "Dependency information not available\n");
  640. return false;
  641. }
  642. // Apply ISL's algorithm only if not overriden by the user. Note that
  643. // post-rescheduling optimizations (tiling, pattern-based, prevectorization)
  644. // rely on the coincidence/permutable annotations on schedule tree bands that
  645. // are added by the rescheduling analyzer. Therefore, disabling the
  646. // rescheduler implicitly also disables these optimizations.
  647. if (!EnableReschedule) {
  648. LLVM_DEBUG(dbgs() << "Skipping rescheduling due to command line option\n");
  649. } else if (HasUserTransformation) {
  650. LLVM_DEBUG(
  651. dbgs() << "Skipping rescheduling due to manual transformation\n");
  652. } else {
  653. // Build input data.
  654. int ValidityKinds =
  655. Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
  656. int ProximityKinds;
  657. if (OptimizeDeps == "all")
  658. ProximityKinds =
  659. Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
  660. else if (OptimizeDeps == "raw")
  661. ProximityKinds = Dependences::TYPE_RAW;
  662. else {
  663. errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
  664. << " Falling back to optimizing all dependences.\n";
  665. ProximityKinds =
  666. Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
  667. }
  668. isl::union_set Domain = S.getDomains();
  669. if (Domain.is_null())
  670. return false;
  671. isl::union_map Validity = D.getDependences(ValidityKinds);
  672. isl::union_map Proximity = D.getDependences(ProximityKinds);
  673. // Simplify the dependences by removing the constraints introduced by the
  674. // domains. This can speed up the scheduling time significantly, as large
  675. // constant coefficients will be removed from the dependences. The
  676. // introduction of some additional dependences reduces the possible
  677. // transformations, but in most cases, such transformation do not seem to be
  678. // interesting anyway. In some cases this option may stop the scheduler to
  679. // find any schedule.
  680. if (SimplifyDeps == "yes") {
  681. Validity = Validity.gist_domain(Domain);
  682. Validity = Validity.gist_range(Domain);
  683. Proximity = Proximity.gist_domain(Domain);
  684. Proximity = Proximity.gist_range(Domain);
  685. } else if (SimplifyDeps != "no") {
  686. errs()
  687. << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
  688. "or 'no'. Falling back to default: 'yes'\n";
  689. }
  690. LLVM_DEBUG(dbgs() << "\n\nCompute schedule from: ");
  691. LLVM_DEBUG(dbgs() << "Domain := " << Domain << ";\n");
  692. LLVM_DEBUG(dbgs() << "Proximity := " << Proximity << ";\n");
  693. LLVM_DEBUG(dbgs() << "Validity := " << Validity << ";\n");
  694. int IslMaximizeBands;
  695. if (MaximizeBandDepth == "yes") {
  696. IslMaximizeBands = 1;
  697. } else if (MaximizeBandDepth == "no") {
  698. IslMaximizeBands = 0;
  699. } else {
  700. errs()
  701. << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
  702. " or 'no'. Falling back to default: 'yes'\n";
  703. IslMaximizeBands = 1;
  704. }
  705. int IslOuterCoincidence;
  706. if (OuterCoincidence == "yes") {
  707. IslOuterCoincidence = 1;
  708. } else if (OuterCoincidence == "no") {
  709. IslOuterCoincidence = 0;
  710. } else {
  711. errs() << "warning: Option -polly-opt-outer-coincidence should either be "
  712. "'yes' or 'no'. Falling back to default: 'no'\n";
  713. IslOuterCoincidence = 0;
  714. }
  715. isl_ctx *Ctx = S.getIslCtx().get();
  716. isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
  717. isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
  718. isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
  719. isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
  720. isl_options_set_tile_scale_tile_loops(Ctx, 0);
  721. auto OnErrorStatus = isl_options_get_on_error(Ctx);
  722. isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
  723. auto SC = isl::schedule_constraints::on_domain(Domain);
  724. SC = SC.set_proximity(Proximity);
  725. SC = SC.set_validity(Validity);
  726. SC = SC.set_coincidence(Validity);
  727. Schedule = SC.compute_schedule();
  728. isl_options_set_on_error(Ctx, OnErrorStatus);
  729. ScopsRescheduled++;
  730. LLVM_DEBUG(printSchedule(dbgs(), Schedule, "After rescheduling"));
  731. }
  732. walkScheduleTreeForStatistics(Schedule, 1);
  733. // In cases the scheduler is not able to optimize the code, we just do not
  734. // touch the schedule.
  735. if (Schedule.is_null())
  736. return false;
  737. if (GreedyFusion) {
  738. isl::union_map Validity = D.getDependences(
  739. Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW);
  740. Schedule = applyGreedyFusion(Schedule, Validity);
  741. assert(!Schedule.is_null());
  742. }
  743. // Apply post-rescheduling optimizations (if enabled) and/or prevectorization.
  744. const OptimizerAdditionalInfoTy OAI = {
  745. TTI, const_cast<Dependences *>(&D),
  746. /*PatternOpts=*/!HasUserTransformation && PMBasedOpts,
  747. /*Postopts=*/!HasUserTransformation && EnablePostopts,
  748. /*Prevect=*/PollyVectorizerChoice != VECTORIZER_NONE};
  749. if (OAI.PatternOpts || OAI.Postopts || OAI.Prevect) {
  750. Schedule = ScheduleTreeOptimizer::optimizeSchedule(Schedule, &OAI);
  751. Schedule = hoistExtensionNodes(Schedule);
  752. LLVM_DEBUG(printSchedule(dbgs(), Schedule, "After post-optimizations"));
  753. walkScheduleTreeForStatistics(Schedule, 2);
  754. }
  755. // Skip profitability check if user transformation(s) have been applied.
  756. if (!HasUserTransformation &&
  757. !ScheduleTreeOptimizer::isProfitableSchedule(S, Schedule))
  758. return false;
  759. auto ScopStats = S.getStatistics();
  760. ScopsOptimized++;
  761. NumAffineLoopsOptimized += ScopStats.NumAffineLoops;
  762. NumBoxedLoopsOptimized += ScopStats.NumBoxedLoops;
  763. LastSchedule = Schedule;
  764. S.setScheduleTree(Schedule);
  765. S.markAsOptimized();
  766. if (OptimizedScops)
  767. errs() << S;
  768. return false;
  769. }
  770. bool IslScheduleOptimizerWrapperPass::runOnScop(Scop &S) {
  771. releaseMemory();
  772. Function &F = S.getFunction();
  773. IslCtx = S.getSharedIslCtx();
  774. auto getDependences =
  775. [this](Dependences::AnalysisLevel) -> const Dependences & {
  776. return getAnalysis<DependenceInfo>().getDependences(
  777. Dependences::AL_Statement);
  778. };
  779. OptimizationRemarkEmitter &ORE =
  780. getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  781. TargetTransformInfo *TTI =
  782. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  783. return runIslScheduleOptimizer(S, getDependences, TTI, &ORE, LastSchedule);
  784. }
  785. static void runScheduleOptimizerPrinter(raw_ostream &OS,
  786. isl::schedule LastSchedule) {
  787. isl_printer *p;
  788. char *ScheduleStr;
  789. OS << "Calculated schedule:\n";
  790. if (LastSchedule.is_null()) {
  791. OS << "n/a\n";
  792. return;
  793. }
  794. p = isl_printer_to_str(LastSchedule.ctx().get());
  795. p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK);
  796. p = isl_printer_print_schedule(p, LastSchedule.get());
  797. ScheduleStr = isl_printer_get_str(p);
  798. isl_printer_free(p);
  799. OS << ScheduleStr << "\n";
  800. free(ScheduleStr);
  801. }
  802. void IslScheduleOptimizerWrapperPass::printScop(raw_ostream &OS, Scop &) const {
  803. runScheduleOptimizerPrinter(OS, LastSchedule);
  804. }
  805. void IslScheduleOptimizerWrapperPass::getAnalysisUsage(
  806. AnalysisUsage &AU) const {
  807. ScopPass::getAnalysisUsage(AU);
  808. AU.addRequired<DependenceInfo>();
  809. AU.addRequired<TargetTransformInfoWrapperPass>();
  810. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  811. AU.addPreserved<DependenceInfo>();
  812. AU.addPreserved<OptimizationRemarkEmitterWrapperPass>();
  813. }
  814. } // namespace
  815. Pass *polly::createIslScheduleOptimizerWrapperPass() {
  816. return new IslScheduleOptimizerWrapperPass();
  817. }
  818. INITIALIZE_PASS_BEGIN(IslScheduleOptimizerWrapperPass, "polly-opt-isl",
  819. "Polly - Optimize schedule of SCoP", false, false);
  820. INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
  821. INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
  822. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
  823. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
  824. INITIALIZE_PASS_END(IslScheduleOptimizerWrapperPass, "polly-opt-isl",
  825. "Polly - Optimize schedule of SCoP", false, false)
  826. static llvm::PreservedAnalyses
  827. runIslScheduleOptimizerUsingNPM(Scop &S, ScopAnalysisManager &SAM,
  828. ScopStandardAnalysisResults &SAR, SPMUpdater &U,
  829. raw_ostream *OS) {
  830. DependenceAnalysis::Result &Deps = SAM.getResult<DependenceAnalysis>(S, SAR);
  831. auto GetDeps = [&Deps](Dependences::AnalysisLevel) -> const Dependences & {
  832. return Deps.getDependences(Dependences::AL_Statement);
  833. };
  834. OptimizationRemarkEmitter ORE(&S.getFunction());
  835. TargetTransformInfo *TTI = &SAR.TTI;
  836. isl::schedule LastSchedule;
  837. bool Modified = runIslScheduleOptimizer(S, GetDeps, TTI, &ORE, LastSchedule);
  838. if (OS) {
  839. *OS << "Printing analysis 'Polly - Optimize schedule of SCoP' for region: '"
  840. << S.getName() << "' in function '" << S.getFunction().getName()
  841. << "':\n";
  842. runScheduleOptimizerPrinter(*OS, LastSchedule);
  843. }
  844. if (!Modified)
  845. return PreservedAnalyses::all();
  846. PreservedAnalyses PA;
  847. PA.preserveSet<AllAnalysesOn<Module>>();
  848. PA.preserveSet<AllAnalysesOn<Function>>();
  849. PA.preserveSet<AllAnalysesOn<Loop>>();
  850. return PA;
  851. }
  852. llvm::PreservedAnalyses
  853. IslScheduleOptimizerPass::run(Scop &S, ScopAnalysisManager &SAM,
  854. ScopStandardAnalysisResults &SAR, SPMUpdater &U) {
  855. return runIslScheduleOptimizerUsingNPM(S, SAM, SAR, U, nullptr);
  856. }
  857. llvm::PreservedAnalyses
  858. IslScheduleOptimizerPrinterPass::run(Scop &S, ScopAnalysisManager &SAM,
  859. ScopStandardAnalysisResults &SAR,
  860. SPMUpdater &U) {
  861. return runIslScheduleOptimizerUsingNPM(S, SAM, SAR, U, &OS);
  862. }