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 entirely 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 choice 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 Transactions 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 "polly/Support/ISLOStream.h"
57 #include "llvm/Analysis/TargetTransformInfo.h"
58 #include "llvm/Support/Debug.h"
59 #include "isl/aff.h"
60 #include "isl/band.h"
61 #include "isl/constraint.h"
62 #include "isl/map.h"
63 #include "isl/options.h"
64 #include "isl/printer.h"
65 #include "isl/schedule.h"
66 #include "isl/schedule_node.h"
67 #include "isl/space.h"
68 #include "isl/union_map.h"
69 #include "isl/union_set.h"
70 
71 using namespace llvm;
72 using namespace polly;
73 
74 #define DEBUG_TYPE "polly-opt-isl"
75 
76 static cl::opt<std::string>
77     OptimizeDeps("polly-opt-optimize-only",
78                  cl::desc("Only a certain kind of dependences (all/raw)"),
79                  cl::Hidden, cl::init("all"), cl::ZeroOrMore,
80                  cl::cat(PollyCategory));
81 
82 static cl::opt<std::string>
83     SimplifyDeps("polly-opt-simplify-deps",
84                  cl::desc("Dependences should be simplified (yes/no)"),
85                  cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
86                  cl::cat(PollyCategory));
87 
88 static cl::opt<int> MaxConstantTerm(
89     "polly-opt-max-constant-term",
90     cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
91     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
92 
93 static cl::opt<int> MaxCoefficient(
94     "polly-opt-max-coefficient",
95     cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
96     cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
97 
98 static cl::opt<std::string> FusionStrategy(
99     "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
100     cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
101 
102 static cl::opt<std::string>
103     MaximizeBandDepth("polly-opt-maximize-bands",
104                       cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
105                       cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
106 
107 static cl::opt<std::string> OuterCoincidence(
108     "polly-opt-outer-coincidence",
109     cl::desc("Try to construct schedules where the outer member of each band "
110              "satisfies the coincidence constraints (yes/no)"),
111     cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory));
112 
113 static cl::opt<int> PrevectorWidth(
114     "polly-prevect-width",
115     cl::desc(
116         "The number of loop iterations to strip-mine for pre-vectorization"),
117     cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
118 
119 static cl::opt<bool> FirstLevelTiling("polly-tiling",
120                                       cl::desc("Enable loop tiling"),
121                                       cl::init(true), cl::ZeroOrMore,
122                                       cl::cat(PollyCategory));
123 
124 static cl::opt<int> LatencyVectorFma(
125     "polly-target-latency-vector-fma",
126     cl::desc("The minimal number of cycles between issuing two "
127              "dependent consecutive vector fused multiply-add "
128              "instructions."),
129     cl::Hidden, cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
130 
131 static cl::opt<int> ThroughputVectorFma(
132     "polly-target-throughput-vector-fma",
133     cl::desc("A throughput of the processor floating-point arithmetic units "
134              "expressed in the number of vector fused multiply-add "
135              "instructions per clock cycle."),
136     cl::Hidden, cl::init(1), cl::ZeroOrMore, cl::cat(PollyCategory));
137 
138 // This option, along with --polly-target-2nd-cache-level-associativity,
139 // --polly-target-1st-cache-level-size, and --polly-target-2st-cache-level-size
140 // represent the parameters of the target cache, which do not have typical
141 // values that can be used by default. However, to apply the pattern matching
142 // optimizations, we use the values of the parameters of Intel Core i7-3820
143 // SandyBridge in case the parameters are not specified. Such an approach helps
144 // also to attain the high-performance on IBM POWER System S822 and IBM Power
145 // 730 Express server.
146 static cl::opt<int> FirstCacheLevelAssociativity(
147     "polly-target-1st-cache-level-associativity",
148     cl::desc("The associativity of the first cache level."), cl::Hidden,
149     cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
150 
151 static cl::opt<int> SecondCacheLevelAssociativity(
152     "polly-target-2nd-cache-level-associativity",
153     cl::desc("The associativity of the second cache level."), cl::Hidden,
154     cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
155 
156 static cl::opt<int> FirstCacheLevelSize(
157     "polly-target-1st-cache-level-size",
158     cl::desc("The size of the first cache level specified in bytes."),
159     cl::Hidden, cl::init(32768), cl::ZeroOrMore, cl::cat(PollyCategory));
160 
161 static cl::opt<int> SecondCacheLevelSize(
162     "polly-target-2nd-cache-level-size",
163     cl::desc("The size of the second level specified in bytes."), cl::Hidden,
164     cl::init(262144), cl::ZeroOrMore, cl::cat(PollyCategory));
165 
166 static cl::opt<int> VectorRegisterBitwidth(
167     "polly-target-vector-register-bitwidth",
168     cl::desc("The size in bits of a vector register (if not set, this "
169              "information is taken from LLVM's target information."),
170     cl::Hidden, cl::init(-1), cl::ZeroOrMore, cl::cat(PollyCategory));
171 
172 static cl::opt<int> FirstLevelDefaultTileSize(
173     "polly-default-tile-size",
174     cl::desc("The default tile size (if not enough were provided by"
175              " --polly-tile-sizes)"),
176     cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
177 
178 static cl::list<int>
179     FirstLevelTileSizes("polly-tile-sizes",
180                         cl::desc("A tile size for each loop dimension, filled "
181                                  "with --polly-default-tile-size"),
182                         cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
183                         cl::cat(PollyCategory));
184 
185 static cl::opt<bool>
186     SecondLevelTiling("polly-2nd-level-tiling",
187                       cl::desc("Enable a 2nd level loop of loop tiling"),
188                       cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
189 
190 static cl::opt<int> SecondLevelDefaultTileSize(
191     "polly-2nd-level-default-tile-size",
192     cl::desc("The default 2nd-level tile size (if not enough were provided by"
193              " --polly-2nd-level-tile-sizes)"),
194     cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
195 
196 static cl::list<int>
197     SecondLevelTileSizes("polly-2nd-level-tile-sizes",
198                          cl::desc("A tile size for each loop dimension, filled "
199                                   "with --polly-default-tile-size"),
200                          cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
201                          cl::cat(PollyCategory));
202 
203 static cl::opt<bool> RegisterTiling("polly-register-tiling",
204                                     cl::desc("Enable register tiling"),
205                                     cl::init(false), cl::ZeroOrMore,
206                                     cl::cat(PollyCategory));
207 
208 static cl::opt<int> RegisterDefaultTileSize(
209     "polly-register-tiling-default-tile-size",
210     cl::desc("The default register tile size (if not enough were provided by"
211              " --polly-register-tile-sizes)"),
212     cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
213 
214 static cl::opt<int> PollyPatternMatchingNcQuotient(
215     "polly-pattern-matching-nc-quotient",
216     cl::desc("Quotient that is obtained by dividing Nc, the parameter of the"
217              "macro-kernel, by Nr, the parameter of the micro-kernel"),
218     cl::Hidden, cl::init(256), cl::ZeroOrMore, cl::cat(PollyCategory));
219 
220 static cl::list<int>
221     RegisterTileSizes("polly-register-tile-sizes",
222                       cl::desc("A tile size for each loop dimension, filled "
223                                "with --polly-register-tile-size"),
224                       cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
225                       cl::cat(PollyCategory));
226 
227 static cl::opt<bool>
228     PMBasedOpts("polly-pattern-matching-based-opts",
229                 cl::desc("Perform optimizations based on pattern matching"),
230                 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory));
231 
232 static cl::opt<bool> OptimizedScops(
233     "polly-optimized-scops",
234     cl::desc("Polly - Dump polyhedral description of Scops optimized with "
235              "the isl scheduling optimizer and the set of post-scheduling "
236              "transformations is applied on the schedule tree"),
237     cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
238 
239 /// Create an isl::union_set, which describes the isolate option based on
240 /// IsolateDomain.
241 ///
242 /// @param IsolateDomain An isl::set whose @p OutDimsNum last dimensions should
243 ///                      belong to the current band node.
244 /// @param OutDimsNum    A number of dimensions that should belong to
245 ///                      the current band node.
246 static isl::union_set getIsolateOptions(isl::set IsolateDomain,
247                                         unsigned OutDimsNum) {
248   unsigned Dims = IsolateDomain.dim(isl::dim::set);
249   assert(OutDimsNum <= Dims &&
250          "The isl::set IsolateDomain is used to describe the range of schedule "
251          "dimensions values, which should be isolated. Consequently, the "
252          "number of its dimensions should be greater than or equal to the "
253          "number of the schedule dimensions.");
254   isl::map IsolateRelation = isl::map::from_domain(IsolateDomain);
255   IsolateRelation = IsolateRelation.move_dims(isl::dim::out, 0, isl::dim::in,
256                                               Dims - OutDimsNum, OutDimsNum);
257   isl::set IsolateOption = IsolateRelation.wrap();
258   isl::id Id = isl::id::alloc(IsolateOption.get_ctx(), "isolate", nullptr);
259   IsolateOption = IsolateOption.set_tuple_id(Id);
260   return isl::union_set(IsolateOption);
261 }
262 
263 /// Create an isl::union_set, which describes the atomic option for the
264 /// dimension of the current node.
265 ///
266 /// It may help to reduce the size of generated code.
267 ///
268 /// @param Ctx An isl::ctx, which is used to create the isl::union_set.
269 static isl::union_set getAtomicOptions(isl::ctx Ctx) {
270   isl::space Space(Ctx, 0, 1);
271   isl::set AtomicOption = isl::set::universe(Space);
272   isl::id Id = isl::id::alloc(Ctx, "atomic", nullptr);
273   AtomicOption = AtomicOption.set_tuple_id(Id);
274   return isl::union_set(AtomicOption);
275 }
276 
277 /// Create an isl::union_set, which describes the option of the form
278 /// [isolate[] -> unroll[x]].
279 ///
280 /// @param Ctx An isl::ctx, which is used to create the isl::union_set.
281 static isl::union_set getUnrollIsolatedSetOptions(isl::ctx Ctx) {
282   isl::space Space = isl::space(Ctx, 0, 0, 1);
283   isl::map UnrollIsolatedSetOption = isl::map::universe(Space);
284   isl::id DimInId = isl::id::alloc(Ctx, "isolate", nullptr);
285   isl::id DimOutId = isl::id::alloc(Ctx, "unroll", nullptr);
286   UnrollIsolatedSetOption =
287       UnrollIsolatedSetOption.set_tuple_id(isl::dim::in, DimInId);
288   UnrollIsolatedSetOption =
289       UnrollIsolatedSetOption.set_tuple_id(isl::dim::out, DimOutId);
290   return UnrollIsolatedSetOption.wrap();
291 }
292 
293 /// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
294 ///
295 /// @param Set         A set, which should be modified.
296 /// @param VectorWidth A parameter, which determines the constraint.
297 static isl::set addExtentConstraints(isl::set Set, int VectorWidth) {
298   unsigned Dims = Set.dim(isl::dim::set);
299   isl::space Space = Set.get_space();
300   isl::local_space LocalSpace = isl::local_space(Space);
301   isl::constraint ExtConstr = isl::constraint::alloc_inequality(LocalSpace);
302   ExtConstr = ExtConstr.set_constant_si(0);
303   ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, 1);
304   Set = Set.add_constraint(ExtConstr);
305   ExtConstr = isl::constraint::alloc_inequality(LocalSpace);
306   ExtConstr = ExtConstr.set_constant_si(VectorWidth - 1);
307   ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, -1);
308   return Set.add_constraint(ExtConstr);
309 }
310 
311 /// Build the desired set of partial tile prefixes.
312 ///
313 /// We build a set of partial tile prefixes, which are prefixes of the vector
314 /// loop that have exactly VectorWidth iterations.
315 ///
316 /// 1. Get all prefixes of the vector loop.
317 /// 2. Extend it to a set, which has exactly VectorWidth iterations for
318 ///    any prefix from the set that was built on the previous step.
319 /// 3. Subtract loop domain from it, project out the vector loop dimension and
320 ///    get a set of prefixes, which don't have exactly VectorWidth iterations.
321 /// 4. Subtract it from all prefixes of the vector loop and get the desired
322 ///    set.
323 ///
324 /// @param ScheduleRange A range of a map, which describes a prefix schedule
325 ///                      relation.
326 static isl::set getPartialTilePrefixes(isl::set ScheduleRange,
327                                        int VectorWidth) {
328   unsigned Dims = ScheduleRange.dim(isl::dim::set);
329   isl::set LoopPrefixes = ScheduleRange.project_out(isl::dim::set, Dims - 1, 1);
330   isl::set ExtentPrefixes = LoopPrefixes.add_dims(isl::dim::set, 1);
331   ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
332   isl::set BadPrefixes = ExtentPrefixes.subtract(ScheduleRange);
333   BadPrefixes = BadPrefixes.project_out(isl::dim::set, Dims - 1, 1);
334   return LoopPrefixes.subtract(BadPrefixes);
335 }
336 
337 isl::schedule_node
338 ScheduleTreeOptimizer::isolateFullPartialTiles(isl::schedule_node Node,
339                                                int VectorWidth) {
340   assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band);
341   Node = Node.child(0).child(0);
342   isl::union_map SchedRelUMap = Node.get_prefix_schedule_relation();
343   isl::map ScheduleRelation = isl::map::from_union_map(SchedRelUMap);
344   isl::set ScheduleRange = ScheduleRelation.range();
345   isl::set IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
346   isl::union_set AtomicOption = getAtomicOptions(IsolateDomain.get_ctx());
347   isl::union_set IsolateOption = getIsolateOptions(IsolateDomain, 1);
348   Node = Node.parent().parent();
349   isl::union_set Options = IsolateOption.unite(AtomicOption);
350   Node = Node.band_set_ast_build_options(Options);
351   return Node;
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 
358   auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
359   auto ScheduleDimensions = Space.dim(isl::dim::set);
360   assert(DimToVectorize < ScheduleDimensions);
361 
362   if (DimToVectorize > 0) {
363     Node = isl::manage(
364         isl_schedule_node_band_split(Node.release(), DimToVectorize));
365     Node = Node.child(0);
366   }
367   if (DimToVectorize < ScheduleDimensions - 1)
368     Node = isl::manage(isl_schedule_node_band_split(Node.release(), 1));
369   Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
370   auto Sizes = isl::multi_val::zero(Space);
371   Sizes = Sizes.set_val(0, isl::val(Node.get_ctx(), VectorWidth));
372   Node =
373       isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release()));
374   Node = isolateFullPartialTiles(Node, VectorWidth);
375   Node = Node.child(0);
376   // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
377   // we will have troubles to match it in the backend.
378   Node = Node.band_set_ast_build_options(
379       isl::union_set(Node.get_ctx(), "{ unroll[x]: 1 = 0 }"));
380   Node = isl::manage(isl_schedule_node_band_sink(Node.release()));
381   Node = Node.child(0);
382   if (isl_schedule_node_get_type(Node.get()) == isl_schedule_node_leaf)
383     Node = Node.parent();
384   auto LoopMarker = isl::id::alloc(Node.get_ctx(), "SIMD", nullptr);
385   return Node.insert_mark(LoopMarker);
386 }
387 
388 isl::schedule_node ScheduleTreeOptimizer::tileNode(isl::schedule_node Node,
389                                                    const char *Identifier,
390                                                    ArrayRef<int> TileSizes,
391                                                    int DefaultTileSize) {
392   auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
393   auto Dims = Space.dim(isl::dim::set);
394   auto Sizes = isl::multi_val::zero(Space);
395   std::string IdentifierString(Identifier);
396   for (unsigned i = 0; i < Dims; i++) {
397     auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
398     Sizes = Sizes.set_val(i, isl::val(Node.get_ctx(), tileSize));
399   }
400   auto TileLoopMarkerStr = IdentifierString + " - Tiles";
401   auto TileLoopMarker =
402       isl::id::alloc(Node.get_ctx(), TileLoopMarkerStr.c_str(), nullptr);
403   Node = Node.insert_mark(TileLoopMarker);
404   Node = Node.child(0);
405   Node =
406       isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release()));
407   Node = Node.child(0);
408   auto PointLoopMarkerStr = IdentifierString + " - Points";
409   auto PointLoopMarker =
410       isl::id::alloc(Node.get_ctx(), PointLoopMarkerStr.c_str(), nullptr);
411   Node = Node.insert_mark(PointLoopMarker);
412   return Node.child(0);
413 }
414 
415 isl::schedule_node
416 ScheduleTreeOptimizer::applyRegisterTiling(isl::schedule_node Node,
417                                            llvm::ArrayRef<int> TileSizes,
418                                            int DefaultTileSize) {
419   Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
420   auto Ctx = Node.get_ctx();
421   return Node.band_set_ast_build_options(isl::union_set(Ctx, "{unroll[x]}"));
422 }
423 
424 namespace {
425 bool isSimpleInnermostBand(const isl::schedule_node &Node) {
426   assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band);
427   assert(isl_schedule_node_n_children(Node.keep()) == 1);
428 
429   auto ChildType = isl_schedule_node_get_type(Node.child(0).keep());
430 
431   if (ChildType == isl_schedule_node_leaf)
432     return true;
433 
434   if (ChildType != isl_schedule_node_sequence)
435     return false;
436 
437   auto Sequence = Node.child(0);
438 
439   for (int c = 0, nc = isl_schedule_node_n_children(Sequence.keep()); c < nc;
440        ++c) {
441     auto Child = Sequence.child(c);
442     if (isl_schedule_node_get_type(Child.keep()) != isl_schedule_node_filter)
443       return false;
444     if (isl_schedule_node_get_type(Child.child(0).keep()) !=
445         isl_schedule_node_leaf)
446       return false;
447   }
448   return true;
449 }
450 } // namespace
451 
452 bool ScheduleTreeOptimizer::isTileableBandNode(isl::schedule_node Node) {
453   if (isl_schedule_node_get_type(Node.get()) != isl_schedule_node_band)
454     return false;
455 
456   if (isl_schedule_node_n_children(Node.get()) != 1)
457     return false;
458 
459   if (!isl_schedule_node_band_get_permutable(Node.get()))
460     return false;
461 
462   auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
463   auto Dims = Space.dim(isl::dim::set);
464 
465   if (Dims <= 1)
466     return false;
467 
468   return isSimpleInnermostBand(Node);
469 }
470 
471 __isl_give isl::schedule_node
472 ScheduleTreeOptimizer::standardBandOpts(isl::schedule_node Node, void *User) {
473   if (FirstLevelTiling)
474     Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
475                     FirstLevelDefaultTileSize);
476 
477   if (SecondLevelTiling)
478     Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
479                     SecondLevelDefaultTileSize);
480 
481   if (RegisterTiling)
482     Node =
483         applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
484 
485   if (PollyVectorizerChoice == VECTORIZER_NONE)
486     return Node;
487 
488   auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
489   auto Dims = Space.dim(isl::dim::set);
490 
491   for (int i = Dims - 1; i >= 0; i--)
492     if (Node.band_member_get_coincident(i)) {
493       Node = prevectSchedBand(Node, i, PrevectorWidth);
494       break;
495     }
496 
497   return Node;
498 }
499 
500 /// Get the position of a dimension with a non-zero coefficient.
501 ///
502 /// Check that isl constraint @p Constraint has only one non-zero
503 /// coefficient for dimensions that have type @p DimType. If this is true,
504 /// return the position of the dimension corresponding to the non-zero
505 /// coefficient and negative value, otherwise.
506 ///
507 /// @param Constraint The isl constraint to be checked.
508 /// @param DimType    The type of the dimensions.
509 /// @return           The position of the dimension in case the isl
510 ///                   constraint satisfies the requirements, a negative
511 ///                   value, otherwise.
512 static int getMatMulConstraintDim(isl::constraint Constraint,
513                                   isl::dim DimType) {
514   int DimPos = -1;
515   auto LocalSpace = Constraint.get_local_space();
516   int LocalSpaceDimNum = LocalSpace.dim(DimType);
517   for (int i = 0; i < LocalSpaceDimNum; i++) {
518     auto Val = Constraint.get_coefficient_val(DimType, i);
519     if (Val.is_zero())
520       continue;
521     if (DimPos >= 0 || (DimType == isl::dim::out && !Val.is_one()) ||
522         (DimType == isl::dim::in && !Val.is_negone()))
523       return -1;
524     DimPos = i;
525   }
526   return DimPos;
527 }
528 
529 /// Check the form of the isl constraint.
530 ///
531 /// Check that the @p DimInPos input dimension of the isl constraint
532 /// @p Constraint has a coefficient that is equal to negative one, the @p
533 /// DimOutPos has a coefficient that is equal to one and others
534 /// have coefficients equal to zero.
535 ///
536 /// @param Constraint The isl constraint to be checked.
537 /// @param DimInPos   The input dimension of the isl constraint.
538 /// @param DimOutPos  The output dimension of the isl constraint.
539 /// @return           isl_stat_ok in case the isl constraint satisfies
540 ///                   the requirements, isl_stat_error otherwise.
541 static isl_stat isMatMulOperandConstraint(isl::constraint Constraint,
542                                           int &DimInPos, int &DimOutPos) {
543   auto Val = Constraint.get_constant_val();
544   if (!isl_constraint_is_equality(Constraint.get()) || !Val.is_zero())
545     return isl_stat_error;
546   DimInPos = getMatMulConstraintDim(Constraint, isl::dim::in);
547   if (DimInPos < 0)
548     return isl_stat_error;
549   DimOutPos = getMatMulConstraintDim(Constraint, isl::dim::out);
550   if (DimOutPos < 0)
551     return isl_stat_error;
552   return isl_stat_ok;
553 }
554 
555 /// Permute the two dimensions of the isl map.
556 ///
557 /// Permute @p DstPos and @p SrcPos dimensions of the isl map @p Map that
558 /// have type @p DimType.
559 ///
560 /// @param Map     The isl map to be modified.
561 /// @param DimType The type of the dimensions.
562 /// @param DstPos  The first dimension.
563 /// @param SrcPos  The second dimension.
564 /// @return        The modified map.
565 isl::map permuteDimensions(isl::map Map, isl::dim DimType, unsigned DstPos,
566                            unsigned SrcPos) {
567   assert(DstPos < Map.dim(DimType) && SrcPos < Map.dim(DimType));
568   if (DstPos == SrcPos)
569     return Map;
570   isl::id DimId;
571   if (Map.has_tuple_id(DimType))
572     DimId = Map.get_tuple_id(DimType);
573   auto FreeDim = DimType == isl::dim::in ? isl::dim::out : isl::dim::in;
574   isl::id FreeDimId;
575   if (Map.has_tuple_id(FreeDim))
576     FreeDimId = Map.get_tuple_id(FreeDim);
577   auto MaxDim = std::max(DstPos, SrcPos);
578   auto MinDim = std::min(DstPos, SrcPos);
579   Map = Map.move_dims(FreeDim, 0, DimType, MaxDim, 1);
580   Map = Map.move_dims(FreeDim, 0, DimType, MinDim, 1);
581   Map = Map.move_dims(DimType, MinDim, FreeDim, 1, 1);
582   Map = Map.move_dims(DimType, MaxDim, FreeDim, 0, 1);
583   if (DimId)
584     Map = Map.set_tuple_id(DimType, DimId);
585   if (FreeDimId)
586     Map = Map.set_tuple_id(FreeDim, FreeDimId);
587   return Map;
588 }
589 
590 /// Check the form of the access relation.
591 ///
592 /// Check that the access relation @p AccMap has the form M[i][j], where i
593 /// is a @p FirstPos and j is a @p SecondPos.
594 ///
595 /// @param AccMap    The access relation to be checked.
596 /// @param FirstPos  The index of the input dimension that is mapped to
597 ///                  the first output dimension.
598 /// @param SecondPos The index of the input dimension that is mapped to the
599 ///                  second output dimension.
600 /// @return          True in case @p AccMap has the expected form and false,
601 ///                  otherwise.
602 static bool isMatMulOperandAcc(isl::map AccMap, int &FirstPos, int &SecondPos) {
603   int DimInPos[] = {FirstPos, SecondPos};
604   auto Lambda = [=, &DimInPos](isl::basic_map BasicMap) -> isl::stat {
605     auto Constraints = BasicMap.get_constraint_list();
606     if (isl_constraint_list_n_constraint(Constraints.get()) != 2)
607       return isl::stat::error;
608     for (int i = 0; i < 2; i++) {
609       auto Constraint =
610           isl::manage(isl_constraint_list_get_constraint(Constraints.get(), i));
611       int InPos, OutPos;
612       if (isMatMulOperandConstraint(Constraint, InPos, OutPos) ==
613               isl_stat_error ||
614           OutPos > 1 || (DimInPos[OutPos] >= 0 && DimInPos[OutPos] != InPos))
615         return isl::stat::error;
616       DimInPos[OutPos] = InPos;
617     }
618     return isl::stat::ok;
619   };
620   if (AccMap.foreach_basic_map(Lambda) != isl::stat::ok || DimInPos[0] < 0 ||
621       DimInPos[1] < 0)
622     return false;
623   FirstPos = DimInPos[0];
624   SecondPos = DimInPos[1];
625   return true;
626 }
627 
628 /// Does the memory access represent a non-scalar operand of the matrix
629 /// multiplication.
630 ///
631 /// Check that the memory access @p MemAccess is the read access to a non-scalar
632 /// operand of the matrix multiplication or its result.
633 ///
634 /// @param MemAccess The memory access to be checked.
635 /// @param MMI       Parameters of the matrix multiplication operands.
636 /// @return          True in case the memory access represents the read access
637 ///                  to a non-scalar operand of the matrix multiplication and
638 ///                  false, otherwise.
639 static bool isMatMulNonScalarReadAccess(MemoryAccess *MemAccess,
640                                         MatMulInfoTy &MMI) {
641   if (!MemAccess->isLatestArrayKind() || !MemAccess->isRead())
642     return false;
643   auto AccMap = MemAccess->getLatestAccessRelation();
644   if (isMatMulOperandAcc(AccMap, MMI.i, MMI.j) && !MMI.ReadFromC &&
645       isl_map_n_basic_map(AccMap.get()) == 1) {
646     MMI.ReadFromC = MemAccess;
647     return true;
648   }
649   if (isMatMulOperandAcc(AccMap, MMI.i, MMI.k) && !MMI.A &&
650       isl_map_n_basic_map(AccMap.get()) == 1) {
651     MMI.A = MemAccess;
652     return true;
653   }
654   if (isMatMulOperandAcc(AccMap, MMI.k, MMI.j) && !MMI.B &&
655       isl_map_n_basic_map(AccMap.get()) == 1) {
656     MMI.B = MemAccess;
657     return true;
658   }
659   return false;
660 }
661 
662 /// Check accesses to operands of the matrix multiplication.
663 ///
664 /// Check that accesses of the SCoP statement, which corresponds to
665 /// the partial schedule @p PartialSchedule, are scalar in terms of loops
666 /// containing the matrix multiplication, in case they do not represent
667 /// accesses to the non-scalar operands of the matrix multiplication or
668 /// its result.
669 ///
670 /// @param  PartialSchedule The partial schedule of the SCoP statement.
671 /// @param  MMI             Parameters of the matrix multiplication operands.
672 /// @return                 True in case the corresponding SCoP statement
673 ///                         represents matrix multiplication and false,
674 ///                         otherwise.
675 static bool containsOnlyMatrMultAcc(isl::map PartialSchedule,
676                                     MatMulInfoTy &MMI) {
677   auto InputDimId = PartialSchedule.get_tuple_id(isl::dim::in);
678   auto *Stmt = static_cast<ScopStmt *>(InputDimId.get_user());
679   unsigned OutDimNum = PartialSchedule.dim(isl::dim::out);
680   assert(OutDimNum > 2 && "In case of the matrix multiplication the loop nest "
681                           "and, consequently, the corresponding scheduling "
682                           "functions have at least three dimensions.");
683   auto MapI =
684       permuteDimensions(PartialSchedule, isl::dim::out, MMI.i, OutDimNum - 1);
685   auto MapJ =
686       permuteDimensions(PartialSchedule, isl::dim::out, MMI.j, OutDimNum - 1);
687   auto MapK =
688       permuteDimensions(PartialSchedule, isl::dim::out, MMI.k, OutDimNum - 1);
689   for (auto *MemA = Stmt->begin(); MemA != Stmt->end() - 1; MemA++) {
690     auto *MemAccessPtr = *MemA;
691     if (MemAccessPtr->isLatestArrayKind() && MemAccessPtr != MMI.WriteToC &&
692         !isMatMulNonScalarReadAccess(MemAccessPtr, MMI) &&
693         !(MemAccessPtr->isStrideZero(MapI)) &&
694         MemAccessPtr->isStrideZero(MapJ) && MemAccessPtr->isStrideZero(MapK))
695       return false;
696   }
697   return true;
698 }
699 
700 /// Check for dependencies corresponding to the matrix multiplication.
701 ///
702 /// Check that there is only true dependence of the form
703 /// S(..., k, ...) -> S(..., k + 1, …), where S is the SCoP statement
704 /// represented by @p Schedule and k is @p Pos. Such a dependence corresponds
705 /// to the dependency produced by the matrix multiplication.
706 ///
707 /// @param  Schedule The schedule of the SCoP statement.
708 /// @param  D The SCoP dependencies.
709 /// @param  Pos The parameter to describe an acceptable true dependence.
710 ///             In case it has a negative value, try to determine its
711 ///             acceptable value.
712 /// @return True in case dependencies correspond to the matrix multiplication
713 ///         and false, otherwise.
714 static bool containsOnlyMatMulDep(isl::map Schedule, const Dependences *D,
715                                   int &Pos) {
716   auto Dep = isl::manage(D->getDependences(Dependences::TYPE_RAW));
717   auto Red = isl::manage(D->getDependences(Dependences::TYPE_RED));
718   if (Red)
719     Dep = Dep.unite(Red);
720   auto DomainSpace = Schedule.get_space().domain();
721   auto Space = DomainSpace.map_from_domain_and_range(DomainSpace);
722   auto Deltas = Dep.extract_map(Space).deltas();
723   int DeltasDimNum = Deltas.dim(isl::dim::set);
724   for (int i = 0; i < DeltasDimNum; i++) {
725     auto Val = Deltas.plain_get_val_if_fixed(isl::dim::set, i);
726     Pos = Pos < 0 && Val.is_one() ? i : Pos;
727     if (Val.is_nan() || !(Val.is_zero() || (i == Pos && Val.is_one())))
728       return false;
729   }
730   if (DeltasDimNum == 0 || Pos < 0)
731     return false;
732   return true;
733 }
734 
735 /// Check if the SCoP statement could probably be optimized with analytical
736 /// modeling.
737 ///
738 /// containsMatrMult tries to determine whether the following conditions
739 /// are true:
740 /// 1. The last memory access modeling an array, MA1, represents writing to
741 ///    memory and has the form S(..., i1, ..., i2, ...) -> M(i1, i2) or
742 ///    S(..., i2, ..., i1, ...) -> M(i1, i2), where S is the SCoP statement
743 ///    under consideration.
744 /// 2. There is only one loop-carried true dependency, and it has the
745 ///    form S(..., i3, ...) -> S(..., i3 + 1, ...), and there are no
746 ///    loop-carried or anti dependencies.
747 /// 3. SCoP contains three access relations, MA2, MA3, and MA4 that represent
748 ///    reading from memory and have the form S(..., i3, ...) -> M(i1, i3),
749 ///    S(..., i3, ...) -> M(i3, i2), S(...) -> M(i1, i2), respectively,
750 ///    and all memory accesses of the SCoP that are different from MA1, MA2,
751 ///    MA3, and MA4 have stride 0, if the innermost loop is exchanged with any
752 ///    of loops i1, i2 and i3.
753 ///
754 /// @param PartialSchedule The PartialSchedule that contains a SCoP statement
755 ///        to check.
756 /// @D     The SCoP dependencies.
757 /// @MMI   Parameters of the matrix multiplication operands.
758 static bool containsMatrMult(isl::map PartialSchedule, const Dependences *D,
759                              MatMulInfoTy &MMI) {
760   auto InputDimsId = PartialSchedule.get_tuple_id(isl::dim::in);
761   auto *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
762   if (Stmt->size() <= 1)
763     return false;
764   for (auto *MemA = Stmt->end() - 1; MemA != Stmt->begin(); MemA--) {
765     auto *MemAccessPtr = *MemA;
766     if (!MemAccessPtr->isLatestArrayKind())
767       continue;
768     if (!MemAccessPtr->isWrite())
769       return false;
770     auto AccMap = MemAccessPtr->getLatestAccessRelation();
771     if (isl_map_n_basic_map(AccMap.get()) != 1 ||
772         !isMatMulOperandAcc(AccMap, MMI.i, MMI.j))
773       return false;
774     MMI.WriteToC = MemAccessPtr;
775     break;
776   }
777 
778   if (!containsOnlyMatMulDep(PartialSchedule, D, MMI.k))
779     return false;
780 
781   if (!MMI.WriteToC || !containsOnlyMatrMultAcc(PartialSchedule, MMI))
782     return false;
783 
784   if (!MMI.A || !MMI.B || !MMI.ReadFromC)
785     return false;
786   return true;
787 }
788 
789 /// Permute two dimensions of the band node.
790 ///
791 /// Permute FirstDim and SecondDim dimensions of the Node.
792 ///
793 /// @param Node The band node to be modified.
794 /// @param FirstDim The first dimension to be permuted.
795 /// @param SecondDim The second dimension to be permuted.
796 static isl::schedule_node permuteBandNodeDimensions(isl::schedule_node Node,
797                                                     unsigned FirstDim,
798                                                     unsigned SecondDim) {
799   assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band &&
800          isl_schedule_node_band_n_member(Node.get()) >
801              std::max(FirstDim, SecondDim));
802   auto PartialSchedule =
803       isl::manage(isl_schedule_node_band_get_partial_schedule(Node.get()));
804   auto PartialScheduleFirstDim = PartialSchedule.get_union_pw_aff(FirstDim);
805   auto PartialScheduleSecondDim = PartialSchedule.get_union_pw_aff(SecondDim);
806   PartialSchedule =
807       PartialSchedule.set_union_pw_aff(SecondDim, PartialScheduleFirstDim);
808   PartialSchedule =
809       PartialSchedule.set_union_pw_aff(FirstDim, PartialScheduleSecondDim);
810   Node = isl::manage(isl_schedule_node_delete(Node.release()));
811   return Node.insert_partial_schedule(PartialSchedule);
812 }
813 
814 isl::schedule_node ScheduleTreeOptimizer::createMicroKernel(
815     isl::schedule_node Node, MicroKernelParamsTy MicroKernelParams) {
816   Node = applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr},
817                              1);
818   Node = Node.parent().parent();
819   return permuteBandNodeDimensions(Node, 0, 1).child(0).child(0);
820 }
821 
822 isl::schedule_node ScheduleTreeOptimizer::createMacroKernel(
823     isl::schedule_node Node, MacroKernelParamsTy MacroKernelParams) {
824   assert(isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band);
825   if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
826       MacroKernelParams.Kc == 1)
827     return Node;
828   int DimOutNum = isl_schedule_node_band_n_member(Node.get());
829   std::vector<int> TileSizes(DimOutNum, 1);
830   TileSizes[DimOutNum - 3] = MacroKernelParams.Mc;
831   TileSizes[DimOutNum - 2] = MacroKernelParams.Nc;
832   TileSizes[DimOutNum - 1] = MacroKernelParams.Kc;
833   Node = tileNode(Node, "1st level tiling", TileSizes, 1);
834   Node = Node.parent().parent();
835   Node = permuteBandNodeDimensions(Node, DimOutNum - 2, DimOutNum - 1);
836   Node = permuteBandNodeDimensions(Node, DimOutNum - 3, DimOutNum - 1);
837   return Node.child(0).child(0);
838 }
839 
840 /// Get the size of the widest type of the matrix multiplication operands
841 /// in bytes, including alignment padding.
842 ///
843 /// @param MMI Parameters of the matrix multiplication operands.
844 /// @return The size of the widest type of the matrix multiplication operands
845 ///         in bytes, including alignment padding.
846 static uint64_t getMatMulAlignTypeSize(MatMulInfoTy MMI) {
847   auto *S = MMI.A->getStatement()->getParent();
848   auto &DL = S->getFunction().getParent()->getDataLayout();
849   auto ElementSizeA = DL.getTypeAllocSize(MMI.A->getElementType());
850   auto ElementSizeB = DL.getTypeAllocSize(MMI.B->getElementType());
851   auto ElementSizeC = DL.getTypeAllocSize(MMI.WriteToC->getElementType());
852   return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
853 }
854 
855 /// Get the size of the widest type of the matrix multiplication operands
856 /// in bits.
857 ///
858 /// @param MMI Parameters of the matrix multiplication operands.
859 /// @return The size of the widest type of the matrix multiplication operands
860 ///         in bits.
861 static uint64_t getMatMulTypeSize(MatMulInfoTy MMI) {
862   auto *S = MMI.A->getStatement()->getParent();
863   auto &DL = S->getFunction().getParent()->getDataLayout();
864   auto ElementSizeA = DL.getTypeSizeInBits(MMI.A->getElementType());
865   auto ElementSizeB = DL.getTypeSizeInBits(MMI.B->getElementType());
866   auto ElementSizeC = DL.getTypeSizeInBits(MMI.WriteToC->getElementType());
867   return std::max({ElementSizeA, ElementSizeB, ElementSizeC});
868 }
869 
870 /// Get parameters of the BLIS micro kernel.
871 ///
872 /// We choose the Mr and Nr parameters of the micro kernel to be large enough
873 /// such that no stalls caused by the combination of latencies and dependencies
874 /// are introduced during the updates of the resulting matrix of the matrix
875 /// multiplication. However, they should also be as small as possible to
876 /// release more registers for entries of multiplied matrices.
877 ///
878 /// @param TTI Target Transform Info.
879 /// @param MMI Parameters of the matrix multiplication operands.
880 /// @return The structure of type MicroKernelParamsTy.
881 /// @see MicroKernelParamsTy
882 static struct MicroKernelParamsTy
883 getMicroKernelParams(const llvm::TargetTransformInfo *TTI, MatMulInfoTy MMI) {
884   assert(TTI && "The target transform info should be provided.");
885 
886   // Nvec - Number of double-precision floating-point numbers that can be hold
887   // by a vector register. Use 2 by default.
888   long RegisterBitwidth = VectorRegisterBitwidth;
889 
890   if (RegisterBitwidth == -1)
891     RegisterBitwidth = TTI->getRegisterBitWidth(true);
892   auto ElementSize = getMatMulTypeSize(MMI);
893   assert(ElementSize > 0 && "The element size of the matrix multiplication "
894                             "operands should be greater than zero.");
895   auto Nvec = RegisterBitwidth / ElementSize;
896   if (Nvec == 0)
897     Nvec = 2;
898   int Nr =
899       ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec;
900   int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr);
901   return {Mr, Nr};
902 }
903 
904 /// Get parameters of the BLIS macro kernel.
905 ///
906 /// During the computation of matrix multiplication, blocks of partitioned
907 /// matrices are mapped to different layers of the memory hierarchy.
908 /// To optimize data reuse, blocks should be ideally kept in cache between
909 /// iterations. Since parameters of the macro kernel determine sizes of these
910 /// blocks, there are upper and lower bounds on these parameters.
911 ///
912 /// @param MicroKernelParams Parameters of the micro-kernel
913 ///                          to be taken into account.
914 /// @param MMI Parameters of the matrix multiplication operands.
915 /// @return The structure of type MacroKernelParamsTy.
916 /// @see MacroKernelParamsTy
917 /// @see MicroKernelParamsTy
918 static struct MacroKernelParamsTy
919 getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams,
920                      MatMulInfoTy MMI) {
921   // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
922   // it requires information about the first two levels of a cache to determine
923   // all the parameters of a macro-kernel. It also checks that an associativity
924   // degree of a cache level is greater than two. Otherwise, another algorithm
925   // for determination of the parameters should be used.
926   if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
927         FirstCacheLevelSize > 0 && SecondCacheLevelSize > 0 &&
928         FirstCacheLevelAssociativity > 2 && SecondCacheLevelAssociativity > 2))
929     return {1, 1, 1};
930   // The quotient should be greater than zero.
931   if (PollyPatternMatchingNcQuotient <= 0)
932     return {1, 1, 1};
933   int Car = floor(
934       (FirstCacheLevelAssociativity - 1) /
935       (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
936 
937   // Car can be computed to be zero since it is floor to int.
938   // On Mac OS, division by 0 does not raise a signal. This causes negative
939   // tile sizes to be computed. Prevent division by Cac==0 by early returning
940   // if this happens.
941   if (Car == 0)
942     return {1, 1, 1};
943 
944   auto ElementSize = getMatMulAlignTypeSize(MMI);
945   assert(ElementSize > 0 && "The element size of the matrix multiplication "
946                             "operands should be greater than zero.");
947   int Kc = (Car * FirstCacheLevelSize) /
948            (MicroKernelParams.Mr * FirstCacheLevelAssociativity * ElementSize);
949   double Cac =
950       static_cast<double>(Kc * ElementSize * SecondCacheLevelAssociativity) /
951       SecondCacheLevelSize;
952   int Mc = floor((SecondCacheLevelAssociativity - 2) / Cac);
953   int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
954 
955   assert(Mc > 0 && Nc > 0 && Kc > 0 &&
956          "Matrix block sizes should be  greater than zero");
957   return {Mc, Nc, Kc};
958 }
959 
960 /// Create an access relation that is specific to
961 ///        the matrix multiplication pattern.
962 ///
963 /// Create an access relation of the following form:
964 /// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
965 /// where I is @p FirstDim, J is @p SecondDim.
966 ///
967 /// It can be used, for example, to create relations that helps to consequently
968 /// access elements of operands of a matrix multiplication after creation of
969 /// the BLIS micro and macro kernels.
970 ///
971 /// @see ScheduleTreeOptimizer::createMicroKernel
972 /// @see ScheduleTreeOptimizer::createMacroKernel
973 ///
974 /// Subsequently, the described access relation is applied to the range of
975 /// @p MapOldIndVar, that is used to map original induction variables to
976 /// the ones, which are produced by schedule transformations. It helps to
977 /// define relations using a new space and, at the same time, keep them
978 /// in the original one.
979 ///
980 /// @param MapOldIndVar The relation, which maps original induction variables
981 ///                     to the ones, which are produced by schedule
982 ///                     transformations.
983 /// @param FirstDim, SecondDim The input dimensions that are used to define
984 ///        the specified access relation.
985 /// @return The specified access relation.
986 isl::map getMatMulAccRel(isl::map MapOldIndVar, unsigned FirstDim,
987                          unsigned SecondDim) {
988   auto AccessRelSpace = isl::space(MapOldIndVar.get_ctx(), 0, 9, 3);
989   auto AccessRel = isl::map::universe(AccessRelSpace);
990   AccessRel = AccessRel.equate(isl::dim::in, FirstDim, isl::dim::out, 0);
991   AccessRel = AccessRel.equate(isl::dim::in, 5, isl::dim::out, 1);
992   AccessRel = AccessRel.equate(isl::dim::in, SecondDim, isl::dim::out, 2);
993   return MapOldIndVar.apply_range(AccessRel);
994 }
995 
996 isl::schedule_node createExtensionNode(isl::schedule_node Node,
997                                        isl::map ExtensionMap) {
998   auto Extension = isl::union_map(ExtensionMap);
999   auto NewNode = isl::schedule_node::from_extension(Extension);
1000   return Node.graft_before(NewNode);
1001 }
1002 
1003 /// Apply the packing transformation.
1004 ///
1005 /// The packing transformation can be described as a data-layout
1006 /// transformation that requires to introduce a new array, copy data
1007 /// to the array, and change memory access locations to reference the array.
1008 /// It can be used to ensure that elements of the new array are read in-stride
1009 /// access, aligned to cache lines boundaries, and preloaded into certain cache
1010 /// levels.
1011 ///
1012 /// As an example let us consider the packing of the array A that would help
1013 /// to read its elements with in-stride access. An access to the array A
1014 /// is represented by an access relation that has the form
1015 /// S[i, j, k] -> A[i, k]. The scheduling function of the SCoP statement S has
1016 /// the form S[i,j, k] -> [floor((j mod Nc) / Nr), floor((i mod Mc) / Mr),
1017 /// k mod Kc, j mod Nr, i mod Mr].
1018 ///
1019 /// To ensure that elements of the array A are read in-stride access, we add
1020 /// a new array Packed_A[Mc/Mr][Kc][Mr] to the SCoP, using
1021 /// Scop::createScopArrayInfo, change the access relation
1022 /// S[i, j, k] -> A[i, k] to
1023 /// S[i, j, k] -> Packed_A[floor((i mod Mc) / Mr), k mod Kc, i mod Mr], using
1024 /// MemoryAccess::setNewAccessRelation, and copy the data to the array, using
1025 /// the copy statement created by Scop::addScopStmt.
1026 ///
1027 /// @param Node The schedule node to be optimized.
1028 /// @param MapOldIndVar The relation, which maps original induction variables
1029 ///                     to the ones, which are produced by schedule
1030 ///                     transformations.
1031 /// @param MicroParams, MacroParams Parameters of the BLIS kernel
1032 ///                                 to be taken into account.
1033 /// @param MMI Parameters of the matrix multiplication operands.
1034 /// @return The optimized schedule node.
1035 static isl::schedule_node
1036 optimizeDataLayoutMatrMulPattern(isl::schedule_node Node, isl::map MapOldIndVar,
1037                                  MicroKernelParamsTy MicroParams,
1038                                  MacroKernelParamsTy MacroParams,
1039                                  MatMulInfoTy &MMI) {
1040   auto InputDimsId = MapOldIndVar.get_tuple_id(isl::dim::in);
1041   auto *Stmt = static_cast<ScopStmt *>(InputDimsId.get_user());
1042 
1043   // Create a copy statement that corresponds to the memory access to the
1044   // matrix B, the second operand of the matrix multiplication.
1045   Node = Node.parent().parent().parent().parent().parent();
1046   Node = isl::manage(isl_schedule_node_band_split(Node.release(), 2)).child(0);
1047   auto AccRel = getMatMulAccRel(isl::manage(MapOldIndVar.copy()), 3, 7);
1048   unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
1049   unsigned SecondDimSize = MacroParams.Kc;
1050   unsigned ThirdDimSize = MicroParams.Nr;
1051   auto *SAI = Stmt->getParent()->createScopArrayInfo(
1052       MMI.B->getElementType(), "Packed_B",
1053       {FirstDimSize, SecondDimSize, ThirdDimSize});
1054   AccRel = AccRel.set_tuple_id(isl::dim::out, SAI->getBasePtrId());
1055   auto OldAcc = MMI.B->getLatestAccessRelation();
1056   MMI.B->setNewAccessRelation(AccRel.release());
1057   auto ExtMap = MapOldIndVar.project_out(isl::dim::out, 2,
1058                                          MapOldIndVar.dim(isl::dim::out) - 2);
1059   ExtMap = ExtMap.reverse();
1060   ExtMap = ExtMap.fix_si(isl::dim::out, MMI.i, 0);
1061   auto Domain = isl::manage(Stmt->getDomain());
1062 
1063   // Restrict the domains of the copy statements to only execute when also its
1064   // originating statement is executed.
1065   auto DomainId = Domain.get_tuple_id();
1066   auto *NewStmt = Stmt->getParent()->addScopStmt(
1067       OldAcc.release(), MMI.B->getLatestAccessRelation().release(),
1068       Domain.copy());
1069   ExtMap = ExtMap.set_tuple_id(isl::dim::out, isl::manage(DomainId.copy()));
1070   ExtMap = ExtMap.intersect_range(isl::manage(Domain.copy()));
1071   ExtMap =
1072       ExtMap.set_tuple_id(isl::dim::out, isl::manage(NewStmt->getDomainId()));
1073   Node = createExtensionNode(Node, ExtMap);
1074 
1075   // Create a copy statement that corresponds to the memory access
1076   // to the matrix A, the first operand of the matrix multiplication.
1077   Node = Node.child(0);
1078   AccRel = getMatMulAccRel(isl::manage(MapOldIndVar.copy()), 4, 6);
1079   FirstDimSize = MacroParams.Mc / MicroParams.Mr;
1080   ThirdDimSize = MicroParams.Mr;
1081   SAI = Stmt->getParent()->createScopArrayInfo(
1082       MMI.A->getElementType(), "Packed_A",
1083       {FirstDimSize, SecondDimSize, ThirdDimSize});
1084   AccRel = AccRel.set_tuple_id(isl::dim::out, SAI->getBasePtrId());
1085   OldAcc = MMI.A->getLatestAccessRelation();
1086   MMI.A->setNewAccessRelation(AccRel.release());
1087   ExtMap = MapOldIndVar.project_out(isl::dim::out, 3,
1088                                     MapOldIndVar.dim(isl::dim::out) - 3);
1089   ExtMap = ExtMap.reverse();
1090   ExtMap = ExtMap.fix_si(isl::dim::out, MMI.j, 0);
1091   NewStmt = Stmt->getParent()->addScopStmt(
1092       OldAcc.release(), MMI.A->getLatestAccessRelation().release(),
1093       Domain.copy());
1094 
1095   // Restrict the domains of the copy statements to only execute when also its
1096   // originating statement is executed.
1097   ExtMap = ExtMap.set_tuple_id(isl::dim::out, DomainId);
1098   ExtMap = ExtMap.intersect_range(Domain);
1099   ExtMap =
1100       ExtMap.set_tuple_id(isl::dim::out, isl::manage(NewStmt->getDomainId()));
1101   Node = createExtensionNode(Node, ExtMap);
1102   return Node.child(0).child(0).child(0).child(0);
1103 }
1104 
1105 /// Get a relation mapping induction variables produced by schedule
1106 /// transformations to the original ones.
1107 ///
1108 /// @param Node The schedule node produced as the result of creation
1109 ///        of the BLIS kernels.
1110 /// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
1111 ///                                             to be taken into account.
1112 /// @return  The relation mapping original induction variables to the ones
1113 ///          produced by schedule transformation.
1114 /// @see ScheduleTreeOptimizer::createMicroKernel
1115 /// @see ScheduleTreeOptimizer::createMacroKernel
1116 /// @see getMacroKernelParams
1117 isl::map
1118 getInductionVariablesSubstitution(isl::schedule_node Node,
1119                                   MicroKernelParamsTy MicroKernelParams,
1120                                   MacroKernelParamsTy MacroKernelParams) {
1121   auto Child = Node.child(0);
1122   auto UnMapOldIndVar = Child.get_prefix_schedule_union_map();
1123   auto MapOldIndVar = isl::map::from_union_map(UnMapOldIndVar);
1124   if (MapOldIndVar.dim(isl::dim::out) > 9)
1125     return MapOldIndVar.project_out(isl::dim::out, 0,
1126                                     MapOldIndVar.dim(isl::dim::out) - 9);
1127   return MapOldIndVar;
1128 }
1129 
1130 /// Isolate a set of partial tile prefixes and unroll the isolated part.
1131 ///
1132 /// The set should ensure that it contains only partial tile prefixes that have
1133 /// exactly Mr x Nr iterations of the two innermost loops produced by
1134 /// the optimization of the matrix multiplication. Mr and Nr are parameters of
1135 /// the micro-kernel.
1136 ///
1137 /// In case of parametric bounds, this helps to auto-vectorize the unrolled
1138 /// innermost loops, using the SLP vectorizer.
1139 ///
1140 /// @param Node              The schedule node to be modified.
1141 /// @param MicroKernelParams Parameters of the micro-kernel
1142 ///                          to be taken into account.
1143 /// @return The modified isl_schedule_node.
1144 static isl::schedule_node
1145 isolateAndUnrollMatMulInnerLoops(isl::schedule_node Node,
1146                                  struct MicroKernelParamsTy MicroKernelParams) {
1147   isl::schedule_node Child = Node.get_child(0);
1148   isl::union_map UnMapOldIndVar = Child.get_prefix_schedule_relation();
1149   isl::set Prefix = isl::map::from_union_map(UnMapOldIndVar).range();
1150   unsigned Dims = Prefix.dim(isl::dim::set);
1151   Prefix = Prefix.project_out(isl::dim::set, Dims - 1, 1);
1152   Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Nr);
1153   Prefix = getPartialTilePrefixes(Prefix, MicroKernelParams.Mr);
1154 
1155   isl::union_set IsolateOption =
1156       getIsolateOptions(Prefix.add_dims(isl::dim::set, 3), 3);
1157   isl::ctx Ctx = Node.get_ctx();
1158   isl::union_set AtomicOption = getAtomicOptions(Ctx);
1159   isl::union_set Options = IsolateOption.unite(AtomicOption);
1160   Options = Options.unite(getUnrollIsolatedSetOptions(Ctx));
1161   Node = Node.band_set_ast_build_options(Options);
1162   Node = Node.parent().parent();
1163   IsolateOption = getIsolateOptions(Prefix, 3);
1164   Options = IsolateOption.unite(AtomicOption);
1165   Node = Node.band_set_ast_build_options(Options);
1166   Node = Node.child(0).child(0);
1167   return Node;
1168 }
1169 
1170 /// Mark @p BasePtr with "Inter iteration alias-free" mark node.
1171 ///
1172 /// @param Node The child of the mark node to be inserted.
1173 /// @param BasePtr The pointer to be marked.
1174 /// @return The modified isl_schedule_node.
1175 static isl::schedule_node markInterIterationAliasFree(isl::schedule_node Node,
1176                                                       llvm::Value *BasePtr) {
1177   if (!BasePtr)
1178     return Node;
1179 
1180   auto Id =
1181       isl::id::alloc(Node.get_ctx(), "Inter iteration alias-free", BasePtr);
1182   return Node.insert_mark(Id).child(0);
1183 }
1184 
1185 /// Restore the initial ordering of dimensions of the band node
1186 ///
1187 /// In case the band node represents all the dimensions of the iteration
1188 /// domain, recreate the band node to restore the initial ordering of the
1189 /// dimensions.
1190 ///
1191 /// @param Node The band node to be modified.
1192 /// @return The modified schedule node.
1193 namespace {
1194 isl::schedule_node getBandNodeWithOriginDimOrder(isl::schedule_node Node) {
1195   assert(isl_schedule_node_get_type(Node.keep()) == isl_schedule_node_band);
1196   if (isl_schedule_node_get_type(Node.child(0).keep()) !=
1197       isl_schedule_node_leaf)
1198     return Node;
1199   auto Domain = Node.get_universe_domain();
1200   assert(isl_union_set_n_set(Domain.keep()) == 1);
1201   if (Node.get_schedule_depth() != 0 ||
1202       (isl::set(isl::manage(Domain.copy())).dim(isl::dim::set) !=
1203        isl_schedule_node_band_n_member(Node.keep())))
1204     return Node;
1205   Node = isl::manage(isl_schedule_node_delete(Node.take()));
1206   auto PartialSchedulePwAff = Domain.identity_union_pw_multi_aff();
1207   auto PartialScheduleMultiPwAff =
1208       isl::multi_union_pw_aff(PartialSchedulePwAff);
1209   PartialScheduleMultiPwAff =
1210       PartialScheduleMultiPwAff.reset_tuple_id(isl::dim::set);
1211   return Node.insert_partial_schedule(PartialScheduleMultiPwAff);
1212 }
1213 } // namespace
1214 
1215 isl::schedule_node ScheduleTreeOptimizer::optimizeMatMulPattern(
1216     isl::schedule_node Node, const llvm::TargetTransformInfo *TTI,
1217     MatMulInfoTy &MMI) {
1218   assert(TTI && "The target transform info should be provided.");
1219   Node = markInterIterationAliasFree(
1220       Node, MMI.WriteToC->getLatestScopArrayInfo()->getBasePtr());
1221   int DimOutNum = isl_schedule_node_band_n_member(Node.get());
1222   assert(DimOutNum > 2 && "In case of the matrix multiplication the loop nest "
1223                           "and, consequently, the corresponding scheduling "
1224                           "functions have at least three dimensions.");
1225   Node = getBandNodeWithOriginDimOrder(Node);
1226   Node = permuteBandNodeDimensions(Node, MMI.i, DimOutNum - 3);
1227   int NewJ = MMI.j == DimOutNum - 3 ? MMI.i : MMI.j;
1228   int NewK = MMI.k == DimOutNum - 3 ? MMI.i : MMI.k;
1229   Node = permuteBandNodeDimensions(Node, NewJ, DimOutNum - 2);
1230   NewK = NewK == DimOutNum - 2 ? NewJ : NewK;
1231   Node = permuteBandNodeDimensions(Node, NewK, DimOutNum - 1);
1232   auto MicroKernelParams = getMicroKernelParams(TTI, MMI);
1233   auto MacroKernelParams = getMacroKernelParams(MicroKernelParams, MMI);
1234   Node = createMacroKernel(Node, MacroKernelParams);
1235   Node = createMicroKernel(Node, MicroKernelParams);
1236   if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
1237       MacroKernelParams.Kc == 1)
1238     return Node;
1239   auto MapOldIndVar = getInductionVariablesSubstitution(Node, MicroKernelParams,
1240                                                         MacroKernelParams);
1241   if (!MapOldIndVar)
1242     return Node;
1243   Node = isolateAndUnrollMatMulInnerLoops(Node, MicroKernelParams);
1244   return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
1245                                           MacroKernelParams, MMI);
1246 }
1247 
1248 bool ScheduleTreeOptimizer::isMatrMultPattern(isl::schedule_node Node,
1249                                               const Dependences *D,
1250                                               MatMulInfoTy &MMI) {
1251   auto PartialSchedule = isl::manage(
1252       isl_schedule_node_band_get_partial_schedule_union_map(Node.get()));
1253   Node = Node.child(0);
1254   auto LeafType = isl_schedule_node_get_type(Node.get());
1255   Node = Node.parent();
1256   if (LeafType != isl_schedule_node_leaf ||
1257       isl_schedule_node_band_n_member(Node.get()) < 3 ||
1258       Node.get_schedule_depth() != 0 ||
1259       isl_union_map_n_map(PartialSchedule.get()) != 1)
1260     return false;
1261   auto NewPartialSchedule = isl::map::from_union_map(PartialSchedule);
1262   if (containsMatrMult(NewPartialSchedule, D, MMI))
1263     return true;
1264   return false;
1265 }
1266 
1267 __isl_give isl_schedule_node *
1268 ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
1269                                     void *User) {
1270   if (!isTileableBandNode(isl::manage(isl_schedule_node_copy(Node))))
1271     return Node;
1272 
1273   const OptimizerAdditionalInfoTy *OAI =
1274       static_cast<const OptimizerAdditionalInfoTy *>(User);
1275 
1276   MatMulInfoTy MMI;
1277   if (PMBasedOpts && User &&
1278       isMatrMultPattern(isl::manage(isl_schedule_node_copy(Node)), OAI->D,
1279                         MMI)) {
1280     DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
1281     return optimizeMatMulPattern(isl::manage(Node), OAI->TTI, MMI).release();
1282   }
1283 
1284   return standardBandOpts(isl::manage(Node), User).release();
1285 }
1286 
1287 isl::schedule
1288 ScheduleTreeOptimizer::optimizeSchedule(isl::schedule Schedule,
1289                                         const OptimizerAdditionalInfoTy *OAI) {
1290   auto Root = Schedule.get_root();
1291   Root = optimizeScheduleNode(Root, OAI);
1292   return Root.get_schedule();
1293 }
1294 
1295 isl::schedule_node ScheduleTreeOptimizer::optimizeScheduleNode(
1296     isl::schedule_node Node, const OptimizerAdditionalInfoTy *OAI) {
1297   Node = isl::manage(isl_schedule_node_map_descendant_bottom_up(
1298       Node.release(), optimizeBand,
1299       const_cast<void *>(static_cast<const void *>(OAI))));
1300   return Node;
1301 }
1302 
1303 bool ScheduleTreeOptimizer::isProfitableSchedule(Scop &S,
1304                                                  isl::schedule NewSchedule) {
1305   // To understand if the schedule has been optimized we check if the schedule
1306   // has changed at all.
1307   // TODO: We can improve this by tracking if any necessarily beneficial
1308   // transformations have been performed. This can e.g. be tiling, loop
1309   // interchange, or ...) We can track this either at the place where the
1310   // transformation has been performed or, in case of automatic ILP based
1311   // optimizations, by comparing (yet to be defined) performance metrics
1312   // before/after the scheduling optimizer
1313   // (e.g., #stride-one accesses)
1314   if (S.containsExtensionNode(NewSchedule.get()))
1315     return true;
1316   auto NewScheduleMap = NewSchedule.get_map();
1317   auto OldSchedule = isl::manage(S.getSchedule());
1318   assert(OldSchedule && "Only IslScheduleOptimizer can insert extension nodes "
1319                         "that make Scop::getSchedule() return nullptr.");
1320   bool changed = !OldSchedule.is_equal(NewScheduleMap);
1321   return changed;
1322 }
1323 
1324 namespace {
1325 class IslScheduleOptimizer : public ScopPass {
1326 public:
1327   static char ID;
1328   explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
1329 
1330   ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
1331 
1332   /// Optimize the schedule of the SCoP @p S.
1333   bool runOnScop(Scop &S) override;
1334 
1335   /// Print the new schedule for the SCoP @p S.
1336   void printScop(raw_ostream &OS, Scop &S) const override;
1337 
1338   /// Register all analyses and transformation required.
1339   void getAnalysisUsage(AnalysisUsage &AU) const override;
1340 
1341   /// Release the internal memory.
1342   void releaseMemory() override {
1343     isl_schedule_free(LastSchedule);
1344     LastSchedule = nullptr;
1345   }
1346 
1347 private:
1348   isl_schedule *LastSchedule;
1349 };
1350 } // namespace
1351 
1352 char IslScheduleOptimizer::ID = 0;
1353 
1354 bool IslScheduleOptimizer::runOnScop(Scop &S) {
1355 
1356   // Skip SCoPs in case they're already optimised by PPCGCodeGeneration
1357   if (S.isToBeSkipped())
1358     return false;
1359 
1360   // Skip empty SCoPs but still allow code generation as it will delete the
1361   // loops present but not needed.
1362   if (S.getSize() == 0) {
1363     S.markAsOptimized();
1364     return false;
1365   }
1366 
1367   const Dependences &D =
1368       getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
1369 
1370   if (!D.hasValidDependences())
1371     return false;
1372 
1373   isl_schedule_free(LastSchedule);
1374   LastSchedule = nullptr;
1375 
1376   // Build input data.
1377   int ValidityKinds =
1378       Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
1379   int ProximityKinds;
1380 
1381   if (OptimizeDeps == "all")
1382     ProximityKinds =
1383         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
1384   else if (OptimizeDeps == "raw")
1385     ProximityKinds = Dependences::TYPE_RAW;
1386   else {
1387     errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
1388            << " Falling back to optimizing all dependences.\n";
1389     ProximityKinds =
1390         Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
1391   }
1392 
1393   isl::union_set Domain = give(S.getDomains());
1394 
1395   if (!Domain)
1396     return false;
1397 
1398   isl::union_map Validity = give(D.getDependences(ValidityKinds));
1399   isl::union_map Proximity = give(D.getDependences(ProximityKinds));
1400 
1401   // Simplify the dependences by removing the constraints introduced by the
1402   // domains. This can speed up the scheduling time significantly, as large
1403   // constant coefficients will be removed from the dependences. The
1404   // introduction of some additional dependences reduces the possible
1405   // transformations, but in most cases, such transformation do not seem to be
1406   // interesting anyway. In some cases this option may stop the scheduler to
1407   // find any schedule.
1408   if (SimplifyDeps == "yes") {
1409     Validity = Validity.gist_domain(Domain);
1410     Validity = Validity.gist_range(Domain);
1411     Proximity = Proximity.gist_domain(Domain);
1412     Proximity = Proximity.gist_range(Domain);
1413   } else if (SimplifyDeps != "no") {
1414     errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
1415               "or 'no'. Falling back to default: 'yes'\n";
1416   }
1417 
1418   DEBUG(dbgs() << "\n\nCompute schedule from: ");
1419   DEBUG(dbgs() << "Domain := " << Domain << ";\n");
1420   DEBUG(dbgs() << "Proximity := " << Proximity << ";\n");
1421   DEBUG(dbgs() << "Validity := " << Validity << ";\n");
1422 
1423   unsigned IslSerializeSCCs;
1424 
1425   if (FusionStrategy == "max") {
1426     IslSerializeSCCs = 0;
1427   } else if (FusionStrategy == "min") {
1428     IslSerializeSCCs = 1;
1429   } else {
1430     errs() << "warning: Unknown fusion strategy. Falling back to maximal "
1431               "fusion.\n";
1432     IslSerializeSCCs = 0;
1433   }
1434 
1435   int IslMaximizeBands;
1436 
1437   if (MaximizeBandDepth == "yes") {
1438     IslMaximizeBands = 1;
1439   } else if (MaximizeBandDepth == "no") {
1440     IslMaximizeBands = 0;
1441   } else {
1442     errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
1443               " or 'no'. Falling back to default: 'yes'\n";
1444     IslMaximizeBands = 1;
1445   }
1446 
1447   int IslOuterCoincidence;
1448 
1449   if (OuterCoincidence == "yes") {
1450     IslOuterCoincidence = 1;
1451   } else if (OuterCoincidence == "no") {
1452     IslOuterCoincidence = 0;
1453   } else {
1454     errs() << "warning: Option -polly-opt-outer-coincidence should either be "
1455               "'yes' or 'no'. Falling back to default: 'no'\n";
1456     IslOuterCoincidence = 0;
1457   }
1458 
1459   isl_ctx *Ctx = S.getIslCtx();
1460 
1461   isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
1462   isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs);
1463   isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
1464   isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
1465   isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
1466   isl_options_set_tile_scale_tile_loops(Ctx, 0);
1467 
1468   auto OnErrorStatus = isl_options_get_on_error(Ctx);
1469   isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
1470 
1471   auto SC = isl::schedule_constraints::on_domain(Domain);
1472   SC = SC.set_proximity(Proximity);
1473   SC = SC.set_validity(Validity);
1474   SC = SC.set_coincidence(Validity);
1475   auto Schedule = SC.compute_schedule();
1476   isl_options_set_on_error(Ctx, OnErrorStatus);
1477 
1478   // In cases the scheduler is not able to optimize the code, we just do not
1479   // touch the schedule.
1480   if (!Schedule)
1481     return false;
1482 
1483   DEBUG({
1484     auto *P = isl_printer_to_str(Ctx);
1485     P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1486     P = isl_printer_print_schedule(P, Schedule.get());
1487     auto *str = isl_printer_get_str(P);
1488     dbgs() << "NewScheduleTree: \n" << str << "\n";
1489     free(str);
1490     isl_printer_free(P);
1491   });
1492 
1493   Function &F = S.getFunction();
1494   auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1495   const OptimizerAdditionalInfoTy OAI = {TTI, const_cast<Dependences *>(&D)};
1496   auto NewSchedule = ScheduleTreeOptimizer::optimizeSchedule(Schedule, &OAI);
1497 
1498   if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule))
1499     return false;
1500 
1501   S.setScheduleTree(NewSchedule.release());
1502   S.markAsOptimized();
1503 
1504   if (OptimizedScops)
1505     errs() << S;
1506 
1507   return false;
1508 }
1509 
1510 void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
1511   isl_printer *p;
1512   char *ScheduleStr;
1513 
1514   OS << "Calculated schedule:\n";
1515 
1516   if (!LastSchedule) {
1517     OS << "n/a\n";
1518     return;
1519   }
1520 
1521   p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
1522   p = isl_printer_print_schedule(p, LastSchedule);
1523   ScheduleStr = isl_printer_get_str(p);
1524   isl_printer_free(p);
1525 
1526   OS << ScheduleStr << "\n";
1527 }
1528 
1529 void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
1530   ScopPass::getAnalysisUsage(AU);
1531   AU.addRequired<DependenceInfo>();
1532   AU.addRequired<TargetTransformInfoWrapperPass>();
1533 }
1534 
1535 Pass *polly::createIslScheduleOptimizerPass() {
1536   return new IslScheduleOptimizer();
1537 }
1538 
1539 INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
1540                       "Polly - Optimize schedule of SCoP", false, false);
1541 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
1542 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
1543 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
1544 INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
1545                     "Polly - Optimize schedule of SCoP", false, false)
1546