Coverage Report

Created: 2019-02-20 07:29

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