Coverage Report

Created: 2018-06-19 22:08

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/include/polly/ScopInfo.h
Line
Count
Source (jump to first uncovered line)
1
//===- polly/ScopInfo.h -----------------------------------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// Store the polyhedral model representation of a static control flow region,
11
// also called SCoP (Static Control Part).
12
//
13
// This representation is shared among several tools in the polyhedral
14
// community, which are e.g. CLooG, Pluto, Loopo, Graphite.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#ifndef POLLY_SCOPINFO_H
19
#define POLLY_SCOPINFO_H
20
21
#include "polly/ScopDetection.h"
22
#include "polly/Support/SCEVAffinator.h"
23
#include "polly/Support/ScopHelper.h"
24
#include "llvm/ADT/ArrayRef.h"
25
#include "llvm/ADT/DenseMap.h"
26
#include "llvm/ADT/DenseSet.h"
27
#include "llvm/ADT/MapVector.h"
28
#include "llvm/ADT/Optional.h"
29
#include "llvm/ADT/SetVector.h"
30
#include "llvm/ADT/SmallVector.h"
31
#include "llvm/ADT/StringMap.h"
32
#include "llvm/ADT/StringRef.h"
33
#include "llvm/ADT/iterator_range.h"
34
#include "llvm/Analysis/RegionPass.h"
35
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
36
#include "llvm/IR/DebugLoc.h"
37
#include "llvm/IR/Instruction.h"
38
#include "llvm/IR/Instructions.h"
39
#include "llvm/IR/IntrinsicInst.h"
40
#include "llvm/IR/PassManager.h"
41
#include "llvm/IR/ValueHandle.h"
42
#include "llvm/Pass.h"
43
#include "llvm/Support/Casting.h"
44
#include "isl/isl-noexceptions.h"
45
#include <algorithm>
46
#include <cassert>
47
#include <cstddef>
48
#include <forward_list>
49
#include <functional>
50
#include <list>
51
#include <map>
52
#include <memory>
53
#include <string>
54
#include <tuple>
55
#include <utility>
56
#include <vector>
57
58
using namespace llvm;
59
60
namespace llvm {
61
62
class AssumptionCache;
63
class BasicBlock;
64
class DataLayout;
65
class DominatorTree;
66
class Function;
67
class Loop;
68
class LoopInfo;
69
class OptimizationRemarkEmitter;
70
class PassRegistry;
71
class raw_ostream;
72
class ScalarEvolution;
73
class SCEV;
74
class Type;
75
class Value;
76
77
void initializeScopInfoRegionPassPass(PassRegistry &);
78
void initializeScopInfoWrapperPassPass(PassRegistry &);
79
} // end namespace llvm
80
81
struct isl_map;
82
struct isl_pw_multi_aff;
83
struct isl_schedule;
84
struct isl_set;
85
struct isl_union_map;
86
87
namespace polly {
88
89
class MemoryAccess;
90
class Scop;
91
class ScopStmt;
92
93
//===---------------------------------------------------------------------===//
94
95
extern bool UseInstructionNames;
96
97
/// Enumeration of assumptions Polly can take.
98
enum AssumptionKind {
99
  ALIASING,
100
  INBOUNDS,
101
  WRAPPING,
102
  UNSIGNED,
103
  PROFITABLE,
104
  ERRORBLOCK,
105
  COMPLEXITY,
106
  INFINITELOOP,
107
  INVARIANTLOAD,
108
  DELINEARIZATION,
109
};
110
111
/// Enum to distinguish between assumptions and restrictions.
112
enum AssumptionSign { AS_ASSUMPTION, AS_RESTRICTION };
113
114
/// The different memory kinds used in Polly.
115
///
116
/// We distinguish between arrays and various scalar memory objects. We use
117
/// the term ``array'' to describe memory objects that consist of a set of
118
/// individual data elements arranged in a multi-dimensional grid. A scalar
119
/// memory object describes an individual data element and is used to model
120
/// the definition and uses of llvm::Values.
121
///
122
/// The polyhedral model does traditionally not reason about SSA values. To
123
/// reason about llvm::Values we model them "as if" they were zero-dimensional
124
/// memory objects, even though they were not actually allocated in (main)
125
/// memory.  Memory for such objects is only alloca[ed] at CodeGeneration
126
/// time. To relate the memory slots used during code generation with the
127
/// llvm::Values they belong to the new names for these corresponding stack
128
/// slots are derived by appending suffixes (currently ".s2a" and ".phiops")
129
/// to the name of the original llvm::Value. To describe how def/uses are
130
/// modeled exactly we use these suffixes here as well.
131
///
132
/// There are currently four different kinds of memory objects:
133
enum class MemoryKind {
134
  /// MemoryKind::Array: Models a one or multi-dimensional array
135
  ///
136
  /// A memory object that can be described by a multi-dimensional array.
137
  /// Memory objects of this type are used to model actual multi-dimensional
138
  /// arrays as they exist in LLVM-IR, but they are also used to describe
139
  /// other objects:
140
  ///   - A single data element allocated on the stack using 'alloca' is
141
  ///     modeled as a one-dimensional, single-element array.
142
  ///   - A single data element allocated as a global variable is modeled as
143
  ///     one-dimensional, single-element array.
144
  ///   - Certain multi-dimensional arrays with variable size, which in
145
  ///     LLVM-IR are commonly expressed as a single-dimensional access with a
146
  ///     complicated access function, are modeled as multi-dimensional
147
  ///     memory objects (grep for "delinearization").
148
  Array,
149
150
  /// MemoryKind::Value: Models an llvm::Value
151
  ///
152
  /// Memory objects of type MemoryKind::Value are used to model the data flow
153
  /// induced by llvm::Values. For each llvm::Value that is used across
154
  /// BasicBlocks, one ScopArrayInfo object is created. A single memory WRITE
155
  /// stores the llvm::Value at its definition into the memory object and at
156
  /// each use of the llvm::Value (ignoring trivial intra-block uses) a
157
  /// corresponding READ is added. For instance, the use/def chain of a
158
  /// llvm::Value %V depicted below
159
  ///              ______________________
160
  ///              |DefBB:              |
161
  ///              |  %V = float op ... |
162
  ///              ----------------------
163
  ///               |                  |
164
  /// _________________               _________________
165
  /// |UseBB1:        |               |UseBB2:        |
166
  /// |  use float %V |               |  use float %V |
167
  /// -----------------               -----------------
168
  ///
169
  /// is modeled as if the following memory accesses occurred:
170
  ///
171
  ///                        __________________________
172
  ///                        |entry:                  |
173
  ///                        |  %V.s2a = alloca float |
174
  ///                        --------------------------
175
  ///                                     |
176
  ///                    ___________________________________
177
  ///                    |DefBB:                           |
178
  ///                    |  store %float %V, float* %V.s2a |
179
  ///                    -----------------------------------
180
  ///                           |                   |
181
  /// ____________________________________ ___________________________________
182
  /// |UseBB1:                           | |UseBB2:                          |
183
  /// |  %V.reload1 = load float* %V.s2a | |  %V.reload2 = load float* %V.s2a|
184
  /// |  use float %V.reload1            | |  use float %V.reload2           |
185
  /// ------------------------------------ -----------------------------------
186
  ///
187
  Value,
188
189
  /// MemoryKind::PHI: Models PHI nodes within the SCoP
190
  ///
191
  /// Besides the MemoryKind::Value memory object used to model the normal
192
  /// llvm::Value dependences described above, PHI nodes require an additional
193
  /// memory object of type MemoryKind::PHI to describe the forwarding of values
194
  /// to
195
  /// the PHI node.
196
  ///
197
  /// As an example, a PHIInst instructions
198
  ///
199
  /// %PHI = phi float [ %Val1, %IncomingBlock1 ], [ %Val2, %IncomingBlock2 ]
200
  ///
201
  /// is modeled as if the accesses occurred this way:
202
  ///
203
  ///                    _______________________________
204
  ///                    |entry:                       |
205
  ///                    |  %PHI.phiops = alloca float |
206
  ///                    -------------------------------
207
  ///                           |              |
208
  /// __________________________________  __________________________________
209
  /// |IncomingBlock1:                 |  |IncomingBlock2:                 |
210
  /// |  ...                           |  |  ...                           |
211
  /// |  store float %Val1 %PHI.phiops |  |  store float %Val2 %PHI.phiops |
212
  /// |  br label % JoinBlock          |  |  br label %JoinBlock           |
213
  /// ----------------------------------  ----------------------------------
214
  ///                             \            /
215
  ///                              \          /
216
  ///               _________________________________________
217
  ///               |JoinBlock:                             |
218
  ///               |  %PHI = load float, float* PHI.phiops |
219
  ///               -----------------------------------------
220
  ///
221
  /// Note that there can also be a scalar write access for %PHI if used in a
222
  /// different BasicBlock, i.e. there can be a memory object %PHI.phiops as
223
  /// well as a memory object %PHI.s2a.
224
  PHI,
225
226
  /// MemoryKind::ExitPHI: Models PHI nodes in the SCoP's exit block
227
  ///
228
  /// For PHI nodes in the Scop's exit block a special memory object kind is
229
  /// used. The modeling used is identical to MemoryKind::PHI, with the
230
  /// exception
231
  /// that there are no READs from these memory objects. The PHINode's
232
  /// llvm::Value is treated as a value escaping the SCoP. WRITE accesses
233
  /// write directly to the escaping value's ".s2a" alloca.
234
  ExitPHI
235
};
236
237
/// Maps from a loop to the affine function expressing its backedge taken count.
238
/// The backedge taken count already enough to express iteration domain as we
239
/// only allow loops with canonical induction variable.
240
/// A canonical induction variable is:
241
/// an integer recurrence that starts at 0 and increments by one each time
242
/// through the loop.
243
using LoopBoundMapType = std::map<const Loop *, const SCEV *>;
244
245
using AccFuncVector = std::vector<std::unique_ptr<MemoryAccess>>;
246
247
/// A class to store information about arrays in the SCoP.
248
///
249
/// Objects are accessible via the ScoP, MemoryAccess or the id associated with
250
/// the MemoryAccess access function.
251
///
252
class ScopArrayInfo {
253
public:
254
  /// Construct a ScopArrayInfo object.
255
  ///
256
  /// @param BasePtr        The array base pointer.
257
  /// @param ElementType    The type of the elements stored in the array.
258
  /// @param IslCtx         The isl context used to create the base pointer id.
259
  /// @param DimensionSizes A vector containing the size of each dimension.
260
  /// @param Kind           The kind of the array object.
261
  /// @param DL             The data layout of the module.
262
  /// @param S              The scop this array object belongs to.
263
  /// @param BaseName       The optional name of this memory reference.
264
  ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx IslCtx,
265
                ArrayRef<const SCEV *> DimensionSizes, MemoryKind Kind,
266
                const DataLayout &DL, Scop *S, const char *BaseName = nullptr);
267
268
  /// Destructor to free the isl id of the base pointer.
269
  ~ScopArrayInfo();
270
271
  ///  Update the element type of the ScopArrayInfo object.
272
  ///
273
  ///  Memory accesses referencing this ScopArrayInfo object may use
274
  ///  different element sizes. This function ensures the canonical element type
275
  ///  stored is small enough to model accesses to the current element type as
276
  ///  well as to @p NewElementType.
277
  ///
278
  ///  @param NewElementType An element type that is used to access this array.
279
  void updateElementType(Type *NewElementType);
280
281
  ///  Update the sizes of the ScopArrayInfo object.
282
  ///
283
  ///  A ScopArrayInfo object may be created without all outer dimensions being
284
  ///  available. This function is called when new memory accesses are added for
285
  ///  this ScopArrayInfo object. It verifies that sizes are compatible and adds
286
  ///  additional outer array dimensions, if needed.
287
  ///
288
  ///  @param Sizes       A vector of array sizes where the rightmost array
289
  ///                     sizes need to match the innermost array sizes already
290
  ///                     defined in SAI.
291
  ///  @param CheckConsistency Update sizes, even if new sizes are inconsistent
292
  ///                          with old sizes
293
  bool updateSizes(ArrayRef<const SCEV *> Sizes, bool CheckConsistency = true);
294
295
  /// Make the ScopArrayInfo model a Fortran array.
296
  /// It receives the Fortran array descriptor and stores this.
297
  /// It also adds a piecewise expression for the outermost dimension
298
  /// since this information is available for Fortran arrays at runtime.
299
  void applyAndSetFAD(Value *FAD);
300
301
  /// Get the FortranArrayDescriptor corresponding to this array if it exists,
302
  /// nullptr otherwise.
303
473
  Value *getFortranArrayDescriptor() const { return this->FAD; }
304
305
  /// Set the base pointer to @p BP.
306
10
  void setBasePtr(Value *BP) { BasePtr = BP; }
307
308
  /// Return the base pointer.
309
4.81k
  Value *getBasePtr() const { return BasePtr; }
310
311
  // Set IsOnHeap to the value in parameter.
312
55
  void setIsOnHeap(bool value) { IsOnHeap = value; }
313
314
  /// For indirect accesses return the origin SAI of the BP, else null.
315
402
  const ScopArrayInfo *getBasePtrOriginSAI() const { return BasePtrOriginSAI; }
316
317
  /// The set of derived indirect SAIs for this origin SAI.
318
105
  const SmallSetVector<ScopArrayInfo *, 2> &getDerivedSAIs() const {
319
105
    return DerivedSAIs;
320
105
  }
321
322
  /// Return the number of dimensions.
323
23.4k
  unsigned getNumberOfDimensions() const {
324
23.4k
    if (Kind == MemoryKind::PHI || 
Kind == MemoryKind::ExitPHI21.6k
||
325
23.4k
        
Kind == MemoryKind::Value21.3k
)
326
4.63k
      return 0;
327
18.7k
    return DimensionSizes.size();
328
18.7k
  }
329
330
  /// Return the size of dimension @p dim as SCEV*.
331
  //
332
  //  Scalars do not have array dimensions and the first dimension of
333
  //  a (possibly multi-dimensional) array also does not carry any size
334
  //  information, in case the array is not newly created.
335
2.39k
  const SCEV *getDimensionSize(unsigned Dim) const {
336
2.39k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
337
2.39k
    return DimensionSizes[Dim];
338
2.39k
  }
339
340
  /// Return the size of dimension @p dim as isl::pw_aff.
341
  //
342
  //  Scalars do not have array dimensions and the first dimension of
343
  //  a (possibly multi-dimensional) array also does not carry any size
344
  //  information, in case the array is not newly created.
345
4.48k
  isl::pw_aff getDimensionSizePw(unsigned Dim) const {
346
4.48k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
347
4.48k
    return DimensionSizesPw[Dim];
348
4.48k
  }
349
350
  /// Get the canonical element type of this array.
351
  ///
352
  /// @returns The canonical element type of this array.
353
3.84k
  Type *getElementType() const { return ElementType; }
354
355
  /// Get element size in bytes.
356
  int getElemSizeInBytes() const;
357
358
  /// Get the name of this memory reference.
359
  std::string getName() const;
360
361
  /// Return the isl id for the base pointer.
362
  isl::id getBasePtrId() const;
363
364
  /// Return what kind of memory this represents.
365
2.16k
  MemoryKind getKind() const { return Kind; }
366
367
  /// Is this array info modeling an llvm::Value?
368
361
  bool isValueKind() const { return Kind == MemoryKind::Value; }
369
370
  /// Is this array info modeling special PHI node memory?
371
  ///
372
  /// During code generation of PHI nodes, there is a need for two kinds of
373
  /// virtual storage. The normal one as it is used for all scalar dependences,
374
  /// where the result of the PHI node is stored and later loaded from as well
375
  /// as a second one where the incoming values of the PHI nodes are stored
376
  /// into and reloaded when the PHI is executed. As both memories use the
377
  /// original PHI node as virtual base pointer, we have this additional
378
  /// attribute to distinguish the PHI node specific array modeling from the
379
  /// normal scalar array modeling.
380
602
  bool isPHIKind() const { return Kind == MemoryKind::PHI; }
381
382
  /// Is this array info modeling an MemoryKind::ExitPHI?
383
333
  bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
384
385
  /// Is this array info modeling an array?
386
786
  bool isArrayKind() const { return Kind == MemoryKind::Array; }
387
388
  /// Is this array allocated on heap
389
  ///
390
  /// This property is only relevant if the array is allocated by Polly instead
391
  /// of pre-existing. If false, it is allocated using alloca instead malloca.
392
10
  bool isOnHeap() const { return IsOnHeap; }
393
394
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
395
  /// Dump a readable representation to stderr.
396
  void dump() const;
397
#endif
398
399
  /// Print a readable representation to @p OS.
400
  ///
401
  /// @param SizeAsPwAff Print the size as isl::pw_aff
402
  void print(raw_ostream &OS, bool SizeAsPwAff = false) const;
403
404
  /// Access the ScopArrayInfo associated with an access function.
405
  static const ScopArrayInfo *getFromAccessFunction(isl::pw_multi_aff PMA);
406
407
  /// Access the ScopArrayInfo associated with an isl Id.
408
  static const ScopArrayInfo *getFromId(isl::id Id);
409
410
  /// Get the space of this array access.
411
  isl::space getSpace() const;
412
413
  /// If the array is read only
414
  bool isReadOnly();
415
416
  /// Verify that @p Array is compatible to this ScopArrayInfo.
417
  ///
418
  /// Two arrays are compatible if their dimensionality, the sizes of their
419
  /// dimensions, and their element sizes match.
420
  ///
421
  /// @param Array The array to compare against.
422
  ///
423
  /// @returns True, if the arrays are compatible, False otherwise.
424
  bool isCompatibleWith(const ScopArrayInfo *Array) const;
425
426
private:
427
91
  void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
428
91
    DerivedSAIs.insert(DerivedSAI);
429
91
  }
430
431
  /// For indirect accesses this is the SAI of the BP origin.
432
  const ScopArrayInfo *BasePtrOriginSAI;
433
434
  /// For origin SAIs the set of derived indirect SAIs.
435
  SmallSetVector<ScopArrayInfo *, 2> DerivedSAIs;
436
437
  /// The base pointer.
438
  AssertingVH<Value> BasePtr;
439
440
  /// The canonical element type of this array.
441
  ///
442
  /// The canonical element type describes the minimal accessible element in
443
  /// this array. Not all elements accessed, need to be of the very same type,
444
  /// but the allocation size of the type of the elements loaded/stored from/to
445
  /// this array needs to be a multiple of the allocation size of the canonical
446
  /// type.
447
  Type *ElementType;
448
449
  /// The isl id for the base pointer.
450
  isl::id Id;
451
452
  /// True if the newly allocated array is on heap.
453
  bool IsOnHeap = false;
454
455
  /// The sizes of each dimension as SCEV*.
456
  SmallVector<const SCEV *, 4> DimensionSizes;
457
458
  /// The sizes of each dimension as isl::pw_aff.
459
  SmallVector<isl::pw_aff, 4> DimensionSizesPw;
460
461
  /// The type of this scop array info object.
462
  ///
463
  /// We distinguish between SCALAR, PHI and ARRAY objects.
464
  MemoryKind Kind;
465
466
  /// The data layout of the module.
467
  const DataLayout &DL;
468
469
  /// The scop this SAI object belongs to.
470
  Scop &S;
471
472
  /// If this array models a Fortran array, then this points
473
  /// to the Fortran array descriptor.
474
  Value *FAD = nullptr;
475
};
476
477
/// Represent memory accesses in statements.
478
class MemoryAccess {
479
  friend class Scop;
480
  friend class ScopStmt;
481
  friend class ScopBuilder;
482
483
public:
484
  /// The access type of a memory access
485
  ///
486
  /// There are three kind of access types:
487
  ///
488
  /// * A read access
489
  ///
490
  /// A certain set of memory locations are read and may be used for internal
491
  /// calculations.
492
  ///
493
  /// * A must-write access
494
  ///
495
  /// A certain set of memory locations is definitely written. The old value is
496
  /// replaced by a newly calculated value. The old value is not read or used at
497
  /// all.
498
  ///
499
  /// * A may-write access
500
  ///
501
  /// A certain set of memory locations may be written. The memory location may
502
  /// contain a new value if there is actually a write or the old value may
503
  /// remain, if no write happens.
504
  enum AccessType {
505
    READ = 0x1,
506
    MUST_WRITE = 0x2,
507
    MAY_WRITE = 0x3,
508
  };
509
510
  /// Reduction access type
511
  ///
512
  /// Commutative and associative binary operations suitable for reductions
513
  enum ReductionType {
514
    RT_NONE, ///< Indicate no reduction at all
515
    RT_ADD,  ///< Addition
516
    RT_MUL,  ///< Multiplication
517
    RT_BOR,  ///< Bitwise Or
518
    RT_BXOR, ///< Bitwise XOr
519
    RT_BAND, ///< Bitwise And
520
  };
521
522
private:
523
  /// A unique identifier for this memory access.
524
  ///
525
  /// The identifier is unique between all memory accesses belonging to the same
526
  /// scop statement.
527
  isl::id Id;
528
529
  /// What is modeled by this MemoryAccess.
530
  /// @see MemoryKind
531
  MemoryKind Kind;
532
533
  /// Whether it a reading or writing access, and if writing, whether it
534
  /// is conditional (MAY_WRITE).
535
  enum AccessType AccType;
536
537
  /// Reduction type for reduction like accesses, RT_NONE otherwise
538
  ///
539
  /// An access is reduction like if it is part of a load-store chain in which
540
  /// both access the same memory location (use the same LLVM-IR value
541
  /// as pointer reference). Furthermore, between the load and the store there
542
  /// is exactly one binary operator which is known to be associative and
543
  /// commutative.
544
  ///
545
  /// TODO:
546
  ///
547
  /// We can later lift the constraint that the same LLVM-IR value defines the
548
  /// memory location to handle scops such as the following:
549
  ///
550
  ///    for i
551
  ///      for j
552
  ///        sum[i+j] = sum[i] + 3;
553
  ///
554
  /// Here not all iterations access the same memory location, but iterations
555
  /// for which j = 0 holds do. After lifting the equality check in ScopBuilder,
556
  /// subsequent transformations do not only need check if a statement is
557
  /// reduction like, but they also need to verify that that the reduction
558
  /// property is only exploited for statement instances that load from and
559
  /// store to the same data location. Doing so at dependence analysis time
560
  /// could allow us to handle the above example.
561
  ReductionType RedType = RT_NONE;
562
563
  /// Parent ScopStmt of this access.
564
  ScopStmt *Statement;
565
566
  /// The domain under which this access is not modeled precisely.
567
  ///
568
  /// The invalid domain for an access describes all parameter combinations
569
  /// under which the statement looks to be executed but is in fact not because
570
  /// some assumption/restriction makes the access invalid.
571
  isl::set InvalidDomain;
572
573
  // Properties describing the accessed array.
574
  // TODO: It might be possible to move them to ScopArrayInfo.
575
  // @{
576
577
  /// The base address (e.g., A for A[i+j]).
578
  ///
579
  /// The #BaseAddr of a memory access of kind MemoryKind::Array is the base
580
  /// pointer of the memory access.
581
  /// The #BaseAddr of a memory access of kind MemoryKind::PHI or
582
  /// MemoryKind::ExitPHI is the PHI node itself.
583
  /// The #BaseAddr of a memory access of kind MemoryKind::Value is the
584
  /// instruction defining the value.
585
  AssertingVH<Value> BaseAddr;
586
587
  /// Type a single array element wrt. this access.
588
  Type *ElementType;
589
590
  /// Size of each dimension of the accessed array.
591
  SmallVector<const SCEV *, 4> Sizes;
592
  // @}
593
594
  // Properties describing the accessed element.
595
  // @{
596
597
  /// The access instruction of this memory access.
598
  ///
599
  /// For memory accesses of kind MemoryKind::Array the access instruction is
600
  /// the Load or Store instruction performing the access.
601
  ///
602
  /// For memory accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI the
603
  /// access instruction of a load access is the PHI instruction. The access
604
  /// instruction of a PHI-store is the incoming's block's terminator
605
  /// instruction.
606
  ///
607
  /// For memory accesses of kind MemoryKind::Value the access instruction of a
608
  /// load access is nullptr because generally there can be multiple
609
  /// instructions in the statement using the same llvm::Value. The access
610
  /// instruction of a write access is the instruction that defines the
611
  /// llvm::Value.
612
  Instruction *AccessInstruction = nullptr;
613
614
  /// Incoming block and value of a PHINode.
615
  SmallVector<std::pair<BasicBlock *, Value *>, 4> Incoming;
616
617
  /// The value associated with this memory access.
618
  ///
619
  ///  - For array memory accesses (MemoryKind::Array) it is the loaded result
620
  ///    or the stored value. If the access instruction is a memory intrinsic it
621
  ///    the access value is also the memory intrinsic.
622
  ///  - For accesses of kind MemoryKind::Value it is the access instruction
623
  ///    itself.
624
  ///  - For accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI it is the
625
  ///    PHI node itself (for both, READ and WRITE accesses).
626
  ///
627
  AssertingVH<Value> AccessValue;
628
629
  /// Are all the subscripts affine expression?
630
  bool IsAffine = true;
631
632
  /// Subscript expression for each dimension.
633
  SmallVector<const SCEV *, 4> Subscripts;
634
635
  /// Relation from statement instances to the accessed array elements.
636
  ///
637
  /// In the common case this relation is a function that maps a set of loop
638
  /// indices to the memory address from which a value is loaded/stored:
639
  ///
640
  ///      for i
641
  ///        for j
642
  ///    S:     A[i + 3 j] = ...
643
  ///
644
  ///    => { S[i,j] -> A[i + 3j] }
645
  ///
646
  /// In case the exact access function is not known, the access relation may
647
  /// also be a one to all mapping { S[i,j] -> A[o] } describing that any
648
  /// element accessible through A might be accessed.
649
  ///
650
  /// In case of an access to a larger element belonging to an array that also
651
  /// contains smaller elements, the access relation models the larger access
652
  /// with multiple smaller accesses of the size of the minimal array element
653
  /// type:
654
  ///
655
  ///      short *A;
656
  ///
657
  ///      for i
658
  ///    S:     A[i] = *((double*)&A[4 * i]);
659
  ///
660
  ///    => { S[i] -> A[i]; S[i] -> A[o] : 4i <= o <= 4i + 3 }
661
  isl::map AccessRelation;
662
663
  /// Updated access relation read from JSCOP file.
664
  isl::map NewAccessRelation;
665
666
  /// Fortran arrays whose sizes are not statically known are stored in terms
667
  /// of a descriptor struct. This maintains a raw pointer to the memory,
668
  /// along with auxiliary fields with information such as dimensions.
669
  /// We hold a reference to the descriptor corresponding to a MemoryAccess
670
  /// into a Fortran array. FAD for "Fortran Array Descriptor"
671
  AssertingVH<Value> FAD;
672
  // @}
673
674
  isl::basic_map createBasicAccessMap(ScopStmt *Statement);
675
676
  void assumeNoOutOfBound();
677
678
  /// Compute bounds on an over approximated  access relation.
679
  ///
680
  /// @param ElementSize The size of one element accessed.
681
  void computeBoundsOnAccessRelation(unsigned ElementSize);
682
683
  /// Get the original access function as read from IR.
684
  isl::map getOriginalAccessRelation() const;
685
686
  /// Return the space in which the access relation lives in.
687
  isl::space getOriginalAccessRelationSpace() const;
688
689
  /// Get the new access function imported or set by a pass
690
  isl::map getNewAccessRelation() const;
691
692
  /// Fold the memory access to consider parametric offsets
693
  ///
694
  /// To recover memory accesses with array size parameters in the subscript
695
  /// expression we post-process the delinearization results.
696
  ///
697
  /// We would normally recover from an access A[exp0(i) * N + exp1(i)] into an
698
  /// array A[][N] the 2D access A[exp0(i)][exp1(i)]. However, another valid
699
  /// delinearization is A[exp0(i) - 1][exp1(i) + N] which - depending on the
700
  /// range of exp1(i) - may be preferable. Specifically, for cases where we
701
  /// know exp1(i) is negative, we want to choose the latter expression.
702
  ///
703
  /// As we commonly do not have any information about the range of exp1(i),
704
  /// we do not choose one of the two options, but instead create a piecewise
705
  /// access function that adds the (-1, N) offsets as soon as exp1(i) becomes
706
  /// negative. For a 2D array such an access function is created by applying
707
  /// the piecewise map:
708
  ///
709
  /// [i,j] -> [i, j] :      j >= 0
710
  /// [i,j] -> [i-1, j+N] :  j <  0
711
  ///
712
  /// We can generalize this mapping to arbitrary dimensions by applying this
713
  /// piecewise mapping pairwise from the rightmost to the leftmost access
714
  /// dimension. It would also be possible to cover a wider range by introducing
715
  /// more cases and adding multiple of Ns to these cases. However, this has
716
  /// not yet been necessary.
717
  /// The introduction of different cases necessarily complicates the memory
718
  /// access function, but cases that can be statically proven to not happen
719
  /// will be eliminated later on.
720
  void foldAccessRelation();
721
722
  /// Create the access relation for the underlying memory intrinsic.
723
  void buildMemIntrinsicAccessRelation();
724
725
  /// Assemble the access relation from all available information.
726
  ///
727
  /// In particular, used the information passes in the constructor and the
728
  /// parent ScopStmt set by setStatment().
729
  ///
730
  /// @param SAI Info object for the accessed array.
731
  void buildAccessRelation(const ScopArrayInfo *SAI);
732
733
  /// Carry index overflows of dimensions with constant size to the next higher
734
  /// dimension.
735
  ///
736
  /// For dimensions that have constant size, modulo the index by the size and
737
  /// add up the carry (floored division) to the next higher dimension. This is
738
  /// how overflow is defined in row-major order.
739
  /// It happens e.g. when ScalarEvolution computes the offset to the base
740
  /// pointer and would algebraically sum up all lower dimensions' indices of
741
  /// constant size.
742
  ///
743
  /// Example:
744
  ///   float (*A)[4];
745
  ///   A[1][6] -> A[2][2]
746
  void wrapConstantDimensions();
747
748
public:
749
  /// Create a new MemoryAccess.
750
  ///
751
  /// @param Stmt       The parent statement.
752
  /// @param AccessInst The instruction doing the access.
753
  /// @param BaseAddr   The accessed array's address.
754
  /// @param ElemType   The type of the accessed array elements.
755
  /// @param AccType    Whether read or write access.
756
  /// @param IsAffine   Whether the subscripts are affine expressions.
757
  /// @param Kind       The kind of memory accessed.
758
  /// @param Subscripts Subscript expressions
759
  /// @param Sizes      Dimension lengths of the accessed array.
760
  MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, AccessType AccType,
761
               Value *BaseAddress, Type *ElemType, bool Affine,
762
               ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
763
               Value *AccessValue, MemoryKind Kind);
764
765
  /// Create a new MemoryAccess that corresponds to @p AccRel.
766
  ///
767
  /// Along with @p Stmt and @p AccType it uses information about dimension
768
  /// lengths of the accessed array, the type of the accessed array elements,
769
  /// the name of the accessed array that is derived from the object accessible
770
  /// via @p AccRel.
771
  ///
772
  /// @param Stmt       The parent statement.
773
  /// @param AccType    Whether read or write access.
774
  /// @param AccRel     The access relation that describes the memory access.
775
  MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel);
776
777
  MemoryAccess(const MemoryAccess &) = delete;
778
  MemoryAccess &operator=(const MemoryAccess &) = delete;
779
  ~MemoryAccess();
780
781
  /// Add a new incoming block/value pairs for this PHI/ExitPHI access.
782
  ///
783
  /// @param IncomingBlock The PHI's incoming block.
784
  /// @param IncomingValue The value when reaching the PHI from the @p
785
  ///                      IncomingBlock.
786
508
  void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
787
508
    assert(!isRead());
788
508
    assert(isAnyPHIKind());
789
508
    Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
790
508
  }
791
792
  /// Return the list of possible PHI/ExitPHI values.
793
  ///
794
  /// After code generation moves some PHIs around during region simplification,
795
  /// we cannot reliably locate the original PHI node and its incoming values
796
  /// anymore. For this reason we remember these explicitly for all PHI-kind
797
  /// accesses.
798
247
  ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
799
247
    assert(isAnyPHIKind());
800
247
    return Incoming;
801
247
  }
802
803
  /// Get the type of a memory access.
804
0
  enum AccessType getType() { return AccType; }
805
806
  /// Is this a reduction like access?
807
3.10k
  bool isReductionLike() const { return RedType != RT_NONE; }
808
809
  /// Is this a read memory access?
810
26.6k
  bool isRead() const { return AccType == MemoryAccess::READ; }
811
812
  /// Is this a must-write memory access?
813
13.2k
  bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
814
815
  /// Is this a may-write memory access?
816
7.70k
  bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
817
818
  /// Is this a write memory access?
819
12.1k
  bool isWrite() const { return isMustWrite() || 
isMayWrite()6.32k
; }
820
821
  /// Is this a memory intrinsic access (memcpy, memset, memmove)?
822
483
  bool isMemoryIntrinsic() const {
823
483
    return isa<MemIntrinsic>(getAccessInstruction());
824
483
  }
825
826
  /// Check if a new access relation was imported or set by a pass.
827
24.0k
  bool hasNewAccessRelation() const { return !NewAccessRelation.is_null(); }
828
829
  /// Return the newest access relation of this access.
830
  ///
831
  /// There are two possibilities:
832
  ///   1) The original access relation read from the LLVM-IR.
833
  ///   2) A new access relation imported from a json file or set by another
834
  ///      pass (e.g., for privatization).
835
  ///
836
  /// As 2) is by construction "newer" than 1) we return the new access
837
  /// relation if present.
838
  ///
839
17.6k
  isl::map getLatestAccessRelation() const {
840
17.6k
    return hasNewAccessRelation() ? 
getNewAccessRelation()535
841
17.6k
                                  : 
getOriginalAccessRelation()17.1k
;
842
17.6k
  }
843
844
  /// Old name of getLatestAccessRelation().
845
16.7k
  isl::map getAccessRelation() const { return getLatestAccessRelation(); }
846
847
  /// Get an isl map describing the memory address accessed.
848
  ///
849
  /// In most cases the memory address accessed is well described by the access
850
  /// relation obtained with getAccessRelation. However, in case of arrays
851
  /// accessed with types of different size the access relation maps one access
852
  /// to multiple smaller address locations. This method returns an isl map that
853
  /// relates each dynamic statement instance to the unique memory location
854
  /// that is loaded from / stored to.
855
  ///
856
  /// For an access relation { S[i] -> A[o] : 4i <= o <= 4i + 3 } this method
857
  /// will return the address function { S[i] -> A[4i] }.
858
  ///
859
  /// @returns The address function for this memory access.
860
  isl::map getAddressFunction() const;
861
862
  /// Return the access relation after the schedule was applied.
863
  isl::pw_multi_aff
864
  applyScheduleToAccessRelation(isl::union_map Schedule) const;
865
866
  /// Get an isl string representing the access function read from IR.
867
  std::string getOriginalAccessRelationStr() const;
868
869
  /// Get an isl string representing a new access function, if available.
870
  std::string getNewAccessRelationStr() const;
871
872
  /// Get an isl string representing the latest access relation.
873
  std::string getAccessRelationStr() const;
874
875
  /// Get the original base address of this access (e.g. A for A[i+j]) when
876
  /// detected.
877
  ///
878
  /// This address may differ from the base address referenced by the original
879
  /// ScopArrayInfo to which this array belongs, as this memory access may
880
  /// have been canonicalized to a ScopArrayInfo which has a different but
881
  /// identically-valued base pointer in case invariant load hoisting is
882
  /// enabled.
883
6.59k
  Value *getOriginalBaseAddr() const { return BaseAddr; }
884
885
  /// Get the detection-time base array isl::id for this access.
886
  isl::id getOriginalArrayId() const;
887
888
  /// Get the base array isl::id for this access, modifiable through
889
  /// setNewAccessRelation().
890
  isl::id getLatestArrayId() const;
891
892
  /// Old name of getOriginalArrayId().
893
23.6k
  isl::id getArrayId() const { return getOriginalArrayId(); }
894
895
  /// Get the detection-time ScopArrayInfo object for the base address.
896
  const ScopArrayInfo *getOriginalScopArrayInfo() const;
897
898
  /// Get the ScopArrayInfo object for the base address, or the one set
899
  /// by setNewAccessRelation().
900
  const ScopArrayInfo *getLatestScopArrayInfo() const;
901
902
  /// Legacy name of getOriginalScopArrayInfo().
903
18.6k
  const ScopArrayInfo *getScopArrayInfo() const {
904
18.6k
    return getOriginalScopArrayInfo();
905
18.6k
  }
906
907
  /// Return a string representation of the access's reduction type.
908
  const std::string getReductionOperatorStr() const;
909
910
  /// Return a string representation of the reduction type @p RT.
911
  static const std::string getReductionOperatorStr(ReductionType RT);
912
913
  /// Return the element type of the accessed array wrt. this access.
914
9.52k
  Type *getElementType() const { return ElementType; }
915
916
  /// Return the access value of this memory access.
917
3.59k
  Value *getAccessValue() const { return AccessValue; }
918
919
  /// Return llvm::Value that is stored by this access, if available.
920
  ///
921
  /// PHI nodes may not have a unique value available that is stored, as in
922
  /// case of region statements one out of possibly several llvm::Values
923
  /// might be stored. In this case nullptr is returned.
924
273
  Value *tryGetValueStored() {
925
273
    assert(isWrite() && "Only write statement store values");
926
273
    if (isAnyPHIKind()) {
927
16
      if (Incoming.size() == 1)
928
14
        return Incoming[0].second;
929
2
      return nullptr;
930
2
    }
931
257
    return AccessValue;
932
257
  }
933
934
  /// Return the access instruction of this memory access.
935
43.5k
  Instruction *getAccessInstruction() const { return AccessInstruction; }
936
937
  /// Return the number of access function subscript.
938
5
  unsigned getNumSubscripts() const { return Subscripts.size(); }
939
940
  /// Return the access function subscript in the dimension @p Dim.
941
2.94k
  const SCEV *getSubscript(unsigned Dim) const { return Subscripts[Dim]; }
942
943
  /// Compute the isl representation for the SCEV @p E wrt. this access.
944
  ///
945
  /// Note that this function will also adjust the invalid context accordingly.
946
  isl::pw_aff getPwAff(const SCEV *E);
947
948
  /// Get the invalid domain for this access.
949
358
  isl::set getInvalidDomain() const { return InvalidDomain; }
950
951
  /// Get the invalid context for this access.
952
358
  isl::set getInvalidContext() const { return getInvalidDomain().params(); }
953
954
  /// Get the stride of this memory access in the specified Schedule. Schedule
955
  /// is a map from the statement to a schedule where the innermost dimension is
956
  /// the dimension of the innermost loop containing the statement.
957
  isl::set getStride(isl::map Schedule) const;
958
959
  /// Get the FortranArrayDescriptor corresponding to this memory access if
960
  /// it exists, and nullptr otherwise.
961
4.68k
  Value *getFortranArrayDescriptor() const { return this->FAD; }
962
963
  /// Is the stride of the access equal to a certain width? Schedule is a map
964
  /// from the statement to a schedule where the innermost dimension is the
965
  /// dimension of the innermost loop containing the statement.
966
  bool isStrideX(isl::map Schedule, int StrideWidth) const;
967
968
  /// Is consecutive memory accessed for a given statement instance set?
969
  /// Schedule is a map from the statement to a schedule where the innermost
970
  /// dimension is the dimension of the innermost loop containing the
971
  /// statement.
972
  bool isStrideOne(isl::map Schedule) const;
973
974
  /// Is always the same memory accessed for a given statement instance set?
975
  /// Schedule is a map from the statement to a schedule where the innermost
976
  /// dimension is the dimension of the innermost loop containing the
977
  /// statement.
978
  bool isStrideZero(isl::map Schedule) const;
979
980
  /// Return the kind when this access was first detected.
981
64.2k
  MemoryKind getOriginalKind() const {
982
64.2k
    assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
983
64.2k
           getOriginalScopArrayInfo()->getKind() == Kind);
984
64.2k
    return Kind;
985
64.2k
  }
986
987
  /// Return the kind considering a potential setNewAccessRelation.
988
2.16k
  MemoryKind getLatestKind() const {
989
2.16k
    return getLatestScopArrayInfo()->getKind();
990
2.16k
  }
991
992
  /// Whether this is an access of an explicit load or store in the IR.
993
15.9k
  bool isOriginalArrayKind() const {
994
15.9k
    return getOriginalKind() == MemoryKind::Array;
995
15.9k
  }
996
997
  /// Whether storage memory is either an custom .s2a/.phiops alloca
998
  /// (false) or an existing pointer into an array (true).
999
1.68k
  bool isLatestArrayKind() const {
1000
1.68k
    return getLatestKind() == MemoryKind::Array;
1001
1.68k
  }
1002
1003
  /// Old name of isOriginalArrayKind.
1004
12.1k
  bool isArrayKind() const { return isOriginalArrayKind(); }
1005
1006
  /// Whether this access is an array to a scalar memory object, without
1007
  /// considering changes by setNewAccessRelation.
1008
  ///
1009
  /// Scalar accesses are accesses to MemoryKind::Value, MemoryKind::PHI or
1010
  /// MemoryKind::ExitPHI.
1011
8.76k
  bool isOriginalScalarKind() const {
1012
8.76k
    return getOriginalKind() != MemoryKind::Array;
1013
8.76k
  }
1014
1015
  /// Whether this access is an array to a scalar memory object, also
1016
  /// considering changes by setNewAccessRelation.
1017
288
  bool isLatestScalarKind() const {
1018
288
    return getLatestKind() != MemoryKind::Array;
1019
288
  }
1020
1021
  /// Old name of isOriginalScalarKind.
1022
7.76k
  bool isScalarKind() const { return isOriginalScalarKind(); }
1023
1024
  /// Was this MemoryAccess detected as a scalar dependences?
1025
15.5k
  bool isOriginalValueKind() const {
1026
15.5k
    return getOriginalKind() == MemoryKind::Value;
1027
15.5k
  }
1028
1029
  /// Is this MemoryAccess currently modeling scalar dependences?
1030
73
  bool isLatestValueKind() const {
1031
73
    return getLatestKind() == MemoryKind::Value;
1032
73
  }
1033
1034
  /// Old name of isOriginalValueKind().
1035
6.53k
  bool isValueKind() const { return isOriginalValueKind(); }
1036
1037
  /// Was this MemoryAccess detected as a special PHI node access?
1038
14.5k
  bool isOriginalPHIKind() const {
1039
14.5k
    return getOriginalKind() == MemoryKind::PHI;
1040
14.5k
  }
1041
1042
  /// Is this MemoryAccess modeling special PHI node accesses, also
1043
  /// considering a potential change by setNewAccessRelation?
1044
60
  bool isLatestPHIKind() const { return getLatestKind() == MemoryKind::PHI; }
1045
1046
  /// Old name of isOriginalPHIKind.
1047
4.77k
  bool isPHIKind() const { return isOriginalPHIKind(); }
1048
1049
  /// Was this MemoryAccess detected as the accesses of a PHI node in the
1050
  /// SCoP's exit block?
1051
9.48k
  bool isOriginalExitPHIKind() const {
1052
9.48k
    return getOriginalKind() == MemoryKind::ExitPHI;
1053
9.48k
  }
1054
1055
  /// Is this MemoryAccess modeling the accesses of a PHI node in the
1056
  /// SCoP's exit block? Can be changed to an array access using
1057
  /// setNewAccessRelation().
1058
62
  bool isLatestExitPHIKind() const {
1059
62
    return getLatestKind() == MemoryKind::ExitPHI;
1060
62
  }
1061
1062
  /// Old name of isOriginalExitPHIKind().
1063
4.16k
  bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
1064
1065
  /// Was this access detected as one of the two PHI types?
1066
6.80k
  bool isOriginalAnyPHIKind() const {
1067
6.80k
    return isOriginalPHIKind() || 
isOriginalExitPHIKind()5.31k
;
1068
6.80k
  }
1069
1070
  /// Does this access originate from one of the two PHI types? Can be
1071
  /// changed to an array access using setNewAccessRelation().
1072
60
  bool isLatestAnyPHIKind() const {
1073
60
    return isLatestPHIKind() || 
isLatestExitPHIKind()58
;
1074
60
  }
1075
1076
  /// Old name of isOriginalAnyPHIKind().
1077
1.35k
  bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
1078
1079
  /// Get the statement that contains this memory access.
1080
26.0k
  ScopStmt *getStatement() const { return Statement; }
1081
1082
  /// Get the reduction type of this access
1083
2.35k
  ReductionType getReductionType() const { return RedType; }
1084
1085
  /// Set the array descriptor corresponding to the Array on which the
1086
  /// memory access is performed.
1087
  void setFortranArrayDescriptor(Value *FAD);
1088
1089
  /// Update the original access relation.
1090
  ///
1091
  /// We need to update the original access relation during scop construction,
1092
  /// when unifying the memory accesses that access the same scop array info
1093
  /// object. After the scop has been constructed, the original access relation
1094
  /// should not be changed any more. Instead setNewAccessRelation should
1095
  /// be called.
1096
  void setAccessRelation(isl::map AccessRelation);
1097
1098
  /// Set the updated access relation read from JSCOP file.
1099
  void setNewAccessRelation(isl::map NewAccessRelation);
1100
1101
  /// Return whether the MemoryyAccess is a partial access. That is, the access
1102
  /// is not executed in some instances of the parent statement's domain.
1103
  bool isLatestPartialAccess() const;
1104
1105
  /// Mark this a reduction like access
1106
584
  void markAsReductionLike(ReductionType RT) { RedType = RT; }
1107
1108
  /// Align the parameters in the access relation to the scop context
1109
  void realignParams();
1110
1111
  /// Update the dimensionality of the memory access.
1112
  ///
1113
  /// During scop construction some memory accesses may not be constructed with
1114
  /// their full dimensionality, but outer dimensions may have been omitted if
1115
  /// they took the value 'zero'. By updating the dimensionality of the
1116
  /// statement we add additional zero-valued dimensions to match the
1117
  /// dimensionality of the ScopArrayInfo object that belongs to this memory
1118
  /// access.
1119
  void updateDimensionality();
1120
1121
  /// Get identifier for the memory access.
1122
  ///
1123
  /// This identifier is unique for all accesses that belong to the same scop
1124
  /// statement.
1125
  isl::id getId() const;
1126
1127
  /// Print the MemoryAccess.
1128
  ///
1129
  /// @param OS The output stream the MemoryAccess is printed to.
1130
  void print(raw_ostream &OS) const;
1131
1132
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1133
  /// Print the MemoryAccess to stderr.
1134
  void dump() const;
1135
#endif
1136
1137
  /// Is the memory access affine?
1138
10.7k
  bool isAffine() const { return IsAffine; }
1139
};
1140
1141
raw_ostream &operator<<(raw_ostream &OS, MemoryAccess::ReductionType RT);
1142
1143
/// Ordered list type to hold accesses.
1144
using MemoryAccessList = std::forward_list<MemoryAccess *>;
1145
1146
/// Helper structure for invariant memory accesses.
1147
struct InvariantAccess {
1148
  /// The memory access that is (partially) invariant.
1149
  MemoryAccess *MA;
1150
1151
  /// The context under which the access is not invariant.
1152
  isl::set NonHoistableCtx;
1153
};
1154
1155
/// Ordered container type to hold invariant accesses.
1156
using InvariantAccessesTy = SmallVector<InvariantAccess, 8>;
1157
1158
/// Type for equivalent invariant accesses and their domain context.
1159
struct InvariantEquivClassTy {
1160
  /// The pointer that identifies this equivalence class
1161
  const SCEV *IdentifyingPointer;
1162
1163
  /// Memory accesses now treated invariant
1164
  ///
1165
  /// These memory accesses access the pointer location that identifies
1166
  /// this equivalence class. They are treated as invariant and hoisted during
1167
  /// code generation.
1168
  MemoryAccessList InvariantAccesses;
1169
1170
  /// The execution context under which the memory location is accessed
1171
  ///
1172
  /// It is the union of the execution domains of the memory accesses in the
1173
  /// InvariantAccesses list.
1174
  isl::set ExecutionContext;
1175
1176
  /// The type of the invariant access
1177
  ///
1178
  /// It is used to differentiate between differently typed invariant loads from
1179
  /// the same location.
1180
  Type *AccessType;
1181
};
1182
1183
/// Type for invariant accesses equivalence classes.
1184
using InvariantEquivClassesTy = SmallVector<InvariantEquivClassTy, 8>;
1185
1186
/// Statement of the Scop
1187
///
1188
/// A Scop statement represents an instruction in the Scop.
1189
///
1190
/// It is further described by its iteration domain, its schedule and its data
1191
/// accesses.
1192
/// At the moment every statement represents a single basic block of LLVM-IR.
1193
class ScopStmt {
1194
  friend class ScopBuilder;
1195
1196
public:
1197
  /// Create the ScopStmt from a BasicBlock.
1198
  ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name, Loop *SurroundingLoop,
1199
           std::vector<Instruction *> Instructions);
1200
1201
  /// Create an overapproximating ScopStmt for the region @p R.
1202
  ///
1203
  /// @param EntryBlockInstructions The list of instructions that belong to the
1204
  ///                               entry block of the region statement.
1205
  ///                               Instructions are only tracked for entry
1206
  ///                               blocks for now. We currently do not allow
1207
  ///                               to modify the instructions of blocks later
1208
  ///                               in the region statement.
1209
  ScopStmt(Scop &parent, Region &R, StringRef Name, Loop *SurroundingLoop,
1210
           std::vector<Instruction *> EntryBlockInstructions);
1211
1212
  /// Create a copy statement.
1213
  ///
1214
  /// @param Stmt       The parent statement.
1215
  /// @param SourceRel  The source location.
1216
  /// @param TargetRel  The target location.
1217
  /// @param Domain     The original domain under which the copy statement would
1218
  ///                   be executed.
1219
  ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1220
           isl::set Domain);
1221
1222
  ScopStmt(const ScopStmt &) = delete;
1223
  const ScopStmt &operator=(const ScopStmt &) = delete;
1224
  ~ScopStmt();
1225
1226
private:
1227
  /// Polyhedral description
1228
  //@{
1229
1230
  /// The Scop containing this ScopStmt.
1231
  Scop &Parent;
1232
1233
  /// The domain under which this statement is not modeled precisely.
1234
  ///
1235
  /// The invalid domain for a statement describes all parameter combinations
1236
  /// under which the statement looks to be executed but is in fact not because
1237
  /// some assumption/restriction makes the statement/scop invalid.
1238
  isl::set InvalidDomain;
1239
1240
  /// The iteration domain describes the set of iterations for which this
1241
  /// statement is executed.
1242
  ///
1243
  /// Example:
1244
  ///     for (i = 0; i < 100 + b; ++i)
1245
  ///       for (j = 0; j < i; ++j)
1246
  ///         S(i,j);
1247
  ///
1248
  /// 'S' is executed for different values of i and j. A vector of all
1249
  /// induction variables around S (i, j) is called iteration vector.
1250
  /// The domain describes the set of possible iteration vectors.
1251
  ///
1252
  /// In this case it is:
1253
  ///
1254
  ///     Domain: 0 <= i <= 100 + b
1255
  ///             0 <= j <= i
1256
  ///
1257
  /// A pair of statement and iteration vector (S, (5,3)) is called statement
1258
  /// instance.
1259
  isl::set Domain;
1260
1261
  /// The memory accesses of this statement.
1262
  ///
1263
  /// The only side effects of a statement are its memory accesses.
1264
  using MemoryAccessVec = SmallVector<MemoryAccess *, 8>;
1265
  MemoryAccessVec MemAccs;
1266
1267
  /// Mapping from instructions to (scalar) memory accesses.
1268
  DenseMap<const Instruction *, MemoryAccessList> InstructionToAccess;
1269
1270
  /// The set of values defined elsewhere required in this ScopStmt and
1271
  ///        their MemoryKind::Value READ MemoryAccesses.
1272
  DenseMap<Value *, MemoryAccess *> ValueReads;
1273
1274
  /// The set of values defined in this ScopStmt that are required
1275
  ///        elsewhere, mapped to their MemoryKind::Value WRITE MemoryAccesses.
1276
  DenseMap<Instruction *, MemoryAccess *> ValueWrites;
1277
1278
  /// Map from PHI nodes to its incoming value when coming from this
1279
  ///        statement.
1280
  ///
1281
  /// Non-affine subregions can have multiple exiting blocks that are incoming
1282
  /// blocks of the PHI nodes. This map ensures that there is only one write
1283
  /// operation for the complete subregion. A PHI selecting the relevant value
1284
  /// will be inserted.
1285
  DenseMap<PHINode *, MemoryAccess *> PHIWrites;
1286
1287
  /// Map from PHI nodes to its read access in this statement.
1288
  DenseMap<PHINode *, MemoryAccess *> PHIReads;
1289
1290
  //@}
1291
1292
  /// A SCoP statement represents either a basic block (affine/precise case) or
1293
  /// a whole region (non-affine case).
1294
  ///
1295
  /// Only one of the following two members will therefore be set and indicate
1296
  /// which kind of statement this is.
1297
  ///
1298
  ///{
1299
1300
  /// The BasicBlock represented by this statement (in the affine case).
1301
  BasicBlock *BB = nullptr;
1302
1303
  /// The region represented by this statement (in the non-affine case).
1304
  Region *R = nullptr;
1305
1306
  ///}
1307
1308
  /// The isl AST build for the new generated AST.
1309
  isl::ast_build Build;
1310
1311
  SmallVector<Loop *, 4> NestLoops;
1312
1313
  std::string BaseName;
1314
1315
  /// The closest loop that contains this statement.
1316
  Loop *SurroundingLoop;
1317
1318
  /// Vector for Instructions in this statement.
1319
  std::vector<Instruction *> Instructions;
1320
1321
  /// Remove @p MA from dictionaries pointing to them.
1322
  void removeAccessData(MemoryAccess *MA);
1323
1324
public:
1325
  /// Get an isl_ctx pointer.
1326
  isl::ctx getIslCtx() const;
1327
1328
  /// Get the iteration domain of this ScopStmt.
1329
  ///
1330
  /// @return The iteration domain of this ScopStmt.
1331
  isl::set getDomain() const;
1332
1333
  /// Get the space of the iteration domain
1334
  ///
1335
  /// @return The space of the iteration domain
1336
  isl::space getDomainSpace() const;
1337
1338
  /// Get the id of the iteration domain space
1339
  ///
1340
  /// @return The id of the iteration domain space
1341
  isl::id getDomainId() const;
1342
1343
  /// Get an isl string representing this domain.
1344
  std::string getDomainStr() const;
1345
1346
  /// Get the schedule function of this ScopStmt.
1347
  ///
1348
  /// @return The schedule function of this ScopStmt, if it does not contain
1349
  /// extension nodes, and nullptr, otherwise.
1350
  isl::map getSchedule() const;
1351
1352
  /// Get an isl string representing this schedule.
1353
  ///
1354
  /// @return An isl string representing this schedule, if it does not contain
1355
  /// extension nodes, and an empty string, otherwise.
1356
  std::string getScheduleStr() const;
1357
1358
  /// Get the invalid domain for this statement.
1359
4.98k
  isl::set getInvalidDomain() const { return InvalidDomain; }
1360
1361
  /// Get the invalid context for this statement.
1362
246
  isl::set getInvalidContext() const { return getInvalidDomain().params(); }
1363
1364
  /// Set the invalid context for this statement to @p ID.
1365
  void setInvalidDomain(isl::set ID);
1366
1367
  /// Get the BasicBlock represented by this ScopStmt (if any).
1368
  ///
1369
  /// @return The BasicBlock represented by this ScopStmt, or null if the
1370
  ///         statement represents a region.
1371
60.6k
  BasicBlock *getBasicBlock() const { return BB; }
1372
1373
  /// Return true if this statement represents a single basic block.
1374
73.8k
  bool isBlockStmt() const { return BB != nullptr; }
1375
1376
  /// Return true if this is a copy statement.
1377
935
  bool isCopyStmt() const { return BB == nullptr && 
R == nullptr89
; }
1378
1379
  /// Get the region represented by this ScopStmt (if any).
1380
  ///
1381
  /// @return The region represented by this ScopStmt, or null if the statement
1382
  ///         represents a basic block.
1383
3.28k
  Region *getRegion() const { return R; }
1384
1385
  /// Return true if this statement represents a whole region.
1386
23.7k
  bool isRegionStmt() const { return R != nullptr; }
1387
1388
  /// Return a BasicBlock from this statement.
1389
  ///
1390
  /// For block statements, it returns the BasicBlock itself. For subregion
1391
  /// statements, return its entry block.
1392
  BasicBlock *getEntryBlock() const;
1393
1394
  /// Return whether @p L is boxed within this statement.
1395
1.78k
  bool contains(const Loop *L) const {
1396
1.78k
    // Block statements never contain loops.
1397
1.78k
    if (isBlockStmt())
1398
1.67k
      return false;
1399
106
1400
106
    return getRegion()->contains(L);
1401
106
  }
1402
1403
  /// Return whether this statement represents @p BB.
1404
12
  bool represents(BasicBlock *BB) const {
1405
12
    if (isCopyStmt())
1406
0
      return false;
1407
12
    if (isBlockStmt())
1408
0
      return BB == getBasicBlock();
1409
12
    return getRegion()->contains(BB);
1410
12
  }
1411
1412
  /// Return whether this statement contains @p Inst.
1413
0
  bool contains(Instruction *Inst) const {
1414
0
    if (!Inst)
1415
0
      return false;
1416
0
    if (isBlockStmt())
1417
0
      return std::find(Instructions.begin(), Instructions.end(), Inst) !=
1418
0
             Instructions.end();
1419
0
    return represents(Inst->getParent());
1420
0
  }
1421
1422
  /// Return the closest innermost loop that contains this statement, but is not
1423
  /// contained in it.
1424
  ///
1425
  /// For block statement, this is just the loop that contains the block. Region
1426
  /// statements can contain boxed loops, so getting the loop of one of the
1427
  /// region's BBs might return such an inner loop. For instance, the region's
1428
  /// entry could be a header of a loop, but the region might extend to BBs
1429
  /// after the loop exit. Similarly, the region might only contain parts of the
1430
  /// loop body and still include the loop header.
1431
  ///
1432
  /// Most of the time the surrounding loop is the top element of #NestLoops,
1433
  /// except when it is empty. In that case it return the loop that the whole
1434
  /// SCoP is contained in. That can be nullptr if there is no such loop.
1435
20.8k
  Loop *getSurroundingLoop() const {
1436
20.8k
    assert(!isCopyStmt() &&
1437
20.8k
           "No surrounding loop for artificially created statements");
1438
20.8k
    return SurroundingLoop;
1439
20.8k
  }
1440
1441
  /// Return true if this statement does not contain any accesses.
1442
11.1k
  bool isEmpty() const { return MemAccs.empty(); }
1443
1444
  /// Find all array accesses for @p Inst.
1445
  ///
1446
  /// @param Inst The instruction accessing an array.
1447
  ///
1448
  /// @return A list of array accesses (MemoryKind::Array) accessed by @p Inst.
1449
  ///         If there is no such access, it returns nullptr.
1450
  const MemoryAccessList *
1451
208
  lookupArrayAccessesFor(const Instruction *Inst) const {
1452
208
    auto It = InstructionToAccess.find(Inst);
1453
208
    if (It == InstructionToAccess.end())
1454
61
      return nullptr;
1455
147
    if (It->second.empty())
1456
0
      return nullptr;
1457
147
    return &It->second;
1458
147
  }
1459
1460
  /// Return the only array access for @p Inst, if existing.
1461
  ///
1462
  /// @param Inst The instruction for which to look up the access.
1463
  /// @returns The unique array memory access related to Inst or nullptr if
1464
  ///          no array access exists
1465
2.93k
  MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
1466
2.93k
    auto It = InstructionToAccess.find(Inst);
1467
2.93k
    if (It == InstructionToAccess.end())
1468
917
      return nullptr;
1469
2.02k
1470
2.02k
    MemoryAccess *ArrayAccess = nullptr;
1471
2.02k
1472
2.02k
    for (auto Access : It->getSecond()) {
1473
2.02k
      if (!Access->isArrayKind())
1474
0
        continue;
1475
2.02k
1476
2.02k
      assert(!ArrayAccess && "More then one array access for instruction");
1477
2.02k
1478
2.02k
      ArrayAccess = Access;
1479
2.02k
    }
1480
2.02k
1481
2.02k
    return ArrayAccess;
1482
2.02k
  }
1483
1484
  /// Return the only array access for @p Inst.
1485
  ///
1486
  /// @param Inst The instruction for which to look up the access.
1487
  /// @returns The unique array memory access related to Inst.
1488
1.61k
  MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
1489
1.61k
    MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
1490
1.61k
1491
1.61k
    assert(ArrayAccess && "No array access found for instruction!");
1492
1.61k
    return *ArrayAccess;
1493
1.61k
  }
1494
1495
  /// Return the MemoryAccess that writes the value of an instruction
1496
  ///        defined in this statement, or nullptr if not existing, respectively
1497
  ///        not yet added.
1498
407
  MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
1499
407
    assert((isRegionStmt() && R->contains(Inst)) ||
1500
407
           (!isRegionStmt() && Inst->getParent() == BB));
1501
407
    return ValueWrites.lookup(Inst);
1502
407
  }
1503
1504
  /// Return the MemoryAccess that reloads a value, or nullptr if not
1505
  ///        existing, respectively not yet added.
1506
1.98k
  MemoryAccess *lookupValueReadOf(Value *Inst) const {
1507
1.98k
    return ValueReads.lookup(Inst);
1508
1.98k
  }
1509
1510
  /// Return the MemoryAccess that loads a PHINode value, or nullptr if not
1511
  /// existing, respectively not yet added.
1512
43
  MemoryAccess *lookupPHIReadOf(PHINode *PHI) const {
1513
43
    return PHIReads.lookup(PHI);
1514
43
  }
1515
1516
  /// Return the PHI write MemoryAccess for the incoming values from any
1517
  ///        basic block in this ScopStmt, or nullptr if not existing,
1518
  ///        respectively not yet added.
1519
508
  MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
1520
508
    assert(isBlockStmt() || R->getExit() == PHI->getParent());
1521
508
    return PHIWrites.lookup(PHI);
1522
508
  }
1523
1524
  /// Return the input access of the value, or null if no such MemoryAccess
1525
  /// exists.
1526
  ///
1527
  /// The input access is the MemoryAccess that makes an inter-statement value
1528
  /// available in this statement by reading it at the start of this statement.
1529
  /// This can be a MemoryKind::Value if defined in another statement or a
1530
  /// MemoryKind::PHI if the value is a PHINode in this statement.
1531
131
  MemoryAccess *lookupInputAccessOf(Value *Val) const {
1532
131
    if (isa<PHINode>(Val))
1533
36
      if (auto InputMA = lookupPHIReadOf(cast<PHINode>(Val))) {
1534
18
        assert(!lookupValueReadOf(Val) && "input accesses must be unique; a "
1535
18
                                          "statement cannot read a .s2a and "
1536
18
                                          ".phiops simultaneously");
1537
18
        return InputMA;
1538
18
      }
1539
113
1540
113
    if (auto *InputMA = lookupValueReadOf(Val))
1541
63
      return InputMA;
1542
50
1543
50
    return nullptr;
1544
50
  }
1545
1546
  /// Add @p Access to this statement's list of accesses.
1547
  ///
1548
  /// @param Access  The access to add.
1549
  /// @param Prepend If true, will add @p Access before all other instructions
1550
  ///                (instead of appending it).
1551
  void addAccess(MemoryAccess *Access, bool Preprend = false);
1552
1553
  /// Remove a MemoryAccess from this statement.
1554
  ///
1555
  /// Note that scalar accesses that are caused by MA will
1556
  /// be eliminated too.
1557
  void removeMemoryAccess(MemoryAccess *MA);
1558
1559
  /// Remove @p MA from this statement.
1560
  ///
1561
  /// In contrast to removeMemoryAccess(), no other access will be eliminated.
1562
  ///
1563
  /// @param MA            The MemoryAccess to be removed.
1564
  /// @param AfterHoisting If true, also remove from data access lists.
1565
  ///                      These lists are filled during
1566
  ///                      ScopBuilder::buildAccessRelations. Therefore, if this
1567
  ///                      method is called before buildAccessRelations, false
1568
  ///                      must be passed.
1569
  void removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting = true);
1570
1571
  using iterator = MemoryAccessVec::iterator;
1572
  using const_iterator = MemoryAccessVec::const_iterator;
1573
1574
37.7k
  iterator begin() { return MemAccs.begin(); }
1575
37.7k
  iterator end() { return MemAccs.end(); }
1576
43
  const_iterator begin() const { return MemAccs.begin(); }
1577
43
  const_iterator end() const { return MemAccs.end(); }
1578
5.25k
  size_t size() const { return MemAccs.size(); }
1579
1580
  unsigned getNumIterators() const;
1581
1582
38.3k
  Scop *getParent() { return &Parent; }
1583
1.26k
  const Scop *getParent() const { return &Parent; }
1584
1585
23.3k
  const std::vector<Instruction *> &getInstructions() const {
1586
23.3k
    return Instructions;
1587
23.3k
  }
1588
1589
  /// Set the list of instructions for this statement. It replaces the current
1590
  /// list.
1591
98
  void setInstructions(ArrayRef<Instruction *> Range) {
1592
98
    Instructions.assign(Range.begin(), Range.end());
1593
98
  }
1594
1595
99
  std::vector<Instruction *>::const_iterator insts_begin() const {
1596
99
    return Instructions.begin();
1597
99
  }
1598
1599
99
  std::vector<Instruction *>::const_iterator insts_end() const {
1600
99
    return Instructions.end();
1601
99
  }
1602
1603
  /// The range of instructions in this statement.
1604
1
  iterator_range<std::vector<Instruction *>::const_iterator> insts() const {
1605
1
    return {insts_begin(), insts_end()};
1606
1
  }
1607
1608
  /// Insert an instruction before all other instructions in this statement.
1609
37
  void prependInstruction(Instruction *Inst) {
1610
37
    Instructions.insert(Instructions.begin(), Inst);
1611
37
  }
1612
1613
  const char *getBaseName() const;
1614
1615
  /// Set the isl AST build.
1616
500
  void setAstBuild(isl::ast_build B) { Build = B; }
1617
1618
  /// Get the isl AST build.
1619
11
  isl::ast_build getAstBuild() const { return Build; }
1620
1621
  /// Restrict the domain of the statement.
1622
  ///
1623
  /// @param NewDomain The new statement domain.
1624
  void restrictDomain(isl::set NewDomain);
1625
1626
  /// Get the loop for a dimension.
1627
  ///
1628
  /// @param Dimension The dimension of the induction variable
1629
  /// @return The loop at a certain dimension.
1630
  Loop *getLoopForDimension(unsigned Dimension) const;
1631
1632
  /// Align the parameters in the statement to the scop context
1633
  void realignParams();
1634
1635
  /// Print the ScopStmt.
1636
  ///
1637
  /// @param OS                The output stream the ScopStmt is printed to.
1638
  /// @param PrintInstructions Whether to print the statement's instructions as
1639
  ///                          well.
1640
  void print(raw_ostream &OS, bool PrintInstructions) const;
1641
1642
  /// Print the instructions in ScopStmt.
1643
  ///
1644
  void printInstructions(raw_ostream &OS) const;
1645
1646
  /// Check whether there is a value read access for @p V in this statement, and
1647
  /// if not, create one.
1648
  ///
1649
  /// This allows to add MemoryAccesses after the initial creation of the Scop
1650
  /// by ScopBuilder.
1651
  ///
1652
  /// @return The already existing or newly created MemoryKind::Value READ
1653
  /// MemoryAccess.
1654
  ///
1655
  /// @see ScopBuilder::ensureValueRead(Value*,ScopStmt*)
1656
  MemoryAccess *ensureValueRead(Value *V);
1657
1658
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1659
  /// Print the ScopStmt to stderr.
1660
  void dump() const;
1661
#endif
1662
};
1663
1664
/// Print ScopStmt S to raw_ostream OS.
1665
raw_ostream &operator<<(raw_ostream &OS, const ScopStmt &S);
1666
1667
/// Static Control Part
1668
///
1669
/// A Scop is the polyhedral representation of a control flow region detected
1670
/// by the Scop detection. It is generated by translating the LLVM-IR and
1671
/// abstracting its effects.
1672
///
1673
/// A Scop consists of a set of:
1674
///
1675
///   * A set of statements executed in the Scop.
1676
///
1677
///   * A set of global parameters
1678
///   Those parameters are scalar integer values, which are constant during
1679
///   execution.
1680
///
1681
///   * A context
1682
///   This context contains information about the values the parameters
1683
///   can take and relations between different parameters.
1684
class Scop {
1685
public:
1686
  /// Type to represent a pair of minimal/maximal access to an array.
1687
  using MinMaxAccessTy = std::pair<isl::pw_multi_aff, isl::pw_multi_aff>;
1688
1689
  /// Vector of minimal/maximal accesses to different arrays.
1690
  using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
1691
1692
  /// Pair of minimal/maximal access vectors representing
1693
  /// read write and read only accesses
1694
  using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
1695
1696
  /// Vector of pair of minimal/maximal access vectors representing
1697
  /// non read only and read only accesses for each alias group.
1698
  using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
1699
1700
private:
1701
  friend class ScopBuilder;
1702
1703
  /// Isl context.
1704
  ///
1705
  /// We need a shared_ptr with reference counter to delete the context when all
1706
  /// isl objects are deleted. We will distribute the shared_ptr to all objects
1707
  /// that use the context to create isl objects, and increase the reference
1708
  /// counter. By doing this, we guarantee that the context is deleted when we
1709
  /// delete the last object that creates isl objects with the context. This
1710
  /// declaration needs to be the first in class to gracefully destroy all isl
1711
  /// objects before the context.
1712
  std::shared_ptr<isl_ctx> IslCtx;
1713
1714
  ScalarEvolution *SE;
1715
  DominatorTree *DT;
1716
1717
  /// The underlying Region.
1718
  Region &R;
1719
1720
  /// The name of the SCoP (identical to the regions name)
1721
  Optional<std::string> name;
1722
1723
  /// The ID to be assigned to the next Scop in a function
1724
  static int NextScopID;
1725
1726
  /// The name of the function currently under consideration
1727
  static std::string CurrentFunc;
1728
1729
  // Access functions of the SCoP.
1730
  //
1731
  // This owns all the MemoryAccess objects of the Scop created in this pass.
1732
  AccFuncVector AccessFunctions;
1733
1734
  /// Flag to indicate that the scheduler actually optimized the SCoP.
1735
  bool IsOptimized = false;
1736
1737
  /// True if the underlying region has a single exiting block.
1738
  bool HasSingleExitEdge;
1739
1740
  /// Flag to remember if the SCoP contained an error block or not.
1741
  bool HasErrorBlock = false;
1742
1743
  /// Max loop depth.
1744
  unsigned MaxLoopDepth = 0;
1745
1746
  /// Number of copy statements.
1747
  unsigned CopyStmtsNum = 0;
1748
1749
  /// Flag to indicate if the Scop is to be skipped.
1750
  bool SkipScop = false;
1751
1752
  using StmtSet = std::list<ScopStmt>;
1753
1754
  /// The statements in this Scop.
1755
  StmtSet Stmts;
1756
1757
  /// Parameters of this Scop
1758
  ParameterSetTy Parameters;
1759
1760
  /// Mapping from parameters to their ids.
1761
  DenseMap<const SCEV *, isl::id> ParameterIds;
1762
1763
  /// The context of the SCoP created during SCoP detection.
1764
  ScopDetection::DetectionContext &DC;
1765
1766
  /// OptimizationRemarkEmitter object for displaying diagnostic remarks
1767
  OptimizationRemarkEmitter &ORE;
1768
1769
  /// A map from basic blocks to vector of SCoP statements. Currently this
1770
  /// vector comprises only of a single statement.
1771
  DenseMap<BasicBlock *, std::vector<ScopStmt *>> StmtMap;
1772
1773
  /// A map from instructions to SCoP statements.
1774
  DenseMap<Instruction *, ScopStmt *> InstStmtMap;
1775
1776
  /// A map from basic blocks to their domains.
1777
  DenseMap<BasicBlock *, isl::set> DomainMap;
1778
1779
  /// Constraints on parameters.
1780
  isl::set Context = nullptr;
1781
1782
  /// The affinator used to translate SCEVs to isl expressions.
1783
  SCEVAffinator Affinator;
1784
1785
  using ArrayInfoMapTy =
1786
      std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
1787
               std::unique_ptr<ScopArrayInfo>>;
1788
1789
  using ArrayNameMapTy = StringMap<std::unique_ptr<ScopArrayInfo>>;
1790
1791
  using ArrayInfoSetTy = SetVector<ScopArrayInfo *>;
1792
1793
  /// A map to remember ScopArrayInfo objects for all base pointers.
1794
  ///
1795
  /// As PHI nodes may have two array info objects associated, we add a flag
1796
  /// that distinguishes between the PHI node specific ArrayInfo object
1797
  /// and the normal one.
1798
  ArrayInfoMapTy ScopArrayInfoMap;
1799
1800
  /// A map to remember ScopArrayInfo objects for all names of memory
1801
  ///        references.
1802
  ArrayNameMapTy ScopArrayNameMap;
1803
1804
  /// A set to remember ScopArrayInfo objects.
1805
  /// @see Scop::ScopArrayInfoMap
1806
  ArrayInfoSetTy ScopArrayInfoSet;
1807
1808
  /// The assumptions under which this scop was built.
1809
  ///
1810
  /// When constructing a scop sometimes the exact representation of a statement
1811
  /// or condition would be very complex, but there is a common case which is a
1812
  /// lot simpler, but which is only valid under certain assumptions. The
1813
  /// assumed context records the assumptions taken during the construction of
1814
  /// this scop and that need to be code generated as a run-time test.
1815
  isl::set AssumedContext;
1816
1817
  /// The restrictions under which this SCoP was built.
1818
  ///
1819
  /// The invalid context is similar to the assumed context as it contains
1820
  /// constraints over the parameters. However, while we need the constraints
1821
  /// in the assumed context to be "true" the constraints in the invalid context
1822
  /// need to be "false". Otherwise they behave the same.
1823
  isl::set InvalidContext;
1824
1825
  /// Helper struct to remember assumptions.
1826
  struct Assumption {
1827
    /// The kind of the assumption (e.g., WRAPPING).
1828
    AssumptionKind Kind;
1829
1830
    /// Flag to distinguish assumptions and restrictions.
1831
    AssumptionSign Sign;
1832
1833
    /// The valid/invalid context if this is an assumption/restriction.
1834
    isl::set Set;
1835
1836
    /// The location that caused this assumption.
1837
    DebugLoc Loc;
1838
1839
    /// An optional block whose domain can simplify the assumption.
1840
    BasicBlock *BB;
1841
  };
1842
1843
  /// Collection to hold taken assumptions.
1844
  ///
1845
  /// There are two reasons why we want to record assumptions first before we
1846
  /// add them to the assumed/invalid context:
1847
  ///   1) If the SCoP is not profitable or otherwise invalid without the
1848
  ///      assumed/invalid context we do not have to compute it.
1849
  ///   2) Information about the context are gathered rather late in the SCoP
1850
  ///      construction (basically after we know all parameters), thus the user
1851
  ///      might see overly complicated assumptions to be taken while they will
1852
  ///      only be simplified later on.
1853
  SmallVector<Assumption, 8> RecordedAssumptions;
1854
1855
  /// The schedule of the SCoP
1856
  ///
1857
  /// The schedule of the SCoP describes the execution order of the statements
1858
  /// in the scop by assigning each statement instance a possibly
1859
  /// multi-dimensional execution time. The schedule is stored as a tree of
1860
  /// schedule nodes.
1861
  ///
1862
  /// The most common nodes in a schedule tree are so-called band nodes. Band
1863
  /// nodes map statement instances into a multi dimensional schedule space.
1864
  /// This space can be seen as a multi-dimensional clock.
1865
  ///
1866
  /// Example:
1867
  ///
1868
  /// <S,(5,4)>  may be mapped to (5,4) by this schedule:
1869
  ///
1870
  /// s0 = i (Year of execution)
1871
  /// s1 = j (Day of execution)
1872
  ///
1873
  /// or to (9, 20) by this schedule:
1874
  ///
1875
  /// s0 = i + j (Year of execution)
1876
  /// s1 = 20 (Day of execution)
1877
  ///
1878
  /// The order statement instances are executed is defined by the
1879
  /// schedule vectors they are mapped to. A statement instance
1880
  /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
1881
  /// the schedule vector of A is lexicographic smaller than the schedule
1882
  /// vector of B.
1883
  ///
1884
  /// Besides band nodes, schedule trees contain additional nodes that specify
1885
  /// a textual ordering between two subtrees or filter nodes that filter the
1886
  /// set of statement instances that will be scheduled in a subtree. There
1887
  /// are also several other nodes. A full description of the different nodes
1888
  /// in a schedule tree is given in the isl manual.
1889
  isl::schedule Schedule = nullptr;
1890
1891
  /// Whether the schedule has been modified after derived from the CFG by
1892
  /// ScopBuilder.
1893
  bool ScheduleModified = false;
1894
1895
  /// The set of minimal/maximal accesses for each alias group.
1896
  ///
1897
  /// When building runtime alias checks we look at all memory instructions and
1898
  /// build so called alias groups. Each group contains a set of accesses to
1899
  /// different base arrays which might alias with each other. However, between
1900
  /// alias groups there is no aliasing possible.
1901
  ///
1902
  /// In a program with int and float pointers annotated with tbaa information
1903
  /// we would probably generate two alias groups, one for the int pointers and
1904
  /// one for the float pointers.
1905
  ///
1906
  /// During code generation we will create a runtime alias check for each alias
1907
  /// group to ensure the SCoP is executed in an alias free environment.
1908
  MinMaxVectorPairVectorTy MinMaxAliasGroups;
1909
1910
  /// Mapping from invariant loads to the representing invariant load of
1911
  ///        their equivalence class.
1912
  ValueToValueMap InvEquivClassVMap;
1913
1914
  /// List of invariant accesses.
1915
  InvariantEquivClassesTy InvariantEquivClasses;
1916
1917
  /// The smallest array index not yet assigned.
1918
  long ArrayIdx = 0;
1919
1920
  /// The smallest statement index not yet assigned.
1921
  long StmtIdx = 0;
1922
1923
  /// A number that uniquely represents a Scop within its function
1924
  const int ID;
1925
1926
  /// Map of values to the MemoryAccess that writes its definition.
1927
  ///
1928
  /// There must be at most one definition per llvm::Instruction in a SCoP.
1929
  DenseMap<Value *, MemoryAccess *> ValueDefAccs;
1930
1931
  /// Map of values to the MemoryAccess that reads a PHI.
1932
  DenseMap<PHINode *, MemoryAccess *> PHIReadAccs;
1933
1934
  /// List of all uses (i.e. read MemoryAccesses) for a MemoryKind::Value
1935
  /// scalar.
1936
  DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>> ValueUseAccs;
1937
1938
  /// List of all incoming values (write MemoryAccess) of a MemoryKind::PHI or
1939
  /// MemoryKind::ExitPHI scalar.
1940
  DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>>
1941
      PHIIncomingAccs;
1942
1943
  /// Return the ID for a new Scop within a function
1944
  static int getNextID(std::string ParentFunc);
1945
1946
  /// Scop constructor; invoked from ScopBuilder::buildScop.
1947
  Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
1948
       ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE);
1949
1950
  //@}
1951
1952
  /// Initialize this ScopBuilder.
1953
  void init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
1954
            LoopInfo &LI);
1955
1956
  /// Propagate domains that are known due to graph properties.
1957
  ///
1958
  /// As a CFG is mostly structured we use the graph properties to propagate
1959
  /// domains without the need to compute all path conditions. In particular, if
1960
  /// a block A dominates a block B and B post-dominates A we know that the
1961
  /// domain of B is a superset of the domain of A. As we do not have
1962
  /// post-dominator information available here we use the less precise region
1963
  /// information. Given a region R, we know that the exit is always executed if
1964
  /// the entry was executed, thus the domain of the exit is a superset of the
1965
  /// domain of the entry. In case the exit can only be reached from within the
1966
  /// region the domains are in fact equal. This function will use this property
1967
  /// to avoid the generation of condition constraints that determine when a
1968
  /// branch is taken. If @p BB is a region entry block we will propagate its
1969
  /// domain to the region exit block. Additionally, we put the region exit
1970
  /// block in the @p FinishedExitBlocks set so we can later skip edges from
1971
  /// within the region to that block.
1972
  ///
1973
  /// @param BB                 The block for which the domain is currently
1974
  ///                           propagated.
1975
  /// @param BBLoop             The innermost affine loop surrounding @p BB.
1976
  /// @param FinishedExitBlocks Set of region exits the domain was set for.
1977
  /// @param LI                 The LoopInfo for the current function.
1978
  /// @param InvalidDomainMap   BB to InvalidDomain map for the BB of current
1979
  ///                           region.
1980
  void propagateDomainConstraintsToRegionExit(
1981
      BasicBlock *BB, Loop *BBLoop,
1982
      SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
1983
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1984
1985
  /// Compute the union of predecessor domains for @p BB.
1986
  ///
1987
  /// To compute the union of all domains of predecessors of @p BB this
1988
  /// function applies similar reasoning on the CFG structure as described for
1989
  ///   @see propagateDomainConstraintsToRegionExit
1990
  ///
1991
  /// @param BB     The block for which the predecessor domains are collected.
1992
  /// @param Domain The domain under which BB is executed.
1993
  /// @param DT     The DominatorTree for the current function.
1994
  /// @param LI     The LoopInfo for the current function.
1995
  ///
1996
  /// @returns The domain under which @p BB is executed.
1997
  isl::set getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
1998
                                           DominatorTree &DT, LoopInfo &LI);
1999
2000
  /// Add loop carried constraints to the header block of the loop @p L.
2001
  ///
2002
  /// @param L                The loop to process.
2003
  /// @param LI               The LoopInfo for the current function.
2004
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2005
  ///                         region.
2006
  ///
2007
  /// @returns True if there was no problem and false otherwise.
2008
  bool addLoopBoundsToHeaderDomain(
2009
      Loop *L, LoopInfo &LI,
2010
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2011
2012
  /// Compute the branching constraints for each basic block in @p R.
2013
  ///
2014
  /// @param R                The region we currently build branching conditions
2015
  ///                         for.
2016
  /// @param DT               The DominatorTree for the current function.
2017
  /// @param LI               The LoopInfo for the current function.
2018
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2019
  ///                         region.
2020
  ///
2021
  /// @returns True if there was no problem and false otherwise.
2022
  bool buildDomainsWithBranchConstraints(
2023
      Region *R, DominatorTree &DT, LoopInfo &LI,
2024
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2025
2026
  /// Propagate the domain constraints through the region @p R.
2027
  ///
2028
  /// @param R                The region we currently build branching conditions
2029
  /// for.
2030
  /// @param DT               The DominatorTree for the current function.
2031
  /// @param LI               The LoopInfo for the current function.
2032
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2033
  ///                         region.
2034
  ///
2035
  /// @returns True if there was no problem and false otherwise.
2036
  bool propagateDomainConstraints(
2037
      Region *R, DominatorTree &DT, LoopInfo &LI,
2038
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2039
2040
  /// Propagate invalid domains of statements through @p R.
2041
  ///
2042
  /// This method will propagate invalid statement domains through @p R and at
2043
  /// the same time add error block domains to them. Additionally, the domains
2044
  /// of error statements and those only reachable via error statements will be
2045
  /// replaced by an empty set. Later those will be removed completely.
2046
  ///
2047
  /// @param R                The currently traversed region.
2048
  /// @param DT               The DominatorTree for the current function.
2049
  /// @param LI               The LoopInfo for the current function.
2050
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2051
  ///                         region.
2052
  //
2053
  /// @returns True if there was no problem and false otherwise.
2054
  bool propagateInvalidStmtDomains(
2055
      Region *R, DominatorTree &DT, LoopInfo &LI,
2056
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2057
2058
  /// Compute the domain for each basic block in @p R.
2059
  ///
2060
  /// @param R                The region we currently traverse.
2061
  /// @param DT               The DominatorTree for the current function.
2062
  /// @param LI               The LoopInfo for the current function.
2063
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2064
  ///                         region.
2065
  ///
2066
  /// @returns True if there was no problem and false otherwise.
2067
  bool buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2068
                    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2069
2070
  /// Add parameter constraints to @p C that imply a non-empty domain.
2071
  isl::set addNonEmptyDomainConstraints(isl::set C) const;
2072
2073
  /// Return the access for the base ptr of @p MA if any.
2074
  MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
2075
2076
  /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
2077
  bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
2078
2079
  /// Create equivalence classes for required invariant accesses.
2080
  ///
2081
  /// These classes will consolidate multiple required invariant loads from the
2082
  /// same address in order to keep the number of dimensions in the SCoP
2083
  /// description small. For each such class equivalence class only one
2084
  /// representing element, hence one required invariant load, will be chosen
2085
  /// and modeled as parameter. The method
2086
  /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
2087
  /// equivalence class with the representing element that is modeled. As a
2088
  /// consequence Scop::getIdForParam() will only return an id for the
2089
  /// representing element of each equivalence class, thus for each required
2090
  /// invariant location.
2091
  void buildInvariantEquivalenceClasses();
2092
2093
  /// Return the context under which the access cannot be hoisted.
2094
  ///
2095
  /// @param Access The access to check.
2096
  /// @param Writes The set of all memory writes in the scop.
2097
  ///
2098
  /// @return Return the context under which the access cannot be hoisted or a
2099
  ///         nullptr if it cannot be hoisted at all.
2100
  isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
2101
2102
  /// Verify that all required invariant loads have been hoisted.
2103
  ///
2104
  /// Invariant load hoisting is not guaranteed to hoist all loads that were
2105
  /// assumed to be scop invariant during scop detection. This function checks
2106
  /// for cases where the hoisting failed, but where it would have been
2107
  /// necessary for our scop modeling to be correct. In case of insufficient
2108
  /// hoisting the scop is marked as invalid.
2109
  ///
2110
  /// In the example below Bound[1] is required to be invariant:
2111
  ///
2112
  /// for (int i = 1; i < Bound[0]; i++)
2113
  ///   for (int j = 1; j < Bound[1]; j++)
2114
  ///     ...
2115
  void verifyInvariantLoads();
2116
2117
  /// Hoist invariant memory loads and check for required ones.
2118
  ///
2119
  /// We first identify "common" invariant loads, thus loads that are invariant
2120
  /// and can be hoisted. Then we check if all required invariant loads have
2121
  /// been identified as (common) invariant. A load is a required invariant load
2122
  /// if it was assumed to be invariant during SCoP detection, e.g., to assume
2123
  /// loop bounds to be affine or runtime alias checks to be placeable. In case
2124
  /// a required invariant load was not identified as (common) invariant we will
2125
  /// drop this SCoP. An example for both "common" as well as required invariant
2126
  /// loads is given below:
2127
  ///
2128
  /// for (int i = 1; i < *LB[0]; i++)
2129
  ///   for (int j = 1; j < *LB[1]; j++)
2130
  ///     A[i][j] += A[0][0] + (*V);
2131
  ///
2132
  /// Common inv. loads: V, A[0][0], LB[0], LB[1]
2133
  /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
2134
  void hoistInvariantLoads();
2135
2136
  /// Canonicalize arrays with base pointers from the same equivalence class.
2137
  ///
2138
  /// Some context: in our normal model we assume that each base pointer is
2139
  /// related to a single specific memory region, where memory regions
2140
  /// associated with different base pointers are disjoint. Consequently we do
2141
  /// not need to compute additional data dependences that model possible
2142
  /// overlaps of these memory regions. To verify our assumption we compute
2143
  /// alias checks that verify that modeled arrays indeed do not overlap. In
2144
  /// case an overlap is detected the runtime check fails and we fall back to
2145
  /// the original code.
2146
  ///
2147
  /// In case of arrays where the base pointers are know to be identical,
2148
  /// because they are dynamically loaded by accesses that are in the same
2149
  /// invariant load equivalence class, such run-time alias check would always
2150
  /// be false.
2151
  ///
2152
  /// This function makes sure that we do not generate consistently failing
2153
  /// run-time checks for code that contains distinct arrays with known
2154
  /// equivalent base pointers. It identifies for each invariant load
2155
  /// equivalence class a single canonical array and canonicalizes all memory
2156
  /// accesses that reference arrays that have base pointers that are known to
2157
  /// be equal to the base pointer of such a canonical array to this canonical
2158
  /// array.
2159
  ///
2160
  /// We currently do not canonicalize arrays for which certain memory accesses
2161
  /// have been hoisted as loop invariant.
2162
  void canonicalizeDynamicBasePtrs();
2163
2164
  /// Check if @p MA can always be hoisted without execution context.
2165
  bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
2166
                          bool MAInvalidCtxIsEmpty,
2167
                          bool NonHoistableCtxIsEmpty);
2168
2169
  /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
2170
  void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
2171
2172
  /// Create an id for @p Param and store it in the ParameterIds map.
2173
  void createParameterId(const SCEV *Param);
2174
2175
  /// Build the Context of the Scop.
2176
  void buildContext();
2177
2178
  /// Add user provided parameter constraints to context (source code).
2179
  void addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
2180
                          DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2181
2182
  /// Add user provided parameter constraints to context (command line).
2183
  void addUserContext();
2184
2185
  /// Add the bounds of the parameters to the context.
2186
  void addParameterBounds();
2187
2188
  /// Simplify the assumed and invalid context.
2189
  void simplifyContexts();
2190
2191
  /// Get the representing SCEV for @p S if applicable, otherwise @p S.
2192
  ///
2193
  /// Invariant loads of the same location are put in an equivalence class and
2194
  /// only one of them is chosen as a representing element that will be
2195
  /// modeled as a parameter. The others have to be normalized, i.e.,
2196
  /// replaced by the representing element of their equivalence class, in order
2197
  /// to get the correct parameter value, e.g., in the SCEVAffinator.
2198
  ///
2199
  /// @param S The SCEV to normalize.
2200
  ///
2201
  /// @return The representing SCEV for invariant loads or @p S if none.
2202
  const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S) const;
2203
2204
  /// Create a new SCoP statement for @p BB.
2205
  ///
2206
  /// A new statement for @p BB will be created and added to the statement
2207
  /// vector
2208
  /// and map.
2209
  ///
2210
  /// @param BB              The basic block we build the statement for.
2211
  /// @param Name            The name of the new statement.
2212
  /// @param SurroundingLoop The loop the created statement is contained in.
2213
  /// @param Instructions    The instructions in the statement.
2214
  void addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
2215
                   std::vector<Instruction *> Instructions);
2216
2217
  /// Create a new SCoP statement for @p R.
2218
  ///
2219
  /// A new statement for @p R will be created and added to the statement vector
2220
  /// and map.
2221
  ///
2222
  /// @param R                      The region we build the statement for.
2223
  /// @param Name                   The name of the new statement.
2224
  /// @param SurroundingLoop        The loop the created statement is contained
2225
  ///                               in.
2226
  /// @param EntryBlockInstructions The (interesting) instructions in the
2227
  ///                               entry block of the region statement.
2228
  void addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
2229
                   std::vector<Instruction *> EntryBlockInstructions);
2230
2231
  /// Update access dimensionalities.
2232
  ///
2233
  /// When detecting memory accesses different accesses to the same array may
2234
  /// have built with different dimensionality, as outer zero-values dimensions
2235
  /// may not have been recognized as separate dimensions. This function goes
2236
  /// again over all memory accesses and updates their dimensionality to match
2237
  /// the dimensionality of the underlying ScopArrayInfo object.
2238
  void updateAccessDimensionality();
2239
2240
  /// Fold size constants to the right.
2241
  ///
2242
  /// In case all memory accesses in a given dimension are multiplied with a
2243
  /// common constant, we can remove this constant from the individual access
2244
  /// functions and move it to the size of the memory access. We do this as this
2245
  /// increases the size of the innermost dimension, consequently widens the
2246
  /// valid range the array subscript in this dimension can evaluate to, and
2247
  /// as a result increases the likelihood that our delinearization is
2248
  /// correct.
2249
  ///
2250
  /// Example:
2251
  ///
2252
  ///    A[][n]
2253
  ///    S[i,j] -> A[2i][2j+1]
2254
  ///    S[i,j] -> A[2i][2j]
2255
  ///
2256
  ///    =>
2257
  ///
2258
  ///    A[][2n]
2259
  ///    S[i,j] -> A[i][2j+1]
2260
  ///    S[i,j] -> A[i][2j]
2261
  ///
2262
  /// Constants in outer dimensions can arise when the elements of a parametric
2263
  /// multi-dimensional array are not elementary data types, but e.g.,
2264
  /// structures.
2265
  void foldSizeConstantsToRight();
2266
2267
  /// Fold memory accesses to handle parametric offset.
2268
  ///
2269
  /// As a post-processing step, we 'fold' memory accesses to parametric
2270
  /// offsets in the access functions. @see MemoryAccess::foldAccess for
2271
  /// details.
2272
  void foldAccessRelations();
2273
2274
  /// Assume that all memory accesses are within bounds.
2275
  ///
2276
  /// After we have built a model of all memory accesses, we need to assume
2277
  /// that the model we built matches reality -- aka. all modeled memory
2278
  /// accesses always remain within bounds. We do this as last step, after
2279
  /// all memory accesses have been modeled and canonicalized.
2280
  void assumeNoOutOfBounds();
2281
2282
  /// Remove statements from the list of scop statements.
2283
  ///
2284
  /// @param ShouldDelete  A function that returns true if the statement passed
2285
  ///                      to it should be deleted.
2286
  /// @param AfterHoisting If true, also remove from data access lists.
2287
  ///                      These lists are filled during
2288
  ///                      ScopBuilder::buildAccessRelations. Therefore, if this
2289
  ///                      method is called before buildAccessRelations, false
2290
  ///                      must be passed.
2291
  void removeStmts(std::function<bool(ScopStmt &)> ShouldDelete,
2292
                   bool AfterHoisting = true);
2293
2294
  /// Removes @p Stmt from the StmtMap.
2295
  void removeFromStmtMap(ScopStmt &Stmt);
2296
2297
  /// Removes all statements where the entry block of the statement does not
2298
  /// have a corresponding domain in the domain map.
2299
  void removeStmtNotInDomainMap();
2300
2301
  /// Mark arrays that have memory accesses with FortranArrayDescriptor.
2302
  void markFortranArrays();
2303
2304
  /// Finalize all access relations.
2305
  ///
2306
  /// When building up access relations, temporary access relations that
2307
  /// correctly represent each individual access are constructed. However, these
2308
  /// access relations can be inconsistent or non-optimal when looking at the
2309
  /// set of accesses as a whole. This function finalizes the memory accesses
2310
  /// and constructs a globally consistent state.
2311
  void finalizeAccesses();
2312
2313
  /// Construct the schedule of this SCoP.
2314
  ///
2315
  /// @param LI The LoopInfo for the current function.
2316
  void buildSchedule(LoopInfo &LI);
2317
2318
  /// A loop stack element to keep track of per-loop information during
2319
  ///        schedule construction.
2320
  using LoopStackElementTy = struct LoopStackElement {
2321
    // The loop for which we keep information.
2322
    Loop *L;
2323
2324
    // The (possibly incomplete) schedule for this loop.
2325
    isl::schedule Schedule;
2326
2327
    // The number of basic blocks in the current loop, for which a schedule has
2328
    // already been constructed.
2329
    unsigned NumBlocksProcessed;
2330
2331
    LoopStackElement(Loop *L, isl::schedule S, unsigned NumBlocksProcessed)
2332
2.78k
        : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
2333
  };
2334
2335
  /// The loop stack used for schedule construction.
2336
  ///
2337
  /// The loop stack keeps track of schedule information for a set of nested
2338
  /// loops as well as an (optional) 'nullptr' loop that models the outermost
2339
  /// schedule dimension. The loops in a loop stack always have a parent-child
2340
  /// relation where the loop at position n is the parent of the loop at
2341
  /// position n + 1.
2342
  using LoopStackTy = SmallVector<LoopStackElementTy, 4>;
2343
2344
  /// Construct schedule information for a given Region and add the
2345
  ///        derived information to @p LoopStack.
2346
  ///
2347
  /// Given a Region we derive schedule information for all RegionNodes
2348
  /// contained in this region ensuring that the assigned execution times
2349
  /// correctly model the existing control flow relations.
2350
  ///
2351
  /// @param R              The region which to process.
2352
  /// @param LoopStack      A stack of loops that are currently under
2353
  ///                       construction.
2354
  /// @param LI The LoopInfo for the current function.
2355
  void buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI);
2356
2357
  /// Build Schedule for the region node @p RN and add the derived
2358
  ///        information to @p LoopStack.
2359
  ///
2360
  /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
2361
  /// schedule for this @p RN and also finalize loop schedules in case the
2362
  /// current @p RN completes the loop.
2363
  ///
2364
  /// In case @p RN is a not-non-affine Region, we delegate the construction to
2365
  /// buildSchedule(Region *R, ...).
2366
  ///
2367
  /// @param RN             The RegionNode region traversed.
2368
  /// @param LoopStack      A stack of loops that are currently under
2369
  ///                       construction.
2370
  /// @param LI The LoopInfo for the current function.
2371
  void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI);
2372
2373
  /// Collect all memory access relations of a given type.
2374
  ///
2375
  /// @param Predicate A predicate function that returns true if an access is
2376
  ///                  of a given type.
2377
  ///
2378
  /// @returns The set of memory accesses in the scop that match the predicate.
2379
  isl::union_map
2380
  getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
2381
2382
  /// @name Helper functions for printing the Scop.
2383
  ///
2384
  //@{
2385
  void printContext(raw_ostream &OS) const;
2386
  void printArrayInfo(raw_ostream &OS) const;
2387
  void printStatements(raw_ostream &OS, bool PrintInstructions) const;
2388
  void printAliasAssumptions(raw_ostream &OS) const;
2389
  //@}
2390
2391
public:
2392
  Scop(const Scop &) = delete;
2393
  Scop &operator=(const Scop &) = delete;
2394
  ~Scop();
2395
2396
  /// Get the count of copy statements added to this Scop.
2397
  ///
2398
  /// @return The count of copy statements added to this Scop.
2399
24
  unsigned getCopyStmtsNum() { return CopyStmtsNum; }
2400
2401
  /// Create a new copy statement.
2402
  ///
2403
  /// A new statement will be created and added to the statement vector.
2404
  ///
2405
  /// @param Stmt       The parent statement.
2406
  /// @param SourceRel  The source location.
2407
  /// @param TargetRel  The target location.
2408
  /// @param Domain     The original domain under which the copy statement would
2409
  ///                   be executed.
2410
  ScopStmt *addScopStmt(isl::map SourceRel, isl::map TargetRel,
2411
                        isl::set Domain);
2412
2413
  /// Add the access function to all MemoryAccess objects of the Scop
2414
  ///        created in this pass.
2415
5.11k
  void addAccessFunction(MemoryAccess *Access) {
2416
5.11k
    AccessFunctions.emplace_back(Access);
2417
5.11k
2418
5.11k
    // Register value definitions.
2419
5.11k
    if (Access->isWrite() && 
Access->isOriginalValueKind()2.64k
) {
2420
341
      assert(!ValueDefAccs.count(Access->getAccessValue()) &&
2421
341
             "there can be just one definition per value");
2422
341
      ValueDefAccs[Access->getAccessValue()] = Access;
2423
4.76k
    } else if (Access->isRead() && 
Access->isOriginalPHIKind()2.46k
) {
2424
235
      PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
2425
235
      assert(!PHIReadAccs.count(PHI) &&
2426
235
             "there can be just one PHI read per PHINode");
2427
235
      PHIReadAccs[PHI] = Access;
2428
235
    }
2429
5.11k
  }
2430
2431
  /// Add metadata for @p Access.
2432
  void addAccessData(MemoryAccess *Access);
2433
2434
  /// Remove the metadata stored for @p Access.
2435
  void removeAccessData(MemoryAccess *Access);
2436
2437
  /// Return the scalar evolution.
2438
  ScalarEvolution *getSE() const;
2439
2440
  /// Return the dominator tree.
2441
2.68k
  DominatorTree *getDT() const { return DT; }
2442
2443
  /// Return the LoopInfo used for this Scop.
2444
2.68k
  LoopInfo *getLI() const { return Affinator.getLI(); }
2445
2446
  /// Get the count of parameters used in this Scop.
2447
  ///
2448
  /// @return The count of parameters used in this Scop.
2449
1.26k
  size_t getNumParams() const { return Parameters.size(); }
2450
2451
  /// Take a list of parameters and add the new ones to the scop.
2452
  void addParams(const ParameterSetTy &NewParameters);
2453
2454
  /// Return an iterator range containing the scop parameters.
2455
288
  iterator_range<ParameterSetTy::iterator> parameters() const {
2456
288
    return make_range(Parameters.begin(), Parameters.end());
2457
288
  }
2458
2459
  /// Return whether this scop is empty, i.e. contains no statements that
2460
  /// could be executed.
2461
1.18k
  bool isEmpty() const { return Stmts.empty(); }
2462
2463
0
  StringRef getName() {
2464
0
    if (!name)
2465
0
      name = R.getNameStr();
2466
0
    return *name;
2467
0
  }
2468
2469
  using array_iterator = ArrayInfoSetTy::iterator;
2470
  using const_array_iterator = ArrayInfoSetTy::const_iterator;
2471
  using array_range = iterator_range<ArrayInfoSetTy::iterator>;
2472
  using const_array_range = iterator_range<ArrayInfoSetTy::const_iterator>;
2473
2474
4.12k
  inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
2475
2476
4.12k
  inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
2477
2478
2.11k
  inline const_array_iterator array_begin() const {
2479
2.11k
    return ScopArrayInfoSet.begin();
2480
2.11k
  }
2481
2482
2.11k
  inline const_array_iterator array_end() const {
2483
2.11k
    return ScopArrayInfoSet.end();
2484
2.11k
  }
2485
2486
4.12k
  inline array_range arrays() {
2487
4.12k
    return array_range(array_begin(), array_end());
2488
4.12k
  }
2489
2490
2.11k
  inline const_array_range arrays() const {
2491
2.11k
    return const_array_range(array_begin(), array_end());
2492
2.11k
  }
2493
2494
  /// Return the isl_id that represents a certain parameter.
2495
  ///
2496
  /// @param Parameter A SCEV that was recognized as a Parameter.
2497
  ///
2498
  /// @return The corresponding isl_id or NULL otherwise.
2499
  isl::id getIdForParam(const SCEV *Parameter) const;
2500
2501
  /// Get the maximum region of this static control part.
2502
  ///
2503
  /// @return The maximum region of this static control part.
2504
30.9k
  inline const Region &getRegion() const { return R; }
2505
56.9k
  inline Region &getRegion() { return R; }
2506
2507
  /// Return the function this SCoP is in.
2508
6.43k
  Function &getFunction() const { return *R.getEntry()->getParent(); }
2509
2510
  /// Check if @p L is contained in the SCoP.
2511
11.8k
  bool contains(const Loop *L) const { return R.contains(L); }
2512
2513
  /// Check if @p BB is contained in the SCoP.
2514
29.8k
  bool contains(const BasicBlock *BB) const { return R.contains(BB); }
2515
2516
  /// Check if @p I is contained in the SCoP.
2517
6.14k
  bool contains(const Instruction *I) const { return R.contains(I); }
2518
2519
  /// Return the unique exit block of the SCoP.
2520
2.74k
  BasicBlock *getExit() const { return R.getExit(); }
2521
2522
  /// Return the unique exiting block of the SCoP if any.
2523
641
  BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
2524
2525
  /// Return the unique entry block of the SCoP.
2526
4.68k
  BasicBlock *getEntry() const { return R.getEntry(); }
2527
2528
  /// Return the unique entering block of the SCoP if any.
2529
872
  BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
2530
2531
  /// Return true if @p BB is the exit block of the SCoP.
2532
1.82k
  bool isExit(BasicBlock *BB) const { return getExit() == BB; }
2533
2534
  /// Return a range of all basic blocks in the SCoP.
2535
3.07k
  Region::block_range blocks() const { return R.blocks(); }
2536
2537
  /// Return true if and only if @p BB dominates the SCoP.
2538
  bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
2539
2540
  /// Get the maximum depth of the loop.
2541
  ///
2542
  /// @return The maximum depth of the loop.
2543
1.60k
  inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
2544
2545
  /// Return the invariant equivalence class for @p Val if any.
2546
  InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
2547
2548
  /// Return the set of invariant accesses.
2549
303
  InvariantEquivClassesTy &getInvariantAccesses() {
2550
303
    return InvariantEquivClasses;
2551
303
  }
2552
2553
  /// Check if the scop has any invariant access.
2554
0
  bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
2555
2556
  /// Mark the SCoP as optimized by the scheduler.
2557
35
  void markAsOptimized() { IsOptimized = true; }
2558
2559
  /// Check if the SCoP has been optimized by the scheduler.
2560
0
  bool isOptimized() const { return IsOptimized; }
2561
2562
  /// Mark the SCoP to be skipped by ScopPass passes.
2563
0
  void markAsToBeSkipped() { SkipScop = true; }
2564
2565
  /// Check if the SCoP is to be skipped by ScopPass passes.
2566
778
  bool isToBeSkipped() const { return SkipScop; }
2567
2568
  /// Return the ID of the Scop
2569
0
  int getID() const { return ID; }
2570
2571
  /// Get the name of the entry and exit blocks of this Scop.
2572
  ///
2573
  /// These along with the function name can uniquely identify a Scop.
2574
  ///
2575
  /// @return std::pair whose first element is the entry name & second element
2576
  ///         is the exit name.
2577
  std::pair<std::string, std::string> getEntryExitStr() const;
2578
2579
  /// Get the name of this Scop.
2580
  std::string getNameStr() const;
2581
2582
  /// Get the constraint on parameter of this Scop.
2583
  ///
2584
  /// @return The constraint on parameter of this Scop.
2585
  isl::set getContext() const;
2586
2587
  /// Return space of isl context parameters.
2588
  ///
2589
  /// Returns the set of context parameters that are currently constrained. In
2590
  /// case the full set of parameters is needed, see @getFullParamSpace.
2591
  isl::space getParamSpace() const;
2592
2593
  /// Return the full space of parameters.
2594
  ///
2595
  /// getParamSpace will only return the parameters of the context that are
2596
  /// actually constrained, whereas getFullParamSpace will return all
2597
  //  parameters. This is useful in cases, where we need to ensure all
2598
  //  parameters are available, as certain isl functions will abort if this is
2599
  //  not the case.
2600
  isl::space getFullParamSpace() const;
2601
2602
  /// Get the assumed context for this Scop.
2603
  ///
2604
  /// @return The assumed context of this Scop.
2605
  isl::set getAssumedContext() const;
2606
2607
  /// Return true if the optimized SCoP can be executed.
2608
  ///
2609
  /// In addition to the runtime check context this will also utilize the domain
2610
  /// constraints to decide it the optimized version can actually be executed.
2611
  ///
2612
  /// @returns True if the optimized SCoP can be executed.
2613
  bool hasFeasibleRuntimeContext() const;
2614
2615
  /// Check if the assumption in @p Set is trivial or not.
2616
  ///
2617
  /// @param Set  The relations between parameters that are assumed to hold.
2618
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2619
  ///             (needed/assumptions) or negative (invalid/restrictions).
2620
  ///
2621
  /// @returns True if the assumption @p Set is not trivial.
2622
  bool isEffectiveAssumption(isl::set Set, AssumptionSign Sign);
2623
2624
  /// Track and report an assumption.
2625
  ///
2626
  /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
2627
  /// -pass-remarks-analysis=polly-scops' to output the assumptions.
2628
  ///
2629
  /// @param Kind The assumption kind describing the underlying cause.
2630
  /// @param Set  The relations between parameters that are assumed to hold.
2631
  /// @param Loc  The location in the source that caused this assumption.
2632
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2633
  ///             (needed/assumptions) or negative (invalid/restrictions).
2634
  /// @param BB   The block in which this assumption was taken. Used to
2635
  ///             calculate hotness when emitting remark.
2636
  ///
2637
  /// @returns True if the assumption is not trivial.
2638
  bool trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2639
                       AssumptionSign Sign, BasicBlock *BB);
2640
2641
  /// Add assumptions to assumed context.
2642
  ///
2643
  /// The assumptions added will be assumed to hold during the execution of the
2644
  /// scop. However, as they are generally not statically provable, at code
2645
  /// generation time run-time checks will be generated that ensure the
2646
  /// assumptions hold.
2647
  ///
2648
  /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
2649
  ///          that assumptions do not change the set of statement instances
2650
  ///          executed.
2651
  ///
2652
  /// @param Kind The assumption kind describing the underlying cause.
2653
  /// @param Set  The relations between parameters that are assumed to hold.
2654
  /// @param Loc  The location in the source that caused this assumption.
2655
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2656
  ///             (needed/assumptions) or negative (invalid/restrictions).
2657
  /// @param BB   The block in which this assumption was taken. Used to
2658
  ///             calculate hotness when emitting remark.
2659
  void addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2660
                     AssumptionSign Sign, BasicBlock *BB);
2661
2662
  /// Record an assumption for later addition to the assumed context.
2663
  ///
2664
  /// This function will add the assumption to the RecordedAssumptions. This
2665
  /// collection will be added (@see addAssumption) to the assumed context once
2666
  /// all paramaters are known and the context is fully built.
2667
  ///
2668
  /// @param Kind The assumption kind describing the underlying cause.
2669
  /// @param Set  The relations between parameters that are assumed to hold.
2670
  /// @param Loc  The location in the source that caused this assumption.
2671
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2672
  ///             (needed/assumptions) or negative (invalid/restrictions).
2673
  /// @param BB   The block in which this assumption was taken. If it is
2674
  ///             set, the domain of that block will be used to simplify the
2675
  ///             actual assumption in @p Set once it is added. This is useful
2676
  ///             if the assumption was created prior to the domain.
2677
  void recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2678
                        AssumptionSign Sign, BasicBlock *BB = nullptr);
2679
2680
  /// Add all recorded assumptions to the assumed context.
2681
  void addRecordedAssumptions();
2682
2683
  /// Mark the scop as invalid.
2684
  ///
2685
  /// This method adds an assumption to the scop that is always invalid. As a
2686
  /// result, the scop will not be optimized later on. This function is commonly
2687
  /// called when a condition makes it impossible (or too compile time
2688
  /// expensive) to process this scop any further.
2689
  ///
2690
  /// @param Kind The assumption kind describing the underlying cause.
2691
  /// @param Loc  The location in the source that triggered .
2692
  /// @param BB   The BasicBlock where it was triggered.
2693
  void invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB = nullptr);
2694
2695
  /// Get the invalid context for this Scop.
2696
  ///
2697
  /// @return The invalid context of this Scop.
2698
  isl::set getInvalidContext() const;
2699
2700
  /// Return true if and only if the InvalidContext is trivial (=empty).
2701
445
  bool hasTrivialInvalidContext() const { return InvalidContext.is_empty(); }
2702
2703
  /// A vector of memory accesses that belong to an alias group.
2704
  using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2705
2706
  /// A vector of alias groups.
2707
  using AliasGroupVectorTy = SmallVector<Scop::AliasGroupTy, 4>;
2708
2709
  /// Build the alias checks for this SCoP.
2710
  bool buildAliasChecks(AliasAnalysis &AA);
2711
2712
  /// Build all alias groups for this SCoP.
2713
  ///
2714
  /// @returns True if __no__ error occurred, false otherwise.
2715
  bool buildAliasGroups(AliasAnalysis &AA);
2716
2717
  /// Build alias groups for all memory accesses in the Scop.
2718
  ///
2719
  /// Using the alias analysis and an alias set tracker we build alias sets
2720
  /// for all memory accesses inside the Scop. For each alias set we then map
2721
  /// the aliasing pointers back to the memory accesses we know, thus obtain
2722
  /// groups of memory accesses which might alias. We also collect the set of
2723
  /// arrays through which memory is written.
2724
  ///
2725
  /// @param AA A reference to the alias analysis.
2726
  ///
2727
  /// @returns A pair consistent of a vector of alias groups and a set of arrays
2728
  ///          through which memory is written.
2729
  std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2730
  buildAliasGroupsForAccesses(AliasAnalysis &AA);
2731
2732
  ///  Split alias groups by iteration domains.
2733
  ///
2734
  ///  We split each group based on the domains of the minimal/maximal accesses.
2735
  ///  That means two minimal/maximal accesses are only in a group if their
2736
  ///  access domains intersect. Otherwise, they are in different groups.
2737
  ///
2738
  ///  @param AliasGroups The alias groups to split
2739
  void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
2740
2741
  /// Build a given alias group and its access data.
2742
  ///
2743
  /// @param AliasGroup     The alias group to build.
2744
  /// @param HasWriteAccess A set of arrays through which memory is not only
2745
  ///                       read, but also written.
2746
  ///
2747
  /// @returns True if __no__ error occurred, false otherwise.
2748
  bool buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2749
                       DenseSet<const ScopArrayInfo *> HasWriteAccess);
2750
2751
  /// Return all alias groups for this SCoP.
2752
445
  const MinMaxVectorPairVectorTy &getAliasGroups() const {
2753
445
    return MinMaxAliasGroups;
2754
445
  }
2755
2756
  /// Get an isl string representing the context.
2757
  std::string getContextStr() const;
2758
2759
  /// Get an isl string representing the assumed context.
2760
  std::string getAssumedContextStr() const;
2761
2762
  /// Get an isl string representing the invalid context.
2763
  std::string getInvalidContextStr() const;
2764
2765
  /// Return the list of ScopStmts that represent the given @p BB.
2766
  ArrayRef<ScopStmt *> getStmtListFor(BasicBlock *BB) const;
2767
2768
  /// Get the statement to put a PHI WRITE into.
2769
  ///
2770
  /// @param U The operand of a PHINode.
2771
  ScopStmt *getIncomingStmtFor(const Use &U) const;
2772
2773
  /// Return the last statement representing @p BB.
2774
  ///
2775
  /// Of the sequence of statements that represent a @p BB, this is the last one
2776
  /// to be executed. It is typically used to determine which instruction to add
2777
  /// a MemoryKind::PHI WRITE to. For this purpose, it is not strictly required
2778
  /// to be executed last, only that the incoming value is available in it.
2779
  ScopStmt *getLastStmtFor(BasicBlock *BB) const;
2780
2781
  /// Return the ScopStmts that represents the Region @p R, or nullptr if
2782
  ///        it is not represented by any statement in this Scop.
2783
  ArrayRef<ScopStmt *> getStmtListFor(Region *R) const;
2784
2785
  /// Return the ScopStmts that represents @p RN; can return nullptr if
2786
  ///        the RegionNode is not within the SCoP or has been removed due to
2787
  ///        simplifications.
2788
  ArrayRef<ScopStmt *> getStmtListFor(RegionNode *RN) const;
2789
2790
  /// Return the ScopStmt an instruction belongs to, or nullptr if it
2791
  ///        does not belong to any statement in this Scop.
2792
4.93k
  ScopStmt *getStmtFor(Instruction *Inst) const {
2793
4.93k
    return InstStmtMap.lookup(Inst);
2794
4.93k
  }
2795
2796
  /// Return the number of statements in the SCoP.
2797
301
  size_t getSize() const { return Stmts.size(); }
2798
2799
  /// @name Statements Iterators
2800
  ///
2801
  /// These iterators iterate over all statements of this Scop.
2802
  //@{
2803
  using iterator = StmtSet::iterator;
2804
  using const_iterator = StmtSet::const_iterator;
2805
2806
13.4k
  iterator begin() { return Stmts.begin(); }
2807
13.4k
  iterator end() { return Stmts.end(); }
2808
13.0k
  const_iterator begin() const { return Stmts.begin(); }
2809
13.0k
  const_iterator end() const { return Stmts.end(); }
2810
2811
  using reverse_iterator = StmtSet::reverse_iterator;
2812
  using const_reverse_iterator = StmtSet::const_reverse_iterator;
2813
2814
0
  reverse_iterator rbegin() { return Stmts.rbegin(); }
2815
0
  reverse_iterator rend() { return Stmts.rend(); }
2816
0
  const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
2817
0
  const_reverse_iterator rend() const { return Stmts.rend(); }
2818
  //@}
2819
2820
  /// Return the set of required invariant loads.
2821
47.7k
  const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
2822
47.7k
    return DC.RequiredILS;
2823
47.7k
  }
2824
2825
  /// Add @p LI to the set of required invariant loads.
2826
0
  void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
2827
2828
  /// Return true if and only if @p LI is a required invariant load.
2829
56
  bool isRequiredInvariantLoad(LoadInst *LI) const {
2830
56
    return getRequiredInvariantLoads().count(LI);
2831
56
  }
2832
2833
  /// Return the set of boxed (thus overapproximated) loops.
2834
14.3k
  const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
2835
2836
  /// Return true if and only if @p R is a non-affine subregion.
2837
10.2k
  bool isNonAffineSubRegion(const Region *R) {
2838
10.2k
    return DC.NonAffineSubRegionSet.count(R);
2839
10.2k
  }
2840
2841
3.36k
  const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
2842
2843
  /// Return the (possibly new) ScopArrayInfo object for @p Access.
2844
  ///
2845
  /// @param ElementType The type of the elements stored in this array.
2846
  /// @param Kind        The kind of the array info object.
2847
  /// @param BaseName    The optional name of this memory reference.
2848
  ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
2849
                                          ArrayRef<const SCEV *> Sizes,
2850
                                          MemoryKind Kind,
2851
                                          const char *BaseName = nullptr);
2852
2853
  /// Create an array and return the corresponding ScopArrayInfo object.
2854
  ///
2855
  /// @param ElementType The type of the elements stored in this array.
2856
  /// @param BaseName    The name of this memory reference.
2857
  /// @param Sizes       The sizes of dimensions.
2858
  ScopArrayInfo *createScopArrayInfo(Type *ElementType,
2859
                                     const std::string &BaseName,
2860
                                     const std::vector<unsigned> &Sizes);
2861
2862
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2863
  ///
2864
  /// @param BasePtr   The base pointer the object has been stored for.
2865
  /// @param Kind      The kind of array info object.
2866
  ///
2867
  /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
2868
  ///          available.
2869
  const ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
2870
2871
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2872
  ///
2873
  /// @param BasePtr   The base pointer the object has been stored for.
2874
  /// @param Kind      The kind of array info object.
2875
  ///
2876
  /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
2877
  ///          available).
2878
  const ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
2879
2880
  /// Invalidate ScopArrayInfo object for base address.
2881
  ///
2882
  /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
2883
  /// @param Kind    The Kind of the ScopArrayInfo object.
2884
0
  void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
2885
0
    auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
2886
0
    if (It == ScopArrayInfoMap.end())
2887
0
      return;
2888
0
    ScopArrayInfoSet.remove(It->second.get());
2889
0
    ScopArrayInfoMap.erase(It);
2890
0
  }
2891
2892
  void setContext(isl::set NewContext);
2893
2894
  /// Align the parameters in the statement to the scop context
2895
  void realignParams();
2896
2897
  /// Return true if this SCoP can be profitably optimized.
2898
  ///
2899
  /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
2900
  ///                               as profitably optimizable.
2901
  ///
2902
  /// @return Whether this SCoP can be profitably optimized.
2903
  bool isProfitable(bool ScalarsAreUnprofitable) const;
2904
2905
  /// Return true if the SCoP contained at least one error block.
2906
1.14k
  bool hasErrorBlock() const { return HasErrorBlock; }
2907
2908
  /// Return true if the underlying region has a single exiting block.
2909
20.3k
  bool hasSingleExitEdge() const { return HasSingleExitEdge; }
2910
2911
  /// Print the static control part.
2912
  ///
2913
  /// @param OS The output stream the static control part is printed to.
2914
  /// @param PrintInstructions Whether to print the statement's instructions as
2915
  ///                          well.
2916
  void print(raw_ostream &OS, bool PrintInstructions) const;
2917
2918
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2919
  /// Print the ScopStmt to stderr.
2920
  void dump() const;
2921
#endif
2922
2923
  /// Get the isl context of this static control part.
2924
  ///
2925
  /// @return The isl context of this static control part.
2926
  isl::ctx getIslCtx() const;
2927
2928
  /// Directly return the shared_ptr of the context.
2929
1.92k
  const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
2930
2931
  /// Compute the isl representation for the SCEV @p E
2932
  ///
2933
  /// @param E  The SCEV that should be translated.
2934
  /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
2935
  ///           SCEVs known to not reference any loops in the SCoP can be
2936
  ///           passed without a @p BB.
2937
  /// @param NonNegative Flag to indicate the @p E has to be non-negative.
2938
  ///
2939
  /// Note that this function will always return a valid isl_pw_aff. However, if
2940
  /// the translation of @p E was deemed to complex the SCoP is invalidated and
2941
  /// a dummy value of appropriate dimension is returned. This allows to bail
2942
  /// for complex cases without "error handling code" needed on the users side.
2943
  PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
2944
                  bool NonNegative = false);
2945
2946
  /// Compute the isl representation for the SCEV @p E
2947
  ///
2948
  /// This function is like @see Scop::getPwAff() but strips away the invalid
2949
  /// domain part associated with the piecewise affine function.
2950
  isl::pw_aff getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr);
2951
2952
  /// Return the domain of @p Stmt.
2953
  ///
2954
  /// @param Stmt The statement for which the conditions should be returned.
2955
  isl::set getDomainConditions(const ScopStmt *Stmt) const;
2956
2957
  /// Return the domain of @p BB.
2958
  ///
2959
  /// @param BB The block for which the conditions should be returned.
2960
  isl::set getDomainConditions(BasicBlock *BB) const;
2961
2962
  /// Get a union set containing the iteration domains of all statements.
2963
  isl::union_set getDomains() const;
2964
2965
  /// Get a union map of all may-writes performed in the SCoP.
2966
  isl::union_map getMayWrites();
2967
2968
  /// Get a union map of all must-writes performed in the SCoP.
2969
  isl::union_map getMustWrites();
2970
2971
  /// Get a union map of all writes performed in the SCoP.
2972
  isl::union_map getWrites();
2973
2974
  /// Get a union map of all reads performed in the SCoP.
2975
  isl::union_map getReads();
2976
2977
  /// Get a union map of all memory accesses performed in the SCoP.
2978
  isl::union_map getAccesses();
2979
2980
  /// Get a union map of all memory accesses performed in the SCoP.
2981
  ///
2982
  /// @param Array The array to which the accesses should belong.
2983
  isl::union_map getAccesses(ScopArrayInfo *Array);
2984
2985
  /// Get the schedule of all the statements in the SCoP.
2986
  ///
2987
  /// @return The schedule of all the statements in the SCoP, if the schedule of
2988
  /// the Scop does not contain extension nodes, and nullptr, otherwise.
2989
  isl::union_map getSchedule() const;
2990
2991
  /// Get a schedule tree describing the schedule of all statements.
2992
  isl::schedule getScheduleTree() const;
2993
2994
  /// Update the current schedule
2995
  ///
2996
  /// NewSchedule The new schedule (given as a flat union-map).
2997
  void setSchedule(isl::union_map NewSchedule);
2998
2999
  /// Update the current schedule
3000
  ///
3001
  /// NewSchedule The new schedule (given as schedule tree).
3002
  void setScheduleTree(isl::schedule NewSchedule);
3003
3004
  /// Whether the schedule is the original schedule as derived from the CFG by
3005
  /// ScopBuilder.
3006
28
  bool isOriginalSchedule() const { return !ScheduleModified; }
3007
3008
  /// Intersects the domains of all statements in the SCoP.
3009
  ///
3010
  /// @return true if a change was made
3011
  bool restrictDomains(isl::union_set Domain);
3012
3013
  /// Get the depth of a loop relative to the outermost loop in the Scop.
3014
  ///
3015
  /// This will return
3016
  ///    0 if @p L is an outermost loop in the SCoP
3017
  ///   >0 for other loops in the SCoP
3018
  ///   -1 if @p L is nullptr or there is no outermost loop in the SCoP
3019
  int getRelativeLoopDepth(const Loop *L) const;
3020
3021
  /// Find the ScopArrayInfo associated with an isl Id
3022
  ///        that has name @p Name.
3023
  ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
3024
3025
  /// Check whether @p Schedule contains extension nodes.
3026
  ///
3027
  /// @return true if @p Schedule contains extension nodes.
3028
  static bool containsExtensionNode(isl::schedule Schedule);
3029
3030
  /// Simplify the SCoP representation.
3031
  ///
3032
  /// @param AfterHoisting Whether it is called after invariant load hoisting.
3033
  ///                      When true, also removes statements without
3034
  ///                      side-effects.
3035
  void simplifySCoP(bool AfterHoisting);
3036
3037
  /// Get the next free array index.
3038
  ///
3039
  /// This function returns a unique index which can be used to identify an
3040
  /// array.
3041
2.45k
  long getNextArrayIdx() { return ArrayIdx++; }
3042
3043
  /// Get the next free statement index.
3044
  ///
3045
  /// This function returns a unique index which can be used to identify a
3046
  /// statement.
3047
5.67k
  long getNextStmtIdx() { return StmtIdx++; }
3048
3049
  /// Return the MemoryAccess that writes an llvm::Value, represented by a
3050
  /// ScopArrayInfo.
3051
  ///
3052
  /// There can be at most one such MemoryAccess per llvm::Value in the SCoP.
3053
  /// Zero is possible for read-only values.
3054
  MemoryAccess *getValueDef(const ScopArrayInfo *SAI) const;
3055
3056
  /// Return all MemoryAccesses that us an llvm::Value, represented by a
3057
  /// ScopArrayInfo.
3058
  ArrayRef<MemoryAccess *> getValueUses(const ScopArrayInfo *SAI) const;
3059
3060
  /// Return the MemoryAccess that represents an llvm::PHINode.
3061
  ///
3062
  /// ExitPHIs's PHINode is not within the SCoPs. This function returns nullptr
3063
  /// for them.
3064
  MemoryAccess *getPHIRead(const ScopArrayInfo *SAI) const;
3065
3066
  /// Return all MemoryAccesses for all incoming statements of a PHINode,
3067
  /// represented by a ScopArrayInfo.
3068
  ArrayRef<MemoryAccess *> getPHIIncomings(const ScopArrayInfo *SAI) const;
3069
3070
  /// Return whether @p Inst has a use outside of this SCoP.
3071
  bool isEscaping(Instruction *Inst);
3072
3073
  struct ScopStatistics {
3074
    int NumAffineLoops = 0;
3075
    int NumBoxedLoops = 0;
3076
3077
    int NumValueWrites = 0;
3078
    int NumValueWritesInLoops = 0;
3079
    int NumPHIWrites = 0;
3080
    int NumPHIWritesInLoops = 0;
3081
    int NumSingletonWrites = 0;
3082
    int NumSingletonWritesInLoops = 0;
3083
  };
3084
3085
  /// Collect statistic about this SCoP.
3086
  ///
3087
  /// These are most commonly used for LLVM's static counters (Statistic.h) in
3088
  /// various places. If statistics are disabled, only zeros are returned to
3089
  /// avoid the overhead.
3090
  ScopStatistics getStatistics() const;
3091
};
3092
3093
/// Print Scop scop to raw_ostream OS.
3094
raw_ostream &operator<<(raw_ostream &OS, const Scop &scop);
3095
3096
/// The legacy pass manager's analysis pass to compute scop information
3097
///        for a region.
3098
class ScopInfoRegionPass : public RegionPass {
3099
  /// The Scop pointer which is used to construct a Scop.
3100
  std::unique_ptr<Scop> S;
3101
3102
public:
3103
  static char ID; // Pass identification, replacement for typeid
3104
3105
1.12k
  ScopInfoRegionPass() : RegionPass(ID) {}
3106
1.09k
  ~ScopInfoRegionPass() override = default;
3107
3108
  /// Build Scop object, the Polly IR of static control
3109
  ///        part for the current SESE-Region.
3110
  ///
3111
  /// @return If the current region is a valid for a static control part,
3112
  ///         return the Polly IR representing this static control part,
3113
  ///         return null otherwise.
3114
6.25k
  Scop *getScop() { return S.get(); }
3115
0
  const Scop *getScop() const { return S.get(); }
3116
3117
  /// Calculate the polyhedral scop information for a given Region.
3118
  bool runOnRegion(Region *R, RGPassManager &RGM) override;
3119
3120
4.09k
  void releaseMemory() override { S.reset(); }
3121
3122
  void print(raw_ostream &O, const Module *M = nullptr) const override;
3123
3124
  void getAnalysisUsage(AnalysisUsage &AU) const override;
3125
};
3126
3127
class ScopInfo {
3128
public:
3129
  using RegionToScopMapTy = MapVector<Region *, std::unique_ptr<Scop>>;
3130
  using reverse_iterator = RegionToScopMapTy::reverse_iterator;
3131
  using const_reverse_iterator = RegionToScopMapTy::const_reverse_iterator;
3132
  using iterator = RegionToScopMapTy::iterator;
3133
  using const_iterator = RegionToScopMapTy::const_iterator;
3134
3135
private:
3136
  /// A map of Region to its Scop object containing
3137
  ///        Polly IR of static control part.
3138
  RegionToScopMapTy RegionToScopMap;
3139
  const DataLayout &DL;
3140
  ScopDetection &SD;
3141
  ScalarEvolution &SE;
3142
  LoopInfo &LI;
3143
  AliasAnalysis &AA;
3144
  DominatorTree &DT;
3145
  AssumptionCache &AC;
3146
  OptimizationRemarkEmitter &ORE;
3147
3148
public:
3149
  ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
3150
           LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
3151
           AssumptionCache &AC, OptimizationRemarkEmitter &ORE);
3152
3153
  /// Get the Scop object for the given Region.
3154
  ///
3155
  /// @return If the given region is the maximal region within a scop, return
3156
  ///         the scop object. If the given region is a subregion, return a
3157
  ///         nullptr. Top level region containing the entry block of a function
3158
  ///         is not considered in the scop creation.
3159
0
  Scop *getScop(Region *R) const {
3160
0
    auto MapIt = RegionToScopMap.find(R);
3161
0
    if (MapIt != RegionToScopMap.end())
3162
0
      return MapIt->second.get();
3163
0
    return nullptr;
3164
0
  }
3165
3166
  /// Recompute the Scop-Information for a function.
3167
  ///
3168
  /// This invalidates any iterators.
3169
  void recompute();
3170
3171
  /// Handle invalidation explicitly
3172
  bool invalidate(Function &F, const PreservedAnalyses &PA,
3173
                  FunctionAnalysisManager::Invalidator &Inv);
3174
3175
82
  iterator begin() { return RegionToScopMap.begin(); }
3176
82
  iterator end() { return RegionToScopMap.end(); }
3177
0
  const_iterator begin() const { return RegionToScopMap.begin(); }
3178
0
  const_iterator end() const { return RegionToScopMap.end(); }
3179
0
  reverse_iterator rbegin() { return RegionToScopMap.rbegin(); }
3180
0
  reverse_iterator rend() { return RegionToScopMap.rend(); }
3181
0
  const_reverse_iterator rbegin() const { return RegionToScopMap.rbegin(); }
3182
0
  const_reverse_iterator rend() const { return RegionToScopMap.rend(); }
3183
1
  bool empty() const { return RegionToScopMap.empty(); }
3184
};
3185
3186
struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
3187
  static AnalysisKey Key;
3188
3189
  using Result = ScopInfo;
3190
3191
  Result run(Function &, FunctionAnalysisManager &);
3192
};
3193
3194
struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
3195
1
  ScopInfoPrinterPass(raw_ostream &OS) : Stream(OS) {}
3196
3197
  PreservedAnalyses run(Function &, FunctionAnalysisManager &);
3198
3199
  raw_ostream &Stream;
3200
};
3201
3202
//===----------------------------------------------------------------------===//
3203
/// The legacy pass manager's analysis pass to compute scop information
3204
///        for the whole function.
3205
///
3206
/// This pass will maintain a map of the maximal region within a scop to its
3207
/// scop object for all the feasible scops present in a function.
3208
/// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
3209
/// region pass manager.
3210
class ScopInfoWrapperPass : public FunctionPass {
3211
  std::unique_ptr<ScopInfo> Result;
3212
3213
public:
3214
44
  ScopInfoWrapperPass() : FunctionPass(ID) {}
3215
44
  ~ScopInfoWrapperPass() override = default;
3216
3217
  static char ID; // Pass identification, replacement for typeid
3218
3219
45
  ScopInfo *getSI() { return Result.get(); }
3220
0
  const ScopInfo *getSI() const { return Result.get(); }
3221
3222
  /// Calculate all the polyhedral scops for a given function.
3223
  bool runOnFunction(Function &F) override;
3224
3225
49
  void releaseMemory() override { Result.reset(); }
3226
3227
  void print(raw_ostream &O, const Module *M = nullptr) const override;
3228
3229
  void getAnalysisUsage(AnalysisUsage &AU) const override;
3230
};
3231
} // end namespace polly
3232
3233
#endif // POLLY_SCOPINFO_H