blob: 017cce9281af58afeba621eaa8ccb5cace1185a9 [file] [log] [blame]
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001//===- 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//
Tobias Grosser2219d152016-08-03 05:28:09 +000010// This pass generates an entirely new schedule tree from the data dependences
Tobias Grosser234a4822015-08-15 09:34:33 +000011// and iteration domains. The new schedule tree is computed in two steps:
Tobias Grosser30aa24c2011-05-14 19:02:06 +000012//
Tobias Grosser234a4822015-08-15 09:34:33 +000013// 1) The isl scheduling optimizer is run
14//
15// The isl scheduling optimizer creates a new schedule tree that maximizes
16// parallelism and tileability and minimizes data-dependence distances. The
17// algorithm used is a modified version of the ``Pluto'' algorithm:
18//
19// U. Bondhugula, A. Hartono, J. Ramanujam, and P. Sadayappan.
20// A Practical Automatic Polyhedral Parallelizer and Locality Optimizer.
21// In Proceedings of the 2008 ACM SIGPLAN Conference On Programming Language
22// Design and Implementation, PLDI ’08, pages 101–113. ACM, 2008.
23//
24// 2) A set of post-scheduling transformations is applied on the schedule tree.
25//
26// These optimizations include:
27//
28// - Tiling of the innermost tilable bands
29// - Prevectorization - The coice of a possible outer loop that is strip-mined
30// to the innermost level to enable inner-loop
31// vectorization.
32// - Some optimizations for spatial locality are also planned.
33//
34// For a detailed description of the schedule tree itself please see section 6
35// of:
36//
37// Polyhedral AST generation is more than scanning polyhedra
38// Tobias Grosser, Sven Verdoolaege, Albert Cohen
39// ACM Transations on Programming Languages and Systems (TOPLAS),
40// 37(4), July 2015
41// http://www.grosser.es/#pub-polyhedral-AST-generation
42//
43// This publication also contains a detailed discussion of the different options
44// for polyhedral loop unrolling, full/partial tile separation and other uses
45// of the schedule tree.
46//
Tobias Grosser30aa24c2011-05-14 19:02:06 +000047//===----------------------------------------------------------------------===//
48
Tobias Grosser967239c2011-10-23 20:59:44 +000049#include "polly/ScheduleOptimizer.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#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"
Roman Gareev42402c92016-06-22 09:52:37 +000056#include "llvm/Analysis/TargetTransformInfo.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000057#include "llvm/Support/Debug.h"
Tobias Grosser2493e922011-12-07 07:42:57 +000058#include "isl/aff.h"
Tobias Grosserde68cc92011-06-30 20:01:02 +000059#include "isl/band.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000060#include "isl/constraint.h"
61#include "isl/map.h"
Tobias Grosser42152ff2012-01-30 19:38:47 +000062#include "isl/options.h"
Tobias Grosser97d87452015-05-30 06:46:59 +000063#include "isl/printer.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000064#include "isl/schedule.h"
Tobias Grosserbbb4cec2015-03-22 12:06:39 +000065#include "isl/schedule_node.h"
Tobias Grosser8ad6bc32012-01-31 13:26:29 +000066#include "isl/space.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000067#include "isl/union_map.h"
68#include "isl/union_set.h"
Tobias Grosser30aa24c2011-05-14 19:02:06 +000069
70using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-opt-isl"
74
Tobias Grossera26db472012-01-30 19:38:43 +000075static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000076 OptimizeDeps("polly-opt-optimize-only",
77 cl::desc("Only a certain kind of dependences (all/raw)"),
78 cl::Hidden, cl::init("all"), cl::ZeroOrMore,
79 cl::cat(PollyCategory));
Tobias Grosser1deda292012-02-14 14:02:48 +000080
81static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +000082 SimplifyDeps("polly-opt-simplify-deps",
83 cl::desc("Dependences should be simplified (yes/no)"),
84 cl::Hidden, cl::init("yes"), cl::ZeroOrMore,
85 cl::cat(PollyCategory));
Tobias Grossera26db472012-01-30 19:38:43 +000086
Tobias Grosser483a90d2014-07-09 10:50:10 +000087static cl::opt<int> MaxConstantTerm(
88 "polly-opt-max-constant-term",
89 cl::desc("The maximal constant term allowed (-1 is unlimited)"), cl::Hidden,
90 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser992e60c2012-02-20 08:41:15 +000091
Tobias Grosser483a90d2014-07-09 10:50:10 +000092static cl::opt<int> MaxCoefficient(
93 "polly-opt-max-coefficient",
94 cl::desc("The maximal coefficient allowed (-1 is unlimited)"), cl::Hidden,
95 cl::init(20), cl::ZeroOrMore, cl::cat(PollyCategory));
96
97static cl::opt<std::string> FusionStrategy(
98 "polly-opt-fusion", cl::desc("The fusion strategy to choose (min/max)"),
99 cl::Hidden, cl::init("min"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser92f54802012-02-20 08:41:47 +0000100
Tobias Grossere602a072013-05-07 07:30:56 +0000101static cl::opt<std::string>
Tobias Grosser483a90d2014-07-09 10:50:10 +0000102 MaximizeBandDepth("polly-opt-maximize-bands",
103 cl::desc("Maximize the band depth (yes/no)"), cl::Hidden,
104 cl::init("yes"), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosserb3ad85b2012-01-30 19:38:50 +0000105
Michael Kruse315aa322016-05-02 11:35:27 +0000106static cl::opt<std::string> OuterCoincidence(
107 "polly-opt-outer-coincidence",
108 cl::desc("Try to construct schedules where the outer member of each band "
109 "satisfies the coincidence constraints (yes/no)"),
110 cl::Hidden, cl::init("no"), cl::ZeroOrMore, cl::cat(PollyCategory));
111
Tobias Grosser07c1c2f2015-08-19 08:46:11 +0000112static cl::opt<int> PrevectorWidth(
113 "polly-prevect-width",
114 cl::desc(
115 "The number of loop iterations to strip-mine for pre-vectorization"),
116 cl::Hidden, cl::init(4), cl::ZeroOrMore, cl::cat(PollyCategory));
117
Tobias Grosser04832712015-08-20 13:45:02 +0000118static cl::opt<bool> FirstLevelTiling("polly-tiling",
119 cl::desc("Enable loop tiling"),
120 cl::init(true), cl::ZeroOrMore,
121 cl::cat(PollyCategory));
122
Roman Gareev42402c92016-06-22 09:52:37 +0000123static cl::opt<int> LatencyVectorFma(
124 "polly-target-latency-vector-fma",
125 cl::desc("The minimal number of cycles between issuing two "
126 "dependent consecutive vector fused multiply-add "
127 "instructions."),
128 cl::Hidden, cl::init(8), cl::ZeroOrMore, cl::cat(PollyCategory));
129
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000130static cl::opt<int> ThroughputVectorFma(
131 "polly-target-throughput-vector-fma",
Roman Gareev42402c92016-06-22 09:52:37 +0000132 cl::desc("A throughput of the processor floating-point arithmetic units "
133 "expressed in the number of vector fused multiply-add "
134 "instructions per clock cycle."),
135 cl::Hidden, cl::init(1), cl::ZeroOrMore, cl::cat(PollyCategory));
136
Roman Gareev3a18a932016-07-25 09:42:53 +0000137static cl::list<int>
138 CacheLevelAssociativity("polly-target-cache-level-associativity",
139 cl::desc("The associativity of each cache level."),
140 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
141 cl::cat(PollyCategory));
142
143static cl::list<int> CacheLevelSizes(
144 "polly-target-cache-level-sizes",
145 cl::desc("The size of each cache level specified in bytes."), cl::Hidden,
146 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
147
Tobias Grosser04832712015-08-20 13:45:02 +0000148static cl::opt<int> FirstLevelDefaultTileSize(
Tobias Grosser483a90d2014-07-09 10:50:10 +0000149 "polly-default-tile-size",
150 cl::desc("The default tile size (if not enough were provided by"
151 " --polly-tile-sizes)"),
152 cl::Hidden, cl::init(32), cl::ZeroOrMore, cl::cat(PollyCategory));
Johannes Doerfertc3958b22014-05-28 17:21:02 +0000153
Tobias Grosser04832712015-08-20 13:45:02 +0000154static cl::list<int> FirstLevelTileSizes(
155 "polly-tile-sizes", cl::desc("A tile size for each loop dimension, filled "
156 "with --polly-default-tile-size"),
157 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory));
158
159static cl::opt<bool>
160 SecondLevelTiling("polly-2nd-level-tiling",
161 cl::desc("Enable a 2nd level loop of loop tiling"),
162 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
163
164static cl::opt<int> SecondLevelDefaultTileSize(
165 "polly-2nd-level-default-tile-size",
166 cl::desc("The default 2nd-level tile size (if not enough were provided by"
167 " --polly-2nd-level-tile-sizes)"),
168 cl::Hidden, cl::init(16), cl::ZeroOrMore, cl::cat(PollyCategory));
169
170static cl::list<int>
171 SecondLevelTileSizes("polly-2nd-level-tile-sizes",
172 cl::desc("A tile size for each loop dimension, filled "
173 "with --polly-default-tile-size"),
174 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
175 cl::cat(PollyCategory));
176
Tobias Grosser42e24892015-08-20 13:45:05 +0000177static cl::opt<bool> RegisterTiling("polly-register-tiling",
178 cl::desc("Enable register tiling"),
179 cl::init(false), cl::ZeroOrMore,
180 cl::cat(PollyCategory));
181
182static cl::opt<int> RegisterDefaultTileSize(
183 "polly-register-tiling-default-tile-size",
184 cl::desc("The default register tile size (if not enough were provided by"
185 " --polly-register-tile-sizes)"),
186 cl::Hidden, cl::init(2), cl::ZeroOrMore, cl::cat(PollyCategory));
187
Roman Gareevbe5299a2016-12-21 12:51:12 +0000188static cl::opt<int> PollyPatternMatchingNcQuotient(
189 "polly-pattern-matching-nc-quotient",
190 cl::desc("Quotient that is obtained by dividing Nc, the parameter of the"
191 "macro-kernel, by Nr, the parameter of the micro-kernel"),
192 cl::Hidden, cl::init(256), cl::ZeroOrMore, cl::cat(PollyCategory));
193
Tobias Grosser42e24892015-08-20 13:45:05 +0000194static cl::list<int>
195 RegisterTileSizes("polly-register-tile-sizes",
196 cl::desc("A tile size for each loop dimension, filled "
197 "with --polly-register-tile-size"),
198 cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated,
199 cl::cat(PollyCategory));
200
Roman Gareev9c3eb592016-05-28 16:17:58 +0000201static cl::opt<bool>
202 PMBasedOpts("polly-pattern-matching-based-opts",
203 cl::desc("Perform optimizations based on pattern matching"),
204 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
205
Roman Gareev5f99f862016-08-21 11:20:39 +0000206static cl::opt<bool> OptimizedScops(
207 "polly-optimized-scops",
208 cl::desc("Polly - Dump polyhedral description of Scops optimized with "
209 "the isl scheduling optimizer and the set of post-scheduling "
210 "transformations is applied on the schedule tree"),
211 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
212
Tobias Grosserc80d6972016-09-02 06:33:33 +0000213/// Create an isl_union_set, which describes the isolate option based on
214/// IsoalteDomain.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000215///
216/// @param IsolateDomain An isl_set whose last dimension is the only one that
217/// should belong to the current band node.
218static __isl_give isl_union_set *
219getIsolateOptions(__isl_take isl_set *IsolateDomain) {
220 auto Dims = isl_set_dim(IsolateDomain, isl_dim_set);
221 auto *IsolateRelation = isl_map_from_domain(IsolateDomain);
222 IsolateRelation = isl_map_move_dims(IsolateRelation, isl_dim_out, 0,
223 isl_dim_in, Dims - 1, 1);
224 auto *IsolateOption = isl_map_wrap(IsolateRelation);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000225 auto *Id = isl_id_alloc(isl_set_get_ctx(IsolateOption), "isolate", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000226 return isl_union_set_from_set(isl_set_set_tuple_id(IsolateOption, Id));
227}
228
Tobias Grosserc80d6972016-09-02 06:33:33 +0000229/// Create an isl_union_set, which describes the atomic option for the dimension
230/// of the current node.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000231///
232/// It may help to reduce the size of generated code.
233///
234/// @param Ctx An isl_ctx, which is used to create the isl_union_set.
235static __isl_give isl_union_set *getAtomicOptions(__isl_take isl_ctx *Ctx) {
236 auto *Space = isl_space_set_alloc(Ctx, 0, 1);
237 auto *AtomicOption = isl_set_universe(Space);
Tobias Grosser8dd653d2016-06-22 16:22:00 +0000238 auto *Id = isl_id_alloc(Ctx, "atomic", nullptr);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000239 return isl_union_set_from_set(isl_set_set_tuple_id(AtomicOption, Id));
240}
241
Tobias Grosserc80d6972016-09-02 06:33:33 +0000242/// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000243///
244/// @param Set A set, which should be modified.
245/// @param VectorWidth A parameter, which determines the constraint.
246static __isl_give isl_set *addExtentConstraints(__isl_take isl_set *Set,
247 int VectorWidth) {
248 auto Dims = isl_set_dim(Set, isl_dim_set);
249 auto Space = isl_set_get_space(Set);
250 auto *LocalSpace = isl_local_space_from_space(Space);
251 auto *ExtConstr =
252 isl_constraint_alloc_inequality(isl_local_space_copy(LocalSpace));
253 ExtConstr = isl_constraint_set_constant_si(ExtConstr, 0);
254 ExtConstr =
255 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, 1);
256 Set = isl_set_add_constraint(Set, ExtConstr);
257 ExtConstr = isl_constraint_alloc_inequality(LocalSpace);
258 ExtConstr = isl_constraint_set_constant_si(ExtConstr, VectorWidth - 1);
259 ExtConstr =
260 isl_constraint_set_coefficient_si(ExtConstr, isl_dim_set, Dims - 1, -1);
261 return isl_set_add_constraint(Set, ExtConstr);
262}
263
Tobias Grosserc80d6972016-09-02 06:33:33 +0000264/// Build the desired set of partial tile prefixes.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000265///
266/// We build a set of partial tile prefixes, which are prefixes of the vector
267/// loop that have exactly VectorWidth iterations.
268///
269/// 1. Get all prefixes of the vector loop.
270/// 2. Extend it to a set, which has exactly VectorWidth iterations for
271/// any prefix from the set that was built on the previous step.
272/// 3. Subtract loop domain from it, project out the vector loop dimension and
Roman Gareev76614d32016-05-31 11:22:21 +0000273/// get a set of prefixes, which don't have exactly VectorWidth iterations.
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000274/// 4. Subtract it from all prefixes of the vector loop and get the desired
275/// set.
276///
277/// @param ScheduleRange A range of a map, which describes a prefix schedule
278/// relation.
279static __isl_give isl_set *
280getPartialTilePrefixes(__isl_take isl_set *ScheduleRange, int VectorWidth) {
281 auto Dims = isl_set_dim(ScheduleRange, isl_dim_set);
282 auto *LoopPrefixes = isl_set_project_out(isl_set_copy(ScheduleRange),
283 isl_dim_set, Dims - 1, 1);
284 auto *ExtentPrefixes =
285 isl_set_add_dims(isl_set_copy(LoopPrefixes), isl_dim_set, 1);
286 ExtentPrefixes = addExtentConstraints(ExtentPrefixes, VectorWidth);
287 auto *BadPrefixes = isl_set_subtract(ExtentPrefixes, ScheduleRange);
288 BadPrefixes = isl_set_project_out(BadPrefixes, isl_dim_set, Dims - 1, 1);
289 return isl_set_subtract(LoopPrefixes, BadPrefixes);
290}
291
292__isl_give isl_schedule_node *ScheduleTreeOptimizer::isolateFullPartialTiles(
293 __isl_take isl_schedule_node *Node, int VectorWidth) {
294 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
295 Node = isl_schedule_node_child(Node, 0);
296 Node = isl_schedule_node_child(Node, 0);
297 auto *SchedRelUMap = isl_schedule_node_get_prefix_schedule_relation(Node);
298 auto *ScheduleRelation = isl_map_from_union_map(SchedRelUMap);
299 auto *ScheduleRange = isl_map_range(ScheduleRelation);
300 auto *IsolateDomain = getPartialTilePrefixes(ScheduleRange, VectorWidth);
301 auto *AtomicOption = getAtomicOptions(isl_set_get_ctx(IsolateDomain));
302 auto *IsolateOption = getIsolateOptions(IsolateDomain);
303 Node = isl_schedule_node_parent(Node);
304 Node = isl_schedule_node_parent(Node);
305 auto *Options = isl_union_set_union(IsolateOption, AtomicOption);
306 Node = isl_schedule_node_band_set_ast_build_options(Node, Options);
307 return Node;
308}
309
Tobias Grosserb241d922015-07-28 18:03:36 +0000310__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000311ScheduleTreeOptimizer::prevectSchedBand(__isl_take isl_schedule_node *Node,
312 unsigned DimToVectorize,
313 int VectorWidth) {
Tobias Grosserb241d922015-07-28 18:03:36 +0000314 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
Tobias Grosserc6699b72011-06-30 20:29:13 +0000315
Tobias Grosserb241d922015-07-28 18:03:36 +0000316 auto Space = isl_schedule_node_band_get_space(Node);
317 auto ScheduleDimensions = isl_space_dim(Space, isl_dim_set);
318 isl_space_free(Space);
319 assert(DimToVectorize < ScheduleDimensions);
Tobias Grosserf5338802011-10-06 00:03:35 +0000320
Tobias Grosserb241d922015-07-28 18:03:36 +0000321 if (DimToVectorize > 0) {
322 Node = isl_schedule_node_band_split(Node, DimToVectorize);
323 Node = isl_schedule_node_child(Node, 0);
324 }
325 if (DimToVectorize < ScheduleDimensions - 1)
326 Node = isl_schedule_node_band_split(Node, 1);
327 Space = isl_schedule_node_band_get_space(Node);
328 auto Sizes = isl_multi_val_zero(Space);
329 auto Ctx = isl_schedule_node_get_ctx(Node);
330 Sizes =
331 isl_multi_val_set_val(Sizes, 0, isl_val_int_from_si(Ctx, VectorWidth));
332 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosserca7f5bb2015-10-20 09:12:21 +0000333 Node = isolateFullPartialTiles(Node, VectorWidth);
Tobias Grosserb241d922015-07-28 18:03:36 +0000334 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser42e24892015-08-20 13:45:05 +0000335 // Make sure the "trivially vectorizable loop" is not unrolled. Otherwise,
336 // we will have troubles to match it in the backend.
337 Node = isl_schedule_node_band_set_ast_build_options(
Tobias Grosserfc490a92015-08-20 19:08:16 +0000338 Node, isl_union_set_read_from_str(Ctx, "{ unroll[x]: 1 = 0 }"));
339 Node = isl_schedule_node_band_sink(Node);
Tobias Grosserb241d922015-07-28 18:03:36 +0000340 Node = isl_schedule_node_child(Node, 0);
Roman Gareev11001e12016-02-23 09:00:13 +0000341 if (isl_schedule_node_get_type(Node) == isl_schedule_node_leaf)
342 Node = isl_schedule_node_parent(Node);
343 isl_id *LoopMarker = isl_id_alloc(Ctx, "SIMD", nullptr);
344 Node = isl_schedule_node_insert_mark(Node, LoopMarker);
Tobias Grosserb241d922015-07-28 18:03:36 +0000345 return Node;
Tobias Grosserc6699b72011-06-30 20:29:13 +0000346}
347
Tobias Grosserd891b542015-08-20 12:16:23 +0000348__isl_give isl_schedule_node *
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000349ScheduleTreeOptimizer::tileNode(__isl_take isl_schedule_node *Node,
350 const char *Identifier, ArrayRef<int> TileSizes,
351 int DefaultTileSize) {
Tobias Grosser9bdea572015-08-20 12:22:37 +0000352 auto Ctx = isl_schedule_node_get_ctx(Node);
353 auto Space = isl_schedule_node_band_get_space(Node);
354 auto Dims = isl_space_dim(Space, isl_dim_set);
355 auto Sizes = isl_multi_val_zero(Space);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000356 std::string IdentifierString(Identifier);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000357 for (unsigned i = 0; i < Dims; i++) {
358 auto tileSize = i < TileSizes.size() ? TileSizes[i] : DefaultTileSize;
359 Sizes = isl_multi_val_set_val(Sizes, i, isl_val_int_from_si(Ctx, tileSize));
360 }
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000361 auto TileLoopMarkerStr = IdentifierString + " - Tiles";
362 isl_id *TileLoopMarker =
363 isl_id_alloc(Ctx, TileLoopMarkerStr.c_str(), nullptr);
364 Node = isl_schedule_node_insert_mark(Node, TileLoopMarker);
365 Node = isl_schedule_node_child(Node, 0);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000366 Node = isl_schedule_node_band_tile(Node, Sizes);
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000367 Node = isl_schedule_node_child(Node, 0);
368 auto PointLoopMarkerStr = IdentifierString + " - Points";
369 isl_id *PointLoopMarker =
370 isl_id_alloc(Ctx, PointLoopMarkerStr.c_str(), nullptr);
371 Node = isl_schedule_node_insert_mark(Node, PointLoopMarker);
372 Node = isl_schedule_node_child(Node, 0);
373 return Node;
Tobias Grosser9bdea572015-08-20 12:22:37 +0000374}
375
Roman Gareevb17b9a82016-06-12 17:20:05 +0000376__isl_give isl_schedule_node *
377ScheduleTreeOptimizer::applyRegisterTiling(__isl_take isl_schedule_node *Node,
378 llvm::ArrayRef<int> TileSizes,
379 int DefaultTileSize) {
380 auto *Ctx = isl_schedule_node_get_ctx(Node);
381 Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
382 Node = isl_schedule_node_band_set_ast_build_options(
383 Node, isl_union_set_read_from_str(Ctx, "{unroll[x]}"));
384 return Node;
385}
386
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000387bool ScheduleTreeOptimizer::isTileableBandNode(
Tobias Grosser862b9b52015-08-20 12:32:45 +0000388 __isl_keep isl_schedule_node *Node) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000389 if (isl_schedule_node_get_type(Node) != isl_schedule_node_band)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000390 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000391
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000392 if (isl_schedule_node_n_children(Node) != 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000393 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000394
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000395 if (!isl_schedule_node_band_get_permutable(Node))
Tobias Grosser862b9b52015-08-20 12:32:45 +0000396 return false;
Tobias Grosser44f19ac2011-07-05 22:15:53 +0000397
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000398 auto Space = isl_schedule_node_band_get_space(Node);
399 auto Dims = isl_space_dim(Space, isl_dim_set);
Tobias Grosser9bdea572015-08-20 12:22:37 +0000400 isl_space_free(Space);
Tobias Grosserde68cc92011-06-30 20:01:02 +0000401
Tobias Grosser9bdea572015-08-20 12:22:37 +0000402 if (Dims <= 1)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000403 return false;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000404
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000405 auto Child = isl_schedule_node_get_child(Node, 0);
406 auto Type = isl_schedule_node_get_type(Child);
407 isl_schedule_node_free(Child);
408
Tobias Grosser9bdea572015-08-20 12:22:37 +0000409 if (Type != isl_schedule_node_leaf)
Tobias Grosser862b9b52015-08-20 12:32:45 +0000410 return false;
411
412 return true;
413}
414
415__isl_give isl_schedule_node *
Roman Gareev9c3eb592016-05-28 16:17:58 +0000416ScheduleTreeOptimizer::standardBandOpts(__isl_take isl_schedule_node *Node,
417 void *User) {
Tobias Grosser04832712015-08-20 13:45:02 +0000418 if (FirstLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000419 Node = tileNode(Node, "1st level tiling", FirstLevelTileSizes,
420 FirstLevelDefaultTileSize);
Tobias Grosser04832712015-08-20 13:45:02 +0000421
422 if (SecondLevelTiling)
Tobias Grosser1ac884d2015-08-23 09:11:00 +0000423 Node = tileNode(Node, "2nd level tiling", SecondLevelTileSizes,
424 SecondLevelDefaultTileSize);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000425
Roman Gareevb17b9a82016-06-12 17:20:05 +0000426 if (RegisterTiling)
427 Node =
428 applyRegisterTiling(Node, RegisterTileSizes, RegisterDefaultTileSize);
Tobias Grosser42e24892015-08-20 13:45:05 +0000429
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000430 if (PollyVectorizerChoice == VECTORIZER_NONE)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000431 return Node;
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000432
Tobias Grosser862b9b52015-08-20 12:32:45 +0000433 auto Space = isl_schedule_node_band_get_space(Node);
434 auto Dims = isl_space_dim(Space, isl_dim_set);
435 isl_space_free(Space);
436
Tobias Grosserb241d922015-07-28 18:03:36 +0000437 for (int i = Dims - 1; i >= 0; i--)
Tobias Grosserf10f4632015-08-19 08:03:37 +0000438 if (isl_schedule_node_band_member_get_coincident(Node, i)) {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +0000439 Node = prevectSchedBand(Node, i, PrevectorWidth);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000440 break;
441 }
Tobias Grosserbbb4cec2015-03-22 12:06:39 +0000442
Tobias Grosserf10f4632015-08-19 08:03:37 +0000443 return Node;
Tobias Grosserde68cc92011-06-30 20:01:02 +0000444}
445
Tobias Grosserc80d6972016-09-02 06:33:33 +0000446/// Check whether output dimensions of the map rely on the specified input
447/// dimension.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000448///
449/// @param IslMap The isl map to be considered.
450/// @param DimNum The number of an input dimension to be checked.
451static bool isInputDimUsed(__isl_take isl_map *IslMap, unsigned DimNum) {
452 auto *CheckedAccessRelation =
453 isl_map_project_out(isl_map_copy(IslMap), isl_dim_in, DimNum, 1);
454 CheckedAccessRelation =
455 isl_map_insert_dims(CheckedAccessRelation, isl_dim_in, DimNum, 1);
456 auto *InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
457 CheckedAccessRelation =
458 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_in, InputDimsId);
459 InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_out);
460 CheckedAccessRelation =
461 isl_map_set_tuple_id(CheckedAccessRelation, isl_dim_out, InputDimsId);
462 auto res = !isl_map_is_equal(CheckedAccessRelation, IslMap);
463 isl_map_free(CheckedAccessRelation);
464 isl_map_free(IslMap);
465 return res;
466}
467
Tobias Grosserc80d6972016-09-02 06:33:33 +0000468/// Check if the SCoP statement could probably be optimized with analytical
469/// modeling.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000470///
471/// containsMatrMult tries to determine whether the following conditions
472/// are true:
473/// 1. all memory accesses of the statement will have stride 0 or 1,
474/// if we interchange loops (switch the variable used in the inner
475/// loop to the outer loop).
476/// 2. all memory accesses of the statement except from the last one, are
477/// read memory access and the last one is write memory access.
Roman Gareev76614d32016-05-31 11:22:21 +0000478/// 3. all subscripts of the last memory access of the statement don't contain
Roman Gareev9c3eb592016-05-28 16:17:58 +0000479/// the variable used in the inner loop.
480///
481/// @param PartialSchedule The PartialSchedule that contains a SCoP statement
482/// to check.
483static bool containsMatrMult(__isl_keep isl_map *PartialSchedule) {
484 auto InputDimsId = isl_map_get_tuple_id(PartialSchedule, isl_dim_in);
485 auto *ScpStmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
486 isl_id_free(InputDimsId);
487 if (ScpStmt->size() <= 1)
488 return false;
489 auto MemA = ScpStmt->begin();
490 for (unsigned i = 0; i < ScpStmt->size() - 2 && MemA != ScpStmt->end();
491 i++, MemA++)
Roman Gareev76614d32016-05-31 11:22:21 +0000492 if (!(*MemA)->isRead() ||
493 ((*MemA)->isArrayKind() &&
494 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000495 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule)))))
496 return false;
497 MemA++;
Roman Gareev76614d32016-05-31 11:22:21 +0000498 if (!(*MemA)->isWrite() || !(*MemA)->isArrayKind() ||
499 !((*MemA)->isStrideOne(isl_map_copy(PartialSchedule)) ||
Roman Gareev9c3eb592016-05-28 16:17:58 +0000500 (*MemA)->isStrideZero(isl_map_copy(PartialSchedule))))
501 return false;
502 auto DimNum = isl_map_dim(PartialSchedule, isl_dim_in);
503 return !isInputDimUsed((*MemA)->getAccessRelation(), DimNum - 1);
504}
505
Tobias Grosserc80d6972016-09-02 06:33:33 +0000506/// Circular shift of output dimensions of the integer map.
Roman Gareev9c3eb592016-05-28 16:17:58 +0000507///
508/// @param IslMap The isl map to be modified.
509static __isl_give isl_map *circularShiftOutputDims(__isl_take isl_map *IslMap) {
Roman Gareev9c3eb592016-05-28 16:17:58 +0000510 auto DimNum = isl_map_dim(IslMap, isl_dim_out);
Roman Gareev4b8c7ae2016-06-03 18:46:29 +0000511 if (DimNum == 0)
512 return IslMap;
513 auto InputDimsId = isl_map_get_tuple_id(IslMap, isl_dim_in);
Roman Gareev9c3eb592016-05-28 16:17:58 +0000514 IslMap = isl_map_move_dims(IslMap, isl_dim_in, 0, isl_dim_out, DimNum - 1, 1);
515 IslMap = isl_map_move_dims(IslMap, isl_dim_out, 0, isl_dim_in, 0, 1);
516 return isl_map_set_tuple_id(IslMap, isl_dim_in, InputDimsId);
517}
518
Tobias Grosserc80d6972016-09-02 06:33:33 +0000519/// Permute two dimensions of the band node.
Roman Gareev3a18a932016-07-25 09:42:53 +0000520///
521/// Permute FirstDim and SecondDim dimensions of the Node.
522///
523/// @param Node The band node to be modified.
524/// @param FirstDim The first dimension to be permuted.
525/// @param SecondDim The second dimension to be permuted.
526static __isl_give isl_schedule_node *
527permuteBandNodeDimensions(__isl_take isl_schedule_node *Node, unsigned FirstDim,
528 unsigned SecondDim) {
529 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band &&
530 isl_schedule_node_band_n_member(Node) > std::max(FirstDim, SecondDim));
531 auto PartialSchedule = isl_schedule_node_band_get_partial_schedule(Node);
532 auto PartialScheduleFirstDim =
533 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, FirstDim);
534 auto PartialScheduleSecondDim =
535 isl_multi_union_pw_aff_get_union_pw_aff(PartialSchedule, SecondDim);
536 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
537 PartialSchedule, SecondDim, PartialScheduleFirstDim);
538 PartialSchedule = isl_multi_union_pw_aff_set_union_pw_aff(
539 PartialSchedule, FirstDim, PartialScheduleSecondDim);
540 Node = isl_schedule_node_delete(Node);
541 Node = isl_schedule_node_insert_partial_schedule(Node, PartialSchedule);
542 return Node;
543}
544
Roman Gareev2cb4d132016-07-25 07:27:59 +0000545__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMicroKernel(
546 __isl_take isl_schedule_node *Node, MicroKernelParamsTy MicroKernelParams) {
Roman Gareev8babe1a2016-12-15 11:47:38 +0000547 applyRegisterTiling(Node, {MicroKernelParams.Mr, MicroKernelParams.Nr}, 1);
548 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
549 Node = permuteBandNodeDimensions(Node, 0, 1);
550 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000551}
552
Roman Gareev3a18a932016-07-25 09:42:53 +0000553__isl_give isl_schedule_node *ScheduleTreeOptimizer::createMacroKernel(
554 __isl_take isl_schedule_node *Node, MacroKernelParamsTy MacroKernelParams) {
555 assert(isl_schedule_node_get_type(Node) == isl_schedule_node_band);
556 if (MacroKernelParams.Mc == 1 && MacroKernelParams.Nc == 1 &&
557 MacroKernelParams.Kc == 1)
558 return Node;
559 Node = tileNode(
560 Node, "1st level tiling",
561 {MacroKernelParams.Mc, MacroKernelParams.Nc, MacroKernelParams.Kc}, 1);
562 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
563 Node = permuteBandNodeDimensions(Node, 1, 2);
Roman Gareev8babe1a2016-12-15 11:47:38 +0000564 Node = permuteBandNodeDimensions(Node, 0, 2);
Roman Gareev3a18a932016-07-25 09:42:53 +0000565 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
566}
567
Roman Gareev2cb4d132016-07-25 07:27:59 +0000568/// Get parameters of the BLIS micro kernel.
569///
570/// We choose the Mr and Nr parameters of the micro kernel to be large enough
571/// such that no stalls caused by the combination of latencies and dependencies
572/// are introduced during the updates of the resulting matrix of the matrix
573/// multiplication. However, they should also be as small as possible to
574/// release more registers for entries of multiplied matrices.
575///
576/// @param TTI Target Transform Info.
577/// @return The structure of type MicroKernelParamsTy.
578/// @see MicroKernelParamsTy
579static struct MicroKernelParamsTy
580getMicroKernelParams(const llvm::TargetTransformInfo *TTI) {
Roman Gareev42402c92016-06-22 09:52:37 +0000581 assert(TTI && "The target transform info should be provided.");
Roman Gareev2cb4d132016-07-25 07:27:59 +0000582
Roman Gareev42402c92016-06-22 09:52:37 +0000583 // Nvec - Number of double-precision floating-point numbers that can be hold
584 // by a vector register. Use 2 by default.
585 auto Nvec = TTI->getRegisterBitWidth(true) / 64;
586 if (Nvec == 0)
587 Nvec = 2;
588 int Nr =
Tobias Grosser0791d5f2016-12-23 07:33:39 +0000589 ceil(sqrt(Nvec * LatencyVectorFma * ThroughputVectorFma) / Nvec) * Nvec;
590 int Mr = ceil(Nvec * LatencyVectorFma * ThroughputVectorFma / Nr);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000591 return {Mr, Nr};
592}
593
Roman Gareev3a18a932016-07-25 09:42:53 +0000594/// Get parameters of the BLIS macro kernel.
595///
596/// During the computation of matrix multiplication, blocks of partitioned
597/// matrices are mapped to different layers of the memory hierarchy.
598/// To optimize data reuse, blocks should be ideally kept in cache between
599/// iterations. Since parameters of the macro kernel determine sizes of these
600/// blocks, there are upper and lower bounds on these parameters.
601///
602/// @param MicroKernelParams Parameters of the micro-kernel
603/// to be taken into account.
604/// @return The structure of type MacroKernelParamsTy.
605/// @see MacroKernelParamsTy
606/// @see MicroKernelParamsTy
607static struct MacroKernelParamsTy
608getMacroKernelParams(const MicroKernelParamsTy &MicroKernelParams) {
609 // According to www.cs.utexas.edu/users/flame/pubs/TOMS-BLIS-Analytical.pdf,
610 // it requires information about the first two levels of a cache to determine
611 // all the parameters of a macro-kernel. It also checks that an associativity
612 // degree of a cache level is greater than two. Otherwise, another algorithm
613 // for determination of the parameters should be used.
614 if (!(MicroKernelParams.Mr > 0 && MicroKernelParams.Nr > 0 &&
615 CacheLevelSizes.size() >= 2 && CacheLevelAssociativity.size() >= 2 &&
616 CacheLevelSizes[0] > 0 && CacheLevelSizes[1] > 0 &&
617 CacheLevelAssociativity[0] > 2 && CacheLevelAssociativity[1] > 2))
618 return {1, 1, 1};
Roman Gareevbe5299a2016-12-21 12:51:12 +0000619 // The quotient should be greater than zero.
620 if (PollyPatternMatchingNcQuotient <= 0)
621 return {1, 1, 1};
Roman Gareev15db81e2016-12-15 12:00:57 +0000622 int Car = floor(
Roman Gareev3a18a932016-07-25 09:42:53 +0000623 (CacheLevelAssociativity[0] - 1) /
Roman Gareev8babe1a2016-12-15 11:47:38 +0000624 (1 + static_cast<double>(MicroKernelParams.Nr) / MicroKernelParams.Mr));
Roman Gareev15db81e2016-12-15 12:00:57 +0000625 int Kc = (Car * CacheLevelSizes[0]) /
Roman Gareev8babe1a2016-12-15 11:47:38 +0000626 (MicroKernelParams.Mr * CacheLevelAssociativity[0] * 8);
627 double Cac = static_cast<double>(Kc * 8 * CacheLevelAssociativity[1]) /
Roman Gareev3a18a932016-07-25 09:42:53 +0000628 CacheLevelSizes[1];
Roman Gareev8babe1a2016-12-15 11:47:38 +0000629 int Mc = floor((CacheLevelAssociativity[1] - 2) / Cac);
Roman Gareevbe5299a2016-12-21 12:51:12 +0000630 int Nc = PollyPatternMatchingNcQuotient * MicroKernelParams.Nr;
Roman Gareev3a18a932016-07-25 09:42:53 +0000631 return {Mc, Nc, Kc};
632}
633
Tobias Grosserc80d6972016-09-02 06:33:33 +0000634/// Identify a memory access through the shape of its memory access relation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000635///
636/// Identify the unique memory access in @p Stmt, that has an access relation
637/// equal to @p ExpectedAccessRelation.
638///
639/// @param Stmt The SCoP statement that contains the memory accesses under
640/// consideration.
641/// @param ExpectedAccessRelation The access relation that identifies
642/// the memory access.
643/// @return The memory access of @p Stmt whose memory access relation is equal
644/// to @p ExpectedAccessRelation. nullptr in case there is no or more
645/// than one such access.
646MemoryAccess *
647identifyAccessByAccessRelation(ScopStmt *Stmt,
648 __isl_take isl_map *ExpectedAccessRelation) {
649 if (isl_map_has_tuple_id(ExpectedAccessRelation, isl_dim_out))
650 ExpectedAccessRelation =
651 isl_map_reset_tuple_id(ExpectedAccessRelation, isl_dim_out);
652 MemoryAccess *IdentifiedAccess = nullptr;
653 for (auto *Access : *Stmt) {
654 auto *AccessRelation = Access->getAccessRelation();
655 AccessRelation = isl_map_reset_tuple_id(AccessRelation, isl_dim_out);
656 if (isl_map_is_equal(ExpectedAccessRelation, AccessRelation)) {
657 if (IdentifiedAccess) {
658 isl_map_free(AccessRelation);
659 isl_map_free(ExpectedAccessRelation);
660 return nullptr;
661 }
662 IdentifiedAccess = Access;
663 }
664 isl_map_free(AccessRelation);
665 }
666 isl_map_free(ExpectedAccessRelation);
667 return IdentifiedAccess;
668}
669
Roman Gareevb3224ad2016-09-14 06:26:09 +0000670/// Add constrains to @Dim dimension of @p ExtMap.
671///
672/// If @ExtMap has the following form [O0, O1, O2]->[I1, I2, I3],
673/// the following constraint will be added
674/// Bound * OM <= IM <= Bound * (OM + 1) - 1,
675/// where M is @p Dim and Bound is @p Bound.
676///
677/// @param ExtMap The isl map to be modified.
678/// @param Dim The output dimension to be modfied.
679/// @param Bound The value that is used to specify the constraint.
680/// @return The modified isl map
681__isl_give isl_map *
682addExtensionMapMatMulDimConstraint(__isl_take isl_map *ExtMap, unsigned Dim,
683 unsigned Bound) {
684 assert(Bound != 0);
685 auto *ExtMapSpace = isl_map_get_space(ExtMap);
686 auto *ConstrSpace = isl_local_space_from_space(ExtMapSpace);
687 auto *Constr =
688 isl_constraint_alloc_inequality(isl_local_space_copy(ConstrSpace));
689 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, 1);
690 Constr =
691 isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound * (-1));
692 ExtMap = isl_map_add_constraint(ExtMap, Constr);
693 Constr = isl_constraint_alloc_inequality(ConstrSpace);
694 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_out, Dim, -1);
695 Constr = isl_constraint_set_coefficient_si(Constr, isl_dim_in, Dim, Bound);
696 Constr = isl_constraint_set_constant_si(Constr, Bound - 1);
697 return isl_map_add_constraint(ExtMap, Constr);
698}
699
700/// Create an access relation that is specific for matrix multiplication
701/// pattern.
702///
703/// Create an access relation of the following form:
704/// { [O0, O1, O2]->[I1, I2, I3] :
705/// FirstOutputDimBound * O0 <= I1 <= FirstOutputDimBound * (O0 + 1) - 1
706/// and SecondOutputDimBound * O1 <= I2 <= SecondOutputDimBound * (O1 + 1) - 1
707/// and ThirdOutputDimBound * O2 <= I3 <= ThirdOutputDimBound * (O2 + 1) - 1}
708/// where FirstOutputDimBound is @p FirstOutputDimBound,
709/// SecondOutputDimBound is @p SecondOutputDimBound,
710/// ThirdOutputDimBound is @p ThirdOutputDimBound
711///
712/// @param Ctx The isl context.
713/// @param FirstOutputDimBound,
714/// SecondOutputDimBound,
715/// ThirdOutputDimBound The parameters of the access relation.
716/// @return The specified access relation.
717__isl_give isl_map *getMatMulExt(isl_ctx *Ctx, unsigned FirstOutputDimBound,
718 unsigned SecondOutputDimBound,
719 unsigned ThirdOutputDimBound) {
720 auto *NewRelSpace = isl_space_alloc(Ctx, 0, 3, 3);
721 auto *extensionMap = isl_map_universe(NewRelSpace);
722 if (!FirstOutputDimBound)
723 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 0, 0);
724 else
725 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 0,
726 FirstOutputDimBound);
727 if (!SecondOutputDimBound)
728 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 1, 0);
729 else
730 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 1,
731 SecondOutputDimBound);
732 if (!ThirdOutputDimBound)
733 extensionMap = isl_map_fix_si(extensionMap, isl_dim_out, 2, 0);
734 else
735 extensionMap = addExtensionMapMatMulDimConstraint(extensionMap, 2,
736 ThirdOutputDimBound);
737 return extensionMap;
738}
739
Tobias Grosserc80d6972016-09-02 06:33:33 +0000740/// Create an access relation that is specific to the matrix
Roman Gareev1c892e92016-08-15 12:22:54 +0000741/// multiplication pattern.
742///
743/// Create an access relation of the following form:
744/// Stmt[O0, O1, O2]->[OI, OJ],
745/// where I is @p I, J is @J
746///
747/// @param Stmt The SCoP statement for which to generate the access relation.
748/// @param I The index of the input dimension that is mapped to the first output
749/// dimension.
750/// @param J The index of the input dimension that is mapped to the second
751/// output dimension.
752/// @return The specified access relation.
753__isl_give isl_map *
754getMatMulPatternOriginalAccessRelation(ScopStmt *Stmt, unsigned I, unsigned J) {
755 auto *AccessRelSpace = isl_space_alloc(Stmt->getIslCtx(), 0, 3, 2);
756 auto *AccessRel = isl_map_universe(AccessRelSpace);
757 AccessRel = isl_map_equate(AccessRel, isl_dim_in, I, isl_dim_out, 0);
758 AccessRel = isl_map_equate(AccessRel, isl_dim_in, J, isl_dim_out, 1);
759 AccessRel = isl_map_set_tuple_id(AccessRel, isl_dim_in, Stmt->getDomainId());
760 return AccessRel;
761}
762
Tobias Grosserc80d6972016-09-02 06:33:33 +0000763/// Identify the memory access that corresponds to the access to the second
764/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000765///
766/// Identify the memory access that corresponds to the access
767/// to the matrix B of the matrix multiplication C = A x B.
768///
769/// @param Stmt The SCoP statement that contains the memory accesses
770/// under consideration.
771/// @return The memory access of @p Stmt that corresponds to the access
772/// to the second operand of the matrix multiplication.
773MemoryAccess *identifyAccessA(ScopStmt *Stmt) {
774 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 0, 2);
775 return identifyAccessByAccessRelation(Stmt, OriginalRel);
776}
777
Tobias Grosserc80d6972016-09-02 06:33:33 +0000778/// Identify the memory access that corresponds to the access to the first
779/// operand of the matrix multiplication.
Roman Gareev1c892e92016-08-15 12:22:54 +0000780///
781/// Identify the memory access that corresponds to the access
782/// to the matrix A of the matrix multiplication C = A x B.
783///
784/// @param Stmt The SCoP statement that contains the memory accesses
785/// under consideration.
786/// @return The memory access of @p Stmt that corresponds to the access
787/// to the first operand of the matrix multiplication.
788MemoryAccess *identifyAccessB(ScopStmt *Stmt) {
789 auto *OriginalRel = getMatMulPatternOriginalAccessRelation(Stmt, 2, 1);
790 return identifyAccessByAccessRelation(Stmt, OriginalRel);
791}
792
Tobias Grosserc80d6972016-09-02 06:33:33 +0000793/// Create an access relation that is specific to
Roman Gareev1c892e92016-08-15 12:22:54 +0000794/// the matrix multiplication pattern.
795///
796/// Create an access relation of the following form:
Roman Gareev92c44602016-12-21 11:18:42 +0000797/// [O0, O1, O2, O3, O4, O5, O6, O7, O8] -> [OI, O5, OJ]
798/// where I is @p FirstDim, J is @p SecondDim.
Roman Gareev1c892e92016-08-15 12:22:54 +0000799///
800/// It can be used, for example, to create relations that helps to consequently
801/// access elements of operands of a matrix multiplication after creation of
802/// the BLIS micro and macro kernels.
803///
804/// @see ScheduleTreeOptimizer::createMicroKernel
805/// @see ScheduleTreeOptimizer::createMacroKernel
806///
807/// Subsequently, the described access relation is applied to the range of
808/// @p MapOldIndVar, that is used to map original induction variables to
809/// the ones, which are produced by schedule transformations. It helps to
810/// define relations using a new space and, at the same time, keep them
811/// in the original one.
812///
813/// @param MapOldIndVar The relation, which maps original induction variables
814/// to the ones, which are produced by schedule
815/// transformations.
Roman Gareev1c892e92016-08-15 12:22:54 +0000816/// @param FirstDim, SecondDim The input dimensions that are used to define
817/// the specified access relation.
818/// @return The specified access relation.
819__isl_give isl_map *getMatMulAccRel(__isl_take isl_map *MapOldIndVar,
Roman Gareev92c44602016-12-21 11:18:42 +0000820 unsigned FirstDim, unsigned SecondDim) {
Roman Gareev1c892e92016-08-15 12:22:54 +0000821 auto *Ctx = isl_map_get_ctx(MapOldIndVar);
Roman Gareev92c44602016-12-21 11:18:42 +0000822 auto *AccessRelSpace = isl_space_alloc(Ctx, 0, 9, 3);
823 auto *AccessRel = isl_map_universe(AccessRelSpace);
824 AccessRel = isl_map_equate(AccessRel, isl_dim_in, FirstDim, isl_dim_out, 0);
825 AccessRel = isl_map_equate(AccessRel, isl_dim_in, 5, isl_dim_out, 1);
826 AccessRel = isl_map_equate(AccessRel, isl_dim_in, SecondDim, isl_dim_out, 2);
Roman Gareev1c892e92016-08-15 12:22:54 +0000827 return isl_map_apply_range(MapOldIndVar, AccessRel);
828}
829
Roman Gareevb3224ad2016-09-14 06:26:09 +0000830__isl_give isl_schedule_node *
831createExtensionNode(__isl_take isl_schedule_node *Node,
832 __isl_take isl_map *ExtensionMap) {
833 auto *Extension = isl_union_map_from_map(ExtensionMap);
834 auto *NewNode = isl_schedule_node_from_extension(Extension);
835 return isl_schedule_node_graft_before(Node, NewNode);
836}
837
Tobias Grosserc80d6972016-09-02 06:33:33 +0000838/// Apply the packing transformation.
Roman Gareev1c892e92016-08-15 12:22:54 +0000839///
840/// The packing transformation can be described as a data-layout
841/// transformation that requires to introduce a new array, copy data
842/// to the array, and change memory access locations of the compute kernel
843/// to reference the array.
844///
845/// @param Node The schedule node to be optimized.
846/// @param MapOldIndVar The relation, which maps original induction variables
847/// to the ones, which are produced by schedule
848/// transformations.
849/// @param MicroParams, MacroParams Parameters of the BLIS kernel
850/// to be taken into account.
851/// @return The optimized schedule node.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000852static __isl_give isl_schedule_node *optimizeDataLayoutMatrMulPattern(
853 __isl_take isl_schedule_node *Node, __isl_take isl_map *MapOldIndVar,
854 MicroKernelParamsTy MicroParams, MacroKernelParamsTy MacroParams) {
Roman Gareev2606c482016-12-15 12:35:59 +0000855 // Check whether memory accesses of the SCoP statement correspond to
856 // the matrix multiplication pattern and if this is true, obtain them.
Roman Gareev1c892e92016-08-15 12:22:54 +0000857 auto InputDimsId = isl_map_get_tuple_id(MapOldIndVar, isl_dim_in);
858 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(InputDimsId));
859 isl_id_free(InputDimsId);
860 MemoryAccess *MemAccessA = identifyAccessA(Stmt);
861 MemoryAccess *MemAccessB = identifyAccessB(Stmt);
862 if (!MemAccessA || !MemAccessB) {
863 isl_map_free(MapOldIndVar);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000864 return Node;
Roman Gareev1c892e92016-08-15 12:22:54 +0000865 }
Roman Gareev2606c482016-12-15 12:35:59 +0000866
867 // Create a copy statement that corresponds to the memory access to the
868 // matrix B, the second operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000869 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
870 Node = isl_schedule_node_parent(isl_schedule_node_parent(Node));
871 Node = isl_schedule_node_parent(Node);
872 Node = isl_schedule_node_child(isl_schedule_node_band_split(Node, 2), 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000873 auto *AccRel = getMatMulAccRel(isl_map_copy(MapOldIndVar), 3, 7);
874 unsigned FirstDimSize = MacroParams.Nc / MicroParams.Nr;
875 unsigned SecondDimSize = MacroParams.Kc;
876 unsigned ThirdDimSize = MicroParams.Nr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000877 auto *SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000878 MemAccessB->getElementType(), "Packed_B",
879 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000880 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000881 auto *OldAcc = MemAccessB->getAccessRelation();
882 MemAccessB->setNewAccessRelation(AccRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000883 auto *ExtMap =
Roman Gareev8babe1a2016-12-15 11:47:38 +0000884 getMatMulExt(Stmt->getIslCtx(), 0, MacroParams.Nc, MacroParams.Kc);
885 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
886 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
887 ExtMap = isl_map_project_out(ExtMap, isl_dim_in, 2, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000888 auto *Domain = Stmt->getDomain();
Roman Gareev2606c482016-12-15 12:35:59 +0000889
890 // Restrict the domains of the copy statements to only execute when also its
891 // originating statement is executed.
892 auto *DomainId = isl_set_get_tuple_id(Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000893 auto *NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev8babe1a2016-12-15 11:47:38 +0000894 OldAcc, MemAccessB->getAccessRelation(), isl_set_copy(Domain));
Roman Gareev2606c482016-12-15 12:35:59 +0000895 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, isl_id_copy(DomainId));
896 ExtMap = isl_map_intersect_range(ExtMap, isl_set_copy(Domain));
Roman Gareevb3224ad2016-09-14 06:26:09 +0000897 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
898 Node = createExtensionNode(Node, ExtMap);
Roman Gareev2606c482016-12-15 12:35:59 +0000899
900 // Create a copy statement that corresponds to the memory access
901 // to the matrix A, the first operand of the matrix multiplication.
Roman Gareevb3224ad2016-09-14 06:26:09 +0000902 Node = isl_schedule_node_child(Node, 0);
Roman Gareev92c44602016-12-21 11:18:42 +0000903 AccRel = getMatMulAccRel(MapOldIndVar, 4, 6);
904 FirstDimSize = MacroParams.Mc / MicroParams.Mr;
905 ThirdDimSize = MicroParams.Mr;
Roman Gareev1c892e92016-08-15 12:22:54 +0000906 SAI = Stmt->getParent()->createScopArrayInfo(
Roman Gareev92c44602016-12-21 11:18:42 +0000907 MemAccessA->getElementType(), "Packed_A",
908 {FirstDimSize, SecondDimSize, ThirdDimSize});
Roman Gareev1c892e92016-08-15 12:22:54 +0000909 AccRel = isl_map_set_tuple_id(AccRel, isl_dim_out, SAI->getBasePtrId());
Roman Gareev8babe1a2016-12-15 11:47:38 +0000910 OldAcc = MemAccessA->getAccessRelation();
911 MemAccessA->setNewAccessRelation(AccRel);
912 ExtMap = getMatMulExt(Stmt->getIslCtx(), MacroParams.Mc, 0, MacroParams.Kc);
913 isl_map_move_dims(ExtMap, isl_dim_out, 0, isl_dim_in, 0, 1);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000914 isl_map_move_dims(ExtMap, isl_dim_in, 2, isl_dim_out, 0, 1);
915 NewStmt = Stmt->getParent()->addScopStmt(
Roman Gareev2606c482016-12-15 12:35:59 +0000916 OldAcc, MemAccessA->getAccessRelation(), isl_set_copy(Domain));
917
918 // Restrict the domains of the copy statements to only execute when also its
919 // originating statement is executed.
920 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, DomainId);
921 ExtMap = isl_map_intersect_range(ExtMap, Domain);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000922 ExtMap = isl_map_set_tuple_id(ExtMap, isl_dim_out, NewStmt->getDomainId());
923 Node = createExtensionNode(Node, ExtMap);
924 Node = isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
925 return isl_schedule_node_child(isl_schedule_node_child(Node, 0), 0);
Roman Gareev1c892e92016-08-15 12:22:54 +0000926}
927
Tobias Grosserc80d6972016-09-02 06:33:33 +0000928/// Get a relation mapping induction variables produced by schedule
929/// transformations to the original ones.
Roman Gareev1c892e92016-08-15 12:22:54 +0000930///
931/// @param Node The schedule node produced as the result of creation
932/// of the BLIS kernels.
933/// @param MicroKernelParams, MacroKernelParams Parameters of the BLIS kernel
934/// to be taken into account.
935/// @return The relation mapping original induction variables to the ones
936/// produced by schedule transformation.
937/// @see ScheduleTreeOptimizer::createMicroKernel
938/// @see ScheduleTreeOptimizer::createMacroKernel
939/// @see getMacroKernelParams
940__isl_give isl_map *
941getInductionVariablesSubstitution(__isl_take isl_schedule_node *Node,
942 MicroKernelParamsTy MicroKernelParams,
943 MacroKernelParamsTy MacroKernelParams) {
944 auto *Child = isl_schedule_node_get_child(Node, 0);
945 auto *UnMapOldIndVar = isl_schedule_node_get_prefix_schedule_union_map(Child);
946 isl_schedule_node_free(Child);
947 auto *MapOldIndVar = isl_map_from_union_map(UnMapOldIndVar);
948 if (isl_map_dim(MapOldIndVar, isl_dim_out) > 9)
949 MapOldIndVar =
950 isl_map_project_out(MapOldIndVar, isl_dim_out, 0,
951 isl_map_dim(MapOldIndVar, isl_dim_out) - 9);
952 return MapOldIndVar;
953}
954
Roman Gareev2cb4d132016-07-25 07:27:59 +0000955__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeMatMulPattern(
956 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
957 assert(TTI && "The target transform info should be provided.");
958 auto MicroKernelParams = getMicroKernelParams(TTI);
Roman Gareev3a18a932016-07-25 09:42:53 +0000959 auto MacroKernelParams = getMacroKernelParams(MicroKernelParams);
960 Node = createMacroKernel(Node, MacroKernelParams);
Roman Gareev2cb4d132016-07-25 07:27:59 +0000961 Node = createMicroKernel(Node, MicroKernelParams);
Roman Gareev1c892e92016-08-15 12:22:54 +0000962 if (MacroKernelParams.Mc == 1 || MacroKernelParams.Nc == 1 ||
963 MacroKernelParams.Kc == 1)
964 return Node;
965 auto *MapOldIndVar = getInductionVariablesSubstitution(
966 Node, MicroKernelParams, MacroKernelParams);
967 if (!MapOldIndVar)
968 return Node;
Roman Gareevb3224ad2016-09-14 06:26:09 +0000969 return optimizeDataLayoutMatrMulPattern(Node, MapOldIndVar, MicroKernelParams,
970 MacroKernelParams);
Roman Gareev42402c92016-06-22 09:52:37 +0000971}
972
Roman Gareev9c3eb592016-05-28 16:17:58 +0000973bool ScheduleTreeOptimizer::isMatrMultPattern(
974 __isl_keep isl_schedule_node *Node) {
975 auto *PartialSchedule =
976 isl_schedule_node_band_get_partial_schedule_union_map(Node);
Roman Gareev397a34a2016-06-22 12:11:30 +0000977 if (isl_schedule_node_band_n_member(Node) != 3 ||
978 isl_union_map_n_map(PartialSchedule) != 1) {
979 isl_union_map_free(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +0000980 return false;
981 }
Roman Gareev397a34a2016-06-22 12:11:30 +0000982 auto *NewPartialSchedule = isl_map_from_union_map(PartialSchedule);
Roman Gareev9c3eb592016-05-28 16:17:58 +0000983 NewPartialSchedule = circularShiftOutputDims(NewPartialSchedule);
984 if (containsMatrMult(NewPartialSchedule)) {
985 isl_map_free(NewPartialSchedule);
986 return true;
987 }
988 isl_map_free(NewPartialSchedule);
989 return false;
990}
991
992__isl_give isl_schedule_node *
993ScheduleTreeOptimizer::optimizeBand(__isl_take isl_schedule_node *Node,
994 void *User) {
995 if (!isTileableBandNode(Node))
996 return Node;
997
Roman Gareev42402c92016-06-22 09:52:37 +0000998 if (PMBasedOpts && User && isMatrMultPattern(Node)) {
Roman Gareev9c3eb592016-05-28 16:17:58 +0000999 DEBUG(dbgs() << "The matrix multiplication pattern was detected\n");
Roman Gareev42402c92016-06-22 09:52:37 +00001000 const llvm::TargetTransformInfo *TTI;
1001 TTI = static_cast<const llvm::TargetTransformInfo *>(User);
1002 Node = optimizeMatMulPattern(Node, TTI);
1003 }
Roman Gareev9c3eb592016-05-28 16:17:58 +00001004
1005 return standardBandOpts(Node, User);
1006}
1007
Tobias Grosser808cd692015-07-14 09:33:13 +00001008__isl_give isl_schedule *
Roman Gareev42402c92016-06-22 09:52:37 +00001009ScheduleTreeOptimizer::optimizeSchedule(__isl_take isl_schedule *Schedule,
1010 const llvm::TargetTransformInfo *TTI) {
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001011 isl_schedule_node *Root = isl_schedule_get_root(Schedule);
Roman Gareev42402c92016-06-22 09:52:37 +00001012 Root = optimizeScheduleNode(Root, TTI);
Tobias Grosser808cd692015-07-14 09:33:13 +00001013 isl_schedule_free(Schedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001014 auto S = isl_schedule_node_get_schedule(Root);
Tobias Grosserbbb4cec2015-03-22 12:06:39 +00001015 isl_schedule_node_free(Root);
Tobias Grosser808cd692015-07-14 09:33:13 +00001016 return S;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001017}
1018
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001019__isl_give isl_schedule_node *ScheduleTreeOptimizer::optimizeScheduleNode(
Roman Gareev42402c92016-06-22 09:52:37 +00001020 __isl_take isl_schedule_node *Node, const llvm::TargetTransformInfo *TTI) {
1021 Node = isl_schedule_node_map_descendant_bottom_up(
1022 Node, optimizeBand, const_cast<void *>(static_cast<const void *>(TTI)));
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001023 return Node;
1024}
1025
1026bool ScheduleTreeOptimizer::isProfitableSchedule(
Roman Gareevb3224ad2016-09-14 06:26:09 +00001027 Scop &S, __isl_keep isl_schedule *NewSchedule) {
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001028 // To understand if the schedule has been optimized we check if the schedule
1029 // has changed at all.
1030 // TODO: We can improve this by tracking if any necessarily beneficial
1031 // transformations have been performed. This can e.g. be tiling, loop
1032 // interchange, or ...) We can track this either at the place where the
1033 // transformation has been performed or, in case of automatic ILP based
1034 // optimizations, by comparing (yet to be defined) performance metrics
1035 // before/after the scheduling optimizer
1036 // (e.g., #stride-one accesses)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001037 if (S.containsExtensionNode(NewSchedule))
1038 return true;
1039 auto *NewScheduleMap = isl_schedule_get_map(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001040 isl_union_map *OldSchedule = S.getSchedule();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001041 assert(OldSchedule && "Only IslScheduleOptimizer can insert extension nodes "
1042 "that make Scop::getSchedule() return nullptr.");
1043 bool changed = !isl_union_map_is_equal(OldSchedule, NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001044 isl_union_map_free(OldSchedule);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001045 isl_union_map_free(NewScheduleMap);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001046 return changed;
1047}
1048
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001049namespace {
1050class IslScheduleOptimizer : public ScopPass {
1051public:
1052 static char ID;
1053 explicit IslScheduleOptimizer() : ScopPass(ID) { LastSchedule = nullptr; }
1054
1055 ~IslScheduleOptimizer() { isl_schedule_free(LastSchedule); }
1056
Tobias Grosserc80d6972016-09-02 06:33:33 +00001057 /// Optimize the schedule of the SCoP @p S.
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001058 bool runOnScop(Scop &S) override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001059
Tobias Grosserc80d6972016-09-02 06:33:33 +00001060 /// Print the new schedule for the SCoP @p S.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001061 void printScop(raw_ostream &OS, Scop &S) const override;
1062
Tobias Grosserc80d6972016-09-02 06:33:33 +00001063 /// Register all analyses and transformation required.
Johannes Doerfert45be6442015-09-27 15:43:29 +00001064 void getAnalysisUsage(AnalysisUsage &AU) const override;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001065
Tobias Grosserc80d6972016-09-02 06:33:33 +00001066 /// Release the internal memory.
Johannes Doerfert0f376302015-09-27 15:42:28 +00001067 void releaseMemory() override {
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001068 isl_schedule_free(LastSchedule);
1069 LastSchedule = nullptr;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001070 }
Johannes Doerfert45be6442015-09-27 15:43:29 +00001071
1072private:
1073 isl_schedule *LastSchedule;
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001074};
Tobias Grosser522478d2016-06-23 22:17:27 +00001075} // namespace
Tobias Grosserfa57e9b2015-08-24 06:01:47 +00001076
1077char IslScheduleOptimizer::ID = 0;
1078
Tobias Grosser73600b82011-10-08 00:30:40 +00001079bool IslScheduleOptimizer::runOnScop(Scop &S) {
Johannes Doerfert6f7921f2015-02-14 12:02:24 +00001080
1081 // Skip empty SCoPs but still allow code generation as it will delete the
1082 // loops present but not needed.
1083 if (S.getSize() == 0) {
1084 S.markAsOptimized();
1085 return false;
1086 }
1087
Hongbin Zheng2a798852016-03-03 08:15:33 +00001088 const Dependences &D =
1089 getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001090
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001091 if (!D.hasValidDependences())
Tobias Grosser38c36ea2014-02-23 15:15:44 +00001092 return false;
1093
Tobias Grosser28781422012-10-16 07:29:19 +00001094 isl_schedule_free(LastSchedule);
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001095 LastSchedule = nullptr;
Tobias Grosser28781422012-10-16 07:29:19 +00001096
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001097 // Build input data.
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001098 int ValidityKinds =
1099 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001100 int ProximityKinds;
1101
1102 if (OptimizeDeps == "all")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001103 ProximityKinds =
1104 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001105 else if (OptimizeDeps == "raw")
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001106 ProximityKinds = Dependences::TYPE_RAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001107 else {
1108 errs() << "Do not know how to optimize for '" << OptimizeDeps << "'"
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001109 << " Falling back to optimizing all dependences.\n";
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001110 ProximityKinds =
1111 Dependences::TYPE_RAW | Dependences::TYPE_WAR | Dependences::TYPE_WAW;
Tobias Grosser1deda292012-02-14 14:02:48 +00001112 }
1113
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001114 isl_union_set *Domain = S.getDomains();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001115
Tobias Grosser98610ee2012-02-13 23:31:39 +00001116 if (!Domain)
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001117 return false;
1118
Johannes Doerfert7e6424b2015-03-05 00:43:48 +00001119 isl_union_map *Validity = D.getDependences(ValidityKinds);
1120 isl_union_map *Proximity = D.getDependences(ProximityKinds);
Tobias Grosser8a507022012-03-16 11:51:41 +00001121
Tobias Grossera26db472012-01-30 19:38:43 +00001122 // Simplify the dependences by removing the constraints introduced by the
1123 // domains. This can speed up the scheduling time significantly, as large
1124 // constant coefficients will be removed from the dependences. The
1125 // introduction of some additional dependences reduces the possible
1126 // transformations, but in most cases, such transformation do not seem to be
1127 // interesting anyway. In some cases this option may stop the scheduler to
1128 // find any schedule.
1129 if (SimplifyDeps == "yes") {
Tobias Grosser00383a72012-02-14 14:02:44 +00001130 Validity = isl_union_map_gist_domain(Validity, isl_union_set_copy(Domain));
1131 Validity = isl_union_map_gist_range(Validity, isl_union_set_copy(Domain));
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001132 Proximity =
1133 isl_union_map_gist_domain(Proximity, isl_union_set_copy(Domain));
Tobias Grosser00383a72012-02-14 14:02:44 +00001134 Proximity = isl_union_map_gist_range(Proximity, isl_union_set_copy(Domain));
Tobias Grossera26db472012-01-30 19:38:43 +00001135 } else if (SimplifyDeps != "no") {
1136 errs() << "warning: Option -polly-opt-simplify-deps should either be 'yes' "
1137 "or 'no'. Falling back to default: 'yes'\n";
1138 }
1139
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001140 DEBUG(dbgs() << "\n\nCompute schedule from: ");
Tobias Grosser01aea582014-10-22 23:16:28 +00001141 DEBUG(dbgs() << "Domain := " << stringFromIslObj(Domain) << ";\n");
1142 DEBUG(dbgs() << "Proximity := " << stringFromIslObj(Proximity) << ";\n");
1143 DEBUG(dbgs() << "Validity := " << stringFromIslObj(Validity) << ";\n");
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001144
Michael Krusec59f22c2015-06-18 16:45:40 +00001145 unsigned IslSerializeSCCs;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001146
1147 if (FusionStrategy == "max") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001148 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001149 } else if (FusionStrategy == "min") {
Michael Krusec59f22c2015-06-18 16:45:40 +00001150 IslSerializeSCCs = 1;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001151 } else {
1152 errs() << "warning: Unknown fusion strategy. Falling back to maximal "
1153 "fusion.\n";
Michael Krusec59f22c2015-06-18 16:45:40 +00001154 IslSerializeSCCs = 0;
Tobias Grosserb3ad85b2012-01-30 19:38:50 +00001155 }
1156
Tobias Grosser95e860c2012-01-30 19:38:54 +00001157 int IslMaximizeBands;
1158
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001159 if (MaximizeBandDepth == "yes") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001160 IslMaximizeBands = 1;
Tobias Grossera4ea90b2012-01-30 22:43:56 +00001161 } else if (MaximizeBandDepth == "no") {
Tobias Grosser95e860c2012-01-30 19:38:54 +00001162 IslMaximizeBands = 0;
1163 } else {
1164 errs() << "warning: Option -polly-opt-maximize-bands should either be 'yes'"
1165 " or 'no'. Falling back to default: 'yes'\n";
1166 IslMaximizeBands = 1;
1167 }
1168
Michael Kruse315aa322016-05-02 11:35:27 +00001169 int IslOuterCoincidence;
1170
1171 if (OuterCoincidence == "yes") {
1172 IslOuterCoincidence = 1;
1173 } else if (OuterCoincidence == "no") {
1174 IslOuterCoincidence = 0;
1175 } else {
1176 errs() << "warning: Option -polly-opt-outer-coincidence should either be "
1177 "'yes' or 'no'. Falling back to default: 'no'\n";
1178 IslOuterCoincidence = 0;
1179 }
1180
Tobias Grosseraf149932016-06-30 20:42:56 +00001181 isl_ctx *Ctx = S.getIslCtx();
Tobias Grosser42152ff2012-01-30 19:38:47 +00001182
Tobias Grosseraf149932016-06-30 20:42:56 +00001183 isl_options_set_schedule_outer_coincidence(Ctx, IslOuterCoincidence);
1184 isl_options_set_schedule_serialize_sccs(Ctx, IslSerializeSCCs);
1185 isl_options_set_schedule_maximize_band_depth(Ctx, IslMaximizeBands);
1186 isl_options_set_schedule_max_constant_term(Ctx, MaxConstantTerm);
1187 isl_options_set_schedule_max_coefficient(Ctx, MaxCoefficient);
1188 isl_options_set_tile_scale_tile_loops(Ctx, 0);
1189
Tobias Grosser3898a042016-06-30 20:42:58 +00001190 auto OnErrorStatus = isl_options_get_on_error(Ctx);
Tobias Grosseraf149932016-06-30 20:42:56 +00001191 isl_options_set_on_error(Ctx, ISL_ON_ERROR_CONTINUE);
Tobias Grossera38c9242014-01-26 19:36:28 +00001192
1193 isl_schedule_constraints *ScheduleConstraints;
1194 ScheduleConstraints = isl_schedule_constraints_on_domain(Domain);
1195 ScheduleConstraints =
1196 isl_schedule_constraints_set_proximity(ScheduleConstraints, Proximity);
1197 ScheduleConstraints = isl_schedule_constraints_set_validity(
1198 ScheduleConstraints, isl_union_map_copy(Validity));
1199 ScheduleConstraints =
1200 isl_schedule_constraints_set_coincidence(ScheduleConstraints, Validity);
Tobias Grosser00383a72012-02-14 14:02:44 +00001201 isl_schedule *Schedule;
Tobias Grossera38c9242014-01-26 19:36:28 +00001202 Schedule = isl_schedule_constraints_compute_schedule(ScheduleConstraints);
Tobias Grosser3898a042016-06-30 20:42:58 +00001203 isl_options_set_on_error(Ctx, OnErrorStatus);
Tobias Grosser42152ff2012-01-30 19:38:47 +00001204
1205 // In cases the scheduler is not able to optimize the code, we just do not
1206 // touch the schedule.
Tobias Grosser98610ee2012-02-13 23:31:39 +00001207 if (!Schedule)
Tobias Grosser42152ff2012-01-30 19:38:47 +00001208 return false;
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001209
Tobias Grosser97d87452015-05-30 06:46:59 +00001210 DEBUG({
Tobias Grosseraf149932016-06-30 20:42:56 +00001211 auto *P = isl_printer_to_str(Ctx);
Tobias Grosser97d87452015-05-30 06:46:59 +00001212 P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1213 P = isl_printer_print_schedule(P, Schedule);
Michael Kruse79c01732016-12-12 14:51:06 +00001214 auto *str = isl_printer_get_str(P);
1215 dbgs() << "NewScheduleTree: \n" << str << "\n";
1216 free(str);
Tobias Grosser97d87452015-05-30 06:46:59 +00001217 isl_printer_free(P);
1218 });
Tobias Grosser4d63b9d2012-02-20 08:41:21 +00001219
Roman Gareev42402c92016-06-22 09:52:37 +00001220 Function &F = S.getFunction();
1221 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1222 isl_schedule *NewSchedule =
1223 ScheduleTreeOptimizer::optimizeSchedule(Schedule, TTI);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001224
Roman Gareevb3224ad2016-09-14 06:26:09 +00001225 if (!ScheduleTreeOptimizer::isProfitableSchedule(S, NewSchedule)) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001226 isl_schedule_free(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001227 return false;
1228 }
1229
Tobias Grosser808cd692015-07-14 09:33:13 +00001230 S.setScheduleTree(NewSchedule);
Johannes Doerfert7ceb0402015-02-11 17:25:09 +00001231 S.markAsOptimized();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001232
Roman Gareev5f99f862016-08-21 11:20:39 +00001233 if (OptimizedScops)
1234 S.dump();
1235
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001236 return false;
1237}
1238
Johannes Doerfert3fe584d2015-03-01 18:40:25 +00001239void IslScheduleOptimizer::printScop(raw_ostream &OS, Scop &) const {
Tobias Grosser28781422012-10-16 07:29:19 +00001240 isl_printer *p;
1241 char *ScheduleStr;
1242
1243 OS << "Calculated schedule:\n";
1244
1245 if (!LastSchedule) {
1246 OS << "n/a\n";
1247 return;
1248 }
1249
1250 p = isl_printer_to_str(isl_schedule_get_ctx(LastSchedule));
1251 p = isl_printer_print_schedule(p, LastSchedule);
1252 ScheduleStr = isl_printer_get_str(p);
1253 isl_printer_free(p);
1254
1255 OS << ScheduleStr << "\n";
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001256}
1257
Tobias Grosser73600b82011-10-08 00:30:40 +00001258void IslScheduleOptimizer::getAnalysisUsage(AnalysisUsage &AU) const {
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001259 ScopPass::getAnalysisUsage(AU);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001260 AU.addRequired<DependenceInfo>();
Roman Gareev42402c92016-06-22 09:52:37 +00001261 AU.addRequired<TargetTransformInfoWrapperPass>();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001262}
1263
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001264Pass *polly::createIslScheduleOptimizerPass() {
Tobias Grosser73600b82011-10-08 00:30:40 +00001265 return new IslScheduleOptimizer();
Tobias Grosser30aa24c2011-05-14 19:02:06 +00001266}
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001267
1268INITIALIZE_PASS_BEGIN(IslScheduleOptimizer, "polly-opt-isl",
1269 "Polly - Optimize schedule of SCoP", false, false);
Johannes Doerfertf6557f92015-03-04 22:43:40 +00001270INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
Johannes Doerfert99191c72016-05-31 09:41:04 +00001271INITIALIZE_PASS_DEPENDENCY(ScopInfoRegionPass);
Roman Gareev42402c92016-06-22 09:52:37 +00001272INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001273INITIALIZE_PASS_END(IslScheduleOptimizer, "polly-opt-isl",
1274 "Polly - Optimize schedule of SCoP", false, false)