[ScopInfo] Remove dependency of Scop::getLastStmtFor(BB) on getStmtFor(BB). NFC.
[polly-mirror.git] / include / polly / ScopInfo.h
blobf4dd6d512550407aedd01f326ab0bdc68f4e61b3
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).
13 // This representation is shared among several tools in the polyhedral
14 // community, which are e.g. CLooG, Pluto, Loopo, Graphite.
16 //===----------------------------------------------------------------------===//
18 #ifndef POLLY_SCOP_INFO_H
19 #define POLLY_SCOP_INFO_H
21 #include "polly/ScopDetection.h"
22 #include "polly/Support/SCEVAffinator.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/Analysis/RegionPass.h"
26 #include "llvm/IR/PassManager.h"
27 #include "isl/aff.h"
28 #include "isl/ctx.h"
29 #include "isl/set.h"
31 #include "isl-noexceptions.h"
33 #include <deque>
34 #include <forward_list>
36 using namespace llvm;
38 namespace llvm {
39 class AssumptionCache;
40 class Loop;
41 class LoopInfo;
42 class PHINode;
43 class ScalarEvolution;
44 class SCEV;
45 class SCEVAddRecExpr;
46 class Type;
47 } // namespace llvm
49 struct isl_ctx;
50 struct isl_map;
51 struct isl_basic_map;
52 struct isl_id;
53 struct isl_set;
54 struct isl_union_set;
55 struct isl_union_map;
56 struct isl_space;
57 struct isl_ast_build;
58 struct isl_constraint;
59 struct isl_pw_aff;
60 struct isl_pw_multi_aff;
61 struct isl_schedule;
63 namespace polly {
65 class MemoryAccess;
66 class Scop;
67 class ScopStmt;
68 class ScopBuilder;
70 //===---------------------------------------------------------------------===//
72 extern bool UseInstructionNames;
74 /// Enumeration of assumptions Polly can take.
75 enum AssumptionKind {
76 ALIASING,
77 INBOUNDS,
78 WRAPPING,
79 UNSIGNED,
80 PROFITABLE,
81 ERRORBLOCK,
82 COMPLEXITY,
83 INFINITELOOP,
84 INVARIANTLOAD,
85 DELINEARIZATION,
88 /// Enum to distinguish between assumptions and restrictions.
89 enum AssumptionSign { AS_ASSUMPTION, AS_RESTRICTION };
91 /// The different memory kinds used in Polly.
92 ///
93 /// We distinguish between arrays and various scalar memory objects. We use
94 /// the term ``array'' to describe memory objects that consist of a set of
95 /// individual data elements arranged in a multi-dimensional grid. A scalar
96 /// memory object describes an individual data element and is used to model
97 /// the definition and uses of llvm::Values.
98 ///
99 /// The polyhedral model does traditionally not reason about SSA values. To
100 /// reason about llvm::Values we model them "as if" they were zero-dimensional
101 /// memory objects, even though they were not actually allocated in (main)
102 /// memory. Memory for such objects is only alloca[ed] at CodeGeneration
103 /// time. To relate the memory slots used during code generation with the
104 /// llvm::Values they belong to the new names for these corresponding stack
105 /// slots are derived by appending suffixes (currently ".s2a" and ".phiops")
106 /// to the name of the original llvm::Value. To describe how def/uses are
107 /// modeled exactly we use these suffixes here as well.
109 /// There are currently four different kinds of memory objects:
110 enum class MemoryKind {
111 /// MemoryKind::Array: Models a one or multi-dimensional array
113 /// A memory object that can be described by a multi-dimensional array.
114 /// Memory objects of this type are used to model actual multi-dimensional
115 /// arrays as they exist in LLVM-IR, but they are also used to describe
116 /// other objects:
117 /// - A single data element allocated on the stack using 'alloca' is
118 /// modeled as a one-dimensional, single-element array.
119 /// - A single data element allocated as a global variable is modeled as
120 /// one-dimensional, single-element array.
121 /// - Certain multi-dimensional arrays with variable size, which in
122 /// LLVM-IR are commonly expressed as a single-dimensional access with a
123 /// complicated access function, are modeled as multi-dimensional
124 /// memory objects (grep for "delinearization").
125 Array,
127 /// MemoryKind::Value: Models an llvm::Value
129 /// Memory objects of type MemoryKind::Value are used to model the data flow
130 /// induced by llvm::Values. For each llvm::Value that is used across
131 /// BasicBocks one ScopArrayInfo object is created. A single memory WRITE
132 /// stores the llvm::Value at its definition into the memory object and at
133 /// each use of the llvm::Value (ignoring trivial intra-block uses) a
134 /// corresponding READ is added. For instance, the use/def chain of a
135 /// llvm::Value %V depicted below
136 /// ______________________
137 /// |DefBB: |
138 /// | %V = float op ... |
139 /// ----------------------
140 /// | |
141 /// _________________ _________________
142 /// |UseBB1: | |UseBB2: |
143 /// | use float %V | | use float %V |
144 /// ----------------- -----------------
146 /// is modeled as if the following memory accesses occurred:
148 /// __________________________
149 /// |entry: |
150 /// | %V.s2a = alloca float |
151 /// --------------------------
152 /// |
153 /// ___________________________________
154 /// |DefBB: |
155 /// | store %float %V, float* %V.s2a |
156 /// -----------------------------------
157 /// | |
158 /// ____________________________________ ___________________________________
159 /// |UseBB1: | |UseBB2: |
160 /// | %V.reload1 = load float* %V.s2a | | %V.reload2 = load float* %V.s2a|
161 /// | use float %V.reload1 | | use float %V.reload2 |
162 /// ------------------------------------ -----------------------------------
164 Value,
166 /// MemoryKind::PHI: Models PHI nodes within the SCoP
168 /// Besides the MemoryKind::Value memory object used to model the normal
169 /// llvm::Value dependences described above, PHI nodes require an additional
170 /// memory object of type MemoryKind::PHI to describe the forwarding of values
171 /// to
172 /// the PHI node.
174 /// As an example, a PHIInst instructions
176 /// %PHI = phi float [ %Val1, %IncomingBlock1 ], [ %Val2, %IncomingBlock2 ]
178 /// is modeled as if the accesses occurred this way:
180 /// _______________________________
181 /// |entry: |
182 /// | %PHI.phiops = alloca float |
183 /// -------------------------------
184 /// | |
185 /// __________________________________ __________________________________
186 /// |IncomingBlock1: | |IncomingBlock2: |
187 /// | ... | | ... |
188 /// | store float %Val1 %PHI.phiops | | store float %Val2 %PHI.phiops |
189 /// | br label % JoinBlock | | br label %JoinBlock |
190 /// ---------------------------------- ----------------------------------
191 /// \ /
192 /// \ /
193 /// _________________________________________
194 /// |JoinBlock: |
195 /// | %PHI = load float, float* PHI.phiops |
196 /// -----------------------------------------
198 /// Note that there can also be a scalar write access for %PHI if used in a
199 /// different BasicBlock, i.e. there can be a memory object %PHI.phiops as
200 /// well as a memory object %PHI.s2a.
201 PHI,
203 /// MemoryKind::ExitPHI: Models PHI nodes in the SCoP's exit block
205 /// For PHI nodes in the Scop's exit block a special memory object kind is
206 /// used. The modeling used is identical to MemoryKind::PHI, with the
207 /// exception
208 /// that there are no READs from these memory objects. The PHINode's
209 /// llvm::Value is treated as a value escaping the SCoP. WRITE accesses
210 /// write directly to the escaping value's ".s2a" alloca.
211 ExitPHI
214 /// Maps from a loop to the affine function expressing its backedge taken count.
215 /// The backedge taken count already enough to express iteration domain as we
216 /// only allow loops with canonical induction variable.
217 /// A canonical induction variable is:
218 /// an integer recurrence that starts at 0 and increments by one each time
219 /// through the loop.
220 typedef std::map<const Loop *, const SCEV *> LoopBoundMapType;
222 typedef std::vector<std::unique_ptr<MemoryAccess>> AccFuncVector;
224 /// A class to store information about arrays in the SCoP.
226 /// Objects are accessible via the ScoP, MemoryAccess or the id associated with
227 /// the MemoryAccess access function.
229 class ScopArrayInfo {
230 public:
231 /// Construct a ScopArrayInfo object.
233 /// @param BasePtr The array base pointer.
234 /// @param ElementType The type of the elements stored in the array.
235 /// @param IslCtx The isl context used to create the base pointer id.
236 /// @param DimensionSizes A vector containing the size of each dimension.
237 /// @param Kind The kind of the array object.
238 /// @param DL The data layout of the module.
239 /// @param S The scop this array object belongs to.
240 /// @param BaseName The optional name of this memory reference.
241 ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *IslCtx,
242 ArrayRef<const SCEV *> DimensionSizes, MemoryKind Kind,
243 const DataLayout &DL, Scop *S, const char *BaseName = nullptr);
245 /// Update the element type of the ScopArrayInfo object.
247 /// Memory accesses referencing this ScopArrayInfo object may use
248 /// different element sizes. This function ensures the canonical element type
249 /// stored is small enough to model accesses to the current element type as
250 /// well as to @p NewElementType.
252 /// @param NewElementType An element type that is used to access this array.
253 void updateElementType(Type *NewElementType);
255 /// Update the sizes of the ScopArrayInfo object.
257 /// A ScopArrayInfo object may be created without all outer dimensions being
258 /// available. This function is called when new memory accesses are added for
259 /// this ScopArrayInfo object. It verifies that sizes are compatible and adds
260 /// additional outer array dimensions, if needed.
262 /// @param Sizes A vector of array sizes where the rightmost array
263 /// sizes need to match the innermost array sizes already
264 /// defined in SAI.
265 /// @param CheckConsistency Update sizes, even if new sizes are inconsistent
266 /// with old sizes
267 bool updateSizes(ArrayRef<const SCEV *> Sizes, bool CheckConsistency = true);
269 /// Make the ScopArrayInfo model a Fortran array.
270 /// It receives the Fortran array descriptor and stores this.
271 /// It also adds a piecewise expression for the outermost dimension
272 /// since this information is available for Fortran arrays at runtime.
273 void applyAndSetFAD(Value *FAD);
275 /// Destructor to free the isl id of the base pointer.
276 ~ScopArrayInfo();
278 /// Set the base pointer to @p BP.
279 void setBasePtr(Value *BP) { BasePtr = BP; }
281 /// Return the base pointer.
282 Value *getBasePtr() const { return BasePtr; }
284 // Set IsOnHeap to the value in parameter.
285 void setIsOnHeap(bool value) { IsOnHeap = value; }
287 /// For indirect accesses return the origin SAI of the BP, else null.
288 const ScopArrayInfo *getBasePtrOriginSAI() const { return BasePtrOriginSAI; }
290 /// The set of derived indirect SAIs for this origin SAI.
291 const SmallSetVector<ScopArrayInfo *, 2> &getDerivedSAIs() const {
292 return DerivedSAIs;
295 /// Return the number of dimensions.
296 unsigned getNumberOfDimensions() const {
297 if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI ||
298 Kind == MemoryKind::Value)
299 return 0;
300 return DimensionSizes.size();
303 /// Return the size of dimension @p dim as SCEV*.
305 // Scalars do not have array dimensions and the first dimension of
306 // a (possibly multi-dimensional) array also does not carry any size
307 // information, in case the array is not newly created.
308 const SCEV *getDimensionSize(unsigned Dim) const {
309 assert(Dim < getNumberOfDimensions() && "Invalid dimension");
310 return DimensionSizes[Dim];
313 /// Return the size of dimension @p dim as isl_pw_aff.
315 // Scalars do not have array dimensions and the first dimension of
316 // a (possibly multi-dimensional) array also does not carry any size
317 // information, in case the array is not newly created.
318 __isl_give isl_pw_aff *getDimensionSizePw(unsigned Dim) const {
319 assert(Dim < getNumberOfDimensions() && "Invalid dimension");
320 return isl_pw_aff_copy(DimensionSizesPw[Dim]);
323 /// Get the canonical element type of this array.
325 /// @returns The canonical element type of this array.
326 Type *getElementType() const { return ElementType; }
328 /// Get element size in bytes.
329 int getElemSizeInBytes() const;
331 /// Get the name of this memory reference.
332 std::string getName() const;
334 /// Return the isl id for the base pointer.
335 __isl_give isl_id *getBasePtrId() const;
337 /// Return what kind of memory this represents.
338 MemoryKind getKind() const { return Kind; }
340 /// Is this array info modeling an llvm::Value?
341 bool isValueKind() const { return Kind == MemoryKind::Value; }
343 /// Is this array info modeling special PHI node memory?
345 /// During code generation of PHI nodes, there is a need for two kinds of
346 /// virtual storage. The normal one as it is used for all scalar dependences,
347 /// where the result of the PHI node is stored and later loaded from as well
348 /// as a second one where the incoming values of the PHI nodes are stored
349 /// into and reloaded when the PHI is executed. As both memories use the
350 /// original PHI node as virtual base pointer, we have this additional
351 /// attribute to distinguish the PHI node specific array modeling from the
352 /// normal scalar array modeling.
353 bool isPHIKind() const { return Kind == MemoryKind::PHI; }
355 /// Is this array info modeling an MemoryKind::ExitPHI?
356 bool isExitPHIKind() const { return Kind == MemoryKind::ExitPHI; }
358 /// Is this array info modeling an array?
359 bool isArrayKind() const { return Kind == MemoryKind::Array; }
361 /// Is this array allocated on heap
363 /// This property is only relevant if the array is allocated by Polly instead
364 /// of pre-existing. If false, it is allocated using alloca instead malloca.
365 bool isOnHeap() const { return IsOnHeap; }
367 /// Dump a readable representation to stderr.
368 void dump() const;
370 /// Print a readable representation to @p OS.
372 /// @param SizeAsPwAff Print the size as isl_pw_aff
373 void print(raw_ostream &OS, bool SizeAsPwAff = false) const;
375 /// Access the ScopArrayInfo associated with an access function.
376 static const ScopArrayInfo *
377 getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA);
379 /// Access the ScopArrayInfo associated with an isl Id.
380 static const ScopArrayInfo *getFromId(__isl_take isl_id *Id);
382 /// Get the space of this array access.
383 __isl_give isl_space *getSpace() const;
385 /// If the array is read only
386 bool isReadOnly();
388 /// Verify that @p Array is compatible to this ScopArrayInfo.
390 /// Two arrays are compatible if their dimensionality, the sizes of their
391 /// dimensions, and their element sizes match.
393 /// @param Array The array to compare against.
395 /// @returns True, if the arrays are compatible, False otherwise.
396 bool isCompatibleWith(const ScopArrayInfo *Array) const;
398 private:
399 void addDerivedSAI(ScopArrayInfo *DerivedSAI) {
400 DerivedSAIs.insert(DerivedSAI);
403 /// For indirect accesses this is the SAI of the BP origin.
404 const ScopArrayInfo *BasePtrOriginSAI;
406 /// For origin SAIs the set of derived indirect SAIs.
407 SmallSetVector<ScopArrayInfo *, 2> DerivedSAIs;
409 /// The base pointer.
410 AssertingVH<Value> BasePtr;
412 /// The canonical element type of this array.
414 /// The canonical element type describes the minimal accessible element in
415 /// this array. Not all elements accessed, need to be of the very same type,
416 /// but the allocation size of the type of the elements loaded/stored from/to
417 /// this array needs to be a multiple of the allocation size of the canonical
418 /// type.
419 Type *ElementType;
421 /// The isl id for the base pointer.
422 isl_id *Id;
424 /// True if the newly allocated array is on heap.
425 bool IsOnHeap;
427 /// The sizes of each dimension as SCEV*.
428 SmallVector<const SCEV *, 4> DimensionSizes;
430 /// The sizes of each dimension as isl_pw_aff.
431 SmallVector<isl_pw_aff *, 4> DimensionSizesPw;
433 /// The type of this scop array info object.
435 /// We distinguish between SCALAR, PHI and ARRAY objects.
436 MemoryKind Kind;
438 /// The data layout of the module.
439 const DataLayout &DL;
441 /// The scop this SAI object belongs to.
442 Scop &S;
444 /// If this array models a Fortran array, then this points
445 /// to the Fortran array descriptor.
446 Value *FAD;
449 /// Represent memory accesses in statements.
450 class MemoryAccess {
451 friend class Scop;
452 friend class ScopStmt;
454 public:
455 /// The access type of a memory access
457 /// There are three kind of access types:
459 /// * A read access
461 /// A certain set of memory locations are read and may be used for internal
462 /// calculations.
464 /// * A must-write access
466 /// A certain set of memory locations is definitely written. The old value is
467 /// replaced by a newly calculated value. The old value is not read or used at
468 /// all.
470 /// * A may-write access
472 /// A certain set of memory locations may be written. The memory location may
473 /// contain a new value if there is actually a write or the old value may
474 /// remain, if no write happens.
475 enum AccessType {
476 READ = 0x1,
477 MUST_WRITE = 0x2,
478 MAY_WRITE = 0x3,
481 /// Reduction access type
483 /// Commutative and associative binary operations suitable for reductions
484 enum ReductionType {
485 RT_NONE, ///< Indicate no reduction at all
486 RT_ADD, ///< Addition
487 RT_MUL, ///< Multiplication
488 RT_BOR, ///< Bitwise Or
489 RT_BXOR, ///< Bitwise XOr
490 RT_BAND, ///< Bitwise And
493 private:
494 MemoryAccess(const MemoryAccess &) = delete;
495 const MemoryAccess &operator=(const MemoryAccess &) = delete;
497 /// A unique identifier for this memory access.
499 /// The identifier is unique between all memory accesses belonging to the same
500 /// scop statement.
501 isl_id *Id;
503 /// What is modeled by this MemoryAccess.
504 /// @see MemoryKind
505 MemoryKind Kind;
507 /// Whether it a reading or writing access, and if writing, whether it
508 /// is conditional (MAY_WRITE).
509 enum AccessType AccType;
511 /// Reduction type for reduction like accesses, RT_NONE otherwise
513 /// An access is reduction like if it is part of a load-store chain in which
514 /// both access the same memory location (use the same LLVM-IR value
515 /// as pointer reference). Furthermore, between the load and the store there
516 /// is exactly one binary operator which is known to be associative and
517 /// commutative.
519 /// TODO:
521 /// We can later lift the constraint that the same LLVM-IR value defines the
522 /// memory location to handle scops such as the following:
524 /// for i
525 /// for j
526 /// sum[i+j] = sum[i] + 3;
528 /// Here not all iterations access the same memory location, but iterations
529 /// for which j = 0 holds do. After lifting the equality check in ScopBuilder,
530 /// subsequent transformations do not only need check if a statement is
531 /// reduction like, but they also need to verify that that the reduction
532 /// property is only exploited for statement instances that load from and
533 /// store to the same data location. Doing so at dependence analysis time
534 /// could allow us to handle the above example.
535 ReductionType RedType = RT_NONE;
537 /// Parent ScopStmt of this access.
538 ScopStmt *Statement;
540 /// The domain under which this access is not modeled precisely.
542 /// The invalid domain for an access describes all parameter combinations
543 /// under which the statement looks to be executed but is in fact not because
544 /// some assumption/restriction makes the access invalid.
545 isl_set *InvalidDomain;
547 // Properties describing the accessed array.
548 // TODO: It might be possible to move them to ScopArrayInfo.
549 // @{
551 /// The base address (e.g., A for A[i+j]).
553 /// The #BaseAddr of a memory access of kind MemoryKind::Array is the base
554 /// pointer of the memory access.
555 /// The #BaseAddr of a memory access of kind MemoryKind::PHI or
556 /// MemoryKind::ExitPHI is the PHI node itself.
557 /// The #BaseAddr of a memory access of kind MemoryKind::Value is the
558 /// instruction defining the value.
559 AssertingVH<Value> BaseAddr;
561 /// Type a single array element wrt. this access.
562 Type *ElementType;
564 /// Size of each dimension of the accessed array.
565 SmallVector<const SCEV *, 4> Sizes;
566 // @}
568 // Properties describing the accessed element.
569 // @{
571 /// The access instruction of this memory access.
573 /// For memory accesses of kind MemoryKind::Array the access instruction is
574 /// the Load or Store instruction performing the access.
576 /// For memory accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI the
577 /// access instruction of a load access is the PHI instruction. The access
578 /// instruction of a PHI-store is the incoming's block's terminator
579 /// instruction.
581 /// For memory accesses of kind MemoryKind::Value the access instruction of a
582 /// load access is nullptr because generally there can be multiple
583 /// instructions in the statement using the same llvm::Value. The access
584 /// instruction of a write access is the instruction that defines the
585 /// llvm::Value.
586 Instruction *AccessInstruction;
588 /// Incoming block and value of a PHINode.
589 SmallVector<std::pair<BasicBlock *, Value *>, 4> Incoming;
591 /// The value associated with this memory access.
593 /// - For array memory accesses (MemoryKind::Array) it is the loaded result
594 /// or the stored value. If the access instruction is a memory intrinsic it
595 /// the access value is also the memory intrinsic.
596 /// - For accesses of kind MemoryKind::Value it is the access instruction
597 /// itself.
598 /// - For accesses of kind MemoryKind::PHI or MemoryKind::ExitPHI it is the
599 /// PHI node itself (for both, READ and WRITE accesses).
601 AssertingVH<Value> AccessValue;
603 /// Are all the subscripts affine expression?
604 bool IsAffine;
606 /// Subscript expression for each dimension.
607 SmallVector<const SCEV *, 4> Subscripts;
609 /// Relation from statement instances to the accessed array elements.
611 /// In the common case this relation is a function that maps a set of loop
612 /// indices to the memory address from which a value is loaded/stored:
614 /// for i
615 /// for j
616 /// S: A[i + 3 j] = ...
618 /// => { S[i,j] -> A[i + 3j] }
620 /// In case the exact access function is not known, the access relation may
621 /// also be a one to all mapping { S[i,j] -> A[o] } describing that any
622 /// element accessible through A might be accessed.
624 /// In case of an access to a larger element belonging to an array that also
625 /// contains smaller elements, the access relation models the larger access
626 /// with multiple smaller accesses of the size of the minimal array element
627 /// type:
629 /// short *A;
631 /// for i
632 /// S: A[i] = *((double*)&A[4 * i]);
634 /// => { S[i] -> A[i]; S[i] -> A[o] : 4i <= o <= 4i + 3 }
635 isl_map *AccessRelation;
637 /// Updated access relation read from JSCOP file.
638 isl_map *NewAccessRelation;
640 /// Fortran arrays whose sizes are not statically known are stored in terms
641 /// of a descriptor struct. This maintains a raw pointer to the memory,
642 /// along with auxiliary fields with information such as dimensions.
643 /// We hold a reference to the descriptor corresponding to a MemoryAccess
644 /// into a Fortran array. FAD for "Fortran Array Descriptor"
645 AssertingVH<Value> FAD;
646 // @}
648 __isl_give isl_basic_map *createBasicAccessMap(ScopStmt *Statement);
650 void assumeNoOutOfBound();
652 /// Compute bounds on an over approximated access relation.
654 /// @param ElementSize The size of one element accessed.
655 void computeBoundsOnAccessRelation(unsigned ElementSize);
657 /// Get the original access function as read from IR.
658 __isl_give isl_map *getOriginalAccessRelation() const;
660 /// Return the space in which the access relation lives in.
661 __isl_give isl_space *getOriginalAccessRelationSpace() const;
663 /// Get the new access function imported or set by a pass
664 __isl_give isl_map *getNewAccessRelation() const;
666 /// Fold the memory access to consider parametric offsets
668 /// To recover memory accesses with array size parameters in the subscript
669 /// expression we post-process the delinearization results.
671 /// We would normally recover from an access A[exp0(i) * N + exp1(i)] into an
672 /// array A[][N] the 2D access A[exp0(i)][exp1(i)]. However, another valid
673 /// delinearization is A[exp0(i) - 1][exp1(i) + N] which - depending on the
674 /// range of exp1(i) - may be preferable. Specifically, for cases where we
675 /// know exp1(i) is negative, we want to choose the latter expression.
677 /// As we commonly do not have any information about the range of exp1(i),
678 /// we do not choose one of the two options, but instead create a piecewise
679 /// access function that adds the (-1, N) offsets as soon as exp1(i) becomes
680 /// negative. For a 2D array such an access function is created by applying
681 /// the piecewise map:
683 /// [i,j] -> [i, j] : j >= 0
684 /// [i,j] -> [i-1, j+N] : j < 0
686 /// We can generalize this mapping to arbitrary dimensions by applying this
687 /// piecewise mapping pairwise from the rightmost to the leftmost access
688 /// dimension. It would also be possible to cover a wider range by introducing
689 /// more cases and adding multiple of Ns to these cases. However, this has
690 /// not yet been necessary.
691 /// The introduction of different cases necessarily complicates the memory
692 /// access function, but cases that can be statically proven to not happen
693 /// will be eliminated later on.
694 void foldAccessRelation();
696 /// Create the access relation for the underlying memory intrinsic.
697 void buildMemIntrinsicAccessRelation();
699 /// Assemble the access relation from all available information.
701 /// In particular, used the information passes in the constructor and the
702 /// parent ScopStmt set by setStatment().
704 /// @param SAI Info object for the accessed array.
705 void buildAccessRelation(const ScopArrayInfo *SAI);
707 /// Carry index overflows of dimensions with constant size to the next higher
708 /// dimension.
710 /// For dimensions that have constant size, modulo the index by the size and
711 /// add up the carry (floored division) to the next higher dimension. This is
712 /// how overflow is defined in row-major order.
713 /// It happens e.g. when ScalarEvolution computes the offset to the base
714 /// pointer and would algebraically sum up all lower dimensions' indices of
715 /// constant size.
717 /// Example:
718 /// float (*A)[4];
719 /// A[1][6] -> A[2][2]
720 void wrapConstantDimensions();
722 public:
723 /// Create a new MemoryAccess.
725 /// @param Stmt The parent statement.
726 /// @param AccessInst The instruction doing the access.
727 /// @param BaseAddr The accessed array's address.
728 /// @param ElemType The type of the accessed array elements.
729 /// @param AccType Whether read or write access.
730 /// @param IsAffine Whether the subscripts are affine expressions.
731 /// @param Kind The kind of memory accessed.
732 /// @param Subscripts Subscript expressions
733 /// @param Sizes Dimension lengths of the accessed array.
734 MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, AccessType AccType,
735 Value *BaseAddress, Type *ElemType, bool Affine,
736 ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
737 Value *AccessValue, MemoryKind Kind);
739 /// Create a new MemoryAccess that corresponds to @p AccRel.
741 /// Along with @p Stmt and @p AccType it uses information about dimension
742 /// lengths of the accessed array, the type of the accessed array elements,
743 /// the name of the accessed array that is derived from the object accessible
744 /// via @p AccRel.
746 /// @param Stmt The parent statement.
747 /// @param AccType Whether read or write access.
748 /// @param AccRel The access relation that describes the memory access.
749 MemoryAccess(ScopStmt *Stmt, AccessType AccType, __isl_take isl_map *AccRel);
751 ~MemoryAccess();
753 /// Add a new incoming block/value pairs for this PHI/ExitPHI access.
755 /// @param IncomingBlock The PHI's incoming block.
756 /// @param IncomingValue The value when reaching the PHI from the @p
757 /// IncomingBlock.
758 void addIncoming(BasicBlock *IncomingBlock, Value *IncomingValue) {
759 assert(!isRead());
760 assert(isAnyPHIKind());
761 Incoming.emplace_back(std::make_pair(IncomingBlock, IncomingValue));
764 /// Return the list of possible PHI/ExitPHI values.
766 /// After code generation moves some PHIs around during region simplification,
767 /// we cannot reliably locate the original PHI node and its incoming values
768 /// anymore. For this reason we remember these explicitly for all PHI-kind
769 /// accesses.
770 ArrayRef<std::pair<BasicBlock *, Value *>> getIncoming() const {
771 assert(isAnyPHIKind());
772 return Incoming;
775 /// Get the type of a memory access.
776 enum AccessType getType() { return AccType; }
778 /// Is this a reduction like access?
779 bool isReductionLike() const { return RedType != RT_NONE; }
781 /// Is this a read memory access?
782 bool isRead() const { return AccType == MemoryAccess::READ; }
784 /// Is this a must-write memory access?
785 bool isMustWrite() const { return AccType == MemoryAccess::MUST_WRITE; }
787 /// Is this a may-write memory access?
788 bool isMayWrite() const { return AccType == MemoryAccess::MAY_WRITE; }
790 /// Is this a write memory access?
791 bool isWrite() const { return isMustWrite() || isMayWrite(); }
793 /// Is this a memory intrinsic access (memcpy, memset, memmove)?
794 bool isMemoryIntrinsic() const {
795 return isa<MemIntrinsic>(getAccessInstruction());
798 /// Check if a new access relation was imported or set by a pass.
799 bool hasNewAccessRelation() const { return NewAccessRelation; }
801 /// Return the newest access relation of this access.
803 /// There are two possibilities:
804 /// 1) The original access relation read from the LLVM-IR.
805 /// 2) A new access relation imported from a json file or set by another
806 /// pass (e.g., for privatization).
808 /// As 2) is by construction "newer" than 1) we return the new access
809 /// relation if present.
811 __isl_give isl_map *getLatestAccessRelation() const {
812 return hasNewAccessRelation() ? getNewAccessRelation()
813 : getOriginalAccessRelation();
816 /// Old name of getLatestAccessRelation().
817 __isl_give isl_map *getAccessRelation() const {
818 return getLatestAccessRelation();
821 /// Get an isl map describing the memory address accessed.
823 /// In most cases the memory address accessed is well described by the access
824 /// relation obtained with getAccessRelation. However, in case of arrays
825 /// accessed with types of different size the access relation maps one access
826 /// to multiple smaller address locations. This method returns an isl map that
827 /// relates each dynamic statement instance to the unique memory location
828 /// that is loaded from / stored to.
830 /// For an access relation { S[i] -> A[o] : 4i <= o <= 4i + 3 } this method
831 /// will return the address function { S[i] -> A[4i] }.
833 /// @returns The address function for this memory access.
834 __isl_give isl_map *getAddressFunction() const;
836 /// Return the access relation after the schedule was applied.
837 __isl_give isl_pw_multi_aff *
838 applyScheduleToAccessRelation(__isl_take isl_union_map *Schedule) const;
840 /// Get an isl string representing the access function read from IR.
841 std::string getOriginalAccessRelationStr() const;
843 /// Get an isl string representing a new access function, if available.
844 std::string getNewAccessRelationStr() const;
846 /// Get an isl string representing the latest access relation.
847 std::string getAccessRelationStr() const;
849 /// Get the original base address of this access (e.g. A for A[i+j]) when
850 /// detected.
852 /// This adress may differ from the base address referenced by the Original
853 /// ScopArrayInfo to which this array belongs, as this memory access may
854 /// have been unified to a ScopArray which has a different but identically
855 /// valued base pointer in case invariant load hoisting is enabled.
856 Value *getOriginalBaseAddr() const { return BaseAddr; }
858 /// Get the detection-time base array isl_id for this access.
859 __isl_give isl_id *getOriginalArrayId() const;
861 /// Get the base array isl_id for this access, modifiable through
862 /// setNewAccessRelation().
863 __isl_give isl_id *getLatestArrayId() const;
865 /// Old name of getOriginalArrayId().
866 __isl_give isl_id *getArrayId() const { return getOriginalArrayId(); }
868 /// Get the detection-time ScopArrayInfo object for the base address.
869 const ScopArrayInfo *getOriginalScopArrayInfo() const;
871 /// Get the ScopArrayInfo object for the base address, or the one set
872 /// by setNewAccessRelation().
873 const ScopArrayInfo *getLatestScopArrayInfo() const;
875 /// Legacy name of getOriginalScopArrayInfo().
876 const ScopArrayInfo *getScopArrayInfo() const {
877 return getOriginalScopArrayInfo();
880 /// Return a string representation of the access's reduction type.
881 const std::string getReductionOperatorStr() const;
883 /// Return a string representation of the reduction type @p RT.
884 static const std::string getReductionOperatorStr(ReductionType RT);
886 /// Return the element type of the accessed array wrt. this access.
887 Type *getElementType() const { return ElementType; }
889 /// Return the access value of this memory access.
890 Value *getAccessValue() const { return AccessValue; }
892 /// Return llvm::Value that is stored by this access, if available.
894 /// PHI nodes may not have a unique value available that is stored, as in
895 /// case of region statements one out of possibly several llvm::Values
896 /// might be stored. In this case nullptr is returned.
897 Value *tryGetValueStored() {
898 assert(isWrite() && "Only write statement store values");
899 if (isAnyPHIKind()) {
900 if (Incoming.size() == 1)
901 return Incoming[0].second;
902 return nullptr;
904 return AccessValue;
907 /// Return the access instruction of this memory access.
908 Instruction *getAccessInstruction() const { return AccessInstruction; }
910 /// Return the number of access function subscript.
911 unsigned getNumSubscripts() const { return Subscripts.size(); }
913 /// Return the access function subscript in the dimension @p Dim.
914 const SCEV *getSubscript(unsigned Dim) const { return Subscripts[Dim]; }
916 /// Compute the isl representation for the SCEV @p E wrt. this access.
918 /// Note that this function will also adjust the invalid context accordingly.
919 __isl_give isl_pw_aff *getPwAff(const SCEV *E);
921 /// Get the invalid domain for this access.
922 __isl_give isl_set *getInvalidDomain() const {
923 return isl_set_copy(InvalidDomain);
926 /// Get the invalid context for this access.
927 __isl_give isl_set *getInvalidContext() const {
928 return isl_set_params(getInvalidDomain());
931 /// Get the stride of this memory access in the specified Schedule. Schedule
932 /// is a map from the statement to a schedule where the innermost dimension is
933 /// the dimension of the innermost loop containing the statement.
934 __isl_give isl_set *getStride(__isl_take const isl_map *Schedule) const;
936 /// Get the FortranArrayDescriptor corresponding to this memory access if
937 /// it exists, and nullptr otherwise.
938 Value *getFortranArrayDescriptor() const { return this->FAD; };
940 /// Is the stride of the access equal to a certain width? Schedule is a map
941 /// from the statement to a schedule where the innermost dimension is the
942 /// dimension of the innermost loop containing the statement.
943 bool isStrideX(__isl_take const isl_map *Schedule, int StrideWidth) const;
945 /// Is consecutive memory accessed for a given statement instance set?
946 /// Schedule is a map from the statement to a schedule where the innermost
947 /// dimension is the dimension of the innermost loop containing the
948 /// statement.
949 bool isStrideOne(__isl_take const isl_map *Schedule) const;
951 /// Is always the same memory accessed for a given statement instance set?
952 /// Schedule is a map from the statement to a schedule where the innermost
953 /// dimension is the dimension of the innermost loop containing the
954 /// statement.
955 bool isStrideZero(__isl_take const isl_map *Schedule) const;
957 /// Return the kind when this access was first detected.
958 MemoryKind getOriginalKind() const {
959 assert(!getOriginalScopArrayInfo() /* not yet initialized */ ||
960 getOriginalScopArrayInfo()->getKind() == Kind);
961 return Kind;
964 /// Return the kind considering a potential setNewAccessRelation.
965 MemoryKind getLatestKind() const {
966 return getLatestScopArrayInfo()->getKind();
969 /// Whether this is an access of an explicit load or store in the IR.
970 bool isOriginalArrayKind() const {
971 return getOriginalKind() == MemoryKind::Array;
974 /// Whether storage memory is either an custom .s2a/.phiops alloca
975 /// (false) or an existing pointer into an array (true).
976 bool isLatestArrayKind() const {
977 return getLatestKind() == MemoryKind::Array;
980 /// Old name of isOriginalArrayKind.
981 bool isArrayKind() const { return isOriginalArrayKind(); }
983 /// Whether this access is an array to a scalar memory object, without
984 /// considering changes by setNewAccessRelation.
986 /// Scalar accesses are accesses to MemoryKind::Value, MemoryKind::PHI or
987 /// MemoryKind::ExitPHI.
988 bool isOriginalScalarKind() const {
989 return getOriginalKind() != MemoryKind::Array;
992 /// Whether this access is an array to a scalar memory object, also
993 /// considering changes by setNewAccessRelation.
994 bool isLatestScalarKind() const {
995 return getLatestKind() != MemoryKind::Array;
998 /// Old name of isOriginalScalarKind.
999 bool isScalarKind() const { return isOriginalScalarKind(); }
1001 /// Was this MemoryAccess detected as a scalar dependences?
1002 bool isOriginalValueKind() const {
1003 return getOriginalKind() == MemoryKind::Value;
1006 /// Is this MemoryAccess currently modeling scalar dependences?
1007 bool isLatestValueKind() const {
1008 return getLatestKind() == MemoryKind::Value;
1011 /// Old name of isOriginalValueKind().
1012 bool isValueKind() const { return isOriginalValueKind(); }
1014 /// Was this MemoryAccess detected as a special PHI node access?
1015 bool isOriginalPHIKind() const {
1016 return getOriginalKind() == MemoryKind::PHI;
1019 /// Is this MemoryAccess modeling special PHI node accesses, also
1020 /// considering a potential change by setNewAccessRelation?
1021 bool isLatestPHIKind() const { return getLatestKind() == MemoryKind::PHI; }
1023 /// Old name of isOriginalPHIKind.
1024 bool isPHIKind() const { return isOriginalPHIKind(); }
1026 /// Was this MemoryAccess detected as the accesses of a PHI node in the
1027 /// SCoP's exit block?
1028 bool isOriginalExitPHIKind() const {
1029 return getOriginalKind() == MemoryKind::ExitPHI;
1032 /// Is this MemoryAccess modeling the accesses of a PHI node in the
1033 /// SCoP's exit block? Can be changed to an array access using
1034 /// setNewAccessRelation().
1035 bool isLatestExitPHIKind() const {
1036 return getLatestKind() == MemoryKind::ExitPHI;
1039 /// Old name of isOriginalExitPHIKind().
1040 bool isExitPHIKind() const { return isOriginalExitPHIKind(); }
1042 /// Was this access detected as one of the two PHI types?
1043 bool isOriginalAnyPHIKind() const {
1044 return isOriginalPHIKind() || isOriginalExitPHIKind();
1047 /// Does this access originate from one of the two PHI types? Can be
1048 /// changed to an array access using setNewAccessRelation().
1049 bool isLatestAnyPHIKind() const {
1050 return isLatestPHIKind() || isLatestExitPHIKind();
1053 /// Old name of isOriginalAnyPHIKind().
1054 bool isAnyPHIKind() const { return isOriginalAnyPHIKind(); }
1056 /// Get the statement that contains this memory access.
1057 ScopStmt *getStatement() const { return Statement; }
1059 /// Get the reduction type of this access
1060 ReductionType getReductionType() const { return RedType; }
1062 /// Set the array descriptor corresponding to the Array on which the
1063 /// memory access is performed.
1064 void setFortranArrayDescriptor(Value *FAD);
1066 /// Update the original access relation.
1068 /// We need to update the original access relation during scop construction,
1069 /// when unifying the memory accesses that access the same scop array info
1070 /// object. After the scop has been constructed, the original access relation
1071 /// should not be changed any more. Instead setNewAccessRelation should
1072 /// be called.
1073 void setAccessRelation(__isl_take isl_map *AccessRelation);
1075 /// Set the updated access relation read from JSCOP file.
1076 void setNewAccessRelation(__isl_take isl_map *NewAccessRelation);
1078 /// Return whether the MemoryyAccess is a partial access. That is, the access
1079 /// is not executed in some instances of the parent statement's domain.
1080 bool isLatestPartialAccess() const;
1082 /// Mark this a reduction like access
1083 void markAsReductionLike(ReductionType RT) { RedType = RT; }
1085 /// Align the parameters in the access relation to the scop context
1086 void realignParams();
1088 /// Update the dimensionality of the memory access.
1090 /// During scop construction some memory accesses may not be constructed with
1091 /// their full dimensionality, but outer dimensions may have been omitted if
1092 /// they took the value 'zero'. By updating the dimensionality of the
1093 /// statement we add additional zero-valued dimensions to match the
1094 /// dimensionality of the ScopArrayInfo object that belongs to this memory
1095 /// access.
1096 void updateDimensionality();
1098 /// Get identifier for the memory access.
1100 /// This identifier is unique for all accesses that belong to the same scop
1101 /// statement.
1102 __isl_give isl_id *getId() const;
1104 /// Print the MemoryAccess.
1106 /// @param OS The output stream the MemoryAccess is printed to.
1107 void print(raw_ostream &OS) const;
1109 /// Print the MemoryAccess to stderr.
1110 void dump() const;
1112 /// Is the memory access affine?
1113 bool isAffine() const { return IsAffine; }
1116 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1117 MemoryAccess::ReductionType RT);
1119 /// Ordered list type to hold accesses.
1120 using MemoryAccessList = std::forward_list<MemoryAccess *>;
1122 /// Helper structure for invariant memory accesses.
1123 struct InvariantAccess {
1124 /// The memory access that is (partially) invariant.
1125 MemoryAccess *MA;
1127 /// The context under which the access is not invariant.
1128 isl_set *NonHoistableCtx;
1131 /// Ordered container type to hold invariant accesses.
1132 using InvariantAccessesTy = SmallVector<InvariantAccess, 8>;
1134 /// Type for equivalent invariant accesses and their domain context.
1135 struct InvariantEquivClassTy {
1137 /// The pointer that identifies this equivalence class
1138 const SCEV *IdentifyingPointer;
1140 /// Memory accesses now treated invariant
1142 /// These memory accesses access the pointer location that identifies
1143 /// this equivalence class. They are treated as invariant and hoisted during
1144 /// code generation.
1145 MemoryAccessList InvariantAccesses;
1147 /// The execution context under which the memory location is accessed
1149 /// It is the union of the execution domains of the memory accesses in the
1150 /// InvariantAccesses list.
1151 isl_set *ExecutionContext;
1153 /// The type of the invariant access
1155 /// It is used to differentiate between differently typed invariant loads from
1156 /// the same location.
1157 Type *AccessType;
1160 /// Type for invariant accesses equivalence classes.
1161 using InvariantEquivClassesTy = SmallVector<InvariantEquivClassTy, 8>;
1163 /// Statement of the Scop
1165 /// A Scop statement represents an instruction in the Scop.
1167 /// It is further described by its iteration domain, its schedule and its data
1168 /// accesses.
1169 /// At the moment every statement represents a single basic block of LLVM-IR.
1170 class ScopStmt {
1171 public:
1172 ScopStmt(const ScopStmt &) = delete;
1173 const ScopStmt &operator=(const ScopStmt &) = delete;
1175 /// Create the ScopStmt from a BasicBlock.
1176 ScopStmt(Scop &parent, BasicBlock &bb, Loop *SurroundingLoop,
1177 std::vector<Instruction *> Instructions);
1179 /// Create an overapproximating ScopStmt for the region @p R.
1180 ScopStmt(Scop &parent, Region &R, Loop *SurroundingLoop);
1182 /// Create a copy statement.
1184 /// @param Stmt The parent statement.
1185 /// @param SourceRel The source location.
1186 /// @param TargetRel The target location.
1187 /// @param Domain The original domain under which the copy statement would
1188 /// be executed.
1189 ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1190 __isl_take isl_map *TargetRel, __isl_take isl_set *Domain);
1192 /// Initialize members after all MemoryAccesses have been added.
1193 void init(LoopInfo &LI);
1195 private:
1196 /// Polyhedral description
1197 //@{
1199 /// The Scop containing this ScopStmt.
1200 Scop &Parent;
1202 /// The domain under which this statement is not modeled precisely.
1204 /// The invalid domain for a statement describes all parameter combinations
1205 /// under which the statement looks to be executed but is in fact not because
1206 /// some assumption/restriction makes the statement/scop invalid.
1207 isl_set *InvalidDomain;
1209 /// The iteration domain describes the set of iterations for which this
1210 /// statement is executed.
1212 /// Example:
1213 /// for (i = 0; i < 100 + b; ++i)
1214 /// for (j = 0; j < i; ++j)
1215 /// S(i,j);
1217 /// 'S' is executed for different values of i and j. A vector of all
1218 /// induction variables around S (i, j) is called iteration vector.
1219 /// The domain describes the set of possible iteration vectors.
1221 /// In this case it is:
1223 /// Domain: 0 <= i <= 100 + b
1224 /// 0 <= j <= i
1226 /// A pair of statement and iteration vector (S, (5,3)) is called statement
1227 /// instance.
1228 isl_set *Domain;
1230 /// The memory accesses of this statement.
1232 /// The only side effects of a statement are its memory accesses.
1233 typedef SmallVector<MemoryAccess *, 8> MemoryAccessVec;
1234 MemoryAccessVec MemAccs;
1236 /// Mapping from instructions to (scalar) memory accesses.
1237 DenseMap<const Instruction *, MemoryAccessList> InstructionToAccess;
1239 /// The set of values defined elsewhere required in this ScopStmt and
1240 /// their MemoryKind::Value READ MemoryAccesses.
1241 DenseMap<Value *, MemoryAccess *> ValueReads;
1243 /// The set of values defined in this ScopStmt that are required
1244 /// elsewhere, mapped to their MemoryKind::Value WRITE MemoryAccesses.
1245 DenseMap<Instruction *, MemoryAccess *> ValueWrites;
1247 /// Map from PHI nodes to its incoming value when coming from this
1248 /// statement.
1250 /// Non-affine subregions can have multiple exiting blocks that are incoming
1251 /// blocks of the PHI nodes. This map ensures that there is only one write
1252 /// operation for the complete subregion. A PHI selecting the relevant value
1253 /// will be inserted.
1254 DenseMap<PHINode *, MemoryAccess *> PHIWrites;
1256 /// Map from PHI nodes to its read access in this statement.
1257 DenseMap<PHINode *, MemoryAccess *> PHIReads;
1259 //@}
1261 /// A SCoP statement represents either a basic block (affine/precise case) or
1262 /// a whole region (non-affine case).
1264 /// Only one of the following two members will therefore be set and indicate
1265 /// which kind of statement this is.
1267 ///{
1269 /// The BasicBlock represented by this statement (in the affine case).
1270 BasicBlock *BB;
1272 /// The region represented by this statement (in the non-affine case).
1273 Region *R;
1275 ///}
1277 /// The isl AST build for the new generated AST.
1278 isl_ast_build *Build;
1280 SmallVector<Loop *, 4> NestLoops;
1282 std::string BaseName;
1284 /// The closest loop that contains this statement.
1285 Loop *SurroundingLoop;
1287 /// Vector for Instructions in a BB.
1288 std::vector<Instruction *> Instructions;
1290 /// Build the statement.
1291 //@{
1292 void buildDomain();
1294 /// Fill NestLoops with loops surrounding this statement.
1295 void collectSurroundingLoops();
1297 /// Build the access relation of all memory accesses.
1298 void buildAccessRelations();
1300 /// Detect and mark reductions in the ScopStmt
1301 void checkForReductions();
1303 /// Collect loads which might form a reduction chain with @p StoreMA
1304 void
1305 collectCandiateReductionLoads(MemoryAccess *StoreMA,
1306 llvm::SmallVectorImpl<MemoryAccess *> &Loads);
1307 //@}
1309 /// Remove @p MA from dictionaries pointing to them.
1310 void removeAccessData(MemoryAccess *MA);
1312 public:
1313 ~ScopStmt();
1315 /// Get an isl_ctx pointer.
1316 isl_ctx *getIslCtx() const;
1318 /// Get the iteration domain of this ScopStmt.
1320 /// @return The iteration domain of this ScopStmt.
1321 __isl_give isl_set *getDomain() const;
1323 /// Get the space of the iteration domain
1325 /// @return The space of the iteration domain
1326 __isl_give isl_space *getDomainSpace() const;
1328 /// Get the id of the iteration domain space
1330 /// @return The id of the iteration domain space
1331 __isl_give isl_id *getDomainId() const;
1333 /// Get an isl string representing this domain.
1334 std::string getDomainStr() const;
1336 /// Get the schedule function of this ScopStmt.
1338 /// @return The schedule function of this ScopStmt, if it does not contain
1339 /// extension nodes, and nullptr, otherwise.
1340 __isl_give isl_map *getSchedule() const;
1342 /// Get an isl string representing this schedule.
1344 /// @return An isl string representing this schedule, if it does not contain
1345 /// extension nodes, and an empty string, otherwise.
1346 std::string getScheduleStr() const;
1348 /// Get the invalid domain for this statement.
1349 __isl_give isl_set *getInvalidDomain() const {
1350 return isl_set_copy(InvalidDomain);
1353 /// Get the invalid context for this statement.
1354 __isl_give isl_set *getInvalidContext() const {
1355 return isl_set_params(getInvalidDomain());
1358 /// Set the invalid context for this statement to @p ID.
1359 void setInvalidDomain(__isl_take isl_set *ID);
1361 /// Get the BasicBlock represented by this ScopStmt (if any).
1363 /// @return The BasicBlock represented by this ScopStmt, or null if the
1364 /// statement represents a region.
1365 BasicBlock *getBasicBlock() const { return BB; }
1367 /// Return true if this statement represents a single basic block.
1368 bool isBlockStmt() const { return BB != nullptr; }
1370 /// Return true if this is a copy statement.
1371 bool isCopyStmt() const { return BB == nullptr && R == nullptr; }
1373 /// Get the region represented by this ScopStmt (if any).
1375 /// @return The region represented by this ScopStmt, or null if the statement
1376 /// represents a basic block.
1377 Region *getRegion() const { return R; }
1379 /// Return true if this statement represents a whole region.
1380 bool isRegionStmt() const { return R != nullptr; }
1382 /// Return a BasicBlock from this statement.
1384 /// For block statements, it returns the BasicBlock itself. For subregion
1385 /// statements, return its entry block.
1386 BasicBlock *getEntryBlock() const;
1388 /// Return whether @p L is boxed within this statement.
1389 bool contains(const Loop *L) const {
1390 // Block statements never contain loops.
1391 if (isBlockStmt())
1392 return false;
1394 return getRegion()->contains(L);
1397 /// Return whether this statement contains @p BB.
1398 bool contains(BasicBlock *BB) const {
1399 if (isCopyStmt())
1400 return false;
1401 if (isBlockStmt())
1402 return BB == getBasicBlock();
1403 return getRegion()->contains(BB);
1406 /// Return whether this statement contains @p Inst.
1407 bool contains(Instruction *Inst) const {
1408 if (!Inst)
1409 return false;
1410 return contains(Inst->getParent());
1413 /// Return the closest innermost loop that contains this statement, but is not
1414 /// contained in it.
1416 /// For block statement, this is just the loop that contains the block. Region
1417 /// statements can contain boxed loops, so getting the loop of one of the
1418 /// region's BBs might return such an inner loop. For instance, the region's
1419 /// entry could be a header of a loop, but the region might extend to BBs
1420 /// after the loop exit. Similarly, the region might only contain parts of the
1421 /// loop body and still include the loop header.
1423 /// Most of the time the surrounding loop is the top element of #NestLoops,
1424 /// except when it is empty. In that case it return the loop that the whole
1425 /// SCoP is contained in. That can be nullptr if there is no such loop.
1426 Loop *getSurroundingLoop() const {
1427 assert(!isCopyStmt() &&
1428 "No surrounding loop for artificially created statements");
1429 return SurroundingLoop;
1432 /// Return true if this statement does not contain any accesses.
1433 bool isEmpty() const { return MemAccs.empty(); }
1435 /// Find all array accesses for @p Inst.
1437 /// @param Inst The instruction accessing an array.
1439 /// @return A list of array accesses (MemoryKind::Array) accessed by @p Inst.
1440 /// If there is no such access, it returns nullptr.
1441 const MemoryAccessList *
1442 lookupArrayAccessesFor(const Instruction *Inst) const {
1443 auto It = InstructionToAccess.find(Inst);
1444 if (It == InstructionToAccess.end())
1445 return nullptr;
1446 if (It->second.empty())
1447 return nullptr;
1448 return &It->second;
1451 /// Return the only array access for @p Inst, if existing.
1453 /// @param Inst The instruction for which to look up the access.
1454 /// @returns The unique array memory access related to Inst or nullptr if
1455 /// no array access exists
1456 MemoryAccess *getArrayAccessOrNULLFor(const Instruction *Inst) const {
1457 auto It = InstructionToAccess.find(Inst);
1458 if (It == InstructionToAccess.end())
1459 return nullptr;
1461 MemoryAccess *ArrayAccess = nullptr;
1463 for (auto Access : It->getSecond()) {
1464 if (!Access->isArrayKind())
1465 continue;
1467 assert(!ArrayAccess && "More then one array access for instruction");
1469 ArrayAccess = Access;
1472 return ArrayAccess;
1475 /// Return the only array access for @p Inst.
1477 /// @param Inst The instruction for which to look up the access.
1478 /// @returns The unique array memory access related to Inst.
1479 MemoryAccess &getArrayAccessFor(const Instruction *Inst) const {
1480 MemoryAccess *ArrayAccess = getArrayAccessOrNULLFor(Inst);
1482 assert(ArrayAccess && "No array access found for instruction!");
1483 return *ArrayAccess;
1486 /// Return the MemoryAccess that writes the value of an instruction
1487 /// defined in this statement, or nullptr if not existing, respectively
1488 /// not yet added.
1489 MemoryAccess *lookupValueWriteOf(Instruction *Inst) const {
1490 assert((isRegionStmt() && R->contains(Inst)) ||
1491 (!isRegionStmt() && Inst->getParent() == BB));
1492 return ValueWrites.lookup(Inst);
1495 /// Return the MemoryAccess that reloads a value, or nullptr if not
1496 /// existing, respectively not yet added.
1497 MemoryAccess *lookupValueReadOf(Value *Inst) const {
1498 return ValueReads.lookup(Inst);
1501 /// Return the MemoryAccess that loads a PHINode value, or nullptr if not
1502 /// existing, respectively not yet added.
1503 MemoryAccess *lookupPHIReadOf(PHINode *PHI) const {
1504 assert(isBlockStmt() || R->getEntry() == PHI->getParent());
1505 return PHIReads.lookup(PHI);
1508 /// Return the PHI write MemoryAccess for the incoming values from any
1509 /// basic block in this ScopStmt, or nullptr if not existing,
1510 /// respectively not yet added.
1511 MemoryAccess *lookupPHIWriteOf(PHINode *PHI) const {
1512 assert(isBlockStmt() || R->getExit() == PHI->getParent());
1513 return PHIWrites.lookup(PHI);
1516 /// Return the input access of the value, or null if no such MemoryAccess
1517 /// exists.
1519 /// The input access is the MemoryAccess that makes an inter-statement value
1520 /// available in this statement by reading it at the start of this statement.
1521 /// This can be a MemoryKind::Value if defined in another statement or a
1522 /// MemoryKind::PHI if the value is a PHINode in this statement.
1523 MemoryAccess *lookupInputAccessOf(Value *Val) const {
1524 if (isa<PHINode>(Val))
1525 if (auto InputMA = lookupPHIReadOf(cast<PHINode>(Val))) {
1526 assert(!lookupValueReadOf(Val) && "input accesses must be unique; a "
1527 "statement cannot read a .s2a and "
1528 ".phiops simultaneously");
1529 return InputMA;
1532 if (auto *InputMA = lookupValueReadOf(Val))
1533 return InputMA;
1535 return nullptr;
1538 /// Add @p Access to this statement's list of accesses.
1539 void addAccess(MemoryAccess *Access);
1541 /// Remove a MemoryAccess from this statement.
1543 /// Note that scalar accesses that are caused by MA will
1544 /// be eliminated too.
1545 void removeMemoryAccess(MemoryAccess *MA);
1547 /// Remove @p MA from this statement.
1549 /// In contrast to removeMemoryAccess(), no other access will be eliminated.
1550 void removeSingleMemoryAccess(MemoryAccess *MA);
1552 typedef MemoryAccessVec::iterator iterator;
1553 typedef MemoryAccessVec::const_iterator const_iterator;
1555 iterator begin() { return MemAccs.begin(); }
1556 iterator end() { return MemAccs.end(); }
1557 const_iterator begin() const { return MemAccs.begin(); }
1558 const_iterator end() const { return MemAccs.end(); }
1559 size_t size() const { return MemAccs.size(); }
1561 unsigned getNumIterators() const;
1563 Scop *getParent() { return &Parent; }
1564 const Scop *getParent() const { return &Parent; }
1566 const std::vector<Instruction *> &getInstructions() const {
1567 return Instructions;
1570 /// Set the list of instructions for this statement. It replaces the current
1571 /// list.
1572 void setInstructions(ArrayRef<Instruction *> Range) {
1573 Instructions.assign(Range.begin(), Range.end());
1576 std::vector<Instruction *>::const_iterator insts_begin() const {
1577 return Instructions.begin();
1580 std::vector<Instruction *>::const_iterator insts_end() const {
1581 return Instructions.end();
1584 /// The range of instructions in this statement.
1585 llvm::iterator_range<std::vector<Instruction *>::const_iterator>
1586 insts() const {
1587 return {insts_begin(), insts_end()};
1590 const char *getBaseName() const;
1592 /// Set the isl AST build.
1593 void setAstBuild(__isl_keep isl_ast_build *B) { Build = B; }
1595 /// Get the isl AST build.
1596 __isl_keep isl_ast_build *getAstBuild() const { return Build; }
1598 /// Restrict the domain of the statement.
1600 /// @param NewDomain The new statement domain.
1601 void restrictDomain(__isl_take isl_set *NewDomain);
1603 /// Get the loop for a dimension.
1605 /// @param Dimension The dimension of the induction variable
1606 /// @return The loop at a certain dimension.
1607 Loop *getLoopForDimension(unsigned Dimension) const;
1609 /// Align the parameters in the statement to the scop context
1610 void realignParams();
1612 /// Print the ScopStmt.
1614 /// @param OS The output stream the ScopStmt is printed to.
1615 void print(raw_ostream &OS) const;
1617 /// Print the instructions in ScopStmt.
1619 void printInstructions(raw_ostream &OS) const;
1621 /// Print the ScopStmt to stderr.
1622 void dump() const;
1625 /// Print ScopStmt S to raw_ostream O.
1626 static inline raw_ostream &operator<<(raw_ostream &O, const ScopStmt &S) {
1627 S.print(O);
1628 return O;
1631 /// Static Control Part
1633 /// A Scop is the polyhedral representation of a control flow region detected
1634 /// by the Scop detection. It is generated by translating the LLVM-IR and
1635 /// abstracting its effects.
1637 /// A Scop consists of a set of:
1639 /// * A set of statements executed in the Scop.
1641 /// * A set of global parameters
1642 /// Those parameters are scalar integer values, which are constant during
1643 /// execution.
1645 /// * A context
1646 /// This context contains information about the values the parameters
1647 /// can take and relations between different parameters.
1648 class Scop {
1649 public:
1650 /// Type to represent a pair of minimal/maximal access to an array.
1651 using MinMaxAccessTy = std::pair<isl_pw_multi_aff *, isl_pw_multi_aff *>;
1653 /// Vector of minimal/maximal accesses to different arrays.
1654 using MinMaxVectorTy = SmallVector<MinMaxAccessTy, 4>;
1656 /// Pair of minimal/maximal access vectors representing
1657 /// read write and read only accesses
1658 using MinMaxVectorPairTy = std::pair<MinMaxVectorTy, MinMaxVectorTy>;
1660 /// Vector of pair of minimal/maximal access vectors representing
1661 /// non read only and read only accesses for each alias group.
1662 using MinMaxVectorPairVectorTy = SmallVector<MinMaxVectorPairTy, 4>;
1664 private:
1665 Scop(const Scop &) = delete;
1666 const Scop &operator=(const Scop &) = delete;
1668 ScalarEvolution *SE;
1670 /// The underlying Region.
1671 Region &R;
1673 /// The name of the SCoP (identical to the regions name)
1674 std::string name;
1676 /// The ID to be assigned to the next Scop in a function
1677 static int NextScopID;
1679 /// The name of the function currently under consideration
1680 static std::string CurrentFunc;
1682 // Access functions of the SCoP.
1684 // This owns all the MemoryAccess objects of the Scop created in this pass.
1685 AccFuncVector AccessFunctions;
1687 /// Flag to indicate that the scheduler actually optimized the SCoP.
1688 bool IsOptimized;
1690 /// True if the underlying region has a single exiting block.
1691 bool HasSingleExitEdge;
1693 /// Flag to remember if the SCoP contained an error block or not.
1694 bool HasErrorBlock;
1696 /// Max loop depth.
1697 unsigned MaxLoopDepth;
1699 /// Number of copy statements.
1700 unsigned CopyStmtsNum;
1702 /// Flag to indicate if the Scop is to be skipped.
1703 bool SkipScop;
1705 typedef std::list<ScopStmt> StmtSet;
1706 /// The statements in this Scop.
1707 StmtSet Stmts;
1709 /// Parameters of this Scop
1710 ParameterSetTy Parameters;
1712 /// Mapping from parameters to their ids.
1713 DenseMap<const SCEV *, isl_id *> ParameterIds;
1715 /// The context of the SCoP created during SCoP detection.
1716 ScopDetection::DetectionContext &DC;
1718 /// OptimizationRemarkEmitter object for displaying diagnostic remarks
1719 OptimizationRemarkEmitter &ORE;
1721 /// Isl context.
1723 /// We need a shared_ptr with reference counter to delete the context when all
1724 /// isl objects are deleted. We will distribute the shared_ptr to all objects
1725 /// that use the context to create isl objects, and increase the reference
1726 /// counter. By doing this, we guarantee that the context is deleted when we
1727 /// delete the last object that creates isl objects with the context.
1728 std::shared_ptr<isl_ctx> IslCtx;
1730 /// A map from basic blocks to vector of SCoP statements. Currently this
1731 /// vector comprises only of a single statement.
1732 DenseMap<BasicBlock *, std::vector<ScopStmt *>> StmtMap;
1734 /// A map from basic blocks to their domains.
1735 DenseMap<BasicBlock *, isl::set> DomainMap;
1737 /// Constraints on parameters.
1738 isl_set *Context;
1740 /// The affinator used to translate SCEVs to isl expressions.
1741 SCEVAffinator Affinator;
1743 typedef std::map<std::pair<AssertingVH<const Value>, MemoryKind>,
1744 std::unique_ptr<ScopArrayInfo>>
1745 ArrayInfoMapTy;
1747 typedef StringMap<std::unique_ptr<ScopArrayInfo>> ArrayNameMapTy;
1749 typedef SetVector<ScopArrayInfo *> ArrayInfoSetTy;
1751 /// A map to remember ScopArrayInfo objects for all base pointers.
1753 /// As PHI nodes may have two array info objects associated, we add a flag
1754 /// that distinguishes between the PHI node specific ArrayInfo object
1755 /// and the normal one.
1756 ArrayInfoMapTy ScopArrayInfoMap;
1758 /// A map to remember ScopArrayInfo objects for all names of memory
1759 /// references.
1760 ArrayNameMapTy ScopArrayNameMap;
1762 /// A set to remember ScopArrayInfo objects.
1763 /// @see Scop::ScopArrayInfoMap
1764 ArrayInfoSetTy ScopArrayInfoSet;
1766 /// The assumptions under which this scop was built.
1768 /// When constructing a scop sometimes the exact representation of a statement
1769 /// or condition would be very complex, but there is a common case which is a
1770 /// lot simpler, but which is only valid under certain assumptions. The
1771 /// assumed context records the assumptions taken during the construction of
1772 /// this scop and that need to be code generated as a run-time test.
1773 isl_set *AssumedContext;
1775 /// The restrictions under which this SCoP was built.
1777 /// The invalid context is similar to the assumed context as it contains
1778 /// constraints over the parameters. However, while we need the constraints
1779 /// in the assumed context to be "true" the constraints in the invalid context
1780 /// need to be "false". Otherwise they behave the same.
1781 isl_set *InvalidContext;
1783 /// Helper struct to remember assumptions.
1784 struct Assumption {
1786 /// The kind of the assumption (e.g., WRAPPING).
1787 AssumptionKind Kind;
1789 /// Flag to distinguish assumptions and restrictions.
1790 AssumptionSign Sign;
1792 /// The valid/invalid context if this is an assumption/restriction.
1793 isl_set *Set;
1795 /// The location that caused this assumption.
1796 DebugLoc Loc;
1798 /// An optional block whose domain can simplify the assumption.
1799 BasicBlock *BB;
1802 /// Collection to hold taken assumptions.
1804 /// There are two reasons why we want to record assumptions first before we
1805 /// add them to the assumed/invalid context:
1806 /// 1) If the SCoP is not profitable or otherwise invalid without the
1807 /// assumed/invalid context we do not have to compute it.
1808 /// 2) Information about the context are gathered rather late in the SCoP
1809 /// construction (basically after we know all parameters), thus the user
1810 /// might see overly complicated assumptions to be taken while they will
1811 /// only be simplified later on.
1812 SmallVector<Assumption, 8> RecordedAssumptions;
1814 /// The schedule of the SCoP
1816 /// The schedule of the SCoP describes the execution order of the statements
1817 /// in the scop by assigning each statement instance a possibly
1818 /// multi-dimensional execution time. The schedule is stored as a tree of
1819 /// schedule nodes.
1821 /// The most common nodes in a schedule tree are so-called band nodes. Band
1822 /// nodes map statement instances into a multi dimensional schedule space.
1823 /// This space can be seen as a multi-dimensional clock.
1825 /// Example:
1827 /// <S,(5,4)> may be mapped to (5,4) by this schedule:
1829 /// s0 = i (Year of execution)
1830 /// s1 = j (Day of execution)
1832 /// or to (9, 20) by this schedule:
1834 /// s0 = i + j (Year of execution)
1835 /// s1 = 20 (Day of execution)
1837 /// The order statement instances are executed is defined by the
1838 /// schedule vectors they are mapped to. A statement instance
1839 /// <A, (i, j, ..)> is executed before a statement instance <B, (i', ..)>, if
1840 /// the schedule vector of A is lexicographic smaller than the schedule
1841 /// vector of B.
1843 /// Besides band nodes, schedule trees contain additional nodes that specify
1844 /// a textual ordering between two subtrees or filter nodes that filter the
1845 /// set of statement instances that will be scheduled in a subtree. There
1846 /// are also several other nodes. A full description of the different nodes
1847 /// in a schedule tree is given in the isl manual.
1848 isl_schedule *Schedule;
1850 /// The set of minimal/maximal accesses for each alias group.
1852 /// When building runtime alias checks we look at all memory instructions and
1853 /// build so called alias groups. Each group contains a set of accesses to
1854 /// different base arrays which might alias with each other. However, between
1855 /// alias groups there is no aliasing possible.
1857 /// In a program with int and float pointers annotated with tbaa information
1858 /// we would probably generate two alias groups, one for the int pointers and
1859 /// one for the float pointers.
1861 /// During code generation we will create a runtime alias check for each alias
1862 /// group to ensure the SCoP is executed in an alias free environment.
1863 MinMaxVectorPairVectorTy MinMaxAliasGroups;
1865 /// Mapping from invariant loads to the representing invariant load of
1866 /// their equivalence class.
1867 ValueToValueMap InvEquivClassVMap;
1869 /// List of invariant accesses.
1870 InvariantEquivClassesTy InvariantEquivClasses;
1872 /// The smallest array index not yet assigned.
1873 long ArrayIdx = 0;
1875 /// The smallest statement index not yet assigned.
1876 long StmtIdx = 0;
1878 /// A number that uniquely represents a Scop within its function
1879 const int ID;
1881 /// List of all uses (i.e. read MemoryAccesses) for a MemoryKind::Value
1882 /// scalar.
1883 DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>> ValueUseAccs;
1885 /// List of all incoming values (write MemoryAccess) of a MemoryKind::PHI or
1886 /// MemoryKind::ExitPHI scalar.
1887 DenseMap<const ScopArrayInfo *, SmallVector<MemoryAccess *, 4>>
1888 PHIIncomingAccs;
1890 /// Return the ID for a new Scop within a function
1891 static int getNextID(std::string ParentFunc);
1893 /// Scop constructor; invoked from ScopBuilder::buildScop.
1894 Scop(Region &R, ScalarEvolution &SE, LoopInfo &LI,
1895 ScopDetection::DetectionContext &DC, OptimizationRemarkEmitter &ORE);
1897 //@}
1899 /// Initialize this ScopBuilder.
1900 void init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
1901 LoopInfo &LI);
1903 /// Propagate domains that are known due to graph properties.
1905 /// As a CFG is mostly structured we use the graph properties to propagate
1906 /// domains without the need to compute all path conditions. In particular, if
1907 /// a block A dominates a block B and B post-dominates A we know that the
1908 /// domain of B is a superset of the domain of A. As we do not have
1909 /// post-dominator information available here we use the less precise region
1910 /// information. Given a region R, we know that the exit is always executed if
1911 /// the entry was executed, thus the domain of the exit is a superset of the
1912 /// domain of the entry. In case the exit can only be reached from within the
1913 /// region the domains are in fact equal. This function will use this property
1914 /// to avoid the generation of condition constraints that determine when a
1915 /// branch is taken. If @p BB is a region entry block we will propagate its
1916 /// domain to the region exit block. Additionally, we put the region exit
1917 /// block in the @p FinishedExitBlocks set so we can later skip edges from
1918 /// within the region to that block.
1920 /// @param BB The block for which the domain is currently
1921 /// propagated.
1922 /// @param BBLoop The innermost affine loop surrounding @p BB.
1923 /// @param FinishedExitBlocks Set of region exits the domain was set for.
1924 /// @param LI The LoopInfo for the current function.
1925 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1926 /// region.
1927 void propagateDomainConstraintsToRegionExit(
1928 BasicBlock *BB, Loop *BBLoop,
1929 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI,
1930 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1932 /// Compute the union of predecessor domains for @p BB.
1934 /// To compute the union of all domains of predecessors of @p BB this
1935 /// function applies similar reasoning on the CFG structure as described for
1936 /// @see propagateDomainConstraintsToRegionExit
1938 /// @param BB The block for which the predecessor domains are collected.
1939 /// @param Domain The domain under which BB is executed.
1940 /// @param DT The DominatorTree for the current function.
1941 /// @param LI The LoopInfo for the current function.
1943 /// @returns The domain under which @p BB is executed.
1944 __isl_give isl_set *
1945 getPredecessorDomainConstraints(BasicBlock *BB, __isl_keep isl_set *Domain,
1946 DominatorTree &DT, LoopInfo &LI);
1948 /// Add loop carried constraints to the header block of the loop @p L.
1950 /// @param L The loop to process.
1951 /// @param LI The LoopInfo for the current function.
1952 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1953 /// region.
1955 /// @returns True if there was no problem and false otherwise.
1956 bool addLoopBoundsToHeaderDomain(
1957 Loop *L, LoopInfo &LI,
1958 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1960 /// Compute the branching constraints for each basic block in @p R.
1962 /// @param R The region we currently build branching conditions
1963 /// for.
1964 /// @param DT The DominatorTree for the current function.
1965 /// @param LI The LoopInfo for the current function.
1966 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1967 /// region.
1969 /// @returns True if there was no problem and false otherwise.
1970 bool buildDomainsWithBranchConstraints(
1971 Region *R, DominatorTree &DT, LoopInfo &LI,
1972 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1974 /// Propagate the domain constraints through the region @p R.
1976 /// @param R The region we currently build branching conditions
1977 /// for.
1978 /// @param DT The DominatorTree for the current function.
1979 /// @param LI The LoopInfo for the current function.
1980 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1981 /// region.
1983 /// @returns True if there was no problem and false otherwise.
1984 bool propagateDomainConstraints(
1985 Region *R, DominatorTree &DT, LoopInfo &LI,
1986 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
1988 /// Propagate invalid domains of statements through @p R.
1990 /// This method will propagate invalid statement domains through @p R and at
1991 /// the same time add error block domains to them. Additionally, the domains
1992 /// of error statements and those only reachable via error statements will be
1993 /// replaced by an empty set. Later those will be removed completely.
1995 /// @param R The currently traversed region.
1996 /// @param DT The DominatorTree for the current function.
1997 /// @param LI The LoopInfo for the current function.
1998 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
1999 /// region.
2001 /// @returns True if there was no problem and false otherwise.
2002 bool propagateInvalidStmtDomains(
2003 Region *R, DominatorTree &DT, LoopInfo &LI,
2004 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2006 /// Compute the domain for each basic block in @p R.
2008 /// @param R The region we currently traverse.
2009 /// @param DT The DominatorTree for the current function.
2010 /// @param LI The LoopInfo for the current function.
2011 /// @param InvalidDomainMap BB to InvalidDomain map for the BB of current
2012 /// region.
2014 /// @returns True if there was no problem and false otherwise.
2015 bool buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI,
2016 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2018 /// Add parameter constraints to @p C that imply a non-empty domain.
2019 __isl_give isl_set *addNonEmptyDomainConstraints(__isl_take isl_set *C) const;
2021 /// Return the access for the base ptr of @p MA if any.
2022 MemoryAccess *lookupBasePtrAccess(MemoryAccess *MA);
2024 /// Check if the base ptr of @p MA is in the SCoP but not hoistable.
2025 bool hasNonHoistableBasePtrInScop(MemoryAccess *MA, isl::union_map Writes);
2027 /// Create equivalence classes for required invariant accesses.
2029 /// These classes will consolidate multiple required invariant loads from the
2030 /// same address in order to keep the number of dimensions in the SCoP
2031 /// description small. For each such class equivalence class only one
2032 /// representing element, hence one required invariant load, will be chosen
2033 /// and modeled as parameter. The method
2034 /// Scop::getRepresentingInvariantLoadSCEV() will replace each element from an
2035 /// equivalence class with the representing element that is modeled. As a
2036 /// consequence Scop::getIdForParam() will only return an id for the
2037 /// representing element of each equivalence class, thus for each required
2038 /// invariant location.
2039 void buildInvariantEquivalenceClasses();
2041 /// Return the context under which the access cannot be hoisted.
2043 /// @param Access The access to check.
2044 /// @param Writes The set of all memory writes in the scop.
2046 /// @return Return the context under which the access cannot be hoisted or a
2047 /// nullptr if it cannot be hoisted at all.
2048 isl::set getNonHoistableCtx(MemoryAccess *Access, isl::union_map Writes);
2050 /// Verify that all required invariant loads have been hoisted.
2052 /// Invariant load hoisting is not guaranteed to hoist all loads that were
2053 /// assumed to be scop invariant during scop detection. This function checks
2054 /// for cases where the hoisting failed, but where it would have been
2055 /// necessary for our scop modeling to be correct. In case of insufficient
2056 /// hoisting the scop is marked as invalid.
2058 /// In the example below Bound[1] is required to be invariant:
2060 /// for (int i = 1; i < Bound[0]; i++)
2061 /// for (int j = 1; j < Bound[1]; j++)
2062 /// ...
2064 void verifyInvariantLoads();
2066 /// Hoist invariant memory loads and check for required ones.
2068 /// We first identify "common" invariant loads, thus loads that are invariant
2069 /// and can be hoisted. Then we check if all required invariant loads have
2070 /// been identified as (common) invariant. A load is a required invariant load
2071 /// if it was assumed to be invariant during SCoP detection, e.g., to assume
2072 /// loop bounds to be affine or runtime alias checks to be placeable. In case
2073 /// a required invariant load was not identified as (common) invariant we will
2074 /// drop this SCoP. An example for both "common" as well as required invariant
2075 /// loads is given below:
2077 /// for (int i = 1; i < *LB[0]; i++)
2078 /// for (int j = 1; j < *LB[1]; j++)
2079 /// A[i][j] += A[0][0] + (*V);
2081 /// Common inv. loads: V, A[0][0], LB[0], LB[1]
2082 /// Required inv. loads: LB[0], LB[1], (V, if it may alias with A or LB)
2084 void hoistInvariantLoads();
2086 /// Canonicalize arrays with base pointers from the same equivalence class.
2088 /// Some context: in our normal model we assume that each base pointer is
2089 /// related to a single specific memory region, where memory regions
2090 /// associated with different base pointers are disjoint. Consequently we do
2091 /// not need to compute additional data dependences that model possible
2092 /// overlaps of these memory regions. To verify our assumption we compute
2093 /// alias checks that verify that modeled arrays indeed do not overlap. In
2094 /// case an overlap is detected the runtime check fails and we fall back to
2095 /// the original code.
2097 /// In case of arrays where the base pointers are know to be identical,
2098 /// because they are dynamically loaded by accesses that are in the same
2099 /// invariant load equivalence class, such run-time alias check would always
2100 /// be false.
2102 /// This function makes sure that we do not generate consistently failing
2103 /// run-time checks for code that contains distinct arrays with known
2104 /// equivalent base pointers. It identifies for each invariant load
2105 /// equivalence class a single canonical array and canonicalizes all memory
2106 /// accesses that reference arrays that have base pointers that are known to
2107 /// be equal to the base pointer of such a canonical array to this canonical
2108 /// array.
2110 /// We currently do not canonicalize arrays for which certain memory accesses
2111 /// have been hoisted as loop invariant.
2112 void canonicalizeDynamicBasePtrs();
2114 /// Add invariant loads listed in @p InvMAs with the domain of @p Stmt.
2115 void addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs);
2117 /// Create an id for @p Param and store it in the ParameterIds map.
2118 void createParameterId(const SCEV *Param);
2120 /// Build the Context of the Scop.
2121 void buildContext();
2123 /// Add user provided parameter constraints to context (source code).
2124 void addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI,
2125 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap);
2127 /// Add user provided parameter constraints to context (command line).
2128 void addUserContext();
2130 /// Add the bounds of the parameters to the context.
2131 void addParameterBounds();
2133 /// Simplify the assumed and invalid context.
2134 void simplifyContexts();
2136 /// Get the representing SCEV for @p S if applicable, otherwise @p S.
2138 /// Invariant loads of the same location are put in an equivalence class and
2139 /// only one of them is chosen as a representing element that will be
2140 /// modeled as a parameter. The others have to be normalized, i.e.,
2141 /// replaced by the representing element of their equivalence class, in order
2142 /// to get the correct parameter value, e.g., in the SCEVAffinator.
2144 /// @param S The SCEV to normalize.
2146 /// @return The representing SCEV for invariant loads or @p S if none.
2147 const SCEV *getRepresentingInvariantLoadSCEV(const SCEV *S);
2149 /// Create a new SCoP statement for @p BB.
2151 /// A new statement for @p BB will be created and added to the statement
2152 /// vector
2153 /// and map.
2155 /// @param BB The basic block we build the statement for.
2156 /// @param SurroundingLoop The loop the created statement is contained in.
2157 /// @param Instructions The instructions in the basic block.
2158 void addScopStmt(BasicBlock *BB, Loop *SurroundingLoop,
2159 std::vector<Instruction *> Instructions);
2161 /// Create a new SCoP statement for @p R.
2163 /// A new statement for @p R will be created and added to the statement vector
2164 /// and map.
2166 /// @param R The region we build the statement for.
2167 /// @param SurroundingLoop The loop the created statement is contained in.
2168 void addScopStmt(Region *R, Loop *SurroundingLoop);
2170 /// Update access dimensionalities.
2172 /// When detecting memory accesses different accesses to the same array may
2173 /// have built with different dimensionality, as outer zero-values dimensions
2174 /// may not have been recognized as separate dimensions. This function goes
2175 /// again over all memory accesses and updates their dimensionality to match
2176 /// the dimensionality of the underlying ScopArrayInfo object.
2177 void updateAccessDimensionality();
2179 /// Fold size constants to the right.
2181 /// In case all memory accesses in a given dimension are multiplied with a
2182 /// common constant, we can remove this constant from the individual access
2183 /// functions and move it to the size of the memory access. We do this as this
2184 /// increases the size of the innermost dimension, consequently widens the
2185 /// valid range the array subscript in this dimension can evaluate to, and
2186 /// as a result increases the likelihood that our delinearization is
2187 /// correct.
2189 /// Example:
2191 /// A[][n]
2192 /// S[i,j] -> A[2i][2j+1]
2193 /// S[i,j] -> A[2i][2j]
2195 /// =>
2197 /// A[][2n]
2198 /// S[i,j] -> A[i][2j+1]
2199 /// S[i,j] -> A[i][2j]
2201 /// Constants in outer dimensions can arise when the elements of a parametric
2202 /// multi-dimensional array are not elementary data types, but e.g.,
2203 /// structures.
2204 void foldSizeConstantsToRight();
2206 /// Fold memory accesses to handle parametric offset.
2208 /// As a post-processing step, we 'fold' memory accesses to parametric
2209 /// offsets in the access functions. @see MemoryAccess::foldAccess for
2210 /// details.
2211 void foldAccessRelations();
2213 /// Assume that all memory accesses are within bounds.
2215 /// After we have built a model of all memory accesses, we need to assume
2216 /// that the model we built matches reality -- aka. all modeled memory
2217 /// accesses always remain within bounds. We do this as last step, after
2218 /// all memory accesses have been modeled and canonicalized.
2219 void assumeNoOutOfBounds();
2221 /// Remove statements from the list of scop statements.
2223 /// @param ShouldDelete A function that returns true if the statement passed
2224 /// to it should be deleted.
2225 void removeStmts(std::function<bool(ScopStmt &)> ShouldDelete);
2227 /// Removes @p Stmt from the StmtMap.
2228 void removeFromStmtMap(ScopStmt &Stmt);
2230 /// Removes all statements where the entry block of the statement does not
2231 /// have a corresponding domain in the domain map.
2232 void removeStmtNotInDomainMap();
2234 /// Mark arrays that have memory accesses with FortranArrayDescriptor.
2235 void markFortranArrays();
2237 /// Finalize all access relations.
2239 /// When building up access relations, temporary access relations that
2240 /// correctly represent each individual access are constructed. However, these
2241 /// access relations can be inconsistent or non-optimal when looking at the
2242 /// set of accesses as a whole. This function finalizes the memory accesses
2243 /// and constructs a globally consistent state.
2244 void finalizeAccesses();
2246 /// Construct the schedule of this SCoP.
2248 /// @param LI The LoopInfo for the current function.
2249 void buildSchedule(LoopInfo &LI);
2251 /// A loop stack element to keep track of per-loop information during
2252 /// schedule construction.
2253 typedef struct LoopStackElement {
2254 // The loop for which we keep information.
2255 Loop *L;
2257 // The (possibly incomplete) schedule for this loop.
2258 isl_schedule *Schedule;
2260 // The number of basic blocks in the current loop, for which a schedule has
2261 // already been constructed.
2262 unsigned NumBlocksProcessed;
2264 LoopStackElement(Loop *L, __isl_give isl_schedule *S,
2265 unsigned NumBlocksProcessed)
2266 : L(L), Schedule(S), NumBlocksProcessed(NumBlocksProcessed) {}
2267 } LoopStackElementTy;
2269 /// The loop stack used for schedule construction.
2271 /// The loop stack keeps track of schedule information for a set of nested
2272 /// loops as well as an (optional) 'nullptr' loop that models the outermost
2273 /// schedule dimension. The loops in a loop stack always have a parent-child
2274 /// relation where the loop at position n is the parent of the loop at
2275 /// position n + 1.
2276 typedef SmallVector<LoopStackElementTy, 4> LoopStackTy;
2278 /// Construct schedule information for a given Region and add the
2279 /// derived information to @p LoopStack.
2281 /// Given a Region we derive schedule information for all RegionNodes
2282 /// contained in this region ensuring that the assigned execution times
2283 /// correctly model the existing control flow relations.
2285 /// @param R The region which to process.
2286 /// @param LoopStack A stack of loops that are currently under
2287 /// construction.
2288 /// @param LI The LoopInfo for the current function.
2289 void buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI);
2291 /// Build Schedule for the region node @p RN and add the derived
2292 /// information to @p LoopStack.
2294 /// In case @p RN is a BasicBlock or a non-affine Region, we construct the
2295 /// schedule for this @p RN and also finalize loop schedules in case the
2296 /// current @p RN completes the loop.
2298 /// In case @p RN is a not-non-affine Region, we delegate the construction to
2299 /// buildSchedule(Region *R, ...).
2301 /// @param RN The RegionNode region traversed.
2302 /// @param LoopStack A stack of loops that are currently under
2303 /// construction.
2304 /// @param LI The LoopInfo for the current function.
2305 void buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI);
2307 /// Collect all memory access relations of a given type.
2309 /// @param Predicate A predicate function that returns true if an access is
2310 /// of a given type.
2312 /// @returns The set of memory accesses in the scop that match the predicate.
2313 __isl_give isl_union_map *
2314 getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate);
2316 /// @name Helper functions for printing the Scop.
2318 //@{
2319 void printContext(raw_ostream &OS) const;
2320 void printArrayInfo(raw_ostream &OS) const;
2321 void printStatements(raw_ostream &OS) const;
2322 void printAliasAssumptions(raw_ostream &OS) const;
2323 //@}
2325 friend class ScopBuilder;
2327 public:
2328 ~Scop();
2330 /// Get the count of copy statements added to this Scop.
2332 /// @return The count of copy statements added to this Scop.
2333 unsigned getCopyStmtsNum() { return CopyStmtsNum; }
2335 /// Create a new copy statement.
2337 /// A new statement will be created and added to the statement vector.
2339 /// @param Stmt The parent statement.
2340 /// @param SourceRel The source location.
2341 /// @param TargetRel The target location.
2342 /// @param Domain The original domain under which the copy statement would
2343 /// be executed.
2344 ScopStmt *addScopStmt(__isl_take isl_map *SourceRel,
2345 __isl_take isl_map *TargetRel,
2346 __isl_take isl_set *Domain);
2348 /// Add the access function to all MemoryAccess objects of the Scop
2349 /// created in this pass.
2350 void addAccessFunction(MemoryAccess *Access) {
2351 AccessFunctions.emplace_back(Access);
2354 /// Add metadata for @p Access.
2355 void addAccessData(MemoryAccess *Access);
2357 /// Remove the metadata stored for @p Access.
2358 void removeAccessData(MemoryAccess *Access);
2360 ScalarEvolution *getSE() const;
2362 /// Get the count of parameters used in this Scop.
2364 /// @return The count of parameters used in this Scop.
2365 size_t getNumParams() const { return Parameters.size(); }
2367 /// Take a list of parameters and add the new ones to the scop.
2368 void addParams(const ParameterSetTy &NewParameters);
2370 /// Return an iterator range containing the scop parameters.
2371 iterator_range<ParameterSetTy::iterator> parameters() const {
2372 return make_range(Parameters.begin(), Parameters.end());
2375 /// Return whether this scop is empty, i.e. contains no statements that
2376 /// could be executed.
2377 bool isEmpty() const { return Stmts.empty(); }
2379 const StringRef getName() const { return name; }
2381 typedef ArrayInfoSetTy::iterator array_iterator;
2382 typedef ArrayInfoSetTy::const_iterator const_array_iterator;
2383 typedef iterator_range<ArrayInfoSetTy::iterator> array_range;
2384 typedef iterator_range<ArrayInfoSetTy::const_iterator> const_array_range;
2386 inline array_iterator array_begin() { return ScopArrayInfoSet.begin(); }
2388 inline array_iterator array_end() { return ScopArrayInfoSet.end(); }
2390 inline const_array_iterator array_begin() const {
2391 return ScopArrayInfoSet.begin();
2394 inline const_array_iterator array_end() const {
2395 return ScopArrayInfoSet.end();
2398 inline array_range arrays() {
2399 return array_range(array_begin(), array_end());
2402 inline const_array_range arrays() const {
2403 return const_array_range(array_begin(), array_end());
2406 /// Return the isl_id that represents a certain parameter.
2408 /// @param Parameter A SCEV that was recognized as a Parameter.
2410 /// @return The corresponding isl_id or NULL otherwise.
2411 __isl_give isl_id *getIdForParam(const SCEV *Parameter);
2413 /// Get the maximum region of this static control part.
2415 /// @return The maximum region of this static control part.
2416 inline const Region &getRegion() const { return R; }
2417 inline Region &getRegion() { return R; }
2419 /// Return the function this SCoP is in.
2420 Function &getFunction() const { return *R.getEntry()->getParent(); }
2422 /// Check if @p L is contained in the SCoP.
2423 bool contains(const Loop *L) const { return R.contains(L); }
2425 /// Check if @p BB is contained in the SCoP.
2426 bool contains(const BasicBlock *BB) const { return R.contains(BB); }
2428 /// Check if @p I is contained in the SCoP.
2429 bool contains(const Instruction *I) const { return R.contains(I); }
2431 /// Return the unique exit block of the SCoP.
2432 BasicBlock *getExit() const { return R.getExit(); }
2434 /// Return the unique exiting block of the SCoP if any.
2435 BasicBlock *getExitingBlock() const { return R.getExitingBlock(); }
2437 /// Return the unique entry block of the SCoP.
2438 BasicBlock *getEntry() const { return R.getEntry(); }
2440 /// Return the unique entering block of the SCoP if any.
2441 BasicBlock *getEnteringBlock() const { return R.getEnteringBlock(); }
2443 /// Return true if @p BB is the exit block of the SCoP.
2444 bool isExit(BasicBlock *BB) const { return getExit() == BB; }
2446 /// Return a range of all basic blocks in the SCoP.
2447 Region::block_range blocks() const { return R.blocks(); }
2449 /// Return true if and only if @p BB dominates the SCoP.
2450 bool isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const;
2452 /// Get the maximum depth of the loop.
2454 /// @return The maximum depth of the loop.
2455 inline unsigned getMaxLoopDepth() const { return MaxLoopDepth; }
2457 /// Return the invariant equivalence class for @p Val if any.
2458 InvariantEquivClassTy *lookupInvariantEquivClass(Value *Val);
2460 /// Return the set of invariant accesses.
2461 InvariantEquivClassesTy &getInvariantAccesses() {
2462 return InvariantEquivClasses;
2465 /// Check if the scop has any invariant access.
2466 bool hasInvariantAccesses() { return !InvariantEquivClasses.empty(); }
2468 /// Mark the SCoP as optimized by the scheduler.
2469 void markAsOptimized() { IsOptimized = true; }
2471 /// Check if the SCoP has been optimized by the scheduler.
2472 bool isOptimized() const { return IsOptimized; }
2474 /// Mark the SCoP to be skipped by ScopPass passes.
2475 void markAsToBeSkipped() { SkipScop = true; }
2477 /// Check if the SCoP is to be skipped by ScopPass passes.
2478 bool isToBeSkipped() const { return SkipScop; }
2480 /// Return the ID of the Scop
2481 int getID() const { return ID; }
2483 /// Get the name of the entry and exit blocks of this Scop.
2485 /// These along with the function name can uniquely identify a Scop.
2487 /// @return std::pair whose first element is the entry name & second element
2488 /// is the exit name.
2489 std::pair<std::string, std::string> getEntryExitStr() const;
2491 /// Get the name of this Scop.
2492 std::string getNameStr() const;
2494 /// Get the constraint on parameter of this Scop.
2496 /// @return The constraint on parameter of this Scop.
2497 __isl_give isl_set *getContext() const;
2498 __isl_give isl_space *getParamSpace() const;
2500 /// Get the assumed context for this Scop.
2502 /// @return The assumed context of this Scop.
2503 __isl_give isl_set *getAssumedContext() const;
2505 /// Return true if the optimized SCoP can be executed.
2507 /// In addition to the runtime check context this will also utilize the domain
2508 /// constraints to decide it the optimized version can actually be executed.
2510 /// @returns True if the optimized SCoP can be executed.
2511 bool hasFeasibleRuntimeContext() const;
2513 /// Check if the assumption in @p Set is trivial or not.
2515 /// @param Set The relations between parameters that are assumed to hold.
2516 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2517 /// (needed/assumptions) or negative (invalid/restrictions).
2519 /// @returns True if the assumption @p Set is not trivial.
2520 bool isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign);
2522 /// Track and report an assumption.
2524 /// Use 'clang -Rpass-analysis=polly-scops' or 'opt
2525 /// -pass-remarks-analysis=polly-scops' to output the assumptions.
2527 /// @param Kind The assumption kind describing the underlying cause.
2528 /// @param Set The relations between parameters that are assumed to hold.
2529 /// @param Loc The location in the source that caused this assumption.
2530 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2531 /// (needed/assumptions) or negative (invalid/restrictions).
2532 /// @param BB The block in which this assumption was taken. Used to
2533 /// calculate hotness when emitting remark.
2535 /// @returns True if the assumption is not trivial.
2536 bool trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2537 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB);
2539 /// Add assumptions to assumed context.
2541 /// The assumptions added will be assumed to hold during the execution of the
2542 /// scop. However, as they are generally not statically provable, at code
2543 /// generation time run-time checks will be generated that ensure the
2544 /// assumptions hold.
2546 /// WARNING: We currently exploit in simplifyAssumedContext the knowledge
2547 /// that assumptions do not change the set of statement instances
2548 /// executed.
2550 /// @param Kind The assumption kind describing the underlying cause.
2551 /// @param Set The relations between parameters that are assumed to hold.
2552 /// @param Loc The location in the source that caused this assumption.
2553 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2554 /// (needed/assumptions) or negative (invalid/restrictions).
2555 /// @param BB The block in which this assumption was taken. Used to
2556 /// calculate hotness when emitting remark.
2557 void addAssumption(AssumptionKind Kind, __isl_take isl_set *Set, DebugLoc Loc,
2558 AssumptionSign Sign, BasicBlock *BB);
2560 /// Record an assumption for later addition to the assumed context.
2562 /// This function will add the assumption to the RecordedAssumptions. This
2563 /// collection will be added (@see addAssumption) to the assumed context once
2564 /// all paramaters are known and the context is fully build.
2566 /// @param Kind The assumption kind describing the underlying cause.
2567 /// @param Set The relations between parameters that are assumed to hold.
2568 /// @param Loc The location in the source that caused this assumption.
2569 /// @param Sign Enum to indicate if the assumptions in @p Set are positive
2570 /// (needed/assumptions) or negative (invalid/restrictions).
2571 /// @param BB The block in which this assumption was taken. If it is
2572 /// set, the domain of that block will be used to simplify the
2573 /// actual assumption in @p Set once it is added. This is useful
2574 /// if the assumption was created prior to the domain.
2575 void recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
2576 DebugLoc Loc, AssumptionSign Sign,
2577 BasicBlock *BB = nullptr);
2579 /// Add all recorded assumptions to the assumed context.
2580 void addRecordedAssumptions();
2582 /// Mark the scop as invalid.
2584 /// This method adds an assumption to the scop that is always invalid. As a
2585 /// result, the scop will not be optimized later on. This function is commonly
2586 /// called when a condition makes it impossible (or too compile time
2587 /// expensive) to process this scop any further.
2589 /// @param Kind The assumption kind describing the underlying cause.
2590 /// @param Loc The location in the source that triggered .
2591 /// @param BB The BasicBlock where it was triggered.
2592 void invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB = nullptr);
2594 /// Get the invalid context for this Scop.
2596 /// @return The invalid context of this Scop.
2597 __isl_give isl_set *getInvalidContext() const;
2599 /// Return true if and only if the InvalidContext is trivial (=empty).
2600 bool hasTrivialInvalidContext() const {
2601 return isl_set_is_empty(InvalidContext);
2604 /// A vector of memory accesses that belong to an alias group.
2605 typedef SmallVector<MemoryAccess *, 4> AliasGroupTy;
2607 /// A vector of alias groups.
2608 typedef SmallVector<Scop::AliasGroupTy, 4> AliasGroupVectorTy;
2610 /// Build the alias checks for this SCoP.
2611 bool buildAliasChecks(AliasAnalysis &AA);
2613 /// Build all alias groups for this SCoP.
2615 /// @returns True if __no__ error occurred, false otherwise.
2616 bool buildAliasGroups(AliasAnalysis &AA);
2618 /// Build alias groups for all memory accesses in the Scop.
2620 /// Using the alias analysis and an alias set tracker we build alias sets
2621 /// for all memory accesses inside the Scop. For each alias set we then map
2622 /// the aliasing pointers back to the memory accesses we know, thus obtain
2623 /// groups of memory accesses which might alias. We also collect the set of
2624 /// arrays through which memory is written.
2626 /// @param AA A reference to the alias analysis.
2628 /// @returns A pair consistent of a vector of alias groups and a set of arrays
2629 /// through which memory is written.
2630 std::tuple<AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2631 buildAliasGroupsForAccesses(AliasAnalysis &AA);
2633 /// Split alias groups by iteration domains.
2635 /// We split each group based on the domains of the minimal/maximal accesses.
2636 /// That means two minimal/maximal accesses are only in a group if their
2637 /// access domains intersect. Otherwise, they are in different groups.
2639 /// @param AliasGroups The alias groups to split
2640 void splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups);
2642 /// Build a given alias group and its access data.
2644 /// @param AliasGroup The alias group to build.
2645 /// @param HasWriteAccess A set of arrays through which memory is not only
2646 /// read, but also written.
2648 /// @returns True if __no__ error occurred, false otherwise.
2649 bool buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
2650 DenseSet<const ScopArrayInfo *> HasWriteAccess);
2652 /// Return all alias groups for this SCoP.
2653 const MinMaxVectorPairVectorTy &getAliasGroups() const {
2654 return MinMaxAliasGroups;
2657 /// Get an isl string representing the context.
2658 std::string getContextStr() const;
2660 /// Get an isl string representing the assumed context.
2661 std::string getAssumedContextStr() const;
2663 /// Get an isl string representing the invalid context.
2664 std::string getInvalidContextStr() const;
2666 /// Return the ScopStmt for the given @p BB or nullptr if there is
2667 /// none.
2668 ScopStmt *getStmtFor(BasicBlock *BB) const;
2670 /// Return the list of ScopStmts that represent the given @p BB.
2671 ArrayRef<ScopStmt *> getStmtListFor(BasicBlock *BB) const;
2673 /// Return the last statement representing @p BB.
2675 /// Of the sequence of statements that represent a @p BB, this is the last one
2676 /// to be executed. It is typically used to determine which instruction to add
2677 /// a MemoryKind::PHI WRITE to. For this purpose, it is not strictly required
2678 /// to be executed last, only that the incoming value is available in it.
2679 ScopStmt *getLastStmtFor(BasicBlock *BB) const;
2681 /// Return the ScopStmt that represents the Region @p R, or nullptr if
2682 /// it is not represented by any statement in this Scop.
2683 ScopStmt *getStmtFor(Region *R) const;
2685 /// Return the ScopStmt that represents @p RN; can return nullptr if
2686 /// the RegionNode is not within the SCoP or has been removed due to
2687 /// simplifications.
2688 ScopStmt *getStmtFor(RegionNode *RN) const;
2690 /// Return the ScopStmt an instruction belongs to, or nullptr if it
2691 /// does not belong to any statement in this Scop.
2692 ScopStmt *getStmtFor(Instruction *Inst) const {
2693 return getStmtFor(Inst->getParent());
2696 /// Return the number of statements in the SCoP.
2697 size_t getSize() const { return Stmts.size(); }
2699 /// @name Statements Iterators
2701 /// These iterators iterate over all statements of this Scop.
2702 //@{
2703 typedef StmtSet::iterator iterator;
2704 typedef StmtSet::const_iterator const_iterator;
2706 iterator begin() { return Stmts.begin(); }
2707 iterator end() { return Stmts.end(); }
2708 const_iterator begin() const { return Stmts.begin(); }
2709 const_iterator end() const { return Stmts.end(); }
2711 typedef StmtSet::reverse_iterator reverse_iterator;
2712 typedef StmtSet::const_reverse_iterator const_reverse_iterator;
2714 reverse_iterator rbegin() { return Stmts.rbegin(); }
2715 reverse_iterator rend() { return Stmts.rend(); }
2716 const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
2717 const_reverse_iterator rend() const { return Stmts.rend(); }
2718 //@}
2720 /// Return the set of required invariant loads.
2721 const InvariantLoadsSetTy &getRequiredInvariantLoads() const {
2722 return DC.RequiredILS;
2725 /// Add @p LI to the set of required invariant loads.
2726 void addRequiredInvariantLoad(LoadInst *LI) { DC.RequiredILS.insert(LI); }
2728 /// Return true if and only if @p LI is a required invariant load.
2729 bool isRequiredInvariantLoad(LoadInst *LI) const {
2730 return getRequiredInvariantLoads().count(LI);
2733 /// Return the set of boxed (thus overapproximated) loops.
2734 const BoxedLoopsSetTy &getBoxedLoops() const { return DC.BoxedLoopsSet; }
2736 /// Return true if and only if @p R is a non-affine subregion.
2737 bool isNonAffineSubRegion(const Region *R) {
2738 return DC.NonAffineSubRegionSet.count(R);
2741 const MapInsnToMemAcc &getInsnToMemAccMap() const { return DC.InsnToMemAcc; }
2743 /// Return the (possibly new) ScopArrayInfo object for @p Access.
2745 /// @param ElementType The type of the elements stored in this array.
2746 /// @param Kind The kind of the array info object.
2747 /// @param BaseName The optional name of this memory reference.
2748 ScopArrayInfo *getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
2749 ArrayRef<const SCEV *> Sizes,
2750 MemoryKind Kind,
2751 const char *BaseName = nullptr);
2753 /// Create an array and return the corresponding ScopArrayInfo object.
2755 /// @param ElementType The type of the elements stored in this array.
2756 /// @param BaseName The name of this memory reference.
2757 /// @param Sizes The sizes of dimensions.
2758 ScopArrayInfo *createScopArrayInfo(Type *ElementType,
2759 const std::string &BaseName,
2760 const std::vector<unsigned> &Sizes);
2762 /// Return the cached ScopArrayInfo object for @p BasePtr.
2764 /// @param BasePtr The base pointer the object has been stored for.
2765 /// @param Kind The kind of array info object.
2767 /// @returns The ScopArrayInfo pointer or NULL if no such pointer is
2768 /// available.
2769 const ScopArrayInfo *getScopArrayInfoOrNull(Value *BasePtr, MemoryKind Kind);
2771 /// Return the cached ScopArrayInfo object for @p BasePtr.
2773 /// @param BasePtr The base pointer the object has been stored for.
2774 /// @param Kind The kind of array info object.
2776 /// @returns The ScopArrayInfo pointer (may assert if no such pointer is
2777 /// available).
2778 const ScopArrayInfo *getScopArrayInfo(Value *BasePtr, MemoryKind Kind);
2780 /// Invalidate ScopArrayInfo object for base address.
2782 /// @param BasePtr The base pointer of the ScopArrayInfo object to invalidate.
2783 /// @param Kind The Kind of the ScopArrayInfo object.
2784 void invalidateScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
2785 auto It = ScopArrayInfoMap.find(std::make_pair(BasePtr, Kind));
2786 if (It == ScopArrayInfoMap.end())
2787 return;
2788 ScopArrayInfoSet.remove(It->second.get());
2789 ScopArrayInfoMap.erase(It);
2792 void setContext(__isl_take isl_set *NewContext);
2794 /// Align the parameters in the statement to the scop context
2795 void realignParams();
2797 /// Return true if this SCoP can be profitably optimized.
2799 /// @param ScalarsAreUnprofitable Never consider statements with scalar writes
2800 /// as profitably optimizable.
2802 /// @return Whether this SCoP can be profitably optimized.
2803 bool isProfitable(bool ScalarsAreUnprofitable) const;
2805 /// Return true if the SCoP contained at least one error block.
2806 bool hasErrorBlock() const { return HasErrorBlock; }
2808 /// Return true if the underlying region has a single exiting block.
2809 bool hasSingleExitEdge() const { return HasSingleExitEdge; }
2811 /// Print the static control part.
2813 /// @param OS The output stream the static control part is printed to.
2814 void print(raw_ostream &OS) const;
2816 /// Print the ScopStmt to stderr.
2817 void dump() const;
2819 /// Get the isl context of this static control part.
2821 /// @return The isl context of this static control part.
2822 isl_ctx *getIslCtx() const;
2824 /// Directly return the shared_ptr of the context.
2825 const std::shared_ptr<isl_ctx> &getSharedIslCtx() const { return IslCtx; }
2827 /// Compute the isl representation for the SCEV @p E
2829 /// @param E The SCEV that should be translated.
2830 /// @param BB An (optional) basic block in which the isl_pw_aff is computed.
2831 /// SCEVs known to not reference any loops in the SCoP can be
2832 /// passed without a @p BB.
2833 /// @param NonNegative Flag to indicate the @p E has to be non-negative.
2835 /// Note that this function will always return a valid isl_pw_aff. However, if
2836 /// the translation of @p E was deemed to complex the SCoP is invalidated and
2837 /// a dummy value of appropriate dimension is returned. This allows to bail
2838 /// for complex cases without "error handling code" needed on the users side.
2839 __isl_give PWACtx getPwAff(const SCEV *E, BasicBlock *BB = nullptr,
2840 bool NonNegative = false);
2842 /// Compute the isl representation for the SCEV @p E
2844 /// This function is like @see Scop::getPwAff() but strips away the invalid
2845 /// domain part associated with the piecewise affine function.
2846 __isl_give isl_pw_aff *getPwAffOnly(const SCEV *E, BasicBlock *BB = nullptr);
2848 /// Return the domain of @p Stmt.
2850 /// @param Stmt The statement for which the conditions should be returned.
2851 __isl_give isl_set *getDomainConditions(const ScopStmt *Stmt) const;
2853 /// Return the domain of @p BB.
2855 /// @param BB The block for which the conditions should be returned.
2856 __isl_give isl_set *getDomainConditions(BasicBlock *BB) const;
2858 /// Get a union set containing the iteration domains of all statements.
2859 __isl_give isl_union_set *getDomains() const;
2861 /// Get a union map of all may-writes performed in the SCoP.
2862 __isl_give isl_union_map *getMayWrites();
2864 /// Get a union map of all must-writes performed in the SCoP.
2865 __isl_give isl_union_map *getMustWrites();
2867 /// Get a union map of all writes performed in the SCoP.
2868 __isl_give isl_union_map *getWrites();
2870 /// Get a union map of all reads performed in the SCoP.
2871 __isl_give isl_union_map *getReads();
2873 /// Get a union map of all memory accesses performed in the SCoP.
2874 __isl_give isl_union_map *getAccesses();
2876 /// Get the schedule of all the statements in the SCoP.
2878 /// @return The schedule of all the statements in the SCoP, if the schedule of
2879 /// the Scop does not contain extension nodes, and nullptr, otherwise.
2880 __isl_give isl_union_map *getSchedule() const;
2882 /// Get a schedule tree describing the schedule of all statements.
2883 __isl_give isl_schedule *getScheduleTree() const;
2885 /// Update the current schedule
2887 /// NewSchedule The new schedule (given as a flat union-map).
2888 void setSchedule(__isl_take isl_union_map *NewSchedule);
2890 /// Update the current schedule
2892 /// NewSchedule The new schedule (given as schedule tree).
2893 void setScheduleTree(__isl_take isl_schedule *NewSchedule);
2895 /// Intersects the domains of all statements in the SCoP.
2897 /// @return true if a change was made
2898 bool restrictDomains(__isl_take isl_union_set *Domain);
2900 /// Get the depth of a loop relative to the outermost loop in the Scop.
2902 /// This will return
2903 /// 0 if @p L is an outermost loop in the SCoP
2904 /// >0 for other loops in the SCoP
2905 /// -1 if @p L is nullptr or there is no outermost loop in the SCoP
2906 int getRelativeLoopDepth(const Loop *L) const;
2908 /// Find the ScopArrayInfo associated with an isl Id
2909 /// that has name @p Name.
2910 ScopArrayInfo *getArrayInfoByName(const std::string BaseName);
2912 /// Check whether @p Schedule contains extension nodes.
2914 /// @return true if @p Schedule contains extension nodes.
2915 static bool containsExtensionNode(__isl_keep isl_schedule *Schedule);
2917 /// Simplify the SCoP representation.
2919 /// @param AfterHoisting Whether it is called after invariant load hoisting.
2920 /// When true, also removes statements without
2921 /// side-effects.
2922 void simplifySCoP(bool AfterHoisting);
2924 /// Get the next free array index.
2926 /// This function returns a unique index which can be used to identify an
2927 /// array.
2928 long getNextArrayIdx() { return ArrayIdx++; }
2930 /// Get the next free statement index.
2932 /// This function returns a unique index which can be used to identify a
2933 /// statement.
2934 long getNextStmtIdx() { return StmtIdx++; }
2936 /// Return the MemoryAccess that writes an llvm::Value, represented by a
2937 /// ScopArrayInfo.
2939 /// There can be at most one such MemoryAccess per llvm::Value in the SCoP.
2940 /// Zero is possible for read-only values.
2941 MemoryAccess *getValueDef(const ScopArrayInfo *SAI) const;
2943 /// Return all MemoryAccesses that us an llvm::Value, represented by a
2944 /// ScopArrayInfo.
2945 ArrayRef<MemoryAccess *> getValueUses(const ScopArrayInfo *SAI) const;
2947 /// Return the MemoryAccess that represents an llvm::PHINode.
2949 /// ExitPHIs's PHINode is not within the SCoPs. This function returns nullptr
2950 /// for them.
2951 MemoryAccess *getPHIRead(const ScopArrayInfo *SAI) const;
2953 /// Return all MemoryAccesses for all incoming statements of a PHINode,
2954 /// represented by a ScopArrayInfo.
2955 ArrayRef<MemoryAccess *> getPHIIncomings(const ScopArrayInfo *SAI) const;
2958 /// Print Scop scop to raw_ostream O.
2959 static inline raw_ostream &operator<<(raw_ostream &O, const Scop &scop) {
2960 scop.print(O);
2961 return O;
2964 /// The legacy pass manager's analysis pass to compute scop information
2965 /// for a region.
2966 class ScopInfoRegionPass : public RegionPass {
2967 /// The Scop pointer which is used to construct a Scop.
2968 std::unique_ptr<Scop> S;
2970 public:
2971 static char ID; // Pass identification, replacement for typeid
2973 ScopInfoRegionPass() : RegionPass(ID) {}
2974 ~ScopInfoRegionPass() {}
2976 /// Build Scop object, the Polly IR of static control
2977 /// part for the current SESE-Region.
2979 /// @return If the current region is a valid for a static control part,
2980 /// return the Polly IR representing this static control part,
2981 /// return null otherwise.
2982 Scop *getScop() { return S.get(); }
2983 const Scop *getScop() const { return S.get(); }
2985 /// Calculate the polyhedral scop information for a given Region.
2986 bool runOnRegion(Region *R, RGPassManager &RGM) override;
2988 void releaseMemory() override { S.reset(); }
2990 void print(raw_ostream &O, const Module *M = nullptr) const override;
2992 void getAnalysisUsage(AnalysisUsage &AU) const override;
2995 class ScopInfo {
2996 public:
2997 using RegionToScopMapTy = DenseMap<Region *, std::unique_ptr<Scop>>;
2998 using iterator = RegionToScopMapTy::iterator;
2999 using const_iterator = RegionToScopMapTy::const_iterator;
3001 private:
3002 /// A map of Region to its Scop object containing
3003 /// Polly IR of static control part.
3004 RegionToScopMapTy RegionToScopMap;
3006 public:
3007 ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
3008 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
3009 AssumptionCache &AC);
3011 /// Get the Scop object for the given Region.
3013 /// @return If the given region is the maximal region within a scop, return
3014 /// the scop object. If the given region is a subregion, return a
3015 /// nullptr. Top level region containing the entry block of a function
3016 /// is not considered in the scop creation.
3017 Scop *getScop(Region *R) const {
3018 auto MapIt = RegionToScopMap.find(R);
3019 if (MapIt != RegionToScopMap.end())
3020 return MapIt->second.get();
3021 return nullptr;
3024 iterator begin() { return RegionToScopMap.begin(); }
3025 iterator end() { return RegionToScopMap.end(); }
3026 const_iterator begin() const { return RegionToScopMap.begin(); }
3027 const_iterator end() const { return RegionToScopMap.end(); }
3028 bool empty() const { return RegionToScopMap.empty(); }
3031 struct ScopInfoAnalysis : public AnalysisInfoMixin<ScopInfoAnalysis> {
3032 static AnalysisKey Key;
3033 using Result = ScopInfo;
3034 Result run(Function &, FunctionAnalysisManager &);
3037 struct ScopInfoPrinterPass : public PassInfoMixin<ScopInfoPrinterPass> {
3038 ScopInfoPrinterPass(raw_ostream &O) : Stream(O) {}
3039 PreservedAnalyses run(Function &, FunctionAnalysisManager &);
3040 raw_ostream &Stream;
3043 //===----------------------------------------------------------------------===//
3044 /// The legacy pass manager's analysis pass to compute scop information
3045 /// for the whole function.
3047 /// This pass will maintain a map of the maximal region within a scop to its
3048 /// scop object for all the feasible scops present in a function.
3049 /// This pass is an alternative to the ScopInfoRegionPass in order to avoid a
3050 /// region pass manager.
3051 class ScopInfoWrapperPass : public FunctionPass {
3052 std::unique_ptr<ScopInfo> Result;
3054 public:
3055 ScopInfoWrapperPass() : FunctionPass(ID) {}
3056 ~ScopInfoWrapperPass() = default;
3058 static char ID; // Pass identification, replacement for typeid
3060 ScopInfo *getSI() { return Result.get(); }
3061 const ScopInfo *getSI() const { return Result.get(); }
3063 /// Calculate all the polyhedral scops for a given function.
3064 bool runOnFunction(Function &F) override;
3066 void releaseMemory() override { Result.reset(); }
3068 void print(raw_ostream &O, const Module *M = nullptr) const override;
3070 void getAnalysisUsage(AnalysisUsage &AU) const override;
3073 } // end namespace polly
3075 namespace llvm {
3076 class PassRegistry;
3077 void initializeScopInfoRegionPassPass(llvm::PassRegistry &);
3078 void initializeScopInfoWrapperPassPass(llvm::PassRegistry &);
3079 } // namespace llvm
3081 #endif