Coverage Report

Created: 2018-02-20 23:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/MaximalStaticExpansion.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MaximalStaticExpansion.cpp -----------------------------------------===//
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
// This pass fully expand the memory accesses of a Scop to get rid of
11
// dependencies.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "polly/DependenceInfo.h"
16
#include "polly/LinkAllPasses.h"
17
#include "polly/ScopInfo.h"
18
#include "polly/ScopPass.h"
19
#include "polly/Support/GICHelper.h"
20
#include "llvm/ADT/SmallPtrSet.h"
21
#include "llvm/ADT/StringRef.h"
22
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
23
#include "llvm/Pass.h"
24
#include "isl/isl-noexceptions.h"
25
#include "isl/union_map.h"
26
#include <cassert>
27
#include <limits>
28
#include <string>
29
#include <vector>
30
31
using namespace llvm;
32
using namespace polly;
33
34
14
#define DEBUG_TYPE "polly-mse"
35
36
namespace {
37
38
class MaximalStaticExpander : public ScopPass {
39
public:
40
  static char ID;
41
42
17
  explicit MaximalStaticExpander() : ScopPass(ID) {}
43
44
17
  ~MaximalStaticExpander() override = default;
45
46
  /// Expand the accesses of the SCoP.
47
  ///
48
  /// @param S The SCoP that must be expanded.
49
  bool runOnScop(Scop &S) override;
50
51
  /// Print the SCoP.
52
  ///
53
  /// @param OS The stream where to print.
54
  /// @param S The SCop that must be printed.
55
  void printScop(raw_ostream &OS, Scop &S) const override;
56
57
  /// Register all analyses and transformations required.
58
  void getAnalysisUsage(AnalysisUsage &AU) const override;
59
60
private:
61
  /// OptimizationRemarkEmitter object for displaying diagnostic remarks.
62
  OptimizationRemarkEmitter *ORE;
63
64
  /// Emit remark
65
  void emitRemark(StringRef Msg, Instruction *Inst);
66
67
  /// Return true if the SAI in parameter is expandable.
68
  ///
69
  /// @param SAI the SAI that need to be checked.
70
  /// @param Writes A set that will contains all the write accesses.
71
  /// @param Reads A set that will contains all the read accesses.
72
  /// @param S The SCop in which the SAI is in.
73
  /// @param Dependences The RAW dependences of the SCop.
74
  bool isExpandable(const ScopArrayInfo *SAI,
75
                    SmallPtrSetImpl<MemoryAccess *> &Writes,
76
                    SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
77
                    const isl::union_map &Dependences);
78
79
  /// Expand the MemoryAccess according to its domain.
80
  ///
81
  /// @param S The SCop in which the memory access appears in.
82
  /// @param MA The memory access that need to be expanded.
83
  ScopArrayInfo *expandAccess(Scop &S, MemoryAccess *MA);
84
85
  /// Filter the dependences to have only one related to current memory access.
86
  ///
87
  /// @param S The SCop in which the memory access appears in.
88
  /// @param MapDependences The dependences to filter.
89
  /// @param MA The memory access that need to be expanded.
90
  isl::union_map filterDependences(Scop &S,
91
                                   const isl::union_map &MapDependences,
92
                                   MemoryAccess *MA);
93
94
  /// Expand the MemoryAccess according to Dependences and already expanded
95
  /// MemoryAccesses.
96
  ///
97
  /// @param The SCop in which the memory access appears in.
98
  /// @param The memory access that need to be expanded.
99
  /// @param Dependences The RAW dependences of the SCop.
100
  /// @param ExpandedSAI The expanded SAI created during write expansion.
101
  /// @param Reverse if true, the Dependences union_map is reversed before
102
  /// intersection.
103
  void mapAccess(Scop &S, SmallPtrSetImpl<MemoryAccess *> &Accesses,
104
                 const isl::union_map &Dependences, ScopArrayInfo *ExpandedSAI,
105
                 bool Reverse);
106
107
  /// Expand PHI memory accesses.
108
  ///
109
  /// @param The SCop in which the memory access appears in.
110
  /// @param The ScopArrayInfo representing the PHI accesses to expand.
111
  /// @param Dependences The RAW dependences of the SCop.
112
  void expandPhi(Scop &S, const ScopArrayInfo *SAI,
113
                 const isl::union_map &Dependences);
114
};
115
116
} // namespace
117
118
#ifndef NDEBUG
119
/// Whether a dimension of a set is bounded (lower and upper) by a constant,
120
/// i.e. there are two constants Min and Max, such that every value x of the
121
/// chosen dimensions is Min <= x <= Max.
122
static bool isDimBoundedByConstant(isl::set Set, unsigned dim) {
123
  auto ParamDims = Set.dim(isl::dim::param);
124
  Set = Set.project_out(isl::dim::param, 0, ParamDims);
125
  Set = Set.project_out(isl::dim::set, 0, dim);
126
  auto SetDims = Set.dim(isl::dim::set);
127
  Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
128
  return bool(Set.is_bounded());
129
}
130
#endif
131
132
/// If @p PwAff maps to a constant, return said constant. If @p Max/@p Min, it
133
/// can also be a piecewise constant and it would return the minimum/maximum
134
/// value. Otherwise, return NaN.
135
80
static isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
136
80
  assert(!Max || !Min);
137
80
  isl::val Result;
138
80
  PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
139
80
    if (Result && 
Result.is_nan()0
)
140
0
      return isl::stat::ok;
141
80
142
80
    // TODO: If Min/Max, we can also determine a minimum/maximum value if
143
80
    // Set is constant-bounded.
144
80
    if (!Aff.is_cst()) {
145
0
      Result = isl::val::nan(Aff.get_ctx());
146
0
      return isl::stat::error;
147
0
    }
148
80
149
80
    auto ThisVal = Aff.get_constant_val();
150
80
    if (!Result) {
151
80
      Result = ThisVal;
152
80
      return isl::stat::ok;
153
80
    }
154
0
155
0
    if (Result.eq(ThisVal))
156
0
      return isl::stat::ok;
157
0
158
0
    if (Max && ThisVal.gt(Result)) {
159
0
      Result = ThisVal;
160
0
      return isl::stat::ok;
161
0
    }
162
0
163
0
    if (Min && ThisVal.lt(Result)) {
164
0
      Result = ThisVal;
165
0
      return isl::stat::ok;
166
0
    }
167
0
168
0
    // Not compatible
169
0
    Result = isl::val::nan(Aff.get_ctx());
170
0
    return isl::stat::error;
171
0
  });
172
80
  return Result;
173
80
}
174
175
char MaximalStaticExpander::ID = 0;
176
177
isl::union_map MaximalStaticExpander::filterDependences(
178
90
    Scop &S, const isl::union_map &Dependences, MemoryAccess *MA) {
179
90
  auto SAI = MA->getLatestScopArrayInfo();
180
90
181
90
  auto AccessDomainSet = MA->getAccessRelation().domain();
182
90
  auto AccessDomainId = AccessDomainSet.get_tuple_id();
183
90
184
90
  isl::union_map MapDependences = isl::union_map::empty(S.getParamSpace());
185
90
186
90
  Dependences.foreach_map([&MapDependences, &AccessDomainId,
187
1.07k
                           &SAI](isl::map Map) -> isl::stat {
188
1.07k
    // Filter out Statement to Statement dependences.
189
1.07k
    if (!Map.can_curry())
190
478
      return isl::stat::ok;
191
594
192
594
    // Intersect with the relevant SAI.
193
594
    auto TmpMapDomainId =
194
594
        Map.get_space().domain().unwrap().range().get_tuple_id(isl::dim::set);
195
594
196
594
    ScopArrayInfo *UserSAI =
197
594
        static_cast<ScopArrayInfo *>(TmpMapDomainId.get_user());
198
594
199
594
    if (SAI != UserSAI)
200
462
      return isl::stat::ok;
201
132
202
132
    // Get the correct S1[] -> S2[] dependence.
203
132
    auto NewMap = Map.factor_domain();
204
132
    auto NewMapDomainId = NewMap.domain().get_tuple_id();
205
132
206
132
    if (AccessDomainId.keep() != NewMapDomainId.keep())
207
42
      return isl::stat::ok;
208
90
209
90
    // Add the corresponding map to MapDependences.
210
90
    MapDependences = MapDependences.add_map(NewMap);
211
90
212
90
    return isl::stat::ok;
213
90
  });
214
90
215
90
  return MapDependences;
216
90
}
217
218
bool MaximalStaticExpander::isExpandable(
219
    const ScopArrayInfo *SAI, SmallPtrSetImpl<MemoryAccess *> &Writes,
220
    SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
221
63
    const isl::union_map &Dependences) {
222
63
  if (SAI->isValueKind()) {
223
3
    Writes.insert(S.getValueDef(SAI));
224
3
    for (auto MA : S.getValueUses(SAI))
225
4
      Reads.insert(MA);
226
3
    return true;
227
60
  } else if (SAI->isPHIKind()) {
228
28
    auto Read = S.getPHIRead(SAI);
229
28
230
28
    auto StmtDomain = isl::union_set(Read->getStatement()->getDomain());
231
28
232
28
    auto Writes = S.getPHIIncomings(SAI);
233
28
234
28
    // Get the domain where all the writes are writing to.
235
28
    auto WriteDomain = isl::union_set::empty(S.getParamSpace());
236
28
237
38
    for (auto Write : Writes) {
238
38
      auto MapDeps = filterDependences(S, Dependences, Write);
239
38
      MapDeps.foreach_map([&WriteDomain](isl::map Map) -> isl::stat {
240
38
        WriteDomain = WriteDomain.add_set(Map.range());
241
38
        return isl::stat::ok;
242
38
      });
243
38
    }
244
28
245
28
    // For now, read from original scalar is not possible.
246
28
    if (!StmtDomain.is_equal(WriteDomain)) {
247
8
      emitRemark(SAI->getName() + " read from its original value.",
248
8
                 Read->getAccessInstruction());
249
8
      return false;
250
8
    }
251
20
252
20
    return true;
253
32
  } else if (SAI->isExitPHIKind()) {
254
0
    // For now, we are not able to expand ExitPhi.
255
0
    emitRemark(SAI->getName() + " is a ExitPhi node.",
256
0
               S.getEnteringBlock()->getFirstNonPHI());
257
0
    return false;
258
0
  }
259
32
260
32
  int NumberWrites = 0;
261
90
  for (ScopStmt &Stmt : S) {
262
90
    auto StmtReads = isl::union_map::empty(S.getParamSpace());
263
90
    auto StmtWrites = isl::union_map::empty(S.getParamSpace());
264
90
265
186
    for (MemoryAccess *MA : Stmt) {
266
186
      // Check if the current MemoryAccess involved the current SAI.
267
186
      if (SAI != MA->getLatestScopArrayInfo())
268
140
        continue;
269
46
270
46
      // For now, we are not able to expand array where read come after write
271
46
      // (to the same location) in a same statement.
272
46
      auto AccRel = isl::union_map(MA->getAccessRelation());
273
46
      if (MA->isRead()) {
274
12
        // Reject load after store to same location.
275
12
        if (!StmtWrites.is_disjoint(AccRel)) {
276
2
          emitRemark(SAI->getName() + " has read after write to the same "
277
2
                                      "element in same statement. The "
278
2
                                      "dependences found during analysis may "
279
2
                                      "be wrong because Polly is not able to "
280
2
                                      "handle such case for now.",
281
2
                     MA->getAccessInstruction());
282
2
          return false;
283
2
        }
284
10
285
10
        StmtReads = give(isl_union_map_union(StmtReads.take(), AccRel.take()));
286
34
      } else {
287
34
        StmtWrites =
288
34
            give(isl_union_map_union(StmtWrites.take(), AccRel.take()));
289
34
      }
290
46
291
46
      // For now, we are not able to expand MayWrite.
292
46
      
if (44
MA->isMayWrite()44
) {
293
0
        emitRemark(SAI->getName() + " has a maywrite access.",
294
0
                   MA->getAccessInstruction());
295
0
        return false;
296
0
      }
297
44
298
44
      // For now, we are not able to expand SAI with more than one write.
299
44
      if (MA->isMustWrite()) {
300
34
        Writes.insert(MA);
301
34
        NumberWrites++;
302
34
        if (NumberWrites > 1) {
303
2
          emitRemark(SAI->getName() + " has more than 1 write access.",
304
2
                     MA->getAccessInstruction());
305
2
          return false;
306
2
        }
307
42
      }
308
42
309
42
      // Check if it is possible to expand this read.
310
42
      if (MA->isRead()) {
311
10
        // Get the domain of the current ScopStmt.
312
10
        auto StmtDomain = Stmt.getDomain();
313
10
314
10
        // Get the domain of the future Read access.
315
10
        auto ReadDomainSet = MA->getAccessRelation().domain();
316
10
        auto ReadDomain = isl::union_set(ReadDomainSet);
317
10
318
10
        // Get the dependences relevant for this MA
319
10
        auto MapDependences = filterDependences(S, Dependences.reverse(), MA);
320
10
        unsigned NumberElementMap = isl_union_map_n_map(MapDependences.get());
321
10
322
10
        if (NumberElementMap == 0) {
323
0
          emitRemark("The expansion of " + SAI->getName() +
324
0
                         " would lead to a read from the original array.",
325
0
                     MA->getAccessInstruction());
326
0
          return false;
327
0
        }
328
10
329
10
        auto DepsDomain = MapDependences.domain();
330
10
331
10
        // If there are multiple maps in the Deps, we cannot handle this case
332
10
        // for now.
333
10
        if (NumberElementMap != 1) {
334
0
          emitRemark(SAI->getName() +
335
0
                         " has too many dependences to be handle for now.",
336
0
                     MA->getAccessInstruction());
337
0
          return false;
338
0
        }
339
10
340
10
        auto DepsDomainSet = isl::set(DepsDomain);
341
10
342
10
        // For now, read from the original array is not possible.
343
10
        if (!StmtDomain.is_subset(DepsDomainSet)) {
344
2
          emitRemark("The expansion of " + SAI->getName() +
345
2
                         " would lead to a read from the original array.",
346
2
                     MA->getAccessInstruction());
347
2
          return false;
348
2
        }
349
8
350
8
        Reads.insert(MA);
351
8
      }
352
42
    }
353
90
  }
354
32
355
32
  // No need to expand SAI with no write.
356
32
  
if (26
NumberWrites == 026
) {
357
0
    emitRemark(SAI->getName() + " has 0 write access.",
358
0
               S.getEnteringBlock()->getFirstNonPHI());
359
0
    return false;
360
0
  }
361
26
362
26
  return true;
363
26
}
364
365
void MaximalStaticExpander::mapAccess(Scop &S,
366
                                      SmallPtrSetImpl<MemoryAccess *> &Accesses,
367
                                      const isl::union_map &Dependences,
368
                                      ScopArrayInfo *ExpandedSAI,
369
49
                                      bool Reverse) {
370
49
  for (auto MA : Accesses) {
371
42
    // Get the current AM.
372
42
    auto CurrentAccessMap = MA->getAccessRelation();
373
42
374
42
    // Get RAW dependences for the current WA.
375
42
    auto DomainSet = MA->getAccessRelation().domain();
376
42
    auto Domain = isl::union_set(DomainSet);
377
42
378
42
    // Get the dependences relevant for this MA.
379
42
    isl::union_map MapDependences =
380
42
        filterDependences(S, Reverse ? 
Dependences.reverse()12
:
Dependences30
, MA);
381
42
382
42
    // If no dependences, no need to modify anything.
383
42
    if (MapDependences.is_empty())
384
0
      return;
385
42
386
42
    assert(isl_union_map_n_map(MapDependences.get()) == 1 &&
387
42
           "There are more than one RAW dependencies in the union map.");
388
42
    auto NewAccessMap = isl::map::from_union_map(MapDependences);
389
42
390
42
    auto Id = ExpandedSAI->getBasePtrId();
391
42
392
42
    // Replace the out tuple id with the one of the access array.
393
42
    NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, Id);
394
42
395
42
    // Set the new access relation.
396
42
    MA->setNewAccessRelation(NewAccessMap);
397
42
  }
398
49
}
399
400
49
ScopArrayInfo *MaximalStaticExpander::expandAccess(Scop &S, MemoryAccess *MA) {
401
49
  // Get the current AM.
402
49
  auto CurrentAccessMap = MA->getAccessRelation();
403
49
404
49
  unsigned in_dimensions = CurrentAccessMap.dim(isl::dim::in);
405
49
406
49
  // Get domain from the current AM.
407
49
  auto Domain = CurrentAccessMap.domain();
408
49
409
49
  // Create a new AM from the domain.
410
49
  auto NewAccessMap = isl::map::from_domain(Domain);
411
49
412
49
  // Add dimensions to the new AM according to the current in_dim.
413
49
  NewAccessMap = NewAccessMap.add_dims(isl::dim::out, in_dimensions);
414
49
415
49
  // Create the string representing the name of the new SAI.
416
49
  // One new SAI for each statement so that each write go to a different memory
417
49
  // cell.
418
49
  auto CurrentStmtDomain = MA->getStatement()->getDomain();
419
49
  auto CurrentStmtName = CurrentStmtDomain.get_tuple_name();
420
49
  auto CurrentOutId = CurrentAccessMap.get_tuple_id(isl::dim::out);
421
49
  std::string CurrentOutIdString =
422
49
      MA->getScopArrayInfo()->getName() + "_" + CurrentStmtName + "_expanded";
423
49
424
49
  // Set the tuple id for the out dimension.
425
49
  NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, CurrentOutId);
426
49
427
49
  // Create the size vector.
428
49
  std::vector<unsigned> Sizes;
429
129
  for (unsigned i = 0; i < in_dimensions; 
i++80
) {
430
80
    assert(isDimBoundedByConstant(CurrentStmtDomain, i) &&
431
80
           "Domain boundary are not constant.");
432
80
    auto UpperBound = getConstant(CurrentStmtDomain.dim_max(i), true, false);
433
80
    assert(!UpperBound.is_null() && UpperBound.is_pos() &&
434
80
           !UpperBound.is_nan() &&
435
80
           "The upper bound is not a positive integer.");
436
80
    assert(UpperBound.le(isl::val(CurrentAccessMap.get_ctx(),
437
80
                                  std::numeric_limits<int>::max() - 1)) &&
438
80
           "The upper bound overflow a int.");
439
80
    Sizes.push_back(UpperBound.get_num_si() + 1);
440
80
  }
441
49
442
49
  // Get the ElementType of the current SAI.
443
49
  auto ElementType = MA->getLatestScopArrayInfo()->getElementType();
444
49
445
49
  // Create (or get if already existing) the new expanded SAI.
446
49
  auto ExpandedSAI =
447
49
      S.createScopArrayInfo(ElementType, CurrentOutIdString, Sizes);
448
49
  ExpandedSAI->setIsOnHeap(true);
449
49
450
49
  // Get the out Id of the expanded Array.
451
49
  auto NewOutId = ExpandedSAI->getBasePtrId();
452
49
453
49
  // Set the out id of the new AM to the new SAI id.
454
49
  NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, NewOutId);
455
49
456
49
  // Add constraints to linked output with input id.
457
49
  auto SpaceMap = NewAccessMap.get_space();
458
49
  auto ConstraintBasicMap =
459
49
      isl::basic_map::equal(SpaceMap, SpaceMap.dim(isl::dim::in));
460
49
  NewAccessMap = isl::map(ConstraintBasicMap);
461
49
462
49
  // Set the new access relation map.
463
49
  MA->setNewAccessRelation(NewAccessMap);
464
49
465
49
  return ExpandedSAI;
466
49
}
467
468
void MaximalStaticExpander::expandPhi(Scop &S, const ScopArrayInfo *SAI,
469
20
                                      const isl::union_map &Dependences) {
470
20
  SmallPtrSet<MemoryAccess *, 4> Writes;
471
20
  for (auto MA : S.getPHIIncomings(SAI))
472
30
    Writes.insert(MA);
473
20
  auto Read = S.getPHIRead(SAI);
474
20
  auto ExpandedSAI = expandAccess(S, Read);
475
20
476
20
  mapAccess(S, Writes, Dependences, ExpandedSAI, false);
477
20
}
478
479
14
void MaximalStaticExpander::emitRemark(StringRef Msg, Instruction *Inst) {
480
14
  ORE->emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ExpansionRejection", Inst)
481
14
            << Msg);
482
14
}
483
484
17
bool MaximalStaticExpander::runOnScop(Scop &S) {
485
17
  // Get the ORE from OptimizationRemarkEmitterWrapperPass.
486
17
  ORE = &(getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
487
17
488
17
  // Get the RAW Dependences.
489
17
  auto &DI = getAnalysis<DependenceInfo>();
490
17
  auto &D = DI.getDependences(Dependences::AL_Reference);
491
17
  auto Dependences = isl::give(D.getDependences(Dependences::TYPE_RAW));
492
17
493
17
  SmallVector<ScopArrayInfo *, 4> CurrentSAI(S.arrays().begin(),
494
17
                                             S.arrays().end());
495
17
496
63
  for (auto SAI : CurrentSAI) {
497
63
    SmallPtrSet<MemoryAccess *, 4> AllWrites;
498
63
    SmallPtrSet<MemoryAccess *, 4> AllReads;
499
63
    if (!isExpandable(SAI, AllWrites, AllReads, S, Dependences))
500
14
      continue;
501
49
502
49
    if (SAI->isValueKind() || 
SAI->isArrayKind()46
) {
503
29
      assert(AllWrites.size() == 1 || SAI->isValueKind());
504
29
505
29
      auto TheWrite = *(AllWrites.begin());
506
29
      ScopArrayInfo *ExpandedArray = expandAccess(S, TheWrite);
507
29
508
29
      mapAccess(S, AllReads, Dependences, ExpandedArray, true);
509
29
    } else 
if (20
SAI->isPHIKind()20
) {
510
20
      expandPhi(S, SAI, Dependences);
511
20
    }
512
49
  }
513
17
514
17
  return false;
515
17
}
516
517
17
void MaximalStaticExpander::printScop(raw_ostream &OS, Scop &S) const {
518
17
  S.print(OS, false);
519
17
}
520
521
17
void MaximalStaticExpander::getAnalysisUsage(AnalysisUsage &AU) const {
522
17
  ScopPass::getAnalysisUsage(AU);
523
17
  AU.addRequired<DependenceInfo>();
524
17
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
525
17
}
526
527
0
Pass *polly::createMaximalStaticExpansionPass() {
528
0
  return new MaximalStaticExpander();
529
0
}
530
531
42.1k
INITIALIZE_PASS_BEGIN(MaximalStaticExpander, "polly-mse",
532
42.1k
                      "Polly - Maximal static expansion of SCoP", false, false);
533
42.1k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
534
42.1k
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
535
42.1k
INITIALIZE_PASS_END(MaximalStaticExpander, "polly-mse",
536
                    "Polly - Maximal static expansion of SCoP", false, false)