Coverage Report

Created: 2018-06-24 14:39

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