1 //===- Schedule.cpp - Calculate an optimized schedule ---------------------===//
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 generates an entirey new schedule tree from the data dependences
11 // and iteration domains. The new schedule tree is computed in two steps:
12 //
13 // 1) The isl scheduling optimizer is run
14 //
15 // The isl scheduling optimizer creates a new schedule tree that maximizes
16 // parallelism and tileability and minimizes data-dependence distances. The
17 // algorithm used is a modified version of the ``Pluto'' algorithm:
18 //
19 //   U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
20 //   A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
21 //   In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
22 //   Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
23 //
24 // 2) A set of post-scheduling transformations is applied on the schedule tree.
25 //
26 // These optimizations include:
27 //
28 //  - Tiling of the innermost tilable bands
29 //  - Prevectorization - The coice of a possible outer loop that is strip-mined
30 //                       to the innermost level to enable inner-loop
31 //                       vectorization.
32 //  - Some optimizations for spatial locality are also planned.
33 //
34 // For a detailed description of the schedule tree itself please see section 6
35 // of:
36 //
37 // Polyhedral AST generation is more than scanning polyhedra
38 // Tobias Grosser, Sven Verdoolaege, Albert Cohen
39 // ACM Transations on Programming Languages and Systems (TOPLAS),
40 // 37(4), July 2015
41 // http://www.grosser.es/#pub-polyhedral-AST-generation
42 //
43 // This publication also contains a detailed discussion of the different options
44 // for polyhedral loop unrolling, full/partial tile separation and other uses
45 // of the schedule tree.
46 //
47 //===----------------------------------------------------------------------===//
48 
49 #include "polly/ScheduleOptimizer.h"
50 #include "polly/CodeGen/CodeGeneration.h"
51 #include "polly/DependenceInfo.h"
52 #include "polly/LinkAllPasses.h"
53 #include "polly/Options.h"
54 #include "polly/ScopInfo.h"
55 #include "polly/Support/GICHelper.h"
56 #include "llvm/Support/Debug.h"
57 #include "isl/aff.h"
58 #include "isl/band.h"
59 #include "isl/constraint.h"
60 #include "isl/map.h"
61 #include "isl/options.h"
62 #include "isl/printer.h"
63 #include "isl/schedule.h"
64 #include "isl/schedule_node.h"
65 #include "isl/space.h"
66 #include "isl/union_map.h"
67 #include "isl/union_set.h"
68 
69 using namespace llvm;
70 using namespace polly;
71 
72 #define DEBUG_TYPE "polly-opt-isl"
73 
74 static cl::opt<std::string>
75     OptimizeDeps("polly-opt-optimize-only",
76                  cl::desc("Only a certain kind of dependences (all/raw)"),
77                  cl::Hidden, cl::init("all"), cl::ZeroOrMore,
78                  cl::cat(PollyCategory));
79 
80 static cl::opt<std::string>
81     SimplifyDeps("polly-opt-simplify-deps",
82                  cl::desc("Dependences should be simplified (yes/no)"),
83                  cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
84                  cl::cat(PollyCategory));
85 
86 static cl::opt<int> MaxConstantTerm(
87     "polly-opt-max-constant-term",
88     cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
89     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
90 
91 static cl::opt<int> MaxCoefficient(
92     "polly-opt-max-coefficient",
93     cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
94     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
95 
96 static cl::opt<std::string> FusionStrategy(
97     "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
98     cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
99 
100 static cl::opt<std::string>
101     MaximizeBandDepth("polly-opt-maximize-bands",
102                       cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
103                       cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
104 
105 static cl::opt<std::string> OuterCoincidence(
106     "polly-opt-outer-coincidence",
107     cl::desc("Try to construct schedules where the outer member of each band "
108              "satisfies the coincidence constraints (yes/no)"),
109     cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory));
110 
111 static cl::opt<int> PrevectorWidth(
112     "polly-prevect-width",
113     cl::desc(
114         "The number of loop iterations to strip-mine for pre-vectorization"),
115     cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
116 
117 static cl::opt<bool> FirstLevelTiling("polly-tiling",
118                                       cl::desc("Enable loop tiling"),
119                                       cl::init(true), cl::ZeroOrMore,
120                                       cl::cat(PollyCategory));
121 
122 static cl::opt<int> FirstLevelDefaultTileSize(
123     "polly-default-tile-size",
124     cl::desc("The default tile size (if not enough were provided by"
125              " --polly-tile-sizes)"),
126     cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
127 
128 static cl::list<int> FirstLevelTileSizes(
129     "polly-tile-sizes", cl::desc("A tile size for each loop dimension, filled "
130                                  "with --polly-default-tile-size"),
131     cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
132 
133 static cl::opt<bool>
134     SecondLevelTiling("polly-2nd-level-tiling",
135                       cl::desc("Enable a 2nd level loop of loop tiling"),
136                       cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
137 
138 static cl::opt<int> SecondLevelDefaultTileSize(
139     "polly-2nd-level-default-tile-size",
140     cl::desc("The default 2nd-level tile size (if not enough were provided by"
141              " --polly-2nd-level-tile-sizes)"),
142     cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
143 
144 static cl::list<int>
145     SecondLevelTileSizes("polly-2nd-level-tile-sizes",
146                          cl::desc("A tile size for each loop dimension, filled "
147                                   "with --polly-default-tile-size"),
148                          cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
149                          cl::cat(PollyCategory));
150 
151 static cl::opt<bool> RegisterTiling("polly-register-tiling",
152                                     cl::desc("Enable register tiling"),
153                                     cl::init(false), cl::ZeroOrMore,
154                                     cl::cat(PollyCategory));
155 
156 static cl::opt<int> RegisterDefaultTileSize(
157     "polly-register-tiling-default-tile-size",
158     cl::desc("The default register tile size (if not enough were provided by"
159              " --polly-register-tile-sizes)"),
160     cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
161 
162 static cl::list<int>
163     RegisterTileSizes("polly-register-tile-sizes",
164                       cl::desc("A tile size for each loop dimension, filled "
165                                "with --polly-register-tile-size"),
166                       cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
167                       cl::cat(PollyCategory));
168 
169 static cl::opt<bool>
170     PMBasedOpts("polly-pattern-matching-based-opts",
171                 cl::desc("Perform optimizations based on pattern matching"),
172                 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
173 
174 /// @brief Create an isl_union_set, which describes the isolate option based
175 ///        on IsoalteDomain.
176 ///
177 /// @param IsolateDomain An isl_set whose last dimension is the only one that
178 ///                      should belong to the current band node.
179 static __isl_give isl_union_set *
180 getIsolateOptions(__isl_take isl_set *IsolateDomain) {
181   auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
182   auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
183   IsolateRelation = isl_map_move_dims(IsolateRelation, isl_dim_out, 0,
184                                       isl_dim_in, Dims - 1, 1);
185   auto *IsolateOption = isl_map_wrap(IsolateRelation);
186   auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", NULL);
187   return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
188 }
189 
190 /// @brief Create an isl_union_set, which describes the atomic option for the
191 ///        dimension of the current node.
192 ///
193 /// It may help to reduce the size of generated code.
194 ///
195 /// @param Ctx An isl_ctx, which is used to create the isl_union_set.
196 static __isl_give isl_union_set *getAtomicOptions(__isl_take isl_ctx *Ctx) {
197   auto *Space = isl_space_set_alloc(Ctx, 0, 1);
198   auto *AtomicOption = isl_set_universe(Space);
199   auto *Id = isl_id_alloc(Ctx, "atomic", NULL);
200   return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
201 }
202 
203 /// @brief Make the last dimension of Set to take values
204 ///        from 0 to VectorWidth - 1.
205 ///
206 /// @param Set         A set, which should be modified.
207 /// @param VectorWidth A parameter, which determines the constraint.
208 static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
209                                                 int VectorWidth) {
210   auto Dims = isl_set_dim(Set, isl_dim_set);
211   auto Space = isl_set_get_space(Set);
212   auto *LocalSpace = isl_local_space_from_space(Space);
213   auto *ExtConstr =
214       isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
215   ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
216   ExtConstr =
217       isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
218   Set = isl_set_add_constraint(Set, ExtConstr);
219   ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
220   ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
221   ExtConstr =
222       isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
223   return isl_set_add_constraint(Set, ExtConstr);
224 }
225 
226 /// @brief Build the desired set of partial tile prefixes.
227 ///
228 /// We build a set of partial tile prefixes, which are prefixes of the vector
229 /// loop that have exactly VectorWidth iterations.
230 ///
231 /// 1. Get all prefixes of the vector loop.
232 /// 2. Extend it to a set, which has exactly VectorWidth iterations for
233 ///    any prefix from the set that was built on the previous step.
234 /// 3. Subtract loop domain from it, project out the vector loop dimension and
235 ///    get a set of prefixes, which don't have exactly VectorWidth iterations.
236 /// 4. Subtract it from all prefixes of the vector loop and get the desired
237 ///    set.
238 ///
239 /// @param ScheduleRange A range of a map, which describes a prefix schedule
240 ///                      relation.
241 static __isl_give isl_set *
242 getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
243   auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
244   auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
245                                            isl_dim_set, Dims - 1, 1);
246   auto *ExtentPrefixes =
247       isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
248   ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
249   auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
250   BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
251   return isl_set_subtract(LoopPrefixes, BadPrefixes);
252 }
253 
254 __isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
255     __isl_take isl_schedule_node *Node, int VectorWidth) {
256   assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
257   Node = isl_schedule_node_child(Node, 0);
258   Node = isl_schedule_node_child(Node, 0);
259   auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
260   auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
261   auto *ScheduleRange = isl_map_range(ScheduleRelation);
262   auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
263   auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
264   auto *IsolateOption = getIsolateOptions(IsolateDomain);
265   Node = isl_schedule_node_parent(Node);
266   Node = isl_schedule_node_parent(Node);
267   auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
268   Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
269   return Node;
270 }
271 
272 __isl_give isl_schedule_node *
273 ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
274                                         unsigned DimToVectorize,
275                                         int VectorWidth) {
276   assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
277 
278   auto Space = isl_schedule_node_band_get_space(Node);
279   auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
280   isl_space_free(Space);
281   assert(DimToVectorize < ScheduleDimensions);
282 
283   if (DimToVectorize > 0) {
284     Node = isl_schedule_node_band_split(Node, DimToVectorize);
285     Node = isl_schedule_node_child(Node, 0);
286   }
287   if (DimToVectorize < ScheduleDimensions - 1)
288     Node = isl_schedule_node_band_split(Node, 1);
289   Space = isl_schedule_node_band_get_space(Node);
290   auto Sizes = isl_multi_val_zero(Space);
291   auto Ctx = isl_schedule_node_get_ctx(Node);
292   Sizes =
293       isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
294   Node = isl_schedule_node_band_tile(Node, Sizes);
295   Node = isolateFullPartialTiles(Node, VectorWidth);
296   Node = isl_schedule_node_child(Node, 0);
297   // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
298   // we will have troubles to match it in the backend.
299   Node = isl_schedule_node_band_set_ast_build_options(
300       Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
301   Node = isl_schedule_node_band_sink(Node);
302   Node = isl_schedule_node_child(Node, 0);
303   if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
304     Node = isl_schedule_node_parent(Node);
305   isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
306   Node = isl_schedule_node_insert_mark(Node, LoopMarker);
307   return Node;
308 }
309 
310 __isl_give isl_schedule_node *
311 ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
312                                 const char *Identifier, ArrayRef<int> TileSizes,
313                                 int DefaultTileSize) {
314   auto Ctx = isl_schedule_node_get_ctx(Node);
315   auto Space = isl_schedule_node_band_get_space(Node);
316   auto Dims = isl_space_dim(Space, isl_dim_set);
317   auto Sizes = isl_multi_val_zero(Space);
318   std::string IdentifierString(Identifier);
319   for (unsigned i = 0; i < Dims; i++) {
320     auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
321     Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
322   }
323   auto TileLoopMarkerStr = IdentifierString + " - Tiles";
324   isl_id *TileLoopMarker =
325       isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
326   Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
327   Node = isl_schedule_node_child(Node, 0);
328   Node = isl_schedule_node_band_tile(Node, Sizes);
329   Node = isl_schedule_node_child(Node, 0);
330   auto PointLoopMarkerStr = IdentifierString + " - Points";
331   isl_id *PointLoopMarker =
332       isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
333   Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
334   Node = isl_schedule_node_child(Node, 0);
335   return Node;
336 }
337 
338 bool ScheduleTreeOptimizer::isTileableBandNode(
339     __isl_keep isl_schedule_node *Node) {
340   if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
341     return false;
342 
343   if (isl_schedule_node_n_children(Node) != 1)
344     return false;
345 
346   if (!isl_schedule_node_band_get_permutable(Node))
347     return false;
348 
349   auto Space = isl_schedule_node_band_get_space(Node);
350   auto Dims = isl_space_dim(Space, isl_dim_set);
351   isl_space_free(Space);
352 
353   if (Dims <= 1)
354     return false;
355 
356   auto Child = isl_schedule_node_get_child(Node, 0);
357   auto Type = isl_schedule_node_get_type(Child);
358   isl_schedule_node_free(Child);
359 
360   if (Type != isl_schedule_node_leaf)
361     return false;
362 
363   return true;
364 }
365 
366 __isl_give isl_schedule_node *
367 ScheduleTreeOptimizer::standardBandOpts(__isl_take isl_schedule_node *Node,
368                                         void *User) {
369   if (FirstLevelTiling)
370     Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
371                     FirstLevelDefaultTileSize);
372 
373   if (SecondLevelTiling)
374     Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
375                     SecondLevelDefaultTileSize);
376 
377   if (RegisterTiling) {
378     auto *Ctx = isl_schedule_node_get_ctx(Node);
379     Node = tileNode(Node, "Register tiling", RegisterTileSizes,
380                     RegisterDefaultTileSize);
381     Node = isl_schedule_node_band_set_ast_build_options(
382         Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
383   }
384 
385   if (PollyVectorizerChoice == VECTORIZER_NONE)
386     return Node;
387 
388   auto Space = isl_schedule_node_band_get_space(Node);
389   auto Dims = isl_space_dim(Space, isl_dim_set);
390   isl_space_free(Space);
391 
392   for (int i = Dims - 1; i >= 0; i--)
393     if (isl_schedule_node_band_member_get_coincident(Node, i)) {
394       Node = prevectSchedBand(Node, i, PrevectorWidth);
395       break;
396     }
397 
398   return Node;
399 }
400 
401 /// @brief Check whether output dimensions of the map rely on the specified
402 ///        input dimension.
403 ///
404 /// @param IslMap The isl map to be considered.
405 /// @param DimNum The number of an input dimension to be checked.
406 static bool isInputDimUsed(__isl_take isl_map *IslMap, unsigned DimNum) {
407   auto *CheckedAccessRelation =
408       isl_map_project_out(isl_map_copy(IslMap), isl_dim_in, DimNum, 1);
409   CheckedAccessRelation =
410       isl_map_insert_dims(CheckedAccessRelation, isl_dim_in, DimNum, 1);
411   auto *InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
412   CheckedAccessRelation =
413       isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_in, InputDimsId);
414   InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_out);
415   CheckedAccessRelation =
416       isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_out, InputDimsId);
417   auto res = !isl_map_is_equal(CheckedAccessRelation, IslMap);
418   isl_map_free(CheckedAccessRelation);
419   isl_map_free(IslMap);
420   return res;
421 }
422 
423 /// @brief Check if the SCoP statement could probably be optimized with
424 ///        analytical modeling.
425 ///
426 /// containsMatrMult tries to determine whether the following conditions
427 /// are true:
428 /// 1. all memory accesses of the statement will have stride 0 or 1,
429 ///    if we interchange loops (switch the variable used in the inner
430 ///    loop to the outer loop).
431 /// 2. all memory accesses of the statement except from the last one, are
432 ///    read memory access and the last one is write memory access.
433 /// 3. all subscripts of the last memory access of the statement don't contain
434 ///    the variable used in the inner loop.
435 ///
436 /// @param PartialSchedule The PartialSchedule that contains a SCoP statement
437 ///        to check.
438 static bool containsMatrMult(__isl_keep isl_map *PartialSchedule) {
439   auto InputDimsId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
440   auto *ScpStmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
441   isl_id_free(InputDimsId);
442   if (ScpStmt->size() <= 1)
443     return false;
444   auto MemA = ScpStmt->begin();
445   for (unsigned i = 0; i < ScpStmt->size() - 2 && MemA != ScpStmt->end();
446        i++, MemA++)
447     if (!(*MemA)->isRead() ||
448         ((*MemA)->isArrayKind() &&
449          !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
450            (*MemA)->isStrideZero(isl_map_copy(PartialSchedule)))))
451       return false;
452   MemA++;
453   if (!(*MemA)->isWrite() || !(*MemA)->isArrayKind() ||
454       !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
455         (*MemA)->isStrideZero(isl_map_copy(PartialSchedule))))
456     return false;
457   auto DimNum = isl_map_dim(PartialSchedule, isl_dim_in);
458   return !isInputDimUsed((*MemA)->getAccessRelation(), DimNum - 1);
459 }
460 
461 /// @brief Circular shift of output dimensions of the integer map.
462 ///
463 /// @param IslMap The isl map to be modified.
464 static __isl_give isl_map *circularShiftOutputDims(__isl_take isl_map *IslMap) {
465   auto DimNum = isl_map_dim(IslMap, isl_dim_out);
466   if (DimNum == 0)
467     return IslMap;
468   auto InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
469   IslMap = isl_map_move_dims(IslMap, isl_dim_in, 0, isl_dim_out, DimNum - 1, 1);
470   IslMap = isl_map_move_dims(IslMap, isl_dim_out, 0, isl_dim_in, 0, 1);
471   return isl_map_set_tuple_id(IslMap, isl_dim_in, InputDimsId);
472 }
473 
474 bool ScheduleTreeOptimizer::isMatrMultPattern(
475     __isl_keep isl_schedule_node *Node) {
476   auto *PartialSchedule =
477       isl_schedule_node_band_get_partial_schedule_union_map(Node);
478   if (isl_union_map_n_map(PartialSchedule) != 1)
479     return false;
480   auto *NewPartialSchedule = isl_map_from_union_map(PartialSchedule);
481   auto DimNum = isl_map_dim(NewPartialSchedule, isl_dim_in);
482   if (DimNum != 3) {
483     isl_map_free(NewPartialSchedule);
484     return false;
485   }
486   assert(isl_map_dim(NewPartialSchedule, isl_dim_out) == 3 &&
487          "Each schedule dimension should be represented by a union piecewise"
488          "quasi-affine expression.");
489   NewPartialSchedule = circularShiftOutputDims(NewPartialSchedule);
490   if (containsMatrMult(NewPartialSchedule)) {
491     isl_map_free(NewPartialSchedule);
492     return true;
493   }
494   isl_map_free(NewPartialSchedule);
495   return false;
496 }
497 
498 __isl_give isl_schedule_node *
499 ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
500                                     void *User) {
501   if (!isTileableBandNode(Node))
502     return Node;
503 
504   if (PMBasedOpts && isMatrMultPattern(Node))
505     DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
506 
507   return standardBandOpts(Node, User);
508 }
509 
510 __isl_give isl_schedule *
511 ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule) {
512   isl_schedule_node *Root = isl_schedule_get_root(Schedule);
513   Root = optimizeScheduleNode(Root);
514   isl_schedule_free(Schedule);
515   auto S = isl_schedule_node_get_schedule(Root);
516   isl_schedule_node_free(Root);
517   return S;
518 }
519 
520 __isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
521     __isl_take isl_schedule_node *Node) {
522   Node = isl_schedule_node_map_descendant_bottom_up(Node, optimizeBand, NULL);
523   return Node;
524 }
525 
526 bool ScheduleTreeOptimizer::isProfitableSchedule(
527     Scop &S, __isl_keep isl_union_map *NewSchedule) {
528   // To understand if the schedule has been optimized we check if the schedule
529   // has changed at all.
530   // TODO: We can improve this by tracking if any necessarily beneficial
531   // transformations have been performed. This can e.g. be tiling, loop
532   // interchange, or ...) We can track this either at the place where the
533   // transformation has been performed or, in case of automatic ILP based
534   // optimizations, by comparing (yet to be defined) performance metrics
535   // before/after the scheduling optimizer
536   // (e.g., #stride-one accesses)
537   isl_union_map *OldSchedule = S.getSchedule();
538   bool changed = !isl_union_map_is_equal(OldSchedule, NewSchedule);
539   isl_union_map_free(OldSchedule);
540   return changed;
541 }
542 
543 namespace {
544 class IslScheduleOptimizer : public ScopPass {
545 public:
546   static char ID;
547   explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
548 
549   ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
550 
551   /// @brief Optimize the schedule of the SCoP @p S.
552   bool runOnScop(Scop &S) override;
553 
554   /// @brief Print the new schedule for the SCoP @p S.
555   void printScop(raw_ostream &OS, Scop &S) const override;
556 
557   /// @brief Register all analyses and transformation required.
558   void getAnalysisUsage(AnalysisUsage &AU) const override;
559 
560   /// @brief Release the internal memory.
561   void releaseMemory() override {
562     isl_schedule_free(LastSchedule);
563     LastSchedule = nullptr;
564   }
565 
566 private:
567   isl_schedule *LastSchedule;
568 };
569 }
570 
571 char IslScheduleOptimizer::ID = 0;
572 
573 bool IslScheduleOptimizer::runOnScop(Scop &S) {
574 
575   // Skip empty SCoPs but still allow code generation as it will delete the
576   // loops present but not needed.
577   if (S.getSize() == 0) {
578     S.markAsOptimized();
579     return false;
580   }
581 
582   const Dependences &D =
583       getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
584 
585   if (!D.hasValidDependences())
586     return false;
587 
588   isl_schedule_free(LastSchedule);
589   LastSchedule = nullptr;
590 
591   // Build input data.
592   int ValidityKinds =
593       Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
594   int ProximityKinds;
595 
596   if (OptimizeDeps == "all")
597     ProximityKinds =
598         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
599   else if (OptimizeDeps == "raw")
600     ProximityKinds = Dependences::TYPE_RAW;
601   else {
602     errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
603            << " Falling back to optimizing all dependences.\n";
604     ProximityKinds =
605         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
606   }
607 
608   isl_union_set *Domain = S.getDomains();
609 
610   if (!Domain)
611     return false;
612 
613   isl_union_map *Validity = D.getDependences(ValidityKinds);
614   isl_union_map *Proximity = D.getDependences(ProximityKinds);
615 
616   // Simplify the dependences by removing the constraints introduced by the
617   // domains. This can speed up the scheduling time significantly, as large
618   // constant coefficients will be removed from the dependences. The
619   // introduction of some additional dependences reduces the possible
620   // transformations, but in most cases, such transformation do not seem to be
621   // interesting anyway. In some cases this option may stop the scheduler to
622   // find any schedule.
623   if (SimplifyDeps == "yes") {
624     Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
625     Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
626     Proximity =
627         isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
628     Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
629   } else if (SimplifyDeps != "no") {
630     errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
631               "or 'no'. Falling back to default: 'yes'\n";
632   }
633 
634   DEBUG(dbgs() << "\n\nCompute schedule from: ");
635   DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
636   DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
637   DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
638 
639   unsigned IslSerializeSCCs;
640 
641   if (FusionStrategy == "max") {
642     IslSerializeSCCs = 0;
643   } else if (FusionStrategy == "min") {
644     IslSerializeSCCs = 1;
645   } else {
646     errs() << "warning: Unknown fusion strategy. Falling back to maximal "
647               "fusion.\n";
648     IslSerializeSCCs = 0;
649   }
650 
651   int IslMaximizeBands;
652 
653   if (MaximizeBandDepth == "yes") {
654     IslMaximizeBands = 1;
655   } else if (MaximizeBandDepth == "no") {
656     IslMaximizeBands = 0;
657   } else {
658     errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
659               " or 'no'. Falling back to default: 'yes'\n";
660     IslMaximizeBands = 1;
661   }
662 
663   int IslOuterCoincidence;
664 
665   if (OuterCoincidence == "yes") {
666     IslOuterCoincidence = 1;
667   } else if (OuterCoincidence == "no") {
668     IslOuterCoincidence = 0;
669   } else {
670     errs() << "warning: Option -polly-opt-outer-coincidence should either be "
671               "'yes' or 'no'. Falling back to default: 'no'\n";
672     IslOuterCoincidence = 0;
673   }
674 
675   isl_options_set_schedule_outer_coincidence(S.getIslCtx(),
676                                              IslOuterCoincidence);
677   isl_options_set_schedule_serialize_sccs(S.getIslCtx(), IslSerializeSCCs);
678   isl_options_set_schedule_maximize_band_depth(S.getIslCtx(), IslMaximizeBands);
679   isl_options_set_schedule_max_constant_term(S.getIslCtx(), MaxConstantTerm);
680   isl_options_set_schedule_max_coefficient(S.getIslCtx(), MaxCoefficient);
681   isl_options_set_tile_scale_tile_loops(S.getIslCtx(), 0);
682 
683   isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_CONTINUE);
684 
685   isl_schedule_constraints *ScheduleConstraints;
686   ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
687   ScheduleConstraints =
688       isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
689   ScheduleConstraints = isl_schedule_constraints_set_validity(
690       ScheduleConstraints, isl_union_map_copy(Validity));
691   ScheduleConstraints =
692       isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
693   isl_schedule *Schedule;
694   Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
695   isl_options_set_on_error(S.getIslCtx(), ISL_ON_ERROR_ABORT);
696 
697   // In cases the scheduler is not able to optimize the code, we just do not
698   // touch the schedule.
699   if (!Schedule)
700     return false;
701 
702   DEBUG({
703     auto *P = isl_printer_to_str(S.getIslCtx());
704     P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
705     P = isl_printer_print_schedule(P, Schedule);
706     dbgs() << "NewScheduleTree: \n" << isl_printer_get_str(P) << "\n";
707     isl_printer_free(P);
708   });
709 
710   isl_schedule *NewSchedule = ScheduleTreeOptimizer::optimizeSchedule(Schedule);
711   isl_union_map *NewScheduleMap = isl_schedule_get_map(NewSchedule);
712 
713   if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewScheduleMap)) {
714     isl_union_map_free(NewScheduleMap);
715     isl_schedule_free(NewSchedule);
716     return false;
717   }
718 
719   S.setScheduleTree(NewSchedule);
720   S.markAsOptimized();
721 
722   isl_union_map_free(NewScheduleMap);
723   return false;
724 }
725 
726 void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
727   isl_printer *p;
728   char *ScheduleStr;
729 
730   OS << "Calculated schedule:\n";
731 
732   if (!LastSchedule) {
733     OS << "n/a\n";
734     return;
735   }
736 
737   p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
738   p = isl_printer_print_schedule(p, LastSchedule);
739   ScheduleStr = isl_printer_get_str(p);
740   isl_printer_free(p);
741 
742   OS << ScheduleStr << "\n";
743 }
744 
745 void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
746   ScopPass::getAnalysisUsage(AU);
747   AU.addRequired<DependenceInfo>();
748 }
749 
750 Pass *polly::createIslScheduleOptimizerPass() {
751   return new IslScheduleOptimizer();
752 }
753 
754 INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
755                       "Polly - Optimize schedule of SCoP", false, false);
756 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
757 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
758 INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
759                     "Polly - Optimize schedule of SCoP", false, false)
760