Coverage Report

Created: 2017-03-27 23:01

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/lib/Transform/FlattenAlgo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ FlattenAlgo.cpp ------------------------------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// Main algorithm of the FlattenSchedulePass. This is a separate file to avoid
11
// the unittest for this requiring linking against LLVM.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "polly/FlattenAlgo.h"
16
#include "llvm/Support/Debug.h"
17
#define DEBUG_TYPE "polly-flatten-algo"
18
19
using namespace polly;
20
using namespace llvm;
21
22
namespace {
23
24
/// Whether a dimension of a set is bounded (lower and upper) by a constant,
25
/// i.e. there are two constants Min and Max, such that every value x of the
26
/// chosen dimensions is Min <= x <= Max.
27
26
bool isDimBoundedByConstant(isl::set Set, unsigned dim) {
28
26
  auto ParamDims = Set.dim(isl::dim::param);
29
26
  Set = Set.project_out(isl::dim::param, 0, ParamDims);
30
26
  Set = Set.project_out(isl::dim::set, 0, dim);
31
26
  auto SetDims = Set.dim(isl::dim::set);
32
26
  Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
33
26
  return bool(Set.is_bounded());
34
26
}
35
36
/// Whether a dimension of a set is (lower and upper) bounded by a constant or
37
/// parameters, i.e. there are two expressions Min_p and Max_p of the parameters
38
/// p, such that every value x of the chosen dimensions is
39
/// Min_p <= x <= Max_p.
40
26
bool isDimBoundedByParameter(isl::set Set, unsigned dim) {
41
26
  Set = Set.project_out(isl::dim::set, 0, dim);
42
26
  auto SetDims = Set.dim(isl::dim::set);
43
26
  Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
44
26
  return bool(Set.is_bounded());
45
26
}
46
47
/// Whether BMap's first out-dimension is not a constant.
48
43
bool isVariableDim(const isl::basic_map &BMap) {
49
43
  auto FixedVal = BMap.plain_get_val_if_fixed(isl::dim::out, 0);
50
43
  return !FixedVal || FixedVal.is_nan();
51
43
}
52
53
/// Whether Map's first out dimension is no constant nor piecewise constant.
54
43
bool isVariableDim(const isl::map &Map) {
55
43
  return foreachEltWithBreak(Map, [](isl::basic_map BMap) -> isl_stat {
56
43
    if (isVariableDim(BMap))
57
11
      return isl_stat_error;
58
32
    return isl_stat_ok;
59
43
  });
60
43
}
61
62
/// Whether UMap's first out dimension is no (piecewise) constant.
63
26
bool isVariableDim(const isl::union_map &UMap) {
64
43
  return foreachEltWithBreak(UMap, [](isl::map Map) -> isl_stat {
65
43
    if (isVariableDim(Map))
66
11
      return isl_stat_error;
67
32
    return isl_stat_ok;
68
43
  });
69
26
}
70
71
/// If @p PwAff maps to a constant, return said constant. If @p Max/@p Min, it
72
/// can also be a piecewise constant and it would return the minimum/maximum
73
/// value. Otherwise, return NaN.
74
22
isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
75
22
  assert(!Max || !Min);
76
22
  isl::val Result;
77
22
  foreachPieceWithBreak(PwAff, [=, &Result](isl::set Set, isl::aff Aff) {
78
22
    if (
Result && 22
Result.is_nan()0
)
79
0
      return isl_stat_ok;
80
22
81
22
    // TODO: If Min/Max, we can also determine a minimum/maximum value if
82
22
    // Set is constant-bounded.
83
22
    
if (22
!Aff.is_cst()22
)
{0
84
0
      Result = isl::val::nan(Aff.get_ctx());
85
0
      return isl_stat_error;
86
0
    }
87
22
88
22
    auto ThisVal = Aff.get_constant();
89
22
    if (
!Result22
)
{22
90
22
      Result = ThisVal;
91
22
      return isl_stat_ok;
92
22
    }
93
22
94
0
    
if (0
Result.eq(ThisVal)0
)
95
0
      return isl_stat_ok;
96
0
97
0
    
if (0
Max && 0
ThisVal.gt(Result)0
)
{0
98
0
      Result = ThisVal;
99
0
      return isl_stat_ok;
100
0
    }
101
0
102
0
    
if (0
Min && 0
ThisVal.lt(Result)0
)
{0
103
0
      Result = ThisVal;
104
0
      return isl_stat_ok;
105
0
    }
106
0
107
0
    // Not compatible
108
0
    Result = isl::val::nan(Aff.get_ctx());
109
0
    return isl_stat_error;
110
0
  });
111
22
  return Result;
112
22
}
113
114
/// Compute @p UPwAff - @p Val.
115
11
isl::union_pw_aff subtract(isl::union_pw_aff UPwAff, isl::val Val) {
116
11
  if (Val.is_zero())
117
11
    return UPwAff;
118
11
119
0
  auto Result = isl::union_pw_aff::empty(UPwAff.get_space());
120
0
  foreachElt(UPwAff, [=, &Result](isl::pw_aff PwAff) {
121
0
    auto ValAff =
122
0
        isl::pw_aff(isl::set::universe(PwAff.get_space().domain()), Val);
123
0
    auto Subtracted = PwAff.sub(ValAff);
124
0
    Result = Result.union_add(isl::union_pw_aff(Subtracted));
125
0
  });
126
0
  return Result;
127
11
}
128
129
/// Compute @UPwAff * @p Val.
130
11
isl::union_pw_aff multiply(isl::union_pw_aff UPwAff, isl::val Val) {
131
11
  if (Val.is_one())
132
1
    return UPwAff;
133
11
134
10
  auto Result = isl::union_pw_aff::empty(UPwAff.get_space());
135
34
  foreachElt(UPwAff, [=, &Result](isl::pw_aff PwAff) {
136
34
    auto ValAff =
137
34
        isl::pw_aff(isl::set::universe(PwAff.get_space().domain()), Val);
138
34
    auto Multiplied = PwAff.mul(ValAff);
139
34
    Result = Result.union_add(Multiplied);
140
34
  });
141
10
  return Result;
142
11
}
143
144
/// Remove @p n dimensions from @p UMap's range, starting at @p first.
145
///
146
/// It is assumed that all maps in the maps have at least the necessary number
147
/// of out dimensions.
148
isl::union_map scheduleProjectOut(const isl::union_map &UMap, unsigned first,
149
100
                                  unsigned n) {
150
100
  if (n == 0)
151
26
    return UMap; /* isl_map_project_out would also reset the tuple, which should
152
100
                    have no effect on schedule ranges */
153
100
154
74
  auto Result = isl::union_map::empty(UMap.get_space());
155
134
  foreachElt(UMap, [=, &Result](isl::map Map) {
156
134
    auto Outprojected = Map.project_out(isl::dim::out, first, n);
157
134
    Result = Result.add_map(Outprojected);
158
134
  });
159
74
  return Result;
160
100
}
161
162
/// Return the number of dimensions in the input map's range.
163
///
164
/// Because this function takes an isl_union_map, the out dimensions could be
165
/// different. We return the maximum number in this case. However, a different
166
/// number of dimensions is not supported by the other code in this file.
167
85
size_t scheduleScatterDims(const isl::union_map &Schedule) {
168
85
  unsigned Dims = 0;
169
164
  foreachElt(Schedule, [&Dims](isl::map Map) {
170
164
    Dims = std::max(Dims, Map.dim(isl::dim::out));
171
164
  });
172
85
  return Dims;
173
85
}
174
175
/// Return the @p pos' range dimension, converted to an isl_union_pw_aff.
176
48
isl::union_pw_aff scheduleExtractDimAff(isl::union_map UMap, unsigned pos) {
177
48
  auto SingleUMap = isl::union_map::empty(UMap.get_space());
178
102
  foreachElt(UMap, [=, &SingleUMap](isl::map Map) {
179
102
    auto MapDims = Map.dim(isl::dim::out);
180
102
    auto SingleMap = Map.project_out(isl::dim::out, 0, pos);
181
102
    SingleMap = SingleMap.project_out(isl::dim::out, 1, MapDims - pos - 1);
182
102
    SingleUMap = SingleUMap.add_map(SingleMap);
183
102
  });
184
48
185
48
  auto UAff = isl::union_pw_multi_aff(SingleUMap);
186
48
  auto FirstMAff = isl::multi_union_pw_aff(UAff);
187
48
  return FirstMAff.get_union_pw_aff(0);
188
48
}
189
190
/// Flatten a sequence-like first dimension.
191
///
192
/// A sequence-like scatter dimension is constant, or at least only small
193
/// variation, typically the result of ordering a sequence of different
194
/// statements. An example would be:
195
///   { Stmt_A[] -> [0, X, ...]; Stmt_B[] -> [1, Y, ...] }
196
/// to schedule all instances of Stmt_A before any instance of Stmt_B.
197
///
198
/// To flatten, first begin with an offset of zero. Then determine the lowest
199
/// possible value of the dimension, call it "i" [In the example we start at 0].
200
/// Considering only schedules with that value, consider only instances with
201
/// that value and determine the extent of the next dimension. Let l_X(i) and
202
/// u_X(i) its minimum (lower bound) and maximum (upper bound) value. Add them
203
/// as "Offset + X - l_X(i)" to the new schedule, then add "u_X(i) - l_X(i) + 1"
204
/// to Offset and remove all i-instances from the old schedule. Repeat with the
205
/// remaining lowest value i' until there are no instances in the old schedule
206
/// left.
207
/// The example schedule would be transformed to:
208
///   { Stmt_X[] -> [X - l_X, ...]; Stmt_B -> [l_X - u_X + 1 + Y - l_Y, ...] }
209
15
isl::union_map tryFlattenSequence(isl::union_map Schedule) {
210
15
  auto IslCtx = Schedule.get_ctx();
211
15
  auto ScatterSet = isl::set(Schedule.range());
212
15
213
15
  auto ParamSpace = Schedule.get_space().params();
214
15
  auto Dims = ScatterSet.dim(isl::dim::set);
215
15
  assert(Dims >= 2);
216
15
217
15
  // Would cause an infinite loop.
218
15
  if (
!isDimBoundedByConstant(ScatterSet, 0)15
)
{0
219
0
    DEBUG(dbgs() << "Abort; dimension is not of fixed size\n");
220
0
    return nullptr;
221
0
  }
222
15
223
15
  auto AllDomains = Schedule.domain();
224
15
  auto AllDomainsToNull = isl::union_pw_multi_aff(AllDomains);
225
15
226
15
  auto NewSchedule = isl::union_map::empty(ParamSpace);
227
15
  auto Counter = isl::pw_aff(isl::local_space(ParamSpace.set_from_params()));
228
15
229
41
  while (
!ScatterSet.is_empty()41
)
{26
230
26
    DEBUG(dbgs() << "Next counter:\n  " << Counter << "\n");
231
26
    DEBUG(dbgs() << "Remaining scatter set:\n  " << ScatterSet << "\n");
232
26
    auto ThisSet = ScatterSet.project_out(isl::dim::set, 1, Dims - 1);
233
26
    auto ThisFirst = ThisSet.lexmin();
234
26
    auto ScatterFirst = ThisFirst.add_dims(isl::dim::set, Dims - 1);
235
26
236
26
    auto SubSchedule = Schedule.intersect_range(ScatterFirst);
237
26
    SubSchedule = scheduleProjectOut(SubSchedule, 0, 1);
238
26
    SubSchedule = flattenSchedule(SubSchedule);
239
26
240
26
    auto SubDims = scheduleScatterDims(SubSchedule);
241
26
    auto FirstSubSchedule = scheduleProjectOut(SubSchedule, 1, SubDims - 1);
242
26
    auto FirstScheduleAff = scheduleExtractDimAff(FirstSubSchedule, 0);
243
26
    auto RemainingSubSchedule = scheduleProjectOut(SubSchedule, 0, 1);
244
26
245
26
    auto FirstSubScatter = isl::set(FirstSubSchedule.range());
246
26
    DEBUG(dbgs() << "Next step in sequence is:\n  " << FirstSubScatter << "\n");
247
26
248
26
    if (
!isDimBoundedByParameter(FirstSubScatter, 0)26
)
{0
249
0
      DEBUG(dbgs() << "Abort; sequence step is not bounded\n");
250
0
      return nullptr;
251
0
    }
252
26
253
26
    auto FirstSubScatterMap = isl::map::from_range(FirstSubScatter);
254
26
255
26
    // isl_set_dim_max returns a strange isl_pw_aff with domain tuple_id of
256
26
    // 'none'. It doesn't match with any space including a 0-dimensional
257
26
    // anonymous tuple.
258
26
    // Interesting, one can create such a set using
259
26
    // isl_set_universe(ParamSpace). Bug?
260
26
    auto PartMin = FirstSubScatterMap.dim_min(0);
261
26
    auto PartMax = FirstSubScatterMap.dim_max(0);
262
26
    auto One = isl::pw_aff(isl::set::universe(ParamSpace.set_from_params()),
263
26
                           isl::val::one(IslCtx));
264
26
    auto PartLen = PartMax.add(PartMin.neg()).add(One);
265
26
266
26
    auto AllPartMin = isl::union_pw_aff(PartMin).pullback(AllDomainsToNull);
267
26
    auto FirstScheduleAffNormalized = FirstScheduleAff.sub(AllPartMin);
268
26
    auto AllCounter = isl::union_pw_aff(Counter).pullback(AllDomainsToNull);
269
26
    auto FirstScheduleAffWithOffset =
270
26
        FirstScheduleAffNormalized.add(AllCounter);
271
26
272
26
    auto ScheduleWithOffset = isl::union_map(FirstScheduleAffWithOffset)
273
26
                                  .flat_range_product(RemainingSubSchedule);
274
26
    NewSchedule = NewSchedule.unite(ScheduleWithOffset);
275
26
276
26
    ScatterSet = ScatterSet.subtract(ScatterFirst);
277
26
    Counter = Counter.add(PartLen);
278
26
  }
279
15
280
15
  
DEBUG15
(dbgs() << "Sequence-flatten result is:\n " << NewSchedule << "\n");15
281
15
  return NewSchedule;
282
15
}
283
284
/// Flatten a loop-like first dimension.
285
///
286
/// A loop-like dimension is one that depends on a variable (usually a loop's
287
/// induction variable). Let the input schedule look like this:
288
///   { Stmt[i] -> [i, X, ...] }
289
///
290
/// To flatten, we determine the largest extent of X which may not depend on the
291
/// actual value of i. Let l_X() the smallest possible value of X and u_X() its
292
/// largest value. Then, construct a new schedule
293
///   { Stmt[i] -> [i * (u_X() - l_X() + 1), ...] }
294
11
isl::union_map tryFlattenLoop(isl::union_map Schedule) {
295
11
  assert(scheduleScatterDims(Schedule) >= 2);
296
11
297
11
  auto Remaining = scheduleProjectOut(Schedule, 0, 1);
298
11
  auto SubSchedule = flattenSchedule(Remaining);
299
11
  auto SubDims = scheduleScatterDims(SubSchedule);
300
11
301
11
  auto SubExtent = isl::set(SubSchedule.range());
302
11
  auto SubExtentDims = SubExtent.dim(isl::dim::param);
303
11
  SubExtent = SubExtent.project_out(isl::dim::param, 0, SubExtentDims);
304
11
  SubExtent = SubExtent.project_out(isl::dim::set, 1, SubDims - 1);
305
11
306
11
  if (
!isDimBoundedByConstant(SubExtent, 0)11
)
{0
307
0
    DEBUG(dbgs() << "Abort; dimension not bounded by constant\n");
308
0
    return nullptr;
309
0
  }
310
11
311
11
  auto Min = SubExtent.dim_min(0);
312
11
  DEBUG(dbgs() << "Min bound:\n  " << Min << "\n");
313
11
  auto MinVal = getConstant(Min, false, true);
314
11
  auto Max = SubExtent.dim_max(0);
315
11
  DEBUG(dbgs() << "Max bound:\n  " << Max << "\n");
316
11
  auto MaxVal = getConstant(Max, true, false);
317
11
318
11
  if (
!MinVal || 11
!MaxVal11
||
MinVal.is_nan()11
||
MaxVal.is_nan()11
)
{0
319
0
    DEBUG(dbgs() << "Abort; dimension bounds could not be determined\n");
320
0
    return nullptr;
321
0
  }
322
11
323
11
  auto FirstSubScheduleAff = scheduleExtractDimAff(SubSchedule, 0);
324
11
  auto RemainingSubSchedule = scheduleProjectOut(std::move(SubSchedule), 0, 1);
325
11
326
11
  auto LenVal = MaxVal.sub(MinVal).add_ui(1);
327
11
  auto FirstSubScheduleNormalized = subtract(FirstSubScheduleAff, MinVal);
328
11
329
11
  // TODO: Normalize FirstAff to zero (convert to isl_map, determine minimum,
330
11
  // subtract it)
331
11
  auto FirstAff = scheduleExtractDimAff(Schedule, 0);
332
11
  auto Offset = multiply(FirstAff, LenVal);
333
11
  auto Index = FirstSubScheduleNormalized.add(Offset);
334
11
  auto IndexMap = isl::union_map(Index);
335
11
336
11
  auto Result = IndexMap.flat_range_product(RemainingSubSchedule);
337
11
  DEBUG(dbgs() << "Loop-flatten result is:\n  " << Result << "\n");
338
11
  return Result;
339
11
}
340
} // anonymous namespace
341
342
48
isl::union_map polly::flattenSchedule(isl::union_map Schedule) {
343
48
  auto Dims = scheduleScatterDims(Schedule);
344
48
  DEBUG(dbgs() << "Recursive schedule to process:\n  " << Schedule << "\n");
345
48
346
48
  // Base case; no dimensions left
347
48
  if (
Dims == 048
)
{0
348
0
    // TODO: Add one dimension?
349
0
    return Schedule;
350
0
  }
351
48
352
48
  // Base case; already one-dimensional
353
48
  
if (48
Dims == 148
)
354
22
    return Schedule;
355
48
356
48
  // Fixed dimension; no need to preserve variabledness.
357
26
  
if (26
!isVariableDim(Schedule)26
)
{15
358
15
    DEBUG(dbgs() << "Fixed dimension; try sequence flattening\n");
359
15
    auto NewScheduleSequence = tryFlattenSequence(Schedule);
360
15
    if (NewScheduleSequence)
361
15
      return NewScheduleSequence;
362
15
  }
363
26
364
26
  // Constant stride
365
11
  
DEBUG11
(dbgs() << "Try loop flattening\n");11
366
11
  auto NewScheduleLoop = tryFlattenLoop(Schedule);
367
11
  if (NewScheduleLoop)
368
11
    return NewScheduleLoop;
369
11
370
11
  // Try again without loop condition (may blow up the number of pieces!!)
371
0
  
DEBUG0
(dbgs() << "Try sequence flattening again\n");0
372
0
  auto NewScheduleSequence = tryFlattenSequence(Schedule);
373
0
  if (NewScheduleSequence)
374
0
    return NewScheduleSequence;
375
0
376
0
  // Cannot flatten
377
0
  return Schedule;
378
0
}