Coverage Report

Created: 2018-08-14 02:14

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Support/ISLTools.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ ISLTools.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
// Tools, utilities, helpers and extensions useful in conjunction with the
11
// Integer Set Library (isl).
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "polly/Support/ISLTools.h"
16
#include "llvm/ADT/StringRef.h"
17
18
using namespace polly;
19
20
namespace {
21
/// Create a map that shifts one dimension by an offset.
22
///
23
/// Example:
24
/// makeShiftDimAff({ [i0, i1] -> [o0, o1] }, 1, -2)
25
///   = { [i0, i1] -> [i0, i1 - 1] }
26
///
27
/// @param Space  The map space of the result. Must have equal number of in- and
28
///               out-dimensions.
29
/// @param Pos    Position to shift.
30
/// @param Amount Value added to the shifted dimension.
31
///
32
/// @return An isl_multi_aff for the map with this shifted dimension.
33
942
isl::multi_aff makeShiftDimAff(isl::space Space, int Pos, int Amount) {
34
942
  auto Identity = isl::multi_aff::identity(Space);
35
942
  if (Amount == 0)
36
0
    return Identity;
37
942
  auto ShiftAff = Identity.get_aff(Pos);
38
942
  ShiftAff = ShiftAff.set_constant_si(Amount);
39
942
  return Identity.set_aff(Pos, ShiftAff);
40
942
}
41
42
/// Construct a map that swaps two nested tuples.
43
///
44
/// @param FromSpace1 { Space1[] }
45
/// @param FromSpace2 { Space2[] }
46
///
47
/// @return { [Space1[] -> Space2[]] -> [Space2[] -> Space1[]] }
48
isl::basic_map makeTupleSwapBasicMap(isl::space FromSpace1,
49
125
                                     isl::space FromSpace2) {
50
125
  // Fast-path on out-of-quota.
51
125
  if (!FromSpace1 || !FromSpace2)
52
0
    return {};
53
125
54
125
  assert(FromSpace1.is_set());
55
125
  assert(FromSpace2.is_set());
56
125
57
125
  unsigned Dims1 = FromSpace1.dim(isl::dim::set);
58
125
  unsigned Dims2 = FromSpace2.dim(isl::dim::set);
59
125
60
125
  isl::space FromSpace =
61
125
      FromSpace1.map_from_domain_and_range(FromSpace2).wrap();
62
125
  isl::space ToSpace = FromSpace2.map_from_domain_and_range(FromSpace1).wrap();
63
125
  isl::space MapSpace = FromSpace.map_from_domain_and_range(ToSpace);
64
125
65
125
  isl::basic_map Result = isl::basic_map::universe(MapSpace);
66
188
  for (auto i = Dims1 - Dims1; i < Dims1; 
i += 163
)
67
63
    Result = Result.equate(isl::dim::in, i, isl::dim::out, Dims2 + i);
68
336
  for (auto i = Dims2 - Dims2; i < Dims2; 
i += 1211
) {
69
211
    Result = Result.equate(isl::dim::in, Dims1 + i, isl::dim::out, i);
70
211
  }
71
125
72
125
  return Result;
73
125
}
74
75
/// Like makeTupleSwapBasicMap(isl::space,isl::space), but returns
76
/// an isl_map.
77
125
isl::map makeTupleSwapMap(isl::space FromSpace1, isl::space FromSpace2) {
78
125
  isl::basic_map BMapResult = makeTupleSwapBasicMap(FromSpace1, FromSpace2);
79
125
  return isl::map(BMapResult);
80
125
}
81
} // anonymous namespace
82
83
243
isl::map polly::beforeScatter(isl::map Map, bool Strict) {
84
243
  isl::space RangeSpace = Map.get_space().range();
85
243
  isl::map ScatterRel =
86
243
      Strict ? 
isl::map::lex_gt(RangeSpace)57
:
isl::map::lex_ge(RangeSpace)186
;
87
243
  return Map.apply_range(ScatterRel);
88
243
}
89
90
98
isl::union_map polly::beforeScatter(isl::union_map UMap, bool Strict) {
91
98
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
92
98
93
109
  for (isl::map Map : UMap.get_map_list()) {
94
109
    isl::map After = beforeScatter(Map, Strict);
95
109
    Result = Result.add_map(After);
96
109
  }
97
98
98
98
  return Result;
99
98
}
100
101
149
isl::map polly::afterScatter(isl::map Map, bool Strict) {
102
149
  isl::space RangeSpace = Map.get_space().range();
103
149
  isl::map ScatterRel =
104
149
      Strict ? 
isl::map::lex_lt(RangeSpace)131
:
isl::map::lex_le(RangeSpace)18
;
105
149
  return Map.apply_range(ScatterRel);
106
149
}
107
108
98
isl::union_map polly::afterScatter(const isl::union_map &UMap, bool Strict) {
109
98
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
110
98
  for (isl::map Map : UMap.get_map_list()) {
111
54
    isl::map After = afterScatter(Map, Strict);
112
54
    Result = Result.add_map(After);
113
54
  }
114
98
  return Result;
115
98
}
116
117
isl::map polly::betweenScatter(isl::map From, isl::map To, bool InclFrom,
118
93
                               bool InclTo) {
119
93
  isl::map AfterFrom = afterScatter(From, !InclFrom);
120
93
  isl::map BeforeTo = beforeScatter(To, !InclTo);
121
93
122
93
  return AfterFrom.intersect(BeforeTo);
123
93
}
124
125
isl::union_map polly::betweenScatter(isl::union_map From, isl::union_map To,
126
86
                                     bool InclFrom, bool InclTo) {
127
86
  isl::union_map AfterFrom = afterScatter(From, !InclFrom);
128
86
  isl::union_map BeforeTo = beforeScatter(To, !InclTo);
129
86
130
86
  return AfterFrom.intersect(BeforeTo);
131
86
}
132
133
289
isl::map polly::singleton(isl::union_map UMap, isl::space ExpectedSpace) {
134
289
  if (!UMap)
135
0
    return nullptr;
136
289
137
289
  if (isl_union_map_n_map(UMap.get()) == 0)
138
3
    return isl::map::empty(ExpectedSpace);
139
286
140
286
  isl::map Result = isl::map::from_union_map(UMap);
141
286
  assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
142
286
143
286
  return Result;
144
286
}
145
146
130
isl::set polly::singleton(isl::union_set USet, isl::space ExpectedSpace) {
147
130
  if (!USet)
148
0
    return nullptr;
149
130
150
130
  if (isl_union_set_n_set(USet.get()) == 0)
151
36
    return isl::set::empty(ExpectedSpace);
152
94
153
94
  isl::set Result(USet);
154
94
  assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
155
94
156
94
  return Result;
157
94
}
158
159
583
unsigned polly::getNumScatterDims(const isl::union_map &Schedule) {
160
583
  unsigned Dims = 0;
161
583
  for (isl::map Map : Schedule.get_map_list())
162
2.34k
    Dims = std::max(Dims, Map.dim(isl::dim::out));
163
583
  return Dims;
164
583
}
165
166
575
isl::space polly::getScatterSpace(const isl::union_map &Schedule) {
167
575
  if (!Schedule)
168
0
    return nullptr;
169
575
  unsigned Dims = getNumScatterDims(Schedule);
170
575
  isl::space ScatterSpace = Schedule.get_space().set_from_params();
171
575
  return ScatterSpace.add_dims(isl::dim::set, Dims);
172
575
}
173
174
isl::union_map polly::makeIdentityMap(const isl::union_set &USet,
175
97
                                      bool RestrictDomain) {
176
97
  isl::union_map Result = isl::union_map::empty(USet.get_space());
177
114
  for (isl::set Set : USet.get_set_list()) {
178
114
    isl::map IdentityMap = isl::map::identity(Set.get_space().map_from_set());
179
114
    if (RestrictDomain)
180
57
      IdentityMap = IdentityMap.intersect_domain(Set);
181
114
    Result = Result.add_map(IdentityMap);
182
114
  }
183
97
  return Result;
184
97
}
185
186
125
isl::map polly::reverseDomain(isl::map Map) {
187
125
  isl::space DomSpace = Map.get_space().domain().unwrap();
188
125
  isl::space Space1 = DomSpace.domain();
189
125
  isl::space Space2 = DomSpace.range();
190
125
  isl::map Swap = makeTupleSwapMap(Space1, Space2);
191
125
  return Map.apply_domain(Swap);
192
125
}
193
194
165
isl::union_map polly::reverseDomain(const isl::union_map &UMap) {
195
165
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
196
165
  for (isl::map Map : UMap.get_map_list()) {
197
124
    auto Reversed = reverseDomain(std::move(Map));
198
124
    Result = Result.add_map(Reversed);
199
124
  }
200
165
  return Result;
201
165
}
202
203
566
isl::set polly::shiftDim(isl::set Set, int Pos, int Amount) {
204
566
  int NumDims = Set.dim(isl::dim::set);
205
566
  if (Pos < 0)
206
563
    Pos = NumDims + Pos;
207
566
  assert(Pos < NumDims && "Dimension index must be in range");
208
566
  isl::space Space = Set.get_space();
209
566
  Space = Space.map_from_domain_and_range(Space);
210
566
  isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
211
566
  isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
212
566
  return Set.apply(TranslatorMap);
213
566
}
214
215
550
isl::union_set polly::shiftDim(isl::union_set USet, int Pos, int Amount) {
216
550
  isl::union_set Result = isl::union_set::empty(USet.get_space());
217
565
  for (isl::set Set : USet.get_set_list()) {
218
565
    isl::set Shifted = shiftDim(Set, Pos, Amount);
219
565
    Result = Result.add_set(Shifted);
220
565
  }
221
550
  return Result;
222
550
}
223
224
376
isl::map polly::shiftDim(isl::map Map, isl::dim Dim, int Pos, int Amount) {
225
376
  int NumDims = Map.dim(Dim);
226
376
  if (Pos < 0)
227
372
    Pos = NumDims + Pos;
228
376
  assert(Pos < NumDims && "Dimension index must be in range");
229
376
  isl::space Space = Map.get_space();
230
376
  switch (Dim) {
231
376
  case isl::dim::in:
232
371
    Space = Space.domain();
233
371
    break;
234
376
  case isl::dim::out:
235
5
    Space = Space.range();
236
5
    break;
237
376
  default:
238
0
    llvm_unreachable("Unsupported value for 'dim'");
239
376
  }
240
376
  Space = Space.map_from_domain_and_range(Space);
241
376
  isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
242
376
  isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
243
376
  switch (Dim) {
244
376
  case isl::dim::in:
245
371
    return Map.apply_domain(TranslatorMap);
246
376
  case isl::dim::out:
247
5
    return Map.apply_range(TranslatorMap);
248
376
  default:
249
0
    llvm_unreachable("Unsupported value for 'dim'");
250
376
  }
251
376
}
252
253
isl::union_map polly::shiftDim(isl::union_map UMap, isl::dim Dim, int Pos,
254
538
                               int Amount) {
255
538
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
256
538
257
538
  for (isl::map Map : UMap.get_map_list()) {
258
374
    isl::map Shifted = shiftDim(Map, Dim, Pos, Amount);
259
374
    Result = Result.add_map(Shifted);
260
374
  }
261
538
  return Result;
262
538
}
263
264
604
void polly::simplify(isl::set &Set) {
265
604
  Set = isl::manage(isl_set_compute_divs(Set.copy()));
266
604
  Set = Set.detect_equalities();
267
604
  Set = Set.coalesce();
268
604
}
269
270
84
void polly::simplify(isl::union_set &USet) {
271
84
  USet = isl::manage(isl_union_set_compute_divs(USet.copy()));
272
84
  USet = USet.detect_equalities();
273
84
  USet = USet.coalesce();
274
84
}
275
276
719
void polly::simplify(isl::map &Map) {
277
719
  Map = isl::manage(isl_map_compute_divs(Map.copy()));
278
719
  Map = Map.detect_equalities();
279
719
  Map = Map.coalesce();
280
719
}
281
282
525
void polly::simplify(isl::union_map &UMap) {
283
525
  UMap = isl::manage(isl_union_map_compute_divs(UMap.copy()));
284
525
  UMap = UMap.detect_equalities();
285
525
  UMap = UMap.coalesce();
286
525
}
287
288
isl::union_map polly::computeReachingWrite(isl::union_map Schedule,
289
                                           isl::union_map Writes, bool Reverse,
290
375
                                           bool InclPrevDef, bool InclNextDef) {
291
375
292
375
  // { Scatter[] }
293
375
  isl::space ScatterSpace = getScatterSpace(Schedule);
294
375
295
375
  // { ScatterRead[] -> ScatterWrite[] }
296
375
  isl::map Relation;
297
375
  if (Reverse)
298
212
    Relation = InclPrevDef ? 
isl::map::lex_lt(ScatterSpace)25
299
212
                           : 
isl::map::lex_le(ScatterSpace)187
;
300
163
  else
301
163
    Relation = InclNextDef ? 
isl::map::lex_gt(ScatterSpace)157
302
163
                           : 
isl::map::lex_ge(ScatterSpace)6
;
303
375
304
375
  // { ScatterWrite[] -> [ScatterRead[] -> ScatterWrite[]] }
305
375
  isl::map RelationMap = Relation.range_map().reverse();
306
375
307
375
  // { Element[] -> ScatterWrite[] }
308
375
  isl::union_map WriteAction = Schedule.apply_domain(Writes);
309
375
310
375
  // { ScatterWrite[] -> Element[] }
311
375
  isl::union_map WriteActionRev = WriteAction.reverse();
312
375
313
375
  // { Element[] -> [ScatterUse[] -> ScatterWrite[]] }
314
375
  isl::union_map DefSchedRelation =
315
375
      isl::union_map(RelationMap).apply_domain(WriteActionRev);
316
375
317
375
  // For each element, at every point in time, map to the times of previous
318
375
  // definitions. { [Element[] -> ScatterRead[]] -> ScatterWrite[] }
319
375
  isl::union_map ReachableWrites = DefSchedRelation.uncurry();
320
375
  if (Reverse)
321
212
    ReachableWrites = ReachableWrites.lexmin();
322
163
  else
323
163
    ReachableWrites = ReachableWrites.lexmax();
324
375
325
375
  // { [Element[] -> ScatterWrite[]] -> ScatterWrite[] }
326
375
  isl::union_map SelfUse = WriteAction.range_map();
327
375
328
375
  if (InclPrevDef && 
InclNextDef29
) {
329
6
    // Add the Def itself to the solution.
330
6
    ReachableWrites = ReachableWrites.unite(SelfUse).coalesce();
331
369
  } else if (!InclPrevDef && 
!InclNextDef346
) {
332
10
    // Remove Def itself from the solution.
333
10
    ReachableWrites = ReachableWrites.subtract(SelfUse);
334
10
  }
335
375
336
375
  // { [Element[] -> ScatterRead[]] -> Domain[] }
337
375
  return ReachableWrites.apply_range(Schedule.reverse());
338
375
}
339
340
isl::union_map
341
polly::computeArrayUnused(isl::union_map Schedule, isl::union_map Writes,
342
                          isl::union_map Reads, bool ReadEltInSameInst,
343
82
                          bool IncludeLastRead, bool IncludeWrite) {
344
82
  // { Element[] -> Scatter[] }
345
82
  isl::union_map ReadActions = Schedule.apply_domain(Reads);
346
82
  isl::union_map WriteActions = Schedule.apply_domain(Writes);
347
82
348
82
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
349
82
  isl::union_map EltDomWrites =
350
82
      Writes.reverse().range_map().apply_range(Schedule);
351
82
352
82
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
353
82
  isl::union_map ReachingOverwrite = computeReachingWrite(
354
82
      Schedule, Writes, true, ReadEltInSameInst, !ReadEltInSameInst);
355
82
356
82
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
357
82
  isl::union_map ReadsOverwritten =
358
82
      ReachingOverwrite.intersect_domain(ReadActions.wrap());
359
82
360
82
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
361
82
  isl::union_map ReadsOverwrittenRotated =
362
82
      reverseDomain(ReadsOverwritten).curry().reverse();
363
82
  isl::union_map LastOverwrittenRead = ReadsOverwrittenRotated.lexmax();
364
82
365
82
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
366
82
  isl::union_map BetweenLastReadOverwrite = betweenScatter(
367
82
      LastOverwrittenRead, EltDomWrites, IncludeLastRead, IncludeWrite);
368
82
369
82
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
370
82
  isl::union_map ReachingOverwriteZone = computeReachingWrite(
371
82
      Schedule, Writes, true, IncludeLastRead, IncludeWrite);
372
82
373
82
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
374
82
  isl::union_map ReachingOverwriteRotated =
375
82
      reverseDomain(ReachingOverwriteZone).curry().reverse();
376
82
377
82
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
378
82
  isl::union_map WritesWithoutReads = ReachingOverwriteRotated.subtract_domain(
379
82
      ReadsOverwrittenRotated.domain());
380
82
381
82
  return BetweenLastReadOverwrite.unite(WritesWithoutReads)
382
82
      .domain_factor_domain();
383
82
}
384
385
isl::union_set polly::convertZoneToTimepoints(isl::union_set Zone,
386
550
                                              bool InclStart, bool InclEnd) {
387
550
  if (!InclStart && 
InclEnd10
)
388
5
    return Zone;
389
545
390
545
  auto ShiftedZone = shiftDim(Zone, -1, -1);
391
545
  if (InclStart && 
!InclEnd540
)
392
535
    return ShiftedZone;
393
10
  else if (!InclStart && 
!InclEnd5
)
394
5
    return Zone.intersect(ShiftedZone);
395
5
396
5
  assert(InclStart && InclEnd);
397
5
  return Zone.unite(ShiftedZone);
398
5
}
399
400
isl::union_map polly::convertZoneToTimepoints(isl::union_map Zone, isl::dim Dim,
401
603
                                              bool InclStart, bool InclEnd) {
402
603
  if (!InclStart && 
InclEnd69
)
403
67
    return Zone;
404
536
405
536
  auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
406
536
  if (InclStart && 
!InclEnd534
)
407
532
    return ShiftedZone;
408
4
  else if (!InclStart && 
!InclEnd2
)
409
2
    return Zone.intersect(ShiftedZone);
410
2
411
2
  assert(InclStart && InclEnd);
412
2
  return Zone.unite(ShiftedZone);
413
2
}
414
415
isl::map polly::convertZoneToTimepoints(isl::map Zone, isl::dim Dim,
416
45
                                        bool InclStart, bool InclEnd) {
417
45
  if (!InclStart && InclEnd)
418
45
    return Zone;
419
0
420
0
  auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
421
0
  if (InclStart && !InclEnd)
422
0
    return ShiftedZone;
423
0
  else if (!InclStart && !InclEnd)
424
0
    return Zone.intersect(ShiftedZone);
425
0
426
0
  assert(InclStart && InclEnd);
427
0
  return Zone.unite(ShiftedZone);
428
0
}
429
430
211
isl::map polly::distributeDomain(isl::map Map) {
431
211
  // Note that we cannot take Map apart into { Domain[] -> Range1[] } and {
432
211
  // Domain[] -> Range2[] } and combine again. We would loose any relation
433
211
  // between Range1[] and Range2[] that is not also a constraint to Domain[].
434
211
435
211
  isl::space Space = Map.get_space();
436
211
  isl::space DomainSpace = Space.domain();
437
211
  unsigned DomainDims = DomainSpace.dim(isl::dim::set);
438
211
  isl::space RangeSpace = Space.range().unwrap();
439
211
  isl::space Range1Space = RangeSpace.domain();
440
211
  unsigned Range1Dims = Range1Space.dim(isl::dim::set);
441
211
  isl::space Range2Space = RangeSpace.range();
442
211
  unsigned Range2Dims = Range2Space.dim(isl::dim::set);
443
211
444
211
  isl::space OutputSpace =
445
211
      DomainSpace.map_from_domain_and_range(Range1Space)
446
211
          .wrap()
447
211
          .map_from_domain_and_range(
448
211
              DomainSpace.map_from_domain_and_range(Range2Space).wrap());
449
211
450
211
  isl::basic_map Translator = isl::basic_map::universe(
451
211
      Space.wrap().map_from_domain_and_range(OutputSpace.wrap()));
452
211
453
425
  for (unsigned i = 0; i < DomainDims; 
i += 1214
) {
454
214
    Translator = Translator.equate(isl::dim::in, i, isl::dim::out, i);
455
214
    Translator = Translator.equate(isl::dim::in, i, isl::dim::out,
456
214
                                   DomainDims + Range1Dims + i);
457
214
  }
458
687
  for (unsigned i = 0; i < Range1Dims; 
i += 1476
)
459
476
    Translator = Translator.equate(isl::dim::in, DomainDims + i, isl::dim::out,
460
476
                                   DomainDims + i);
461
378
  for (unsigned i = 0; i < Range2Dims; 
i += 1167
)
462
167
    Translator = Translator.equate(isl::dim::in, DomainDims + Range1Dims + i,
463
167
                                   isl::dim::out,
464
167
                                   DomainDims + Range1Dims + DomainDims + i);
465
211
466
211
  return Map.wrap().apply(Translator).unwrap();
467
211
}
468
469
120
isl::union_map polly::distributeDomain(isl::union_map UMap) {
470
120
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
471
209
  for (isl::map Map : UMap.get_map_list()) {
472
209
    auto Distributed = distributeDomain(Map);
473
209
    Result = Result.add_map(Distributed);
474
209
  }
475
120
  return Result;
476
120
}
477
478
57
isl::union_map polly::liftDomains(isl::union_map UMap, isl::union_set Factor) {
479
57
480
57
  // { Factor[] -> Factor[] }
481
57
  isl::union_map Factors = makeIdentityMap(Factor, true);
482
57
483
57
  return Factors.product(UMap);
484
57
}
485
486
isl::union_map polly::applyDomainRange(isl::union_map UMap,
487
54
                                       isl::union_map Func) {
488
54
  // This implementation creates unnecessary cross products of the
489
54
  // DomainDomain[] and Func. An alternative implementation could reverse
490
54
  // domain+uncurry,apply Func to what now is the domain, then undo the
491
54
  // preparing transformation. Another alternative implementation could create a
492
54
  // translator map for each piece.
493
54
494
54
  // { DomainDomain[] }
495
54
  isl::union_set DomainDomain = UMap.domain().unwrap().domain();
496
54
497
54
  // { [DomainDomain[] -> DomainRange[]] -> [DomainDomain[] -> NewDomainRange[]]
498
54
  // }
499
54
  isl::union_map LifetedFunc = liftDomains(std::move(Func), DomainDomain);
500
54
501
54
  return UMap.apply_domain(LifetedFunc);
502
54
}
503
504
184
isl::map polly::intersectRange(isl::map Map, isl::union_set Range) {
505
184
  isl::set RangeSet = Range.extract_set(Map.get_space().range());
506
184
  return Map.intersect_range(RangeSet);
507
184
}
508
509
158
isl::val polly::getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
510
158
  assert(!Max || !Min); // Cannot return min and max at the same time.
511
158
  isl::val Result;
512
158
  isl::stat Stat = PwAff.foreach_piece(
513
158
      [=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
514
158
        if (Result && 
Result.is_nan()0
)
515
0
          return isl::stat::ok();
516
158
517
158
        // TODO: If Min/Max, we can also determine a minimum/maximum value if
518
158
        // Set is constant-bounded.
519
158
        if (!Aff.is_cst()) {
520
0
          Result = isl::val::nan(Aff.get_ctx());
521
0
          return isl::stat::error();
522
0
        }
523
158
524
158
        isl::val ThisVal = Aff.get_constant_val();
525
158
        if (!Result) {
526
158
          Result = ThisVal;
527
158
          return isl::stat::ok();
528
158
        }
529
0
530
0
        if (Result.eq(ThisVal))
531
0
          return isl::stat::ok();
532
0
533
0
        if (Max && ThisVal.gt(Result)) {
534
0
          Result = ThisVal;
535
0
          return isl::stat::ok();
536
0
        }
537
0
538
0
        if (Min && ThisVal.lt(Result)) {
539
0
          Result = ThisVal;
540
0
          return isl::stat::ok();
541
0
        }
542
0
543
0
        // Not compatible
544
0
        Result = isl::val::nan(Aff.get_ctx());
545
0
        return isl::stat::error();
546
0
      });
547
158
548
158
  if (Stat.is_error())
549
0
    return {};
550
158
551
158
  return Result;
552
158
}
553
554
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
555
static void foreachPoint(const isl::set &Set,
556
                         const std::function<void(isl::point P)> &F) {
557
  Set.foreach_point([&](isl::point P) -> isl::stat {
558
    F(P);
559
    return isl::stat::ok();
560
  });
561
}
562
563
static void foreachPoint(isl::basic_set BSet,
564
                         const std::function<void(isl::point P)> &F) {
565
  foreachPoint(isl::set(BSet), F);
566
}
567
568
/// Determine the sorting order of the sets @p A and @p B without considering
569
/// the space structure.
570
///
571
/// Ordering is based on the lower bounds of the set's dimensions. First
572
/// dimensions are considered first.
573
static int flatCompare(const isl::basic_set &A, const isl::basic_set &B) {
574
  unsigned ALen = A.dim(isl::dim::set);
575
  unsigned BLen = B.dim(isl::dim::set);
576
  unsigned Len = std::min(ALen, BLen);
577
578
  for (unsigned i = 0; i < Len; i += 1) {
579
    isl::basic_set ADim =
580
        A.project_out(isl::dim::param, 0, A.dim(isl::dim::param))
581
            .project_out(isl::dim::set, i + 1, ALen - i - 1)
582
            .project_out(isl::dim::set, 0, i);
583
    isl::basic_set BDim =
584
        B.project_out(isl::dim::param, 0, B.dim(isl::dim::param))
585
            .project_out(isl::dim::set, i + 1, BLen - i - 1)
586
            .project_out(isl::dim::set, 0, i);
587
588
    isl::basic_set AHull = isl::set(ADim).convex_hull();
589
    isl::basic_set BHull = isl::set(BDim).convex_hull();
590
591
    bool ALowerBounded =
592
        bool(isl::set(AHull).dim_has_any_lower_bound(isl::dim::set, 0));
593
    bool BLowerBounded =
594
        bool(isl::set(BHull).dim_has_any_lower_bound(isl::dim::set, 0));
595
596
    int BoundedCompare = BLowerBounded - ALowerBounded;
597
    if (BoundedCompare != 0)
598
      return BoundedCompare;
599
600
    if (!ALowerBounded || !BLowerBounded)
601
      continue;
602
603
    isl::pw_aff AMin = isl::set(ADim).dim_min(0);
604
    isl::pw_aff BMin = isl::set(BDim).dim_min(0);
605
606
    isl::val AMinVal = polly::getConstant(AMin, false, true);
607
    isl::val BMinVal = polly::getConstant(BMin, false, true);
608
609
    int MinCompare = AMinVal.sub(BMinVal).sgn();
610
    if (MinCompare != 0)
611
      return MinCompare;
612
  }
613
614
  // If all the dimensions' lower bounds are equal or incomparable, sort based
615
  // on the number of dimensions.
616
  return ALen - BLen;
617
}
618
619
/// Compare the sets @p A and @p B according to their nested space structure.
620
/// Returns 0 if the structure is considered equal.
621
/// If @p ConsiderTupleLen is false, the number of dimensions in a tuple are
622
/// ignored, i.e. a tuple with the same name but different number of dimensions
623
/// are considered equal.
624
static int structureCompare(const isl::space &ASpace, const isl::space &BSpace,
625
                            bool ConsiderTupleLen) {
626
  int WrappingCompare = bool(ASpace.is_wrapping()) - bool(BSpace.is_wrapping());
627
  if (WrappingCompare != 0)
628
    return WrappingCompare;
629
630
  if (ASpace.is_wrapping() && BSpace.is_wrapping()) {
631
    isl::space AMap = ASpace.unwrap();
632
    isl::space BMap = BSpace.unwrap();
633
634
    int FirstResult =
635
        structureCompare(AMap.domain(), BMap.domain(), ConsiderTupleLen);
636
    if (FirstResult != 0)
637
      return FirstResult;
638
639
    return structureCompare(AMap.range(), BMap.range(), ConsiderTupleLen);
640
  }
641
642
  std::string AName;
643
  if (ASpace.has_tuple_name(isl::dim::set))
644
    AName = ASpace.get_tuple_name(isl::dim::set);
645
646
  std::string BName;
647
  if (BSpace.has_tuple_name(isl::dim::set))
648
    BName = BSpace.get_tuple_name(isl::dim::set);
649
650
  int NameCompare = AName.compare(BName);
651
  if (NameCompare != 0)
652
    return NameCompare;
653
654
  if (ConsiderTupleLen) {
655
    int LenCompare = BSpace.dim(isl::dim::set) - ASpace.dim(isl::dim::set);
656
    if (LenCompare != 0)
657
      return LenCompare;
658
  }
659
660
  return 0;
661
}
662
663
/// Compare the sets @p A and @p B according to their nested space structure. If
664
/// the structure is the same, sort using the dimension lower bounds.
665
/// Returns an std::sort compatible bool.
666
static bool orderComparer(const isl::basic_set &A, const isl::basic_set &B) {
667
  isl::space ASpace = A.get_space();
668
  isl::space BSpace = B.get_space();
669
670
  // Ignoring number of dimensions first ensures that structures with same tuple
671
  // names, but different number of dimensions are still sorted close together.
672
  int TupleNestingCompare = structureCompare(ASpace, BSpace, false);
673
  if (TupleNestingCompare != 0)
674
    return TupleNestingCompare < 0;
675
676
  int TupleCompare = structureCompare(ASpace, BSpace, true);
677
  if (TupleCompare != 0)
678
    return TupleCompare < 0;
679
680
  return flatCompare(A, B) < 0;
681
}
682
683
/// Print a string representation of @p USet to @p OS.
684
///
685
/// The pieces of @p USet are printed in a sorted order. Spaces with equal or
686
/// similar nesting structure are printed together. Compared to isl's own
687
/// printing function the uses the structure itself as base of the sorting, not
688
/// a hash of it. It ensures that e.g. maps spaces with same domain structure
689
/// are printed together. Set pieces with same structure are printed in order of
690
/// their lower bounds.
691
///
692
/// @param USet     Polyhedra to print.
693
/// @param OS       Target stream.
694
/// @param Simplify Whether to simplify the polyhedron before printing.
695
/// @param IsMap    Whether @p USet is a wrapped map. If true, sets are
696
///                 unwrapped before printing to again appear as a map.
697
static void printSortedPolyhedra(isl::union_set USet, llvm::raw_ostream &OS,
698
                                 bool Simplify, bool IsMap) {
699
  if (!USet) {
700
    OS << "<null>\n";
701
    return;
702
  }
703
704
  if (Simplify)
705
    simplify(USet);
706
707
  // Get all the polyhedra.
708
  std::vector<isl::basic_set> BSets;
709
710
  for (isl::set Set : USet.get_set_list()) {
711
    for (isl::basic_set BSet : Set.get_basic_set_list()) {
712
      BSets.push_back(BSet);
713
    }
714
  }
715
716
  if (BSets.empty()) {
717
    OS << "{\n}\n";
718
    return;
719
  }
720
721
  // Sort the polyhedra.
722
  llvm::sort(BSets.begin(), BSets.end(), orderComparer);
723
724
  // Print the polyhedra.
725
  bool First = true;
726
  for (const isl::basic_set &BSet : BSets) {
727
    std::string Str;
728
    if (IsMap)
729
      Str = isl::map(BSet.unwrap()).to_str();
730
    else
731
      Str = isl::set(BSet).to_str();
732
    size_t OpenPos = Str.find_first_of('{');
733
    assert(OpenPos != std::string::npos);
734
    size_t ClosePos = Str.find_last_of('}');
735
    assert(ClosePos != std::string::npos);
736
737
    if (First)
738
      OS << llvm::StringRef(Str).substr(0, OpenPos + 1) << "\n ";
739
    else
740
      OS << ";\n ";
741
742
    OS << llvm::StringRef(Str).substr(OpenPos + 1, ClosePos - OpenPos - 2);
743
    First = false;
744
  }
745
  assert(!First);
746
  OS << "\n}\n";
747
}
748
749
static void recursiveExpand(isl::basic_set BSet, int Dim, isl::set &Expanded) {
750
  int Dims = BSet.dim(isl::dim::set);
751
  if (Dim >= Dims) {
752
    Expanded = Expanded.unite(BSet);
753
    return;
754
  }
755
756
  isl::basic_set DimOnly =
757
      BSet.project_out(isl::dim::param, 0, BSet.dim(isl::dim::param))
758
          .project_out(isl::dim::set, Dim + 1, Dims - Dim - 1)
759
          .project_out(isl::dim::set, 0, Dim);
760
  if (!DimOnly.is_bounded()) {
761
    recursiveExpand(BSet, Dim + 1, Expanded);
762
    return;
763
  }
764
765
  foreachPoint(DimOnly, [&, Dim](isl::point P) {
766
    isl::val Val = P.get_coordinate_val(isl::dim::set, 0);
767
    isl::basic_set FixBSet = BSet.fix_val(isl::dim::set, Dim, Val);
768
    recursiveExpand(FixBSet, Dim + 1, Expanded);
769
  });
770
}
771
772
/// Make each point of a set explicit.
773
///
774
/// "Expanding" makes each point a set contains explicit. That is, the result is
775
/// a set of singleton polyhedra. Unbounded dimensions are not expanded.
776
///
777
/// Example:
778
///   { [i] : 0 <= i < 2 }
779
/// is expanded to:
780
///   { [0]; [1] }
781
static isl::set expand(const isl::set &Set) {
782
  isl::set Expanded = isl::set::empty(Set.get_space());
783
  for (isl::basic_set BSet : Set.get_basic_set_list())
784
    recursiveExpand(BSet, 0, Expanded);
785
  return Expanded;
786
}
787
788
/// Expand all points of a union set explicit.
789
///
790
/// @see expand(const isl::set)
791
static isl::union_set expand(const isl::union_set &USet) {
792
  isl::union_set Expanded = isl::union_set::empty(USet.get_space());
793
  for (isl::set Set : USet.get_set_list()) {
794
    isl::set SetExpanded = expand(Set);
795
    Expanded = Expanded.add_set(SetExpanded);
796
  }
797
  return Expanded;
798
}
799
800
LLVM_DUMP_METHOD void polly::dumpPw(const isl::set &Set) {
801
  printSortedPolyhedra(Set, llvm::errs(), true, false);
802
}
803
804
LLVM_DUMP_METHOD void polly::dumpPw(const isl::map &Map) {
805
  printSortedPolyhedra(Map.wrap(), llvm::errs(), true, true);
806
}
807
808
LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_set &USet) {
809
  printSortedPolyhedra(USet, llvm::errs(), true, false);
810
}
811
812
LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_map &UMap) {
813
  printSortedPolyhedra(UMap.wrap(), llvm::errs(), true, true);
814
}
815
816
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_set *Set) {
817
  dumpPw(isl::manage_copy(Set));
818
}
819
820
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_map *Map) {
821
  dumpPw(isl::manage_copy(Map));
822
}
823
824
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_set *USet) {
825
  dumpPw(isl::manage_copy(USet));
826
}
827
828
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_map *UMap) {
829
  dumpPw(isl::manage_copy(UMap));
830
}
831
832
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::set &Set) {
833
  printSortedPolyhedra(expand(Set), llvm::errs(), false, false);
834
}
835
836
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::map &Map) {
837
  printSortedPolyhedra(expand(Map.wrap()), llvm::errs(), false, true);
838
}
839
840
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_set &USet) {
841
  printSortedPolyhedra(expand(USet), llvm::errs(), false, false);
842
}
843
844
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_map &UMap) {
845
  printSortedPolyhedra(expand(UMap.wrap()), llvm::errs(), false, true);
846
}
847
848
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_set *Set) {
849
  dumpExpanded(isl::manage_copy(Set));
850
}
851
852
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_map *Map) {
853
  dumpExpanded(isl::manage_copy(Map));
854
}
855
856
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_set *USet) {
857
  dumpExpanded(isl::manage_copy(USet));
858
}
859
860
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_map *UMap) {
861
  dumpExpanded(isl::manage_copy(UMap));
862
}
863
#endif