1 //===- ScheduleOptimizer.cpp - Calculate an optimized schedule ------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This pass generates an entirely new schedule tree from the data dependences
10 // and iteration domains. The new schedule tree is computed in two steps:
12 // 1) The isl scheduling optimizer is run
14 // The isl scheduling optimizer creates a new schedule tree that maximizes
15 // parallelism and tileability and minimizes data-dependence distances. The
16 // algorithm used is a modified version of the ``Pluto'' algorithm:
18 // U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
19 // A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
20 // In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
21 // Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
23 // 2) A set of post-scheduling transformations is applied on the schedule tree.
25 // These optimizations include:
27 // - Tiling of the innermost tilable bands
28 // - Prevectorization - The choice of a possible outer loop that is strip-mined
29 // to the innermost level to enable inner-loop
31 // - Some optimizations for spatial locality are also planned.
33 // For a detailed description of the schedule tree itself please see section 6
36 // Polyhedral AST generation is more than scanning polyhedra
37 // Tobias Grosser, Sven Verdoolaege, Albert Cohen
38 // ACM Transactions on Programming Languages and Systems (TOPLAS),
40 // http://www.grosser.es/#pub-polyhedral-AST-generation
42 // This publication also contains a detailed discussion of the different options
43 // for polyhedral loop unrolling, full/partial tile separation and other uses
44 // of the schedule tree.
46 //===----------------------------------------------------------------------===//
48 #include "polly/ScheduleOptimizer.h"
49 #include "polly/CodeGen/CodeGeneration.h"
50 #include "polly/DependenceInfo.h"
51 #include "polly/ManualOptimizer.h"
52 #include "polly/MatmulOptimizer.h"
53 #include "polly/Options.h"
54 #include "polly/ScheduleTreeTransform.h"
55 #include "polly/Support/ISLOStream.h"
56 #include "polly/Support/ISLTools.h"
57 #include "llvm/ADT/Sequence.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
60 #include "llvm/InitializePasses.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "isl/options.h"
65 using namespace polly
;
72 #define DEBUG_TYPE "polly-opt-isl"
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::cat(PollyCategory
));
79 static cl::opt
<std::string
>
80 SimplifyDeps("polly-opt-simplify-deps",
81 cl::desc("Dependences should be simplified (yes/no)"),
82 cl::Hidden
, cl::init("yes"), cl::cat(PollyCategory
));
84 static cl::opt
<int> MaxConstantTerm(
85 "polly-opt-max-constant-term",
86 cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden
,
87 cl::init(20), cl::cat(PollyCategory
));
89 static cl::opt
<int> MaxCoefficient(
90 "polly-opt-max-coefficient",
91 cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden
,
92 cl::init(20), cl::cat(PollyCategory
));
94 static cl::opt
<std::string
>
95 MaximizeBandDepth("polly-opt-maximize-bands",
96 cl::desc("Maximize the band depth (yes/no)"), cl::Hidden
,
97 cl::init("yes"), cl::cat(PollyCategory
));
100 GreedyFusion("polly-loopfusion-greedy",
101 cl::desc("Aggressively try to fuse everything"), cl::Hidden
,
102 cl::cat(PollyCategory
));
104 static cl::opt
<std::string
> OuterCoincidence(
105 "polly-opt-outer-coincidence",
106 cl::desc("Try to construct schedules where the outer member of each band "
107 "satisfies the coincidence constraints (yes/no)"),
108 cl::Hidden
, cl::init("no"), cl::cat(PollyCategory
));
110 static cl::opt
<int> PrevectorWidth(
111 "polly-prevect-width",
113 "The number of loop iterations to strip-mine for pre-vectorization"),
114 cl::Hidden
, cl::init(4), cl::cat(PollyCategory
));
116 static cl::opt
<bool> FirstLevelTiling("polly-tiling",
117 cl::desc("Enable loop tiling"),
118 cl::init(true), cl::cat(PollyCategory
));
120 static cl::opt
<int> FirstLevelDefaultTileSize(
121 "polly-default-tile-size",
122 cl::desc("The default tile size (if not enough were provided by"
123 " --polly-tile-sizes)"),
124 cl::Hidden
, cl::init(32), cl::cat(PollyCategory
));
127 FirstLevelTileSizes("polly-tile-sizes",
128 cl::desc("A tile size for each loop dimension, filled "
129 "with --polly-default-tile-size"),
130 cl::Hidden
, cl::CommaSeparated
, cl::cat(PollyCategory
));
133 SecondLevelTiling("polly-2nd-level-tiling",
134 cl::desc("Enable a 2nd level loop of loop tiling"),
135 cl::cat(PollyCategory
));
137 static cl::opt
<int> SecondLevelDefaultTileSize(
138 "polly-2nd-level-default-tile-size",
139 cl::desc("The default 2nd-level tile size (if not enough were provided by"
140 " --polly-2nd-level-tile-sizes)"),
141 cl::Hidden
, cl::init(16), cl::cat(PollyCategory
));
144 SecondLevelTileSizes("polly-2nd-level-tile-sizes",
145 cl::desc("A tile size for each loop dimension, filled "
146 "with --polly-default-tile-size"),
147 cl::Hidden
, cl::CommaSeparated
,
148 cl::cat(PollyCategory
));
150 static cl::opt
<bool> RegisterTiling("polly-register-tiling",
151 cl::desc("Enable register tiling"),
152 cl::cat(PollyCategory
));
154 static cl::opt
<int> RegisterDefaultTileSize(
155 "polly-register-tiling-default-tile-size",
156 cl::desc("The default register tile size (if not enough were provided by"
157 " --polly-register-tile-sizes)"),
158 cl::Hidden
, cl::init(2), cl::cat(PollyCategory
));
161 RegisterTileSizes("polly-register-tile-sizes",
162 cl::desc("A tile size for each loop dimension, filled "
163 "with --polly-register-tile-size"),
164 cl::Hidden
, cl::CommaSeparated
, cl::cat(PollyCategory
));
166 static cl::opt
<bool> PragmaBasedOpts(
167 "polly-pragma-based-opts",
168 cl::desc("Apply user-directed transformation from metadata"),
169 cl::init(true), cl::cat(PollyCategory
));
171 static cl::opt
<bool> EnableReschedule("polly-reschedule",
172 cl::desc("Optimize SCoPs using ISL"),
173 cl::init(true), cl::cat(PollyCategory
));
176 PMBasedOpts("polly-pattern-matching-based-opts",
177 cl::desc("Perform optimizations based on pattern matching"),
178 cl::init(true), cl::cat(PollyCategory
));
181 EnablePostopts("polly-postopts",
182 cl::desc("Apply post-rescheduling optimizations such as "
183 "tiling (requires -polly-reschedule)"),
184 cl::init(true), cl::cat(PollyCategory
));
186 static cl::opt
<bool> OptimizedScops(
187 "polly-optimized-scops",
188 cl::desc("Polly - Dump polyhedral description of Scops optimized with "
189 "the isl scheduling optimizer and the set of post-scheduling "
190 "transformations is applied on the schedule tree"),
191 cl::cat(PollyCategory
));
193 STATISTIC(ScopsProcessed
, "Number of scops processed");
194 STATISTIC(ScopsRescheduled
, "Number of scops rescheduled");
195 STATISTIC(ScopsOptimized
, "Number of scops optimized");
197 STATISTIC(NumAffineLoopsOptimized
, "Number of affine loops optimized");
198 STATISTIC(NumBoxedLoopsOptimized
, "Number of boxed loops optimized");
200 #define THREE_STATISTICS(VARNAME, DESC) \
201 static Statistic VARNAME[3] = { \
202 {DEBUG_TYPE, #VARNAME "0", DESC " (original)"}, \
203 {DEBUG_TYPE, #VARNAME "1", DESC " (after scheduler)"}, \
204 {DEBUG_TYPE, #VARNAME "2", DESC " (after optimizer)"}}
206 THREE_STATISTICS(NumBands
, "Number of bands");
207 THREE_STATISTICS(NumBandMembers
, "Number of band members");
208 THREE_STATISTICS(NumCoincident
, "Number of coincident band members");
209 THREE_STATISTICS(NumPermutable
, "Number of permutable bands");
210 THREE_STATISTICS(NumFilters
, "Number of filter nodes");
211 THREE_STATISTICS(NumExtension
, "Number of extension nodes");
213 STATISTIC(FirstLevelTileOpts
, "Number of first level tiling applied");
214 STATISTIC(SecondLevelTileOpts
, "Number of second level tiling applied");
215 STATISTIC(RegisterTileOpts
, "Number of register tiling applied");
216 STATISTIC(PrevectOpts
, "Number of strip-mining for prevectorization applied");
217 STATISTIC(MatMulOpts
,
218 "Number of matrix multiplication patterns detected and optimized");
221 /// Additional parameters of the schedule optimizer.
223 /// Target Transform Info and the SCoP dependencies used by the schedule
225 struct OptimizerAdditionalInfoTy
{
226 const llvm::TargetTransformInfo
*TTI
;
227 const Dependences
*D
;
234 class ScheduleTreeOptimizer final
{
236 /// Apply schedule tree transformations.
238 /// This function takes an (possibly already optimized) schedule tree and
239 /// applies a set of additional optimizations on the schedule tree. The
240 /// transformations applied include:
242 /// - Pattern-based optimizations
244 /// - Prevectorization
246 /// @param Schedule The schedule object the transformations will be applied
248 /// @param OAI Target Transform Info and the SCoP dependencies.
249 /// @returns The transformed schedule.
251 optimizeSchedule(isl::schedule Schedule
,
252 const OptimizerAdditionalInfoTy
*OAI
= nullptr);
254 /// Apply schedule tree transformations.
256 /// This function takes a node in an (possibly already optimized) schedule
257 /// tree and applies a set of additional optimizations on this schedule tree
258 /// node and its descendants. The transformations applied include:
260 /// - Pattern-based optimizations
262 /// - Prevectorization
264 /// @param Node The schedule object post-transformations will be applied to.
265 /// @param OAI Target Transform Info and the SCoP dependencies.
266 /// @returns The transformed schedule.
267 static isl::schedule_node
268 optimizeScheduleNode(isl::schedule_node Node
,
269 const OptimizerAdditionalInfoTy
*OAI
= nullptr);
271 /// Decide if the @p NewSchedule is profitable for @p S.
273 /// @param S The SCoP we optimize.
274 /// @param NewSchedule The new schedule we computed.
276 /// @return True, if we believe @p NewSchedule is an improvement for @p S.
277 static bool isProfitableSchedule(polly::Scop
&S
, isl::schedule NewSchedule
);
279 /// Isolate a set of partial tile prefixes.
281 /// This set should ensure that it contains only partial tile prefixes that
282 /// have exactly VectorWidth iterations.
284 /// @param Node A schedule node band, which is a parent of a band node,
285 /// that contains a vector loop.
286 /// @return Modified isl_schedule_node.
287 static isl::schedule_node
isolateFullPartialTiles(isl::schedule_node Node
,
291 /// Check if this node is a band node we want to tile.
293 /// We look for innermost band nodes where individual dimensions are marked as
296 /// @param Node The node to check.
297 static bool isTileableBandNode(isl::schedule_node Node
);
299 /// Check if this node is a band node we want to transform using pattern
302 /// We look for innermost band nodes where individual dimensions are marked as
303 /// permutable. There is no restriction on the number of individual
306 /// @param Node The node to check.
307 static bool isPMOptimizableBandNode(isl::schedule_node Node
);
309 /// Pre-vectorizes one scheduling dimension of a schedule band.
311 /// prevectSchedBand splits out the dimension DimToVectorize, tiles it and
312 /// sinks the resulting point loop.
314 /// Example (DimToVectorize=0, VectorWidth=4):
316 /// | Before transformation:
318 /// | A[i,j] -> [i,j]
320 /// | for (i = 0; i < 128; i++)
321 /// | for (j = 0; j < 128; j++)
324 /// | After transformation:
326 /// | for (it = 0; it < 32; it+=1)
327 /// | for (j = 0; j < 128; j++)
328 /// | for (ip = 0; ip <= 3; ip++)
329 /// | A(4 * it + ip,j);
331 /// The goal of this transformation is to create a trivially vectorizable
332 /// loop. This means a parallel loop at the innermost level that has a
333 /// constant number of iterations corresponding to the target vector width.
335 /// This transformation creates a loop at the innermost level. The loop has
336 /// a constant number of iterations, if the number of loop iterations at
337 /// DimToVectorize can be divided by VectorWidth. The default VectorWidth is
338 /// currently constant and not yet target specific. This function does not
339 /// reason about parallelism.
340 static isl::schedule_node
prevectSchedBand(isl::schedule_node Node
,
341 unsigned DimToVectorize
,
344 /// Apply additional optimizations on the bands in the schedule tree.
346 /// We are looking for an innermost band node and apply the following
350 /// - if the band is tileable
351 /// - if the band has more than one loop dimension
353 /// - Prevectorize the schedule of the band (or the point loop in case of
355 /// - if vectorization is enabled
357 /// @param Node The schedule node to (possibly) optimize.
358 /// @param User A pointer to forward some use information
359 /// (currently unused).
360 static isl_schedule_node
*optimizeBand(isl_schedule_node
*Node
, void *User
);
362 /// Apply tiling optimizations on the bands in the schedule tree.
364 /// @param Node The schedule node to (possibly) optimize.
365 static isl::schedule_node
applyTileBandOpt(isl::schedule_node Node
);
367 /// Apply prevectorization on the bands in the schedule tree.
369 /// @param Node The schedule node to (possibly) prevectorize.
370 static isl::schedule_node
applyPrevectBandOpt(isl::schedule_node Node
);
374 ScheduleTreeOptimizer::isolateFullPartialTiles(isl::schedule_node Node
,
376 assert(isl_schedule_node_get_type(Node
.get()) == isl_schedule_node_band
);
377 Node
= Node
.child(0).child(0);
378 isl::union_map SchedRelUMap
= Node
.get_prefix_schedule_relation();
379 isl::union_set ScheduleRangeUSet
= SchedRelUMap
.range();
380 isl::set ScheduleRange
{ScheduleRangeUSet
};
381 isl::set IsolateDomain
= getPartialTilePrefixes(ScheduleRange
, VectorWidth
);
382 auto AtomicOption
= getDimOptions(IsolateDomain
.ctx(), "atomic");
383 isl::union_set IsolateOption
= getIsolateOptions(IsolateDomain
, 1);
384 Node
= Node
.parent().parent();
385 isl::union_set Options
= IsolateOption
.unite(AtomicOption
);
386 isl::schedule_node_band Result
=
387 Node
.as
<isl::schedule_node_band
>().set_ast_build_options(Options
);
391 struct InsertSimdMarkers final
: ScheduleNodeRewriter
<InsertSimdMarkers
> {
392 isl::schedule_node
visitBand(isl::schedule_node_band Band
) {
393 isl::schedule_node Node
= visitChildren(Band
);
395 // Only add SIMD markers to innermost bands.
396 if (!Node
.first_child().isa
<isl::schedule_node_leaf
>())
399 isl::id LoopMarker
= isl::id::alloc(Band
.ctx(), "SIMD", nullptr);
400 return Band
.insert_mark(LoopMarker
);
404 isl::schedule_node
ScheduleTreeOptimizer::prevectSchedBand(
405 isl::schedule_node Node
, unsigned DimToVectorize
, int VectorWidth
) {
406 assert(isl_schedule_node_get_type(Node
.get()) == isl_schedule_node_band
);
408 auto Space
= isl::manage(isl_schedule_node_band_get_space(Node
.get()));
409 unsigned ScheduleDimensions
= unsignedFromIslSize(Space
.dim(isl::dim::set
));
410 assert(DimToVectorize
< ScheduleDimensions
);
412 if (DimToVectorize
> 0) {
414 isl_schedule_node_band_split(Node
.release(), DimToVectorize
));
415 Node
= Node
.child(0);
417 if (DimToVectorize
< ScheduleDimensions
- 1)
418 Node
= isl::manage(isl_schedule_node_band_split(Node
.release(), 1));
419 Space
= isl::manage(isl_schedule_node_band_get_space(Node
.get()));
420 auto Sizes
= isl::multi_val::zero(Space
);
421 Sizes
= Sizes
.set_val(0, isl::val(Node
.ctx(), VectorWidth
));
423 isl::manage(isl_schedule_node_band_tile(Node
.release(), Sizes
.release()));
424 Node
= isolateFullPartialTiles(Node
, VectorWidth
);
425 Node
= Node
.child(0);
426 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
427 // we will have troubles to match it in the backend.
428 Node
= Node
.as
<isl::schedule_node_band
>().set_ast_build_options(
429 isl::union_set(Node
.ctx(), "{ unroll[x]: 1 = 0 }"));
431 // Sink the inner loop into the smallest possible statements to make them
432 // represent a single vector instruction if possible.
433 Node
= isl::manage(isl_schedule_node_band_sink(Node
.release()));
435 // Add SIMD markers to those vector statements.
436 InsertSimdMarkers SimdMarkerInserter
;
437 Node
= SimdMarkerInserter
.visit(Node
);
440 return Node
.parent();
443 static bool isSimpleInnermostBand(const isl::schedule_node
&Node
) {
444 assert(isl_schedule_node_get_type(Node
.get()) == isl_schedule_node_band
);
445 assert(isl_schedule_node_n_children(Node
.get()) == 1);
447 auto ChildType
= isl_schedule_node_get_type(Node
.child(0).get());
449 if (ChildType
== isl_schedule_node_leaf
)
452 if (ChildType
!= isl_schedule_node_sequence
)
455 auto Sequence
= Node
.child(0);
457 for (int c
= 0, nc
= isl_schedule_node_n_children(Sequence
.get()); c
< nc
;
459 auto Child
= Sequence
.child(c
);
460 if (isl_schedule_node_get_type(Child
.get()) != isl_schedule_node_filter
)
462 if (isl_schedule_node_get_type(Child
.child(0).get()) !=
463 isl_schedule_node_leaf
)
469 /// Check if this node is a band node, which has only one child.
471 /// @param Node The node to check.
472 static bool isOneTimeParentBandNode(isl::schedule_node Node
) {
473 if (isl_schedule_node_get_type(Node
.get()) != isl_schedule_node_band
)
476 if (isl_schedule_node_n_children(Node
.get()) != 1)
482 bool ScheduleTreeOptimizer::isTileableBandNode(isl::schedule_node Node
) {
483 if (!isOneTimeParentBandNode(Node
))
486 if (!isl_schedule_node_band_get_permutable(Node
.get()))
489 auto Space
= isl::manage(isl_schedule_node_band_get_space(Node
.get()));
491 if (unsignedFromIslSize(Space
.dim(isl::dim::set
)) <= 1u)
494 return isSimpleInnermostBand(Node
);
497 bool ScheduleTreeOptimizer::isPMOptimizableBandNode(isl::schedule_node Node
) {
498 if (!isOneTimeParentBandNode(Node
))
501 return Node
.child(0).isa
<isl::schedule_node_leaf
>();
504 __isl_give
isl::schedule_node
505 ScheduleTreeOptimizer::applyTileBandOpt(isl::schedule_node Node
) {
506 if (FirstLevelTiling
) {
507 Node
= tileNode(Node
, "1st level tiling", FirstLevelTileSizes
,
508 FirstLevelDefaultTileSize
);
509 FirstLevelTileOpts
++;
512 if (SecondLevelTiling
) {
513 Node
= tileNode(Node
, "2nd level tiling", SecondLevelTileSizes
,
514 SecondLevelDefaultTileSize
);
515 SecondLevelTileOpts
++;
518 if (RegisterTiling
) {
520 applyRegisterTiling(Node
, RegisterTileSizes
, RegisterDefaultTileSize
);
528 ScheduleTreeOptimizer::applyPrevectBandOpt(isl::schedule_node Node
) {
529 auto Space
= isl::manage(isl_schedule_node_band_get_space(Node
.get()));
530 int Dims
= unsignedFromIslSize(Space
.dim(isl::dim::set
));
532 for (int i
= Dims
- 1; i
>= 0; i
--)
533 if (Node
.as
<isl::schedule_node_band
>().member_get_coincident(i
)) {
534 Node
= prevectSchedBand(Node
, i
, PrevectorWidth
);
541 __isl_give isl_schedule_node
*
542 ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node
*NodeArg
,
544 const OptimizerAdditionalInfoTy
*OAI
=
545 static_cast<const OptimizerAdditionalInfoTy
*>(User
);
546 assert(OAI
&& "Expecting optimization options");
548 isl::schedule_node Node
= isl::manage(NodeArg
);
550 if (OAI
->PatternOpts
&& isPMOptimizableBandNode(Node
)) {
551 isl::schedule_node PatternOptimizedSchedule
=
552 tryOptimizeMatMulPattern(Node
, OAI
->TTI
, OAI
->D
);
553 if (!PatternOptimizedSchedule
.is_null()) {
555 OAI
->DepsChanged
= true;
556 return PatternOptimizedSchedule
.release();
560 if (!isTileableBandNode(Node
))
561 return Node
.release();
564 Node
= applyTileBandOpt(Node
);
567 // FIXME: Prevectorization requirements are different from those checked by
568 // isTileableBandNode.
569 Node
= applyPrevectBandOpt(Node
);
572 return Node
.release();
576 ScheduleTreeOptimizer::optimizeSchedule(isl::schedule Schedule
,
577 const OptimizerAdditionalInfoTy
*OAI
) {
578 auto Root
= Schedule
.get_root();
579 Root
= optimizeScheduleNode(Root
, OAI
);
580 return Root
.get_schedule();
583 isl::schedule_node
ScheduleTreeOptimizer::optimizeScheduleNode(
584 isl::schedule_node Node
, const OptimizerAdditionalInfoTy
*OAI
) {
585 Node
= isl::manage(isl_schedule_node_map_descendant_bottom_up(
586 Node
.release(), optimizeBand
,
587 const_cast<void *>(static_cast<const void *>(OAI
))));
591 bool ScheduleTreeOptimizer::isProfitableSchedule(Scop
&S
,
592 isl::schedule NewSchedule
) {
593 // To understand if the schedule has been optimized we check if the schedule
594 // has changed at all.
595 // TODO: We can improve this by tracking if any necessarily beneficial
596 // transformations have been performed. This can e.g. be tiling, loop
597 // interchange, or ...) We can track this either at the place where the
598 // transformation has been performed or, in case of automatic ILP based
599 // optimizations, by comparing (yet to be defined) performance metrics
600 // before/after the scheduling optimizer
601 // (e.g., #stride-one accesses)
602 // FIXME: A schedule tree whose union_map-conversion is identical to the
603 // original schedule map may still allow for parallelization, i.e. can still
605 auto NewScheduleMap
= NewSchedule
.get_map();
606 auto OldSchedule
= S
.getSchedule();
607 assert(!OldSchedule
.is_null() &&
608 "Only IslScheduleOptimizer can insert extension nodes "
609 "that make Scop::getSchedule() return nullptr.");
610 bool changed
= !OldSchedule
.is_equal(NewScheduleMap
);
614 class IslScheduleOptimizerWrapperPass final
: public ScopPass
{
618 explicit IslScheduleOptimizerWrapperPass() : ScopPass(ID
) {}
620 /// Optimize the schedule of the SCoP @p S.
621 bool runOnScop(Scop
&S
) override
;
623 /// Print the new schedule for the SCoP @p S.
624 void printScop(raw_ostream
&OS
, Scop
&S
) const override
;
626 /// Register all analyses and transformation required.
627 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
629 /// Release the internal memory.
630 void releaseMemory() override
{
636 std::shared_ptr
<isl_ctx
> IslCtx
;
637 isl::schedule LastSchedule
;
640 char IslScheduleOptimizerWrapperPass::ID
= 0;
643 static void printSchedule(llvm::raw_ostream
&OS
, const isl::schedule
&Schedule
,
645 isl::ctx Ctx
= Schedule
.ctx();
646 isl_printer
*P
= isl_printer_to_str(Ctx
.get());
647 P
= isl_printer_set_yaml_style(P
, ISL_YAML_STYLE_BLOCK
);
648 P
= isl_printer_print_schedule(P
, Schedule
.get());
649 char *Str
= isl_printer_get_str(P
);
650 OS
<< Desc
<< ": \n" << Str
<< "\n";
656 /// Collect statistics for the schedule tree.
658 /// @param Schedule The schedule tree to analyze. If not a schedule tree it is
660 /// @param Version The version of the schedule tree that is analyzed.
661 /// 0 for the original schedule tree before any transformation.
662 /// 1 for the schedule tree after isl's rescheduling.
663 /// 2 for the schedule tree after optimizations are applied
664 /// (tiling, pattern matching)
665 static void walkScheduleTreeForStatistics(isl::schedule Schedule
, int Version
) {
666 auto Root
= Schedule
.get_root();
670 isl_schedule_node_foreach_descendant_top_down(
672 [](__isl_keep isl_schedule_node
*nodeptr
, void *user
) -> isl_bool
{
673 isl::schedule_node Node
= isl::manage_copy(nodeptr
);
674 int Version
= *static_cast<int *>(user
);
676 switch (isl_schedule_node_get_type(Node
.get())) {
677 case isl_schedule_node_band
: {
679 if (isl_schedule_node_band_get_permutable(Node
.get()) ==
681 NumPermutable
[Version
]++;
683 int CountMembers
= isl_schedule_node_band_n_member(Node
.get());
684 NumBandMembers
[Version
] += CountMembers
;
685 for (int i
= 0; i
< CountMembers
; i
+= 1) {
686 if (Node
.as
<isl::schedule_node_band
>().member_get_coincident(i
))
687 NumCoincident
[Version
]++;
692 case isl_schedule_node_filter
:
693 NumFilters
[Version
]++;
696 case isl_schedule_node_extension
:
697 NumExtension
[Version
]++;
704 return isl_bool_true
;
709 static void runIslScheduleOptimizer(
711 function_ref
<const Dependences
&(Dependences::AnalysisLevel
)> GetDeps
,
712 TargetTransformInfo
*TTI
, OptimizationRemarkEmitter
*ORE
,
713 isl::schedule
&LastSchedule
, bool &DepsChanged
) {
714 // Skip empty SCoPs but still allow code generation as it will delete the
715 // loops present but not needed.
716 if (S
.getSize() == 0) {
723 // Schedule without optimizations.
724 isl::schedule Schedule
= S
.getScheduleTree();
725 walkScheduleTreeForStatistics(S
.getScheduleTree(), 0);
726 LLVM_DEBUG(printSchedule(dbgs(), Schedule
, "Original schedule tree"));
728 bool HasUserTransformation
= false;
729 if (PragmaBasedOpts
) {
730 isl::schedule ManuallyTransformed
= applyManualTransformations(
731 &S
, Schedule
, GetDeps(Dependences::AL_Statement
), ORE
);
732 if (ManuallyTransformed
.is_null()) {
733 LLVM_DEBUG(dbgs() << "Error during manual optimization\n");
737 if (ManuallyTransformed
.get() != Schedule
.get()) {
738 // User transformations have precedence over other transformations.
739 HasUserTransformation
= true;
740 Schedule
= std::move(ManuallyTransformed
);
742 printSchedule(dbgs(), Schedule
, "After manual transformations"));
746 // Only continue if either manual transformations have been applied or we are
747 // allowed to apply heuristics.
748 // TODO: Detect disabled heuristics and no user-directed transformation
749 // metadata earlier in ScopDetection.
750 if (!HasUserTransformation
&& S
.hasDisableHeuristicsHint()) {
751 LLVM_DEBUG(dbgs() << "Heuristic optimizations disabled by metadata\n");
755 // Get dependency analysis.
756 const Dependences
&D
= GetDeps(Dependences::AL_Statement
);
757 if (D
.getSharedIslCtx() != S
.getSharedIslCtx()) {
758 LLVM_DEBUG(dbgs() << "DependenceInfo for another SCoP/isl_ctx\n");
761 if (!D
.hasValidDependences()) {
762 LLVM_DEBUG(dbgs() << "Dependency information not available\n");
766 // Apply ISL's algorithm only if not overriden by the user. Note that
767 // post-rescheduling optimizations (tiling, pattern-based, prevectorization)
768 // rely on the coincidence/permutable annotations on schedule tree bands that
769 // are added by the rescheduling analyzer. Therefore, disabling the
770 // rescheduler implicitly also disables these optimizations.
771 if (!EnableReschedule
) {
772 LLVM_DEBUG(dbgs() << "Skipping rescheduling due to command line option\n");
773 } else if (HasUserTransformation
) {
775 dbgs() << "Skipping rescheduling due to manual transformation\n");
779 Dependences::TYPE_RAW
| Dependences::TYPE_WAR
| Dependences::TYPE_WAW
;
782 if (OptimizeDeps
== "all")
784 Dependences::TYPE_RAW
| Dependences::TYPE_WAR
| Dependences::TYPE_WAW
;
785 else if (OptimizeDeps
== "raw")
786 ProximityKinds
= Dependences::TYPE_RAW
;
788 errs() << "Do not know how to optimize for '" << OptimizeDeps
<< "'"
789 << " Falling back to optimizing all dependences.\n";
791 Dependences::TYPE_RAW
| Dependences::TYPE_WAR
| Dependences::TYPE_WAW
;
794 isl::union_set Domain
= S
.getDomains();
796 if (Domain
.is_null())
799 isl::union_map Validity
= D
.getDependences(ValidityKinds
);
800 isl::union_map Proximity
= D
.getDependences(ProximityKinds
);
802 // Simplify the dependences by removing the constraints introduced by the
803 // domains. This can speed up the scheduling time significantly, as large
804 // constant coefficients will be removed from the dependences. The
805 // introduction of some additional dependences reduces the possible
806 // transformations, but in most cases, such transformation do not seem to be
807 // interesting anyway. In some cases this option may stop the scheduler to
808 // find any schedule.
809 if (SimplifyDeps
== "yes") {
810 Validity
= Validity
.gist_domain(Domain
);
811 Validity
= Validity
.gist_range(Domain
);
812 Proximity
= Proximity
.gist_domain(Domain
);
813 Proximity
= Proximity
.gist_range(Domain
);
814 } else if (SimplifyDeps
!= "no") {
816 << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
817 "or 'no'. Falling back to default: 'yes'\n";
820 LLVM_DEBUG(dbgs() << "\n\nCompute schedule from: ");
821 LLVM_DEBUG(dbgs() << "Domain := " << Domain
<< ";\n");
822 LLVM_DEBUG(dbgs() << "Proximity := " << Proximity
<< ";\n");
823 LLVM_DEBUG(dbgs() << "Validity := " << Validity
<< ";\n");
825 int IslMaximizeBands
;
826 if (MaximizeBandDepth
== "yes") {
827 IslMaximizeBands
= 1;
828 } else if (MaximizeBandDepth
== "no") {
829 IslMaximizeBands
= 0;
832 << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
833 " or 'no'. Falling back to default: 'yes'\n";
834 IslMaximizeBands
= 1;
837 int IslOuterCoincidence
;
838 if (OuterCoincidence
== "yes") {
839 IslOuterCoincidence
= 1;
840 } else if (OuterCoincidence
== "no") {
841 IslOuterCoincidence
= 0;
843 errs() << "warning: Option -polly-opt-outer-coincidence should either be "
844 "'yes' or 'no'. Falling back to default: 'no'\n";
845 IslOuterCoincidence
= 0;
848 isl_ctx
*Ctx
= S
.getIslCtx().get();
850 isl_options_set_schedule_outer_coincidence(Ctx
, IslOuterCoincidence
);
851 isl_options_set_schedule_maximize_band_depth(Ctx
, IslMaximizeBands
);
852 isl_options_set_schedule_max_constant_term(Ctx
, MaxConstantTerm
);
853 isl_options_set_schedule_max_coefficient(Ctx
, MaxCoefficient
);
854 isl_options_set_tile_scale_tile_loops(Ctx
, 0);
856 auto OnErrorStatus
= isl_options_get_on_error(Ctx
);
857 isl_options_set_on_error(Ctx
, ISL_ON_ERROR_CONTINUE
);
859 auto SC
= isl::schedule_constraints::on_domain(Domain
);
860 SC
= SC
.set_proximity(Proximity
);
861 SC
= SC
.set_validity(Validity
);
862 SC
= SC
.set_coincidence(Validity
);
863 Schedule
= SC
.compute_schedule();
864 isl_options_set_on_error(Ctx
, OnErrorStatus
);
867 LLVM_DEBUG(printSchedule(dbgs(), Schedule
, "After rescheduling"));
870 walkScheduleTreeForStatistics(Schedule
, 1);
872 // In cases the scheduler is not able to optimize the code, we just do not
873 // touch the schedule.
874 if (Schedule
.is_null())
878 isl::union_map Validity
= D
.getDependences(
879 Dependences::TYPE_RAW
| Dependences::TYPE_WAR
| Dependences::TYPE_WAW
);
880 Schedule
= applyGreedyFusion(Schedule
, Validity
);
881 assert(!Schedule
.is_null());
884 // Apply post-rescheduling optimizations (if enabled) and/or prevectorization.
885 const OptimizerAdditionalInfoTy OAI
= {
887 const_cast<Dependences
*>(&D
),
888 /*PatternOpts=*/!HasUserTransformation
&& PMBasedOpts
,
889 /*Postopts=*/!HasUserTransformation
&& EnablePostopts
,
890 /*Prevect=*/PollyVectorizerChoice
!= VECTORIZER_NONE
,
892 if (OAI
.PatternOpts
|| OAI
.Postopts
|| OAI
.Prevect
) {
893 Schedule
= ScheduleTreeOptimizer::optimizeSchedule(Schedule
, &OAI
);
894 Schedule
= hoistExtensionNodes(Schedule
);
895 LLVM_DEBUG(printSchedule(dbgs(), Schedule
, "After post-optimizations"));
896 walkScheduleTreeForStatistics(Schedule
, 2);
899 // Skip profitability check if user transformation(s) have been applied.
900 if (!HasUserTransformation
&&
901 !ScheduleTreeOptimizer::isProfitableSchedule(S
, Schedule
))
904 auto ScopStats
= S
.getStatistics();
906 NumAffineLoopsOptimized
+= ScopStats
.NumAffineLoops
;
907 NumBoxedLoopsOptimized
+= ScopStats
.NumBoxedLoops
;
908 LastSchedule
= Schedule
;
910 S
.setScheduleTree(Schedule
);
917 bool IslScheduleOptimizerWrapperPass::runOnScop(Scop
&S
) {
920 Function
&F
= S
.getFunction();
921 IslCtx
= S
.getSharedIslCtx();
923 auto getDependences
=
924 [this](Dependences::AnalysisLevel
) -> const Dependences
& {
925 return getAnalysis
<DependenceInfo
>().getDependences(
926 Dependences::AL_Statement
);
928 OptimizationRemarkEmitter
&ORE
=
929 getAnalysis
<OptimizationRemarkEmitterWrapperPass
>().getORE();
930 TargetTransformInfo
*TTI
=
931 &getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
933 bool DepsChanged
= false;
934 runIslScheduleOptimizer(S
, getDependences
, TTI
, &ORE
, LastSchedule
,
937 getAnalysis
<DependenceInfo
>().abandonDependences();
941 static void runScheduleOptimizerPrinter(raw_ostream
&OS
,
942 isl::schedule LastSchedule
) {
946 OS
<< "Calculated schedule:\n";
948 if (LastSchedule
.is_null()) {
953 p
= isl_printer_to_str(LastSchedule
.ctx().get());
954 p
= isl_printer_set_yaml_style(p
, ISL_YAML_STYLE_BLOCK
);
955 p
= isl_printer_print_schedule(p
, LastSchedule
.get());
956 ScheduleStr
= isl_printer_get_str(p
);
959 OS
<< ScheduleStr
<< "\n";
964 void IslScheduleOptimizerWrapperPass::printScop(raw_ostream
&OS
, Scop
&) const {
965 runScheduleOptimizerPrinter(OS
, LastSchedule
);
968 void IslScheduleOptimizerWrapperPass::getAnalysisUsage(
969 AnalysisUsage
&AU
) const {
970 ScopPass::getAnalysisUsage(AU
);
971 AU
.addRequired
<DependenceInfo
>();
972 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
973 AU
.addRequired
<OptimizationRemarkEmitterWrapperPass
>();
975 AU
.addPreserved
<DependenceInfo
>();
976 AU
.addPreserved
<OptimizationRemarkEmitterWrapperPass
>();
981 Pass
*polly::createIslScheduleOptimizerWrapperPass() {
982 return new IslScheduleOptimizerWrapperPass();
985 INITIALIZE_PASS_BEGIN(IslScheduleOptimizerWrapperPass
, "polly-opt-isl",
986 "Polly - Optimize schedule of SCoP", false, false);
987 INITIALIZE_PASS_DEPENDENCY(DependenceInfo
);
988 INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass
);
989 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
);
990 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass
);
991 INITIALIZE_PASS_END(IslScheduleOptimizerWrapperPass
, "polly-opt-isl",
992 "Polly - Optimize schedule of SCoP", false, false)
994 static llvm::PreservedAnalyses
995 runIslScheduleOptimizerUsingNPM(Scop
&S
, ScopAnalysisManager
&SAM
,
996 ScopStandardAnalysisResults
&SAR
, SPMUpdater
&U
,
998 DependenceAnalysis::Result
&Deps
= SAM
.getResult
<DependenceAnalysis
>(S
, SAR
);
999 auto GetDeps
= [&Deps
](Dependences::AnalysisLevel
) -> const Dependences
& {
1000 return Deps
.getDependences(Dependences::AL_Statement
);
1002 OptimizationRemarkEmitter
ORE(&S
.getFunction());
1003 TargetTransformInfo
*TTI
= &SAR
.TTI
;
1004 isl::schedule LastSchedule
;
1005 bool DepsChanged
= false;
1006 runIslScheduleOptimizer(S
, GetDeps
, TTI
, &ORE
, LastSchedule
, DepsChanged
);
1008 Deps
.abandonDependences();
1011 *OS
<< "Printing analysis 'Polly - Optimize schedule of SCoP' for region: '"
1012 << S
.getName() << "' in function '" << S
.getFunction().getName()
1014 runScheduleOptimizerPrinter(*OS
, LastSchedule
);
1016 return PreservedAnalyses::all();
1019 llvm::PreservedAnalyses
1020 IslScheduleOptimizerPass::run(Scop
&S
, ScopAnalysisManager
&SAM
,
1021 ScopStandardAnalysisResults
&SAR
, SPMUpdater
&U
) {
1022 return runIslScheduleOptimizerUsingNPM(S
, SAM
, SAR
, U
, nullptr);
1025 llvm::PreservedAnalyses
1026 IslScheduleOptimizerPrinterPass::run(Scop
&S
, ScopAnalysisManager
&SAM
,
1027 ScopStandardAnalysisResults
&SAR
,
1029 return runIslScheduleOptimizerUsingNPM(S
, SAM
, SAR
, U
, &OS
);
1032 //===----------------------------------------------------------------------===//
1035 /// Print result from IslScheduleOptimizerWrapperPass.
1036 class IslScheduleOptimizerPrinterLegacyPass final
: public ScopPass
{
1040 IslScheduleOptimizerPrinterLegacyPass()
1041 : IslScheduleOptimizerPrinterLegacyPass(outs()) {}
1042 explicit IslScheduleOptimizerPrinterLegacyPass(llvm::raw_ostream
&OS
)
1043 : ScopPass(ID
), OS(OS
) {}
1045 bool runOnScop(Scop
&S
) override
{
1046 IslScheduleOptimizerWrapperPass
&P
=
1047 getAnalysis
<IslScheduleOptimizerWrapperPass
>();
1049 OS
<< "Printing analysis '" << P
.getPassName() << "' for region: '"
1050 << S
.getRegion().getNameStr() << "' in function '"
1051 << S
.getFunction().getName() << "':\n";
1057 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
1058 ScopPass::getAnalysisUsage(AU
);
1059 AU
.addRequired
<IslScheduleOptimizerWrapperPass
>();
1060 AU
.setPreservesAll();
1064 llvm::raw_ostream
&OS
;
1067 char IslScheduleOptimizerPrinterLegacyPass::ID
= 0;
1070 Pass
*polly::createIslScheduleOptimizerPrinterLegacyPass(raw_ostream
&OS
) {
1071 return new IslScheduleOptimizerPrinterLegacyPass(OS
);
1074 INITIALIZE_PASS_BEGIN(IslScheduleOptimizerPrinterLegacyPass
,
1075 "polly-print-opt-isl",
1076 "Polly - Print optimizer schedule of SCoP", false, false);
1077 INITIALIZE_PASS_DEPENDENCY(IslScheduleOptimizerWrapperPass
)
1078 INITIALIZE_PASS_END(IslScheduleOptimizerPrinterLegacyPass
,
1079 "polly-print-opt-isl",
1080 "Polly - Print optimizer schedule of SCoP", false, false)