Coverage Report

Created: 2017-11-21 03:47

/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/SetVector.h"
29
#include "llvm/ADT/SmallVector.h"
30
#include "llvm/ADT/StringMap.h"
31
#include "llvm/ADT/StringRef.h"
32
#include "llvm/ADT/iterator_range.h"
33
#include "llvm/Analysis/RegionPass.h"
34
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
35
#include "llvm/IR/DebugLoc.h"
36
#include "llvm/IR/Instruction.h"
37
#include "llvm/IR/Instructions.h"
38
#include "llvm/IR/IntrinsicInst.h"
39
#include "llvm/IR/PassManager.h"
40
#include "llvm/IR/ValueHandle.h"
41
#include "llvm/Pass.h"
42
#include "llvm/Support/Casting.h"
43
#include "isl/isl-noexceptions.h"
44
#include <algorithm>
45
#include <cassert>
46
#include <cstddef>
47
#include <forward_list>
48
#include <functional>
49
#include <list>
50
#include <map>
51
#include <memory>
52
#include <string>
53
#include <tuple>
54
#include <utility>
55
#include <vector>
56
57
using namespace llvm;
58
59
namespace llvm {
60
61
class AssumptionCache;
62
class BasicBlock;
63
class DataLayout;
64
class DominatorTree;
65
class Function;
66
class Loop;
67
class LoopInfo;
68
class OptimizationRemarkEmitter;
69
class PassRegistry;
70
class raw_ostream;
71
class ScalarEvolution;
72
class SCEV;
73
class Type;
74
class Value;
75
76
void initializeScopInfoRegionPassPass(PassRegistry &);
77
void initializeScopInfoWrapperPassPass(PassRegistry &);
78
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
467
  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.75k
  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
390
  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.1k
  unsigned getNumberOfDimensions() const {
324
23.1k
    if (Kind == MemoryKind::PHI || 
Kind == MemoryKind::ExitPHI21.4k
||
325
23.1k
        
Kind == MemoryKind::Value21.1k
)
326
4.52k
      return 0;
327
18.6k
    return DimensionSizes.size();
328
18.6k
  }
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.38k
  const SCEV *getDimensionSize(unsigned Dim) const {
336
2.38k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
337
2.38k
    return DimensionSizes[Dim];
338
2.38k
  }
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.43k
  isl::pw_aff getDimensionSizePw(unsigned Dim) const {
346
4.43k
    assert(Dim < getNumberOfDimensions() && "Invalid dimension");
347
4.43k
    return DimensionSizesPw[Dim];
348
4.43k
  }
349
350
  /// Get the canonical element type of this array.
351
  ///
352
  /// @returns The canonical element type of this array.
353
3.80k
  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.07k
  MemoryKind getKind() const { return Kind; }
366
367
  /// Is this array info modeling an llvm::Value?
368
358
  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
595
  bool isPHIKind() const { return Kind == MemoryKind::PHI; }
381
382
  /// Is this array info modeling an MemoryKind::ExitPHI?
383
334
  bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
384
385
  /// Is this array info modeling an array?
386
773
  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
89
  void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
428
89
    DerivedSAIs.insert(DerivedSAI);
429
89
  }
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
491
  void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
787
491
    assert(!isRead());
788
491
    assert(isAnyPHIKind());
789
491
    Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
790
491
  }
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
240
  ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
799
240
    assert(isAnyPHIKind());
800
240
    return Incoming;
801
240
  }
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.07k
  bool isReductionLike() const { return RedType != RT_NONE; }
808
809
  /// Is this a read memory access?
810
25.8k
  bool isRead() const { return AccType == MemoryAccess::READ; }
811
812
  /// Is this a must-write memory access?
813
12.8k
  bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
814
815
  /// Is this a may-write memory access?
816
7.43k
  bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
817
818
  /// Is this a write memory access?
819
11.7k
  bool isWrite() const { return isMustWrite() || 
isMayWrite()6.08k
; }
820
821
  /// Is this a memory intrinsic access (memcpy, memset, memmove)?
822
481
  bool isMemoryIntrinsic() const {
823
481
    return isa<MemIntrinsic>(getAccessInstruction());
824
481
  }
825
826
  /// Check if a new access relation was imported or set by a pass.
827
23.7k
  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.4k
  isl::map getLatestAccessRelation() const {
840
17.4k
    return hasNewAccessRelation() ? 
getNewAccessRelation()520
841
17.4k
                                  : 
getOriginalAccessRelation()16.9k
;
842
17.4k
  }
843
844
  /// Old name of getLatestAccessRelation().
845
16.6k
  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.48k
  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.2k
  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.3k
  const ScopArrayInfo *getScopArrayInfo() const {
904
18.3k
    return getOriginalScopArrayInfo();
905
18.3k
  }
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.35k
  Type *getElementType() const { return ElementType; }
915
916
  /// Return the access value of this memory access.
917
3.50k
  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
42.7k
  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.92k
  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
356
  isl::set getInvalidDomain() const { return InvalidDomain; }
950
951
  /// Get the invalid context for this access.
952
356
  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.60k
  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
62.9k
  MemoryKind getOriginalKind() const {
982
62.9k
    assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
983
62.9k
           getOriginalScopArrayInfo()->getKind() == Kind);
984
62.9k
    return Kind;
985
62.9k
  }
986
987
  /// Return the kind considering a potential setNewAccessRelation.
988
2.07k
  MemoryKind getLatestKind() const {
989
2.07k
    return getLatestScopArrayInfo()->getKind();
990
2.07k
  }
991
992
  /// Whether this is an access of an explicit load or store in the IR.
993
15.6k
  bool isOriginalArrayKind() const {
994
15.6k
    return getOriginalKind() == MemoryKind::Array;
995
15.6k
  }
996
997
  /// Whether storage memory is either an custom .s2a/.phiops alloca
998
  /// (false) or an existing pointer into an array (true).
999
1.60k
  bool isLatestArrayKind() const {
1000
1.60k
    return getLatestKind() == MemoryKind::Array;
1001
1.60k
  }
1002
1003
  /// Old name of isOriginalArrayKind.
1004
11.9k
  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.69k
  bool isOriginalScalarKind() const {
1012
8.69k
    return getOriginalKind() != MemoryKind::Array;
1013
8.69k
  }
1014
1015
  /// Whether this access is an array to a scalar memory object, also
1016
  /// considering changes by setNewAccessRelation.
1017
280
  bool isLatestScalarKind() const {
1018
280
    return getLatestKind() != MemoryKind::Array;
1019
280
  }
1020
1021
  /// Old name of isOriginalScalarKind.
1022
7.68k
  bool isScalarKind() const { return isOriginalScalarKind(); }
1023
1024
  /// Was this MemoryAccess detected as a scalar dependences?
1025
15.1k
  bool isOriginalValueKind() const {
1026
15.1k
    return getOriginalKind() == MemoryKind::Value;
1027
15.1k
  }
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.39k
  bool isValueKind() const { return isOriginalValueKind(); }
1036
1037
  /// Was this MemoryAccess detected as a special PHI node access?
1038
14.1k
  bool isOriginalPHIKind() const {
1039
14.1k
    return getOriginalKind() == MemoryKind::PHI;
1040
14.1k
  }
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.68k
  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.31k
  bool isOriginalExitPHIKind() const {
1052
9.31k
    return getOriginalKind() == MemoryKind::ExitPHI;
1053
9.31k
  }
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.12k
  bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
1064
1065
  /// Was this access detected as one of the two PHI types?
1066
6.58k
  bool isOriginalAnyPHIKind() const {
1067
6.58k
    return isOriginalPHIKind() || 
isOriginalExitPHIKind()5.19k
;
1068
6.58k
  }
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.29k
  bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
1078
1079
  /// Get the statement that contains this memory access.
1080
25.5k
  ScopStmt *getStatement() const { return Statement; }
1081
1082
  /// Get the reduction type of this access
1083
2.36k
  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
580
  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.5k
  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, Loop *SurroundingLoop,
1199
           std::vector<Instruction *> Instructions, int Count);
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, 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.89k
  isl::set getInvalidDomain() const { return InvalidDomain; }
1360
1361
  /// Get the invalid context for this statement.
1362
239
  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
41.4k
  BasicBlock *getBasicBlock() const { return BB; }
1372
1373
  /// Return true if this statement represents a single basic block.
1374
54.4k
  bool isBlockStmt() const { return BB != nullptr; }
1375
1376
  /// Return true if this is a copy statement.
1377
843
  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.13k
  Region *getRegion() const { return R; }
1384
1385
  /// Return true if this statement represents a whole region.
1386
14.9k
  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.76k
  bool contains(const Loop *L) const {
1396
1.76k
    // Block statements never contain loops.
1397
1.76k
    if (isBlockStmt())
1398
1.65k
      return false;
1399
108
1400
108
    return getRegion()->contains(L);
1401
108
  }
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.6k
  Loop *getSurroundingLoop() const {
1436
20.6k
    assert(!isCopyStmt() &&
1437
20.6k
           "No surrounding loop for artificially created statements");
1438
20.6k
    return SurroundingLoop;
1439
20.6k
  }
1440
1441
  /// Return true if this statement does not contain any accesses.
1442
7.61k
  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.89k
  MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
1466
2.89k
    auto It = InstructionToAccess.find(Inst);
1467
2.89k
    if (It == InstructionToAccess.end())
1468
870
      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.89k
1481
2.89k
    return ArrayAccess;
1482
2.89k
  }
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.62k
  MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
1489
1.62k
    MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
1490
1.62k
1491
1.62k
    assert(ArrayAccess && "No array access found for instruction!");
1492
1.62k
    return *ArrayAccess;
1493
1.62k
  }
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
397
  MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
1499
397
    assert((isRegionStmt() && R->contains(Inst)) ||
1500
397
           (!isRegionStmt() && Inst->getParent() == BB));
1501
397
    return ValueWrites.lookup(Inst);
1502
397
  }
1503
1504
  /// Return the MemoryAccess that reloads a value, or nullptr if not
1505
  ///        existing, respectively not yet added.
1506
1.92k
  MemoryAccess *lookupValueReadOf(Value *Inst) const {
1507
1.92k
    return ValueReads.lookup(Inst);
1508
1.92k
  }
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
491
  MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
1520
491
    assert(isBlockStmt() || R->getExit() == PHI->getParent());
1521
491
    return PHIWrites.lookup(PHI);
1522
491
  }
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
128
  MemoryAccess *lookupInputAccessOf(Value *Val) const {
1532
128
    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
110
1540
110
    if (auto *InputMA = lookupValueReadOf(Val))
1541
63
      return InputMA;
1542
47
1543
47
    return nullptr;
1544
47
  }
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
  void removeSingleMemoryAccess(MemoryAccess *MA);
1563
1564
  using iterator = MemoryAccessVec::iterator;
1565
  using const_iterator = MemoryAccessVec::const_iterator;
1566
1567
28.2k
  iterator begin() { return MemAccs.begin(); }
1568
28.2k
  iterator end() { return MemAccs.end(); }
1569
43
  const_iterator begin() const { return MemAccs.begin(); }
1570
43
  const_iterator end() const { return MemAccs.end(); }
1571
5.16k
  size_t size() const { return MemAccs.size(); }
1572
1573
  unsigned getNumIterators() const;
1574
1575
35.9k
  Scop *getParent() { return &Parent; }
1576
1.25k
  const Scop *getParent() const { return &Parent; }
1577
1578
13.3k
  const std::vector<Instruction *> &getInstructions() const {
1579
13.3k
    return Instructions;
1580
13.3k
  }
1581
1582
  /// Set the list of instructions for this statement. It replaces the current
1583
  /// list.
1584
67
  void setInstructions(ArrayRef<Instruction *> Range) {
1585
67
    Instructions.assign(Range.begin(), Range.end());
1586
67
  }
1587
1588
67
  std::vector<Instruction *>::const_iterator insts_begin() const {
1589
67
    return Instructions.begin();
1590
67
  }
1591
1592
67
  std::vector<Instruction *>::const_iterator insts_end() const {
1593
67
    return Instructions.end();
1594
67
  }
1595
1596
  /// The range of instructions in this statement.
1597
0
  iterator_range<std::vector<Instruction *>::const_iterator> insts() const {
1598
0
    return {insts_begin(), insts_end()};
1599
0
  }
1600
1601
  /// Insert an instruction before all other instructions in this statement.
1602
33
  void prependInstruction(Instruction *Inst) {
1603
33
    Instructions.insert(Instructions.begin(), Inst);
1604
33
  }
1605
1606
  const char *getBaseName() const;
1607
1608
  /// Set the isl AST build.
1609
453
  void setAstBuild(isl::ast_build B) { Build = B; }
1610
1611
  /// Get the isl AST build.
1612
10
  isl::ast_build getAstBuild() const { return Build; }
1613
1614
  /// Restrict the domain of the statement.
1615
  ///
1616
  /// @param NewDomain The new statement domain.
1617
  void restrictDomain(isl::set NewDomain);
1618
1619
  /// Get the loop for a dimension.
1620
  ///
1621
  /// @param Dimension The dimension of the induction variable
1622
  /// @return The loop at a certain dimension.
1623
  Loop *getLoopForDimension(unsigned Dimension) const;
1624
1625
  /// Align the parameters in the statement to the scop context
1626
  void realignParams();
1627
1628
  /// Print the ScopStmt.
1629
  ///
1630
  /// @param OS                The output stream the ScopStmt is printed to.
1631
  /// @param PrintInstructions Whether to print the statement's instructions as
1632
  ///                          well.
1633
  void print(raw_ostream &OS, bool PrintInstructions) const;
1634
1635
  /// Print the instructions in ScopStmt.
1636
  ///
1637
  void printInstructions(raw_ostream &OS) const;
1638
1639
  /// Check whether there is a value read access for @p V in this statement, and
1640
  /// if not, create one.
1641
  ///
1642
  /// This allows to add MemoryAccesses after the initial creation of the Scop
1643
  /// by ScopBuilder.
1644
  ///
1645
  /// @return The already existing or newly created MemoryKind::Value READ
1646
  /// MemoryAccess.
1647
  ///
1648
  /// @see ScopBuilder::ensureValueRead(Value*,ScopStmt*)
1649
  MemoryAccess *ensureValueRead(Value *V);
1650
1651
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1652
  /// Print the ScopStmt to stderr.
1653
  void dump() const;
1654
#endif
1655
};
1656
1657
/// Print ScopStmt S to raw_ostream OS.
1658
raw_ostream &operator<<(raw_ostream &OS, const ScopStmt &S);
1659
1660
/// Static Control Part
1661
///
1662
/// A Scop is the polyhedral representation of a control flow region detected
1663
/// by the Scop detection. It is generated by translating the LLVM-IR and
1664
/// abstracting its effects.
1665
///
1666
/// A Scop consists of a set of:
1667
///
1668
///   * A set of statements executed in the Scop.
1669
///
1670
///   * A set of global parameters
1671
///   Those parameters are scalar integer values, which are constant during
1672
///   execution.
1673
///
1674
///   * A context
1675
///   This context contains information about the values the parameters
1676
///   can take and relations between different parameters.
1677
class Scop {
1678
public:
1679
  /// Type to represent a pair of minimal/maximal access to an array.
1680
  using MinMaxAccessTy = std::pair<isl::pw_multi_aff, isl::pw_multi_aff>;
1681
1682
  /// Vector of minimal/maximal accesses to different arrays.
1683
  using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
1684
1685
  /// Pair of minimal/maximal access vectors representing
1686
  /// read write and read only accesses
1687
  using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
1688
1689
  /// Vector of pair of minimal/maximal access vectors representing
1690
  /// non read only and read only accesses for each alias group.
1691
  using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
1692
1693
private:
1694
  friend class ScopBuilder;
1695
1696
  /// Isl context.
1697
  ///
1698
  /// We need a shared_ptr with reference counter to delete the context when all
1699
  /// isl objects are deleted. We will distribute the shared_ptr to all objects
1700
  /// that use the context to create isl objects, and increase the reference
1701
  /// counter. By doing this, we guarantee that the context is deleted when we
1702
  /// delete the last object that creates isl objects with the context. This
1703
  /// declaration needs to be the first in class to gracefully destroy all isl
1704
  /// objects before the context.
1705
  std::shared_ptr<isl_ctx> IslCtx;
1706
1707
  ScalarEvolution *SE;
1708
  DominatorTree *DT;
1709
1710
  /// The underlying Region.
1711
  Region &R;
1712
1713
  /// The name of the SCoP (identical to the regions name)
1714
  std::string name;
1715
1716
  /// The ID to be assigned to the next Scop in a function
1717
  static int NextScopID;
1718
1719
  /// The name of the function currently under consideration
1720
  static std::string CurrentFunc;
1721
1722
  // Access functions of the SCoP.
1723
  //
1724
  // This owns all the MemoryAccess objects of the Scop created in this pass.
1725
  AccFuncVector AccessFunctions;
1726
1727
  /// Flag to indicate that the scheduler actually optimized the SCoP.
1728
  bool IsOptimized = false;
1729
1730
  /// True if the underlying region has a single exiting block.
1731
  bool HasSingleExitEdge;
1732
1733
  /// Flag to remember if the SCoP contained an error block or not.
1734
  bool HasErrorBlock = false;
1735
1736
  /// Max loop depth.
1737
  unsigned MaxLoopDepth = 0;
1738
1739
  /// Number of copy statements.
1740
  unsigned CopyStmtsNum = 0;
1741
1742
  /// Flag to indicate if the Scop is to be skipped.
1743
  bool SkipScop = false;
1744
1745
  using StmtSet = std::list<ScopStmt>;
1746
1747
  /// The statements in this Scop.
1748
  StmtSet Stmts;
1749
1750
  /// Parameters of this Scop
1751
  ParameterSetTy Parameters;
1752
1753
  /// Mapping from parameters to their ids.
1754
  DenseMap<const SCEV *, isl::id> ParameterIds;
1755
1756
  /// The context of the SCoP created during SCoP detection.
1757
  ScopDetection::DetectionContext &DC;
1758
1759
  /// OptimizationRemarkEmitter object for displaying diagnostic remarks
1760
  OptimizationRemarkEmitter &ORE;
1761
1762
  /// A map from basic blocks to vector of SCoP statements. Currently this
1763
  /// vector comprises only of a single statement.
1764
  DenseMap<BasicBlock *, std::vector<ScopStmt *>> StmtMap;
1765
1766
  /// A map from instructions to SCoP statements.
1767
  DenseMap<Instruction *, ScopStmt *> InstStmtMap;
1768
1769
  /// A map from basic blocks to their domains.
1770
  DenseMap<BasicBlock *, isl::set> DomainMap;
1771
1772
  /// Constraints on parameters.
1773
  isl::set Context = nullptr;
1774
1775
  /// The affinator used to translate SCEVs to isl expressions.
1776
  SCEVAffinator Affinator;
1777
1778
  using ArrayInfoMapTy =
1779
      std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
1780
               std::unique_ptr<ScopArrayInfo>>;
1781
1782
  using ArrayNameMapTy = StringMap<std::unique_ptr<ScopArrayInfo>>;
1783
1784
  using ArrayInfoSetTy = SetVector<ScopArrayInfo *>;
1785
1786
  /// A map to remember ScopArrayInfo objects for all base pointers.
1787
  ///
1788
  /// As PHI nodes may have two array info objects associated, we add a flag
1789
  /// that distinguishes between the PHI node specific ArrayInfo object
1790
  /// and the normal one.
1791
  ArrayInfoMapTy ScopArrayInfoMap;
1792
1793
  /// A map to remember ScopArrayInfo objects for all names of memory
1794
  ///        references.
1795
  ArrayNameMapTy ScopArrayNameMap;
1796
1797
  /// A set to remember ScopArrayInfo objects.
1798
  /// @see Scop::ScopArrayInfoMap
1799
  ArrayInfoSetTy ScopArrayInfoSet;
1800
1801
  /// The assumptions under which this scop was built.
1802
  ///
1803
  /// When constructing a scop sometimes the exact representation of a statement
1804
  /// or condition would be very complex, but there is a common case which is a
1805
  /// lot simpler, but which is only valid under certain assumptions. The
1806
  /// assumed context records the assumptions taken during the construction of
1807
  /// this scop and that need to be code generated as a run-time test.
1808
  isl::set AssumedContext;
1809
1810
  /// The restrictions under which this SCoP was built.
1811
  ///
1812
  /// The invalid context is similar to the assumed context as it contains
1813
  /// constraints over the parameters. However, while we need the constraints
1814
  /// in the assumed context to be "true" the constraints in the invalid context
1815
  /// need to be "false". Otherwise they behave the same.
1816
  isl::set InvalidContext;
1817
1818
  /// Helper struct to remember assumptions.
1819
  struct Assumption {
1820
    /// The kind of the assumption (e.g., WRAPPING).
1821
    AssumptionKind Kind;
1822
1823
    /// Flag to distinguish assumptions and restrictions.
1824
    AssumptionSign Sign;
1825
1826
    /// The valid/invalid context if this is an assumption/restriction.
1827
    isl::set Set;
1828
1829
    /// The location that caused this assumption.
1830
    DebugLoc Loc;
1831
1832
    /// An optional block whose domain can simplify the assumption.
1833
    BasicBlock *BB;
1834
  };
1835
1836
  /// Collection to hold taken assumptions.
1837
  ///
1838
  /// There are two reasons why we want to record assumptions first before we
1839
  /// add them to the assumed/invalid context:
1840
  ///   1) If the SCoP is not profitable or otherwise invalid without the
1841
  ///      assumed/invalid context we do not have to compute it.
1842
  ///   2) Information about the context are gathered rather late in the SCoP
1843
  ///      construction (basically after we know all parameters), thus the user
1844
  ///      might see overly complicated assumptions to be taken while they will
1845
  ///      only be simplified later on.
1846
  SmallVector<Assumption, 8> RecordedAssumptions;
1847
1848
  /// The schedule of the SCoP
1849
  ///
1850
  /// The schedule of the SCoP describes the execution order of the statements
1851
  /// in the scop by assigning each statement instance a possibly
1852
  /// multi-dimensional execution time. The schedule is stored as a tree of
1853
  /// schedule nodes.
1854
  ///
1855
  /// The most common nodes in a schedule tree are so-called band nodes. Band
1856
  /// nodes map statement instances into a multi dimensional schedule space.
1857
  /// This space can be seen as a multi-dimensional clock.
1858
  ///
1859
  /// Example:
1860
  ///
1861
  /// <S,(5,4)>  may be mapped to (5,4) by this schedule:
1862
  ///
1863
  /// s0 = i (Year of execution)
1864
  /// s1 = j (Day of execution)
1865
  ///
1866
  /// or to (9, 20) by this schedule:
1867
  ///
1868
  /// s0 = i + j (Year of execution)
1869
  /// s1 = 20 (Day of execution)
1870
  ///
1871
  /// The order statement instances are executed is defined by the
1872
  /// schedule vectors they are mapped to. A statement instance
1873
  /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
1874
  /// the schedule vector of A is lexicographic smaller than the schedule
1875
  /// vector of B.
1876
  ///
1877
  /// Besides band nodes, schedule trees contain additional nodes that specify
1878
  /// a textual ordering between two subtrees or filter nodes that filter the
1879
  /// set of statement instances that will be scheduled in a subtree. There
1880
  /// are also several other nodes. A full description of the different nodes
1881
  /// in a schedule tree is given in the isl manual.
1882
  isl::schedule Schedule = nullptr;
1883
1884
  /// The set of minimal/maximal accesses for each alias group.
1885
  ///
1886
  /// When building runtime alias checks we look at all memory instructions and
1887
  /// build so called alias groups. Each group contains a set of accesses to
1888
  /// different base arrays which might alias with each other. However, between
1889
  /// alias groups there is no aliasing possible.
1890
  ///
1891
  /// In a program with int and float pointers annotated with tbaa information
1892
  /// we would probably generate two alias groups, one for the int pointers and
1893
  /// one for the float pointers.
1894
  ///
1895
  /// During code generation we will create a runtime alias check for each alias
1896
  /// group to ensure the SCoP is executed in an alias free environment.
1897
  MinMaxVectorPairVectorTy MinMaxAliasGroups;
1898
1899
  /// Mapping from invariant loads to the representing invariant load of
1900
  ///        their equivalence class.
1901
  ValueToValueMap InvEquivClassVMap;
1902
1903
  /// List of invariant accesses.
1904
  InvariantEquivClassesTy InvariantEquivClasses;
1905
1906
  /// The smallest array index not yet assigned.
1907
  long ArrayIdx = 0;
1908
1909
  /// The smallest statement index not yet assigned.
1910
  long StmtIdx = 0;
1911
1912
  /// A number that uniquely represents a Scop within its function
1913
  const int ID;
1914
1915
  /// Map of values to the MemoryAccess that writes its definition.
1916
  ///
1917
  /// There must be at most one definition per llvm::Instruction in a SCoP.
1918
  DenseMap<Value *, MemoryAccess *> ValueDefAccs;
1919
1920
  /// Map of values to the MemoryAccess that reads a PHI.
1921
  DenseMap<PHINode *, MemoryAccess *> PHIReadAccs;
1922
1923
  /// List of all uses (i.e. read MemoryAccesses) for a MemoryKind::Value
1924
  /// scalar.
1925
  DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>> ValueUseAccs;
1926
1927
  /// List of all incoming values (write MemoryAccess) of a MemoryKind::PHI or
1928
  /// MemoryKind::ExitPHI scalar.
1929
  DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>>
1930
      PHIIncomingAccs;
1931
1932
  /// Return the ID for a new Scop within a function
1933
  static int getNextID(std::string ParentFunc);
1934
1935
  /// Scop constructor; invoked from ScopBuilder::buildScop.
1936
  Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT,
1937
       ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE);
1938
1939
  //@}
1940
1941
  /// Initialize this ScopBuilder.
1942
  void init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
1943
            LoopInfo &LI);
1944
1945
  /// Propagate domains that are known due to graph properties.
1946
  ///
1947
  /// As a CFG is mostly structured we use the graph properties to propagate
1948
  /// domains without the need to compute all path conditions. In particular, if
1949
  /// a block A dominates a block B and B post-dominates A we know that the
1950
  /// domain of B is a superset of the domain of A. As we do not have
1951
  /// post-dominator information available here we use the less precise region
1952
  /// information. Given a region R, we know that the exit is always executed if
1953
  /// the entry was executed, thus the domain of the exit is a superset of the
1954
  /// domain of the entry. In case the exit can only be reached from within the
1955
  /// region the domains are in fact equal. This function will use this property
1956
  /// to avoid the generation of condition constraints that determine when a
1957
  /// branch is taken. If @p BB is a region entry block we will propagate its
1958
  /// domain to the region exit block. Additionally, we put the region exit
1959
  /// block in the @p FinishedExitBlocks set so we can later skip edges from
1960
  /// within the region to that block.
1961
  ///
1962
  /// @param BB                 The block for which the domain is currently
1963
  ///                           propagated.
1964
  /// @param BBLoop             The innermost affine loop surrounding @p BB.
1965
  /// @param FinishedExitBlocks Set of region exits the domain was set for.
1966
  /// @param LI                 The LoopInfo for the current function.
1967
  /// @param InvalidDomainMap   BB to InvalidDomain map for the BB of current
1968
  ///                           region.
1969
  void propagateDomainConstraintsToRegionExit(
1970
      BasicBlock *BB, Loop *BBLoop,
1971
      SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
1972
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1973
1974
  /// Compute the union of predecessor domains for @p BB.
1975
  ///
1976
  /// To compute the union of all domains of predecessors of @p BB this
1977
  /// function applies similar reasoning on the CFG structure as described for
1978
  ///   @see propagateDomainConstraintsToRegionExit
1979
  ///
1980
  /// @param BB     The block for which the predecessor domains are collected.
1981
  /// @param Domain The domain under which BB is executed.
1982
  /// @param DT     The DominatorTree for the current function.
1983
  /// @param LI     The LoopInfo for the current function.
1984
  ///
1985
  /// @returns The domain under which @p BB is executed.
1986
  isl::set getPredecessorDomainConstraints(BasicBlock *BB, isl::set Domain,
1987
                                           DominatorTree &DT, LoopInfo &LI);
1988
1989
  /// Add loop carried constraints to the header block of the loop @p L.
1990
  ///
1991
  /// @param L                The loop to process.
1992
  /// @param LI               The LoopInfo for the current function.
1993
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1994
  ///                         region.
1995
  ///
1996
  /// @returns True if there was no problem and false otherwise.
1997
  bool addLoopBoundsToHeaderDomain(
1998
      Loop *L, LoopInfo &LI,
1999
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2000
2001
  /// Compute the branching constraints for each basic block in @p R.
2002
  ///
2003
  /// @param R                The region we currently build branching conditions
2004
  ///                         for.
2005
  /// @param DT               The DominatorTree for the current function.
2006
  /// @param LI               The LoopInfo for the current function.
2007
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2008
  ///                         region.
2009
  ///
2010
  /// @returns True if there was no problem and false otherwise.
2011
  bool buildDomainsWithBranchConstraints(
2012
      Region *R, DominatorTree &DT, LoopInfo &LI,
2013
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2014
2015
  /// Propagate the domain constraints through the region @p R.
2016
  ///
2017
  /// @param R                The region we currently build branching conditions
2018
  /// for.
2019
  /// @param DT               The DominatorTree for the current function.
2020
  /// @param LI               The LoopInfo for the current function.
2021
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2022
  ///                         region.
2023
  ///
2024
  /// @returns True if there was no problem and false otherwise.
2025
  bool propagateDomainConstraints(
2026
      Region *R, DominatorTree &DT, LoopInfo &LI,
2027
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2028
2029
  /// Propagate invalid domains of statements through @p R.
2030
  ///
2031
  /// This method will propagate invalid statement domains through @p R and at
2032
  /// the same time add error block domains to them. Additionally, the domains
2033
  /// of error statements and those only reachable via error statements will be
2034
  /// replaced by an empty set. Later those will be removed completely.
2035
  ///
2036
  /// @param R                The currently traversed region.
2037
  /// @param DT               The DominatorTree for the current function.
2038
  /// @param LI               The LoopInfo for the current function.
2039
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2040
  ///                         region.
2041
  //
2042
  /// @returns True if there was no problem and false otherwise.
2043
  bool propagateInvalidStmtDomains(
2044
      Region *R, DominatorTree &DT, LoopInfo &LI,
2045
      DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2046
2047
  /// Compute the domain for each basic block in @p R.
2048
  ///
2049
  /// @param R                The region we currently traverse.
2050
  /// @param DT               The DominatorTree for the current function.
2051
  /// @param LI               The LoopInfo for the current function.
2052
  /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2053
  ///                         region.
2054
  ///
2055
  /// @returns True if there was no problem and false otherwise.
2056
  bool buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2057
                    DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2058
2059
  /// Add parameter constraints to @p C that imply a non-empty domain.
2060
  isl::set addNonEmptyDomainConstraints(isl::set C) const;
2061
2062
  /// Return the access for the base ptr of @p MA if any.
2063
  MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
2064
2065
  /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
2066
  bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
2067
2068
  /// Create equivalence classes for required invariant accesses.
2069
  ///
2070
  /// These classes will consolidate multiple required invariant loads from the
2071
  /// same address in order to keep the number of dimensions in the SCoP
2072
  /// description small. For each such class equivalence class only one
2073
  /// representing element, hence one required invariant load, will be chosen
2074
  /// and modeled as parameter. The method
2075
  /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
2076
  /// equivalence class with the representing element that is modeled. As a
2077
  /// consequence Scop::getIdForParam() will only return an id for the
2078
  /// representing element of each equivalence class, thus for each required
2079
  /// invariant location.
2080
  void buildInvariantEquivalenceClasses();
2081
2082
  /// Return the context under which the access cannot be hoisted.
2083
  ///
2084
  /// @param Access The access to check.
2085
  /// @param Writes The set of all memory writes in the scop.
2086
  ///
2087
  /// @return Return the context under which the access cannot be hoisted or a
2088
  ///         nullptr if it cannot be hoisted at all.
2089
  isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
2090
2091
  /// Verify that all required invariant loads have been hoisted.
2092
  ///
2093
  /// Invariant load hoisting is not guaranteed to hoist all loads that were
2094
  /// assumed to be scop invariant during scop detection. This function checks
2095
  /// for cases where the hoisting failed, but where it would have been
2096
  /// necessary for our scop modeling to be correct. In case of insufficient
2097
  /// hoisting the scop is marked as invalid.
2098
  ///
2099
  /// In the example below Bound[1] is required to be invariant:
2100
  ///
2101
  /// for (int i = 1; i < Bound[0]; i++)
2102
  ///   for (int j = 1; j < Bound[1]; j++)
2103
  ///     ...
2104
  void verifyInvariantLoads();
2105
2106
  /// Hoist invariant memory loads and check for required ones.
2107
  ///
2108
  /// We first identify "common" invariant loads, thus loads that are invariant
2109
  /// and can be hoisted. Then we check if all required invariant loads have
2110
  /// been identified as (common) invariant. A load is a required invariant load
2111
  /// if it was assumed to be invariant during SCoP detection, e.g., to assume
2112
  /// loop bounds to be affine or runtime alias checks to be placeable. In case
2113
  /// a required invariant load was not identified as (common) invariant we will
2114
  /// drop this SCoP. An example for both "common" as well as required invariant
2115
  /// loads is given below:
2116
  ///
2117
  /// for (int i = 1; i < *LB[0]; i++)
2118
  ///   for (int j = 1; j < *LB[1]; j++)
2119
  ///     A[i][j] += A[0][0] + (*V);
2120
  ///
2121
  /// Common inv. loads: V, A[0][0], LB[0], LB[1]
2122
  /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
2123
  void hoistInvariantLoads();
2124
2125
  /// Canonicalize arrays with base pointers from the same equivalence class.
2126
  ///
2127
  /// Some context: in our normal model we assume that each base pointer is
2128
  /// related to a single specific memory region, where memory regions
2129
  /// associated with different base pointers are disjoint. Consequently we do
2130
  /// not need to compute additional data dependences that model possible
2131
  /// overlaps of these memory regions. To verify our assumption we compute
2132
  /// alias checks that verify that modeled arrays indeed do not overlap. In
2133
  /// case an overlap is detected the runtime check fails and we fall back to
2134
  /// the original code.
2135
  ///
2136
  /// In case of arrays where the base pointers are know to be identical,
2137
  /// because they are dynamically loaded by accesses that are in the same
2138
  /// invariant load equivalence class, such run-time alias check would always
2139
  /// be false.
2140
  ///
2141
  /// This function makes sure that we do not generate consistently failing
2142
  /// run-time checks for code that contains distinct arrays with known
2143
  /// equivalent base pointers. It identifies for each invariant load
2144
  /// equivalence class a single canonical array and canonicalizes all memory
2145
  /// accesses that reference arrays that have base pointers that are known to
2146
  /// be equal to the base pointer of such a canonical array to this canonical
2147
  /// array.
2148
  ///
2149
  /// We currently do not canonicalize arrays for which certain memory accesses
2150
  /// have been hoisted as loop invariant.
2151
  void canonicalizeDynamicBasePtrs();
2152
2153
  /// Check if @p MA can always be hoisted without execution context.
2154
  bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
2155
                          bool MAInvalidCtxIsEmpty,
2156
                          bool NonHoistableCtxIsEmpty);
2157
2158
  /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
2159
  void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
2160
2161
  /// Create an id for @p Param and store it in the ParameterIds map.
2162
  void createParameterId(const SCEV *Param);
2163
2164
  /// Build the Context of the Scop.
2165
  void buildContext();
2166
2167
  /// Add user provided parameter constraints to context (source code).
2168
  void addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
2169
                          DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2170
2171
  /// Add user provided parameter constraints to context (command line).
2172
  void addUserContext();
2173
2174
  /// Add the bounds of the parameters to the context.
2175
  void addParameterBounds();
2176
2177
  /// Simplify the assumed and invalid context.
2178
  void simplifyContexts();
2179
2180
  /// Get the representing SCEV for @p S if applicable, otherwise @p S.
2181
  ///
2182
  /// Invariant loads of the same location are put in an equivalence class and
2183
  /// only one of them is chosen as a representing element that will be
2184
  /// modeled as a parameter. The others have to be normalized, i.e.,
2185
  /// replaced by the representing element of their equivalence class, in order
2186
  /// to get the correct parameter value, e.g., in the SCEVAffinator.
2187
  ///
2188
  /// @param S The SCEV to normalize.
2189
  ///
2190
  /// @return The representing SCEV for invariant loads or @p S if none.
2191
  const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S) const;
2192
2193
  /// Create a new SCoP statement for @p BB.
2194
  ///
2195
  /// A new statement for @p BB will be created and added to the statement
2196
  /// vector
2197
  /// and map.
2198
  ///
2199
  /// @param BB              The basic block we build the statement for.
2200
  /// @param SurroundingLoop The loop the created statement is contained in.
2201
  /// @param Instructions    The instructions in the statement.
2202
  /// @param Count           The index of the created statement in @p BB.
2203
  void addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
2204
                   std::vector<Instruction *> Instructions, int Count);
2205
2206
  /// Create a new SCoP statement for @p R.
2207
  ///
2208
  /// A new statement for @p R will be created and added to the statement vector
2209
  /// and map.
2210
  ///
2211
  /// @param R                      The region we build the statement for.
2212
  /// @param SurroundingLoop        The loop the created statement is contained
2213
  ///                               in.
2214
  /// @param EntryBlockInstructions The (interesting) instructions in the
2215
  ///                               entry block of the region statement.
2216
  void addScopStmt(Region *R, Loop *SurroundingLoop,
2217
                   std::vector<Instruction *> EntryBlockInstructions);
2218
2219
  /// Update access dimensionalities.
2220
  ///
2221
  /// When detecting memory accesses different accesses to the same array may
2222
  /// have built with different dimensionality, as outer zero-values dimensions
2223
  /// may not have been recognized as separate dimensions. This function goes
2224
  /// again over all memory accesses and updates their dimensionality to match
2225
  /// the dimensionality of the underlying ScopArrayInfo object.
2226
  void updateAccessDimensionality();
2227
2228
  /// Fold size constants to the right.
2229
  ///
2230
  /// In case all memory accesses in a given dimension are multiplied with a
2231
  /// common constant, we can remove this constant from the individual access
2232
  /// functions and move it to the size of the memory access. We do this as this
2233
  /// increases the size of the innermost dimension, consequently widens the
2234
  /// valid range the array subscript in this dimension can evaluate to, and
2235
  /// as a result increases the likelihood that our delinearization is
2236
  /// correct.
2237
  ///
2238
  /// Example:
2239
  ///
2240
  ///    A[][n]
2241
  ///    S[i,j] -> A[2i][2j+1]
2242
  ///    S[i,j] -> A[2i][2j]
2243
  ///
2244
  ///    =>
2245
  ///
2246
  ///    A[][2n]
2247
  ///    S[i,j] -> A[i][2j+1]
2248
  ///    S[i,j] -> A[i][2j]
2249
  ///
2250
  /// Constants in outer dimensions can arise when the elements of a parametric
2251
  /// multi-dimensional array are not elementary data types, but e.g.,
2252
  /// structures.
2253
  void foldSizeConstantsToRight();
2254
2255
  /// Fold memory accesses to handle parametric offset.
2256
  ///
2257
  /// As a post-processing step, we 'fold' memory accesses to parametric
2258
  /// offsets in the access functions. @see MemoryAccess::foldAccess for
2259
  /// details.
2260
  void foldAccessRelations();
2261
2262
  /// Assume that all memory accesses are within bounds.
2263
  ///
2264
  /// After we have built a model of all memory accesses, we need to assume
2265
  /// that the model we built matches reality -- aka. all modeled memory
2266
  /// accesses always remain within bounds. We do this as last step, after
2267
  /// all memory accesses have been modeled and canonicalized.
2268
  void assumeNoOutOfBounds();
2269
2270
  /// Remove statements from the list of scop statements.
2271
  ///
2272
  /// @param ShouldDelete A function that returns true if the statement passed
2273
  ///                     to it should be deleted.
2274
  void removeStmts(std::function<bool(ScopStmt &)> ShouldDelete);
2275
2276
  /// Removes @p Stmt from the StmtMap.
2277
  void removeFromStmtMap(ScopStmt &Stmt);
2278
2279
  /// Removes all statements where the entry block of the statement does not
2280
  /// have a corresponding domain in the domain map.
2281
  void removeStmtNotInDomainMap();
2282
2283
  /// Mark arrays that have memory accesses with FortranArrayDescriptor.
2284
  void markFortranArrays();
2285
2286
  /// Finalize all access relations.
2287
  ///
2288
  /// When building up access relations, temporary access relations that
2289
  /// correctly represent each individual access are constructed. However, these
2290
  /// access relations can be inconsistent or non-optimal when looking at the
2291
  /// set of accesses as a whole. This function finalizes the memory accesses
2292
  /// and constructs a globally consistent state.
2293
  void finalizeAccesses();
2294
2295
  /// Construct the schedule of this SCoP.
2296
  ///
2297
  /// @param LI The LoopInfo for the current function.
2298
  void buildSchedule(LoopInfo &LI);
2299
2300
  /// A loop stack element to keep track of per-loop information during
2301
  ///        schedule construction.
2302
  using LoopStackElementTy = struct LoopStackElement {
2303
    // The loop for which we keep information.
2304
    Loop *L;
2305
2306
    // The (possibly incomplete) schedule for this loop.
2307
    isl::schedule Schedule;
2308
2309
    // The number of basic blocks in the current loop, for which a schedule has
2310
    // already been constructed.
2311
    unsigned NumBlocksProcessed;
2312
2313
    LoopStackElement(Loop *L, isl::schedule S, unsigned NumBlocksProcessed)
2314
2.75k
        : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
2315
  };
2316
2317
  /// The loop stack used for schedule construction.
2318
  ///
2319
  /// The loop stack keeps track of schedule information for a set of nested
2320
  /// loops as well as an (optional) 'nullptr' loop that models the outermost
2321
  /// schedule dimension. The loops in a loop stack always have a parent-child
2322
  /// relation where the loop at position n is the parent of the loop at
2323
  /// position n + 1.
2324
  using LoopStackTy = SmallVector<LoopStackElementTy, 4>;
2325
2326
  /// Construct schedule information for a given Region and add the
2327
  ///        derived information to @p LoopStack.
2328
  ///
2329
  /// Given a Region we derive schedule information for all RegionNodes
2330
  /// contained in this region ensuring that the assigned execution times
2331
  /// correctly model the existing control flow relations.
2332
  ///
2333
  /// @param R              The region which to process.
2334
  /// @param LoopStack      A stack of loops that are currently under
2335
  ///                       construction.
2336
  /// @param LI The LoopInfo for the current function.
2337
  void buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI);
2338
2339
  /// Build Schedule for the region node @p RN and add the derived
2340
  ///        information to @p LoopStack.
2341
  ///
2342
  /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
2343
  /// schedule for this @p RN and also finalize loop schedules in case the
2344
  /// current @p RN completes the loop.
2345
  ///
2346
  /// In case @p RN is a not-non-affine Region, we delegate the construction to
2347
  /// buildSchedule(Region *R, ...).
2348
  ///
2349
  /// @param RN             The RegionNode region traversed.
2350
  /// @param LoopStack      A stack of loops that are currently under
2351
  ///                       construction.
2352
  /// @param LI The LoopInfo for the current function.
2353
  void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI);
2354
2355
  /// Collect all memory access relations of a given type.
2356
  ///
2357
  /// @param Predicate A predicate function that returns true if an access is
2358
  ///                  of a given type.
2359
  ///
2360
  /// @returns The set of memory accesses in the scop that match the predicate.
2361
  isl::union_map
2362
  getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
2363
2364
  /// @name Helper functions for printing the Scop.
2365
  ///
2366
  //@{
2367
  void printContext(raw_ostream &OS) const;
2368
  void printArrayInfo(raw_ostream &OS) const;
2369
  void printStatements(raw_ostream &OS, bool PrintInstructions) const;
2370
  void printAliasAssumptions(raw_ostream &OS) const;
2371
  //@}
2372
2373
public:
2374
  Scop(const Scop &) = delete;
2375
  Scop &operator=(const Scop &) = delete;
2376
  ~Scop();
2377
2378
  /// Get the count of copy statements added to this Scop.
2379
  ///
2380
  /// @return The count of copy statements added to this Scop.
2381
24
  unsigned getCopyStmtsNum() { return CopyStmtsNum; }
2382
2383
  /// Create a new copy statement.
2384
  ///
2385
  /// A new statement will be created and added to the statement vector.
2386
  ///
2387
  /// @param Stmt       The parent statement.
2388
  /// @param SourceRel  The source location.
2389
  /// @param TargetRel  The target location.
2390
  /// @param Domain     The original domain under which the copy statement would
2391
  ///                   be executed.
2392
  ScopStmt *addScopStmt(isl::map SourceRel, isl::map TargetRel,
2393
                        isl::set Domain);
2394
2395
  /// Add the access function to all MemoryAccess objects of the Scop
2396
  ///        created in this pass.
2397
5.02k
  void addAccessFunction(MemoryAccess *Access) {
2398
5.02k
    AccessFunctions.emplace_back(Access);
2399
5.02k
2400
5.02k
    // Register value definitions.
2401
5.02k
    if (Access->isWrite() && 
Access->isOriginalValueKind()2.61k
) {
2402
336
      assert(!ValueDefAccs.count(Access->getAccessValue()) &&
2403
336
             "there can be just one definition per value");
2404
336
      ValueDefAccs[Access->getAccessValue()] = Access;
2405
4.69k
    } else if (Access->isRead() && 
Access->isOriginalPHIKind()2.40k
) {
2406
222
      PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
2407
222
      assert(!PHIReadAccs.count(PHI) &&
2408
222
             "there can be just one PHI read per PHINode");
2409
222
      PHIReadAccs[PHI] = Access;
2410
222
    }
2411
5.02k
  }
2412
2413
  /// Add metadata for @p Access.
2414
  void addAccessData(MemoryAccess *Access);
2415
2416
  /// Remove the metadata stored for @p Access.
2417
  void removeAccessData(MemoryAccess *Access);
2418
2419
  /// Return the scalar evolution.
2420
  ScalarEvolution *getSE() const;
2421
2422
  /// Return the dominator tree.
2423
2.66k
  DominatorTree *getDT() const { return DT; }
2424
2425
  /// Return the LoopInfo used for this Scop.
2426
2.66k
  LoopInfo *getLI() const { return Affinator.getLI(); }
2427
2428
  /// Get the count of parameters used in this Scop.
2429
  ///
2430
  /// @return The count of parameters used in this Scop.
2431
1.25k
  size_t getNumParams() const { return Parameters.size(); }
2432
2433
  /// Take a list of parameters and add the new ones to the scop.
2434
  void addParams(const ParameterSetTy &NewParameters);
2435
2436
  /// Return an iterator range containing the scop parameters.
2437
285
  iterator_range<ParameterSetTy::iterator> parameters() const {
2438
285
    return make_range(Parameters.begin(), Parameters.end());
2439
285
  }
2440
2441
  /// Return whether this scop is empty, i.e. contains no statements that
2442
  /// could be executed.
2443
1.17k
  bool isEmpty() const { return Stmts.empty(); }
2444
2445
0
  const StringRef getName() const { return name; }
2446
2447
  using array_iterator = ArrayInfoSetTy::iterator;
2448
  using const_array_iterator = ArrayInfoSetTy::const_iterator;
2449
  using array_range = iterator_range<ArrayInfoSetTy::iterator>;
2450
  using const_array_range = iterator_range<ArrayInfoSetTy::const_iterator>;
2451
2452
4.08k
  inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
2453
2454
4.08k
  inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
2455
2456
2.10k
  inline const_array_iterator array_begin() const {
2457
2.10k
    return ScopArrayInfoSet.begin();
2458
2.10k
  }
2459
2460
2.10k
  inline const_array_iterator array_end() const {
2461
2.10k
    return ScopArrayInfoSet.end();
2462
2.10k
  }
2463
2464
4.08k
  inline array_range arrays() {
2465
4.08k
    return array_range(array_begin(), array_end());
2466
4.08k
  }
2467
2468
2.10k
  inline const_array_range arrays() const {
2469
2.10k
    return const_array_range(array_begin(), array_end());
2470
2.10k
  }
2471
2472
  /// Return the isl_id that represents a certain parameter.
2473
  ///
2474
  /// @param Parameter A SCEV that was recognized as a Parameter.
2475
  ///
2476
  /// @return The corresponding isl_id or NULL otherwise.
2477
  isl::id getIdForParam(const SCEV *Parameter) const;
2478
2479
  /// Get the maximum region of this static control part.
2480
  ///
2481
  /// @return The maximum region of this static control part.
2482
30.8k
  inline const Region &getRegion() const { return R; }
2483
50.4k
  inline Region &getRegion() { return R; }
2484
2485
  /// Return the function this SCoP is in.
2486
6.52k
  Function &getFunction() const { return *R.getEntry()->getParent(); }
2487
2488
  /// Check if @p L is contained in the SCoP.
2489
11.8k
  bool contains(const Loop *L) const { return R.contains(L); }
2490
2491
  /// Check if @p BB is contained in the SCoP.
2492
29.5k
  bool contains(const BasicBlock *BB) const { return R.contains(BB); }
2493
2494
  /// Check if @p I is contained in the SCoP.
2495
6.05k
  bool contains(const Instruction *I) const { return R.contains(I); }
2496
2497
  /// Return the unique exit block of the SCoP.
2498
2.69k
  BasicBlock *getExit() const { return R.getExit(); }
2499
2500
  /// Return the unique exiting block of the SCoP if any.
2501
636
  BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
2502
2503
  /// Return the unique entry block of the SCoP.
2504
4.62k
  BasicBlock *getEntry() const { return R.getEntry(); }
2505
2506
  /// Return the unique entering block of the SCoP if any.
2507
863
  BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
2508
2509
  /// Return true if @p BB is the exit block of the SCoP.
2510
1.77k
  bool isExit(BasicBlock *BB) const { return getExit() == BB; }
2511
2512
  /// Return a range of all basic blocks in the SCoP.
2513
3.03k
  Region::block_range blocks() const { return R.blocks(); }
2514
2515
  /// Return true if and only if @p BB dominates the SCoP.
2516
  bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
2517
2518
  /// Get the maximum depth of the loop.
2519
  ///
2520
  /// @return The maximum depth of the loop.
2521
1.59k
  inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
2522
2523
  /// Return the invariant equivalence class for @p Val if any.
2524
  InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
2525
2526
  /// Return the set of invariant accesses.
2527
300
  InvariantEquivClassesTy &getInvariantAccesses() {
2528
300
    return InvariantEquivClasses;
2529
300
  }
2530
2531
  /// Check if the scop has any invariant access.
2532
0
  bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
2533
2534
  /// Mark the SCoP as optimized by the scheduler.
2535
34
  void markAsOptimized() { IsOptimized = true; }
2536
2537
  /// Check if the SCoP has been optimized by the scheduler.
2538
0
  bool isOptimized() const { return IsOptimized; }
2539
2540
  /// Mark the SCoP to be skipped by ScopPass passes.
2541
0
  void markAsToBeSkipped() { SkipScop = true; }
2542
2543
  /// Check if the SCoP is to be skipped by ScopPass passes.
2544
771
  bool isToBeSkipped() const { return SkipScop; }
2545
2546
  /// Return the ID of the Scop
2547
0
  int getID() const { return ID; }
2548
2549
  /// Get the name of the entry and exit blocks of this Scop.
2550
  ///
2551
  /// These along with the function name can uniquely identify a Scop.
2552
  ///
2553
  /// @return std::pair whose first element is the entry name & second element
2554
  ///         is the exit name.
2555
  std::pair<std::string, std::string> getEntryExitStr() const;
2556
2557
  /// Get the name of this Scop.
2558
  std::string getNameStr() const;
2559
2560
  /// Get the constraint on parameter of this Scop.
2561
  ///
2562
  /// @return The constraint on parameter of this Scop.
2563
  isl::set getContext() const;
2564
2565
  /// Return space of isl context parameters.
2566
  ///
2567
  /// Returns the set of context parameters that are currently constrained. In
2568
  /// case the full set of parameters is needed, see @getFullParamSpace.
2569
  isl::space getParamSpace() const;
2570
2571
  /// Return the full space of parameters.
2572
  ///
2573
  /// getParamSpace will only return the parameters of the context that are
2574
  /// actually constrained, whereas getFullParamSpace will return all
2575
  //  parameters. This is useful in cases, where we need to ensure all
2576
  //  parameters are available, as certain isl functions will abort if this is
2577
  //  not the case.
2578
  isl::space getFullParamSpace() const;
2579
2580
  /// Get the assumed context for this Scop.
2581
  ///
2582
  /// @return The assumed context of this Scop.
2583
  isl::set getAssumedContext() const;
2584
2585
  /// Return true if the optimized SCoP can be executed.
2586
  ///
2587
  /// In addition to the runtime check context this will also utilize the domain
2588
  /// constraints to decide it the optimized version can actually be executed.
2589
  ///
2590
  /// @returns True if the optimized SCoP can be executed.
2591
  bool hasFeasibleRuntimeContext() const;
2592
2593
  /// Check if the assumption in @p Set is trivial or not.
2594
  ///
2595
  /// @param Set  The relations between parameters that are assumed to hold.
2596
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2597
  ///             (needed/assumptions) or negative (invalid/restrictions).
2598
  ///
2599
  /// @returns True if the assumption @p Set is not trivial.
2600
  bool isEffectiveAssumption(isl::set Set, AssumptionSign Sign);
2601
2602
  /// Track and report an assumption.
2603
  ///
2604
  /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
2605
  /// -pass-remarks-analysis=polly-scops' to output the assumptions.
2606
  ///
2607
  /// @param Kind The assumption kind describing the underlying cause.
2608
  /// @param Set  The relations between parameters that are assumed to hold.
2609
  /// @param Loc  The location in the source that caused this assumption.
2610
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2611
  ///             (needed/assumptions) or negative (invalid/restrictions).
2612
  /// @param BB   The block in which this assumption was taken. Used to
2613
  ///             calculate hotness when emitting remark.
2614
  ///
2615
  /// @returns True if the assumption is not trivial.
2616
  bool trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2617
                       AssumptionSign Sign, BasicBlock *BB);
2618
2619
  /// Add assumptions to assumed context.
2620
  ///
2621
  /// The assumptions added will be assumed to hold during the execution of the
2622
  /// scop. However, as they are generally not statically provable, at code
2623
  /// generation time run-time checks will be generated that ensure the
2624
  /// assumptions hold.
2625
  ///
2626
  /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
2627
  ///          that assumptions do not change the set of statement instances
2628
  ///          executed.
2629
  ///
2630
  /// @param Kind The assumption kind describing the underlying cause.
2631
  /// @param Set  The relations between parameters that are assumed to hold.
2632
  /// @param Loc  The location in the source that caused this assumption.
2633
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2634
  ///             (needed/assumptions) or negative (invalid/restrictions).
2635
  /// @param BB   The block in which this assumption was taken. Used to
2636
  ///             calculate hotness when emitting remark.
2637
  void addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2638
                     AssumptionSign Sign, BasicBlock *BB);
2639
2640
  /// Record an assumption for later addition to the assumed context.
2641
  ///
2642
  /// This function will add the assumption to the RecordedAssumptions. This
2643
  /// collection will be added (@see addAssumption) to the assumed context once
2644
  /// all paramaters are known and the context is fully built.
2645
  ///
2646
  /// @param Kind The assumption kind describing the underlying cause.
2647
  /// @param Set  The relations between parameters that are assumed to hold.
2648
  /// @param Loc  The location in the source that caused this assumption.
2649
  /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2650
  ///             (needed/assumptions) or negative (invalid/restrictions).
2651
  /// @param BB   The block in which this assumption was taken. If it is
2652
  ///             set, the domain of that block will be used to simplify the
2653
  ///             actual assumption in @p Set once it is added. This is useful
2654
  ///             if the assumption was created prior to the domain.
2655
  void recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2656
                        AssumptionSign Sign, BasicBlock *BB = nullptr);
2657
2658
  /// Add all recorded assumptions to the assumed context.
2659
  void addRecordedAssumptions();
2660
2661
  /// Mark the scop as invalid.
2662
  ///
2663
  /// This method adds an assumption to the scop that is always invalid. As a
2664
  /// result, the scop will not be optimized later on. This function is commonly
2665
  /// called when a condition makes it impossible (or too compile time
2666
  /// expensive) to process this scop any further.
2667
  ///
2668
  /// @param Kind The assumption kind describing the underlying cause.
2669
  /// @param Loc  The location in the source that triggered .
2670
  /// @param BB   The BasicBlock where it was triggered.
2671
  void invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB = nullptr);
2672
2673
  /// Get the invalid context for this Scop.
2674
  ///
2675
  /// @return The invalid context of this Scop.
2676
  isl::set getInvalidContext() const;
2677
2678
  /// Return true if and only if the InvalidContext is trivial (=empty).
2679
442
  bool hasTrivialInvalidContext() const { return InvalidContext.is_empty(); }
2680
2681
  /// A vector of memory accesses that belong to an alias group.
2682
  using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2683
2684
  /// A vector of alias groups.
2685
  using AliasGroupVectorTy = SmallVector<Scop::AliasGroupTy, 4>;
2686
2687
  /// Build the alias checks for this SCoP.
2688
  bool buildAliasChecks(AliasAnalysis &AA);
2689
2690
  /// Build all alias groups for this SCoP.
2691
  ///
2692
  /// @returns True if __no__ error occurred, false otherwise.
2693
  bool buildAliasGroups(AliasAnalysis &AA);
2694
2695
  /// Build alias groups for all memory accesses in the Scop.
2696
  ///
2697
  /// Using the alias analysis and an alias set tracker we build alias sets
2698
  /// for all memory accesses inside the Scop. For each alias set we then map
2699
  /// the aliasing pointers back to the memory accesses we know, thus obtain
2700
  /// groups of memory accesses which might alias. We also collect the set of
2701
  /// arrays through which memory is written.
2702
  ///
2703
  /// @param AA A reference to the alias analysis.
2704
  ///
2705
  /// @returns A pair consistent of a vector of alias groups and a set of arrays
2706
  ///          through which memory is written.
2707
  std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2708
  buildAliasGroupsForAccesses(AliasAnalysis &AA);
2709
2710
  ///  Split alias groups by iteration domains.
2711
  ///
2712
  ///  We split each group based on the domains of the minimal/maximal accesses.
2713
  ///  That means two minimal/maximal accesses are only in a group if their
2714
  ///  access domains intersect. Otherwise, they are in different groups.
2715
  ///
2716
  ///  @param AliasGroups The alias groups to split
2717
  void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
2718
2719
  /// Build a given alias group and its access data.
2720
  ///
2721
  /// @param AliasGroup     The alias group to build.
2722
  /// @param HasWriteAccess A set of arrays through which memory is not only
2723
  ///                       read, but also written.
2724
  ///
2725
  /// @returns True if __no__ error occurred, false otherwise.
2726
  bool buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2727
                       DenseSet<const ScopArrayInfo *> HasWriteAccess);
2728
2729
  /// Return all alias groups for this SCoP.
2730
442
  const MinMaxVectorPairVectorTy &getAliasGroups() const {
2731
442
    return MinMaxAliasGroups;
2732
442
  }
2733
2734
  /// Get an isl string representing the context.
2735
  std::string getContextStr() const;
2736
2737
  /// Get an isl string representing the assumed context.
2738
  std::string getAssumedContextStr() const;
2739
2740
  /// Get an isl string representing the invalid context.
2741
  std::string getInvalidContextStr() const;
2742
2743
  /// Return the list of ScopStmts that represent the given @p BB.
2744
  ArrayRef<ScopStmt *> getStmtListFor(BasicBlock *BB) const;
2745
2746
  /// Return the last statement representing @p BB.
2747
  ///
2748
  /// Of the sequence of statements that represent a @p BB, this is the last one
2749
  /// to be executed. It is typically used to determine which instruction to add
2750
  /// a MemoryKind::PHI WRITE to. For this purpose, it is not strictly required
2751
  /// to be executed last, only that the incoming value is available in it.
2752
  ScopStmt *getLastStmtFor(BasicBlock *BB) const;
2753
2754
  /// Return the ScopStmts that represents the Region @p R, or nullptr if
2755
  ///        it is not represented by any statement in this Scop.
2756
  ArrayRef<ScopStmt *> getStmtListFor(Region *R) const;
2757
2758
  /// Return the ScopStmts that represents @p RN; can return nullptr if
2759
  ///        the RegionNode is not within the SCoP or has been removed due to
2760
  ///        simplifications.
2761
  ArrayRef<ScopStmt *> getStmtListFor(RegionNode *RN) const;
2762
2763
  /// Return the ScopStmt an instruction belongs to, or nullptr if it
2764
  ///        does not belong to any statement in this Scop.
2765
4.69k
  ScopStmt *getStmtFor(Instruction *Inst) const {
2766
4.69k
    return InstStmtMap.lookup(Inst);
2767
4.69k
  }
2768
2769
  /// Return the number of statements in the SCoP.
2770
298
  size_t getSize() const { return Stmts.size(); }
2771
2772
  /// @name Statements Iterators
2773
  ///
2774
  /// These iterators iterate over all statements of this Scop.
2775
  //@{
2776
  using iterator = StmtSet::iterator;
2777
  using const_iterator = StmtSet::const_iterator;
2778
2779
13.3k
  iterator begin() { return Stmts.begin(); }
2780
13.3k
  iterator end() { return Stmts.end(); }
2781
12.8k
  const_iterator begin() const { return Stmts.begin(); }
2782
12.8k
  const_iterator end() const { return Stmts.end(); }
2783
2784
  using reverse_iterator = StmtSet::reverse_iterator;
2785
  using const_reverse_iterator = StmtSet::const_reverse_iterator;
2786
2787
0
  reverse_iterator rbegin() { return Stmts.rbegin(); }
2788
0
  reverse_iterator rend() { return Stmts.rend(); }
2789
0
  const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
2790
0
  const_reverse_iterator rend() const { return Stmts.rend(); }
2791
  //@}
2792
2793
  /// Return the set of required invariant loads.
2794
44.2k
  const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
2795
44.2k
    return DC.RequiredILS;
2796
44.2k
  }
2797
2798
  /// Add @p LI to the set of required invariant loads.
2799
0
  void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
2800
2801
  /// Return true if and only if @p LI is a required invariant load.
2802
56
  bool isRequiredInvariantLoad(LoadInst *LI) const {
2803
56
    return getRequiredInvariantLoads().count(LI);
2804
56
  }
2805
2806
  /// Return the set of boxed (thus overapproximated) loops.
2807
14.2k
  const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
2808
2809
  /// Return true if and only if @p R is a non-affine subregion.
2810
10.0k
  bool isNonAffineSubRegion(const Region *R) {
2811
10.0k
    return DC.NonAffineSubRegionSet.count(R);
2812
10.0k
  }
2813
2814
3.33k
  const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
2815
2816
  /// Return the (possibly new) ScopArrayInfo object for @p Access.
2817
  ///
2818
  /// @param ElementType The type of the elements stored in this array.
2819
  /// @param Kind        The kind of the array info object.
2820
  /// @param BaseName    The optional name of this memory reference.
2821
  ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
2822
                                          ArrayRef<const SCEV *> Sizes,
2823
                                          MemoryKind Kind,
2824
                                          const char *BaseName = nullptr);
2825
2826
  /// Create an array and return the corresponding ScopArrayInfo object.
2827
  ///
2828
  /// @param ElementType The type of the elements stored in this array.
2829
  /// @param BaseName    The name of this memory reference.
2830
  /// @param Sizes       The sizes of dimensions.
2831
  ScopArrayInfo *createScopArrayInfo(Type *ElementType,
2832
                                     const std::string &BaseName,
2833
                                     const std::vector<unsigned> &Sizes);
2834
2835
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2836
  ///
2837
  /// @param BasePtr   The base pointer the object has been stored for.
2838
  /// @param Kind      The kind of array info object.
2839
  ///
2840
  /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
2841
  ///          available.
2842
  const ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
2843
2844
  /// Return the cached ScopArrayInfo object for @p BasePtr.
2845
  ///
2846
  /// @param BasePtr   The base pointer the object has been stored for.
2847
  /// @param Kind      The kind of array info object.
2848
  ///
2849
  /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
2850
  ///          available).
2851
  const ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
2852
2853
  /// Invalidate ScopArrayInfo object for base address.
2854
  ///
2855
  /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
2856
  /// @param Kind    The Kind of the ScopArrayInfo object.
2857
0
  void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
2858
0
    auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
2859
0
    if (It == ScopArrayInfoMap.end())
2860
0
      return;
2861
0
    ScopArrayInfoSet.remove(It->second.get());
2862
0
    ScopArrayInfoMap.erase(It);
2863
0
  }
2864
2865
  void setContext(isl::set NewContext);
2866
2867
  /// Align the parameters in the statement to the scop context
2868
  void realignParams();
2869
2870
  /// Return true if this SCoP can be profitably optimized.
2871
  ///
2872
  /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
2873
  ///                               as profitably optimizable.
2874
  ///
2875
  /// @return Whether this SCoP can be profitably optimized.
2876
  bool isProfitable(bool ScalarsAreUnprofitable) const;
2877
2878
  /// Return true if the SCoP contained at least one error block.
2879
1.13k
  bool hasErrorBlock() const { return HasErrorBlock; }
2880
2881
  /// Return true if the underlying region has a single exiting block.
2882
20.0k
  bool hasSingleExitEdge() const { return HasSingleExitEdge; }
2883
2884
  /// Print the static control part.
2885
  ///
2886
  /// @param OS The output stream the static control part is printed to.
2887
  /// @param PrintInstructions Whether to print the statement's instructions as
2888
  ///                          well.
2889
  void print(raw_ostream &OS, bool PrintInstructions) const;
2890
2891
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2892
  /// Print the ScopStmt to stderr.
2893
  void dump() const;
2894
#endif
2895
2896
  /// Get the isl context of this static control part.
2897
  ///
2898
  /// @return The isl context of this static control part.
2899
  isl::ctx getIslCtx() const;
2900
2901
  /// Directly return the shared_ptr of the context.
2902
1.91k
  const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
2903
2904
  /// Compute the isl representation for the SCEV @p E
2905
  ///
2906
  /// @param E  The SCEV that should be translated.
2907
  /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
2908
  ///           SCEVs known to not reference any loops in the SCoP can be
2909
  ///           passed without a @p BB.
2910
  /// @param NonNegative Flag to indicate the @p E has to be non-negative.
2911
  ///
2912
  /// Note that this function will always return a valid isl_pw_aff. However, if
2913
  /// the translation of @p E was deemed to complex the SCoP is invalidated and
2914
  /// a dummy value of appropriate dimension is returned. This allows to bail
2915
  /// for complex cases without "error handling code" needed on the users side.
2916
  PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
2917
                  bool NonNegative = false);
2918
2919
  /// Compute the isl representation for the SCEV @p E
2920
  ///
2921
  /// This function is like @see Scop::getPwAff() but strips away the invalid
2922
  /// domain part associated with the piecewise affine function.
2923
  isl::pw_aff getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr);
2924
2925
  /// Return the domain of @p Stmt.
2926
  ///
2927
  /// @param Stmt The statement for which the conditions should be returned.
2928
  isl::set getDomainConditions(const ScopStmt *Stmt) const;
2929
2930
  /// Return the domain of @p BB.
2931
  ///
2932
  /// @param BB The block for which the conditions should be returned.
2933
  isl::set getDomainConditions(BasicBlock *BB) const;
2934
2935
  /// Get a union set containing the iteration domains of all statements.
2936
  isl::union_set getDomains() const;
2937
2938
  /// Get a union map of all may-writes performed in the SCoP.
2939
  isl::union_map getMayWrites();
2940
2941
  /// Get a union map of all must-writes performed in the SCoP.
2942
  isl::union_map getMustWrites();
2943
2944
  /// Get a union map of all writes performed in the SCoP.
2945
  isl::union_map getWrites();
2946
2947
  /// Get a union map of all reads performed in the SCoP.
2948
  isl::union_map getReads();
2949
2950
  /// Get a union map of all memory accesses performed in the SCoP.
2951
  isl::union_map getAccesses();
2952
2953
  /// Get a union map of all memory accesses performed in the SCoP.
2954
  ///
2955
  /// @param Array The array to which the accesses should belong.
2956
  isl::union_map getAccesses(ScopArrayInfo *Array);
2957
2958
  /// Get the schedule of all the statements in the SCoP.
2959
  ///
2960
  /// @return The schedule of all the statements in the SCoP, if the schedule of
2961
  /// the Scop does not contain extension nodes, and nullptr, otherwise.
2962
  isl::union_map getSchedule() const;
2963
2964
  /// Get a schedule tree describing the schedule of all statements.
2965
  isl::schedule getScheduleTree() const;
2966
2967
  /// Update the current schedule
2968
  ///
2969
  /// NewSchedule The new schedule (given as a flat union-map).
2970
  void setSchedule(isl::union_map NewSchedule);
2971
2972
  /// Update the current schedule
2973
  ///
2974
  /// NewSchedule The new schedule (given as schedule tree).
2975
  void setScheduleTree(isl::schedule NewSchedule);
2976
2977
  /// Intersects the domains of all statements in the SCoP.
2978
  ///
2979
  /// @return true if a change was made
2980
  bool restrictDomains(isl::union_set Domain);
2981
2982
  /// Get the depth of a loop relative to the outermost loop in the Scop.
2983
  ///
2984
  /// This will return
2985
  ///    0 if @p L is an outermost loop in the SCoP
2986
  ///   >0 for other loops in the SCoP
2987
  ///   -1 if @p L is nullptr or there is no outermost loop in the SCoP
2988
  int getRelativeLoopDepth(const Loop *L) const;
2989
2990
  /// Find the ScopArrayInfo associated with an isl Id
2991
  ///        that has name @p Name.
2992
  ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
2993
2994
  /// Check whether @p Schedule contains extension nodes.
2995
  ///
2996
  /// @return true if @p Schedule contains extension nodes.
2997
  static bool containsExtensionNode(isl::schedule Schedule);
2998
2999
  /// Simplify the SCoP representation.
3000
  ///
3001
  /// @param AfterHoisting Whether it is called after invariant load hoisting.
3002
  ///                      When true, also removes statements without
3003
  ///                      side-effects.
3004
  void simplifySCoP(bool AfterHoisting);
3005
3006
  /// Get the next free array index.
3007
  ///
3008
  /// This function returns a unique index which can be used to identify an
3009
  /// array.
3010
2.41k
  long getNextArrayIdx() { return ArrayIdx++; }
3011
3012
  /// Get the next free statement index.
3013
  ///
3014
  /// This function returns a unique index which can be used to identify a
3015
  /// statement.
3016
5.68k
  long getNextStmtIdx() { return StmtIdx++; }
3017
3018
  /// Return the MemoryAccess that writes an llvm::Value, represented by a
3019
  /// ScopArrayInfo.
3020
  ///
3021
  /// There can be at most one such MemoryAccess per llvm::Value in the SCoP.
3022
  /// Zero is possible for read-only values.
3023
  MemoryAccess *getValueDef(const ScopArrayInfo *SAI) const;
3024
3025
  /// Return all MemoryAccesses that us an llvm::Value, represented by a
3026
  /// ScopArrayInfo.
3027
  ArrayRef<MemoryAccess *> getValueUses(const ScopArrayInfo *SAI) const;
3028
3029
  /// Return the MemoryAccess that represents an llvm::PHINode.
3030
  ///
3031
  /// ExitPHIs's PHINode is not within the SCoPs. This function returns nullptr
3032
  /// for them.
3033
  MemoryAccess *getPHIRead(const ScopArrayInfo *SAI) const;
3034
3035
  /// Return all MemoryAccesses for all incoming statements of a PHINode,
3036
  /// represented by a ScopArrayInfo.
3037
  ArrayRef<MemoryAccess *> getPHIIncomings(const ScopArrayInfo *SAI) const;
3038
3039
  /// Return whether @p Inst has a use outside of this SCoP.
3040
  bool isEscaping(Instruction *Inst);
3041
3042
  struct ScopStatistics {
3043
    int NumAffineLoops = 0;
3044
    int NumBoxedLoops = 0;
3045
3046
    int NumValueWrites = 0;
3047
    int NumValueWritesInLoops = 0;
3048
    int NumPHIWrites = 0;
3049
    int NumPHIWritesInLoops = 0;
3050
    int NumSingletonWrites = 0;
3051
    int NumSingletonWritesInLoops = 0;
3052
  };
3053
3054
  /// Collect statistic about this SCoP.
3055
  ///
3056
  /// These are most commonly used for LLVM's static counters (Statistic.h) in
3057
  /// various places. If statistics are disabled, only zeros are returned to
3058
  /// avoid the overhead.
3059
  ScopStatistics getStatistics() const;
3060
};
3061
3062
/// Print Scop scop to raw_ostream OS.
3063
raw_ostream &operator<<(raw_ostream &OS, const Scop &scop);
3064
3065
/// The legacy pass manager's analysis pass to compute scop information
3066
///        for a region.
3067
class ScopInfoRegionPass : public RegionPass {
3068
  /// The Scop pointer which is used to construct a Scop.
3069
  std::unique_ptr<Scop> S;
3070
3071
public:
3072
  static char ID; // Pass identification, replacement for typeid
3073
3074
1.10k
  ScopInfoRegionPass() : RegionPass(ID) {}
3075
1.08k
  ~ScopInfoRegionPass() override = default;
3076
3077
  /// Build Scop object, the Polly IR of static control
3078
  ///        part for the current SESE-Region.
3079
  ///
3080
  /// @return If the current region is a valid for a static control part,
3081
  ///         return the Polly IR representing this static control part,
3082
  ///         return null otherwise.
3083
6.19k
  Scop *getScop() { return S.get(); }
3084
0
  const Scop *getScop() const { return S.get(); }
3085
3086
  /// Calculate the polyhedral scop information for a given Region.
3087
  bool runOnRegion(Region *R, RGPassManager &RGM) override;
3088
3089
4.03k
  void releaseMemory() override { S.reset(); }
3090
3091
  void print(raw_ostream &O, const Module *M = nullptr) const override;
3092
3093
  void getAnalysisUsage(AnalysisUsage &AU) const override;
3094
};
3095
3096
class ScopInfo {
3097
public:
3098
  using RegionToScopMapTy = MapVector<Region *, std::unique_ptr<Scop>>;
3099
  using reverse_iterator = RegionToScopMapTy::reverse_iterator;
3100
  using const_reverse_iterator = RegionToScopMapTy::const_reverse_iterator;
3101
  using iterator = RegionToScopMapTy::iterator;
3102
  using const_iterator = RegionToScopMapTy::const_iterator;
3103
3104
private:
3105
  /// A map of Region to its Scop object containing
3106
  ///        Polly IR of static control part.
3107
  RegionToScopMapTy RegionToScopMap;
3108
  const DataLayout &DL;
3109
  ScopDetection &SD;
3110
  ScalarEvolution &SE;
3111
  LoopInfo &LI;
3112
  AliasAnalysis &AA;
3113
  DominatorTree &DT;
3114
  AssumptionCache &AC;
3115
  OptimizationRemarkEmitter &ORE;
3116
3117
public:
3118
  ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
3119
           LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
3120
           AssumptionCache &AC, OptimizationRemarkEmitter &ORE);
3121
3122
  /// Get the Scop object for the given Region.
3123
  ///
3124
  /// @return If the given region is the maximal region within a scop, return
3125
  ///         the scop object. If the given region is a subregion, return a
3126
  ///         nullptr. Top level region containing the entry block of a function
3127
  ///         is not considered in the scop creation.
3128
0
  Scop *getScop(Region *R) const {
3129
0
    auto MapIt = RegionToScopMap.find(R);
3130
0
    if (MapIt != RegionToScopMap.end())
3131
0
      return MapIt->second.get();
3132
0
    return nullptr;
3133
0
  }
3134
3135
  /// Recompute the Scop-Information for a function.
3136
  ///
3137
  /// This invalidates any iterators.
3138
  void recompute();
3139
3140
  /// Handle invalidation explicitly
3141
  bool invalidate(Function &F, const PreservedAnalyses &PA,
3142
                  FunctionAnalysisManager::Invalidator &Inv);
3143
3144
82
  iterator begin() { return RegionToScopMap.begin(); }
3145
82
  iterator end() { return RegionToScopMap.end(); }
3146
0
  const_iterator begin() const { return RegionToScopMap.begin(); }
3147
0
  const_iterator end() const { return RegionToScopMap.end(); }
3148
0
  reverse_iterator rbegin() { return RegionToScopMap.rbegin(); }
3149
0
  reverse_iterator rend() { return RegionToScopMap.rend(); }
3150
0
  const_reverse_iterator rbegin() const { return RegionToScopMap.rbegin(); }
3151
0
  const_reverse_iterator rend() const { return RegionToScopMap.rend(); }
3152
0
  bool empty() const { return RegionToScopMap.empty(); }
3153
};
3154
3155
struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
3156
  static AnalysisKey Key;
3157
3158
  using Result = ScopInfo;
3159
3160
  Result run(Function &, FunctionAnalysisManager &);
3161
};
3162
3163
struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
3164
1
  ScopInfoPrinterPass(raw_ostream &OS) : Stream(OS) {}
3165
3166
  PreservedAnalyses run(Function &, FunctionAnalysisManager &);
3167
3168
  raw_ostream &Stream;
3169
};
3170
3171
//===----------------------------------------------------------------------===//
3172
/// The legacy pass manager's analysis pass to compute scop information
3173
///        for the whole function.
3174
///
3175
/// This pass will maintain a map of the maximal region within a scop to its
3176
/// scop object for all the feasible scops present in a function.
3177
/// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
3178
/// region pass manager.
3179
class ScopInfoWrapperPass : public FunctionPass {
3180
  std::unique_ptr<ScopInfo> Result;
3181
3182
public:
3183
44
  ScopInfoWrapperPass() : FunctionPass(ID) {}
3184
44
  ~ScopInfoWrapperPass() override = default;
3185
3186
  static char ID; // Pass identification, replacement for typeid
3187
3188
45
  ScopInfo *getSI() { return Result.get(); }
3189
0
  const ScopInfo *getSI() const { return Result.get(); }
3190
3191
  /// Calculate all the polyhedral scops for a given function.
3192
  bool runOnFunction(Function &F) override;
3193
3194
49
  void releaseMemory() override { Result.reset(); }
3195
3196
  void print(raw_ostream &O, const Module *M = nullptr) const override;
3197
3198
  void getAnalysisUsage(AnalysisUsage &AU) const override;
3199
};
3200
3201
} // end namespace polly
3202
3203
#endif // POLLY_SCOPINFO_H