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