FLANG
AliasAnalysis.h
1//===-- AliasAnalysis.h - Alias Analysis in FIR -----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef FORTRAN_OPTIMIZER_ANALYSIS_ALIASANALYSIS_H
10#define FORTRAN_OPTIMIZER_ANALYSIS_ALIASANALYSIS_H
11
12#include "flang/Common/enum-class.h"
13#include "flang/Common/enum-set.h"
14#include "mlir/Analysis/AliasAnalysis.h"
15#include "mlir/IR/BuiltinAttributes.h"
16#include "mlir/IR/Dominance.h"
17#include "mlir/IR/SymbolTable.h"
18#include "mlir/IR/Value.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/PointerUnion.h"
21#include "llvm/ADT/SmallVector.h"
22#include <cstddef>
23#include <memory>
24#include <utility>
25
26namespace fir {
27
29
30//===----------------------------------------------------------------------===//
31// AliasAnalysis
32//===----------------------------------------------------------------------===//
33struct AliasAnalysis {
34 AliasAnalysis() = default;
35
37 explicit AliasAnalysis(AliasAnalysisRecursiveEffectsCache &cache);
38
39 AliasAnalysis(AliasAnalysis &&other) noexcept;
40
41 ~AliasAnalysis();
42
43 AliasAnalysis(const AliasAnalysis &) = delete;
44 AliasAnalysis &operator=(const AliasAnalysis &) = delete;
45 AliasAnalysis &operator=(AliasAnalysis &&) = delete;
46
47 // Structures to describe the memory source of a value.
48
54 ENUM_CLASS(SourceKind,
59 Null,
62 Allocate,
64 Global,
67 Argument,
70 HostAssoc,
74 Indirect,
77 Unknown);
78
80 ENUM_CLASS(Attribute, Target, Pointer, IntentIn, CrayPointer, CrayPointee);
81
82 // See
83 // https://discourse.llvm.org/t/rfc-distinguish-between-data-and-non-data-in-fir-alias-analysis/78759/1
84 //
85 // It is possible, while following the source of a memory reference through
86 // the use-def chain, to arrive at the same origin, even though the starting
87 // points were known to not alias.
88 //
89 // clang-format off
90 // Example:
91 // ------------------- test.f90 --------------------
92 // module top
93 // real, pointer :: a(:)
94 // end module
95 //
96 // subroutine test()
97 // use top
98 // a(1) = 1
99 // end subroutine
100 // -------------------------------------------------
101 //
102 // flang -fc1 -emit-fir test.f90 -o test.fir
103 //
104 // ------------------- test.fir --------------------
105 // fir.global @_QMtopEa : !fir.box<!fir.ptr<!fir.array<?xf32>>>
106 //
107 // func.func @_QPtest() {
108 // %c1 = arith.constant 1 : index
109 // %cst = arith.constant 1.000000e+00 : f32
110 // %0 = fir.address_of(@_QMtopEa) : !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>
111 // %1 = fir.declare %0 {fortran_attrs = #fir.var_attrs<pointer>, uniq_name = "_QMtopEa"} : (!fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>) -> !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>
112 // %2 = fir.load %1 : !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>
113 // ...
114 // %5 = fir.array_coor %2 %c1 : (!fir.box<!fir.ptr<!fir.array<?xf32>>>, !fir.shift<1>, index) -> !fir.ref<f32>
115 // fir.store %cst to %5 : !fir.ref<f32>
116 // return
117 // }
118 // -------------------------------------------------
119 //
120 // With high level operations, such as fir.array_coor, it is possible to
121 // reach into the data wrapped by the box (the descriptor). Therefore when
122 // asking about the memory source of %5, we are really asking about the
123 // source of the data of box %2.
124 //
125 // When asking about the source of %0 which is the address of the box, we
126 // reach the same source as in the first case: the global @_QMtopEa. Yet one
127 // source refers to the data while the other refers to the address of the box
128 // itself.
129 //
130 // To distinguish between the two, the isData flag has been added, whereby
131 // data is defined as any memory reference that is not a box reference.
132 // Additionally, because it is relied on in HLFIR lowering, we allow querying
133 // on a box SSA value, which is interpreted as querying on its data.
134 //
135 // So in the above example, !fir.ref<f32> and !fir.box<!fir.ptr<!fir.array<?xf32>>> is data,
136 // while !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>> is not data.
137
138 // This also applies to function arguments. In the example below, %arg0
139 // is data, %arg1 is not data but a load of %arg1 is.
140 //
141 // func.func @_QFPtest2(%arg0: !fir.ref<f32>, %arg1: !fir.ref<!fir.box<!fir.ptr<f32>>> ) {
142 // %0 = fir.load %arg1 : !fir.ref<!fir.box<!fir.ptr<f32>>>
143 // ... }
144 //
145 // clang-format on
146
147 struct Source {
148 using SourceUnion = llvm::PointerUnion<mlir::SymbolRefAttr, mlir::Value>;
150
153 SourceUnion u;
154
164 mlir::Operation *instantiationPoint;
165
167 bool isData{false};
168 };
169
173 struct PathStep {
183 Kind kind;
187 mlir::StringAttr component;
190 mlir::Type recordType;
191
192 bool operator==(const PathStep &o) const {
193 return kind == o.kind && component == o.component &&
195 }
196 bool operator!=(const PathStep &o) const { return !(*this == o); }
197 };
198
210 struct AccessPath {
212
216 bool isApproximate{false};
217
221 bool isIncomplete{false};
222
227 mlir::Operation *storageDecl{nullptr};
228
231 bool mayHavePointerDeref() const {
232 return isIncomplete || llvm::any_of(steps, [](const PathStep &s) {
233 return s.kind == PathStep::Kind::PointerDeref;
234 });
235 }
236
237 bool operator==(const AccessPath &o) const {
238 return isApproximate == o.isApproximate &&
240 steps == o.steps;
241 }
242 bool operator!=(const AccessPath &o) const { return !(*this == o); }
243
244 void print(llvm::raw_ostream &os) const;
245 };
246
282 mlir::Value scope;
284 mlir::Value declValue;
291 Attributes attributes;
293 bool approximateSource{false};
296 bool isData{false};
297 };
298
299 SourceOrigin origin;
300
302 SourceKind kind;
304 mlir::Type valueType;
306 Attributes attributes;
319
321 void print(llvm::raw_ostream &os) const;
322
324 bool isTargetOrPointer() const;
325
327 bool isTarget() const;
328
330 bool isPointer() const;
331
334 bool isDeclaredAllocatable() const;
335
337 bool isCrayPointer() const;
338
340 bool isCrayPointee() const;
341
343 bool isCrayPointerOrPointee() const;
344
345 bool isDummyArgument() const;
346 bool isData() const;
347 bool isBoxData() const;
348
350 bool isFortranUserVariable() const;
351
358
362 bool mayBeDummyArgOrHostAssoc() const;
364 bool mayBePtrDummyArgOrHostAssoc() const;
366 bool mayBeActualArg() const;
369 bool mayBeActualArgWithPtr(const mlir::Value *val) const;
371
372 mlir::Type getType() const;
373 };
374
375 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
376 const AliasAnalysis::Source &op);
377
379 mlir::AliasResult alias(Source lhsSrc, Source rhsSrc, mlir::Value lhs,
380 mlir::Value rhs);
381
383 mlir::AliasResult alias(mlir::Value lhs, mlir::Value rhs);
384
386 mlir::ModRefResult getModRef(mlir::Operation *op, mlir::Value location);
387
392 mlir::ModRefResult getModRef(mlir::Region &region, mlir::Value location);
393
412 bool getLastInstantiationPoint = false,
413 bool collectScopedOrigins = true);
414
419 void enableSourceCache();
420
422 void disableSourceCache();
423
429 void disableSymbolLookups() { symbolLookupsDisabled = true; }
430
432 std::size_t getSourceCacheSizeForTesting() const {
433 return getSourceCache.size();
434 }
435
437 std::size_t getSourceCacheHitsForTesting() const { return sourceCacheHits; }
438 std::size_t getSourceCacheMissesForTesting() const {
439 return sourceCacheMisses;
440 }
441
444 static bool isPointerReference(mlir::Type ty);
445
454 bool functionHasMultipleScopes(mlir::Value v);
455
456private:
457 friend class AliasAnalysisRecursiveEffectsCache;
458
462 fir::AliasAnalysis::Source getSourceImpl(mlir::Value v,
463 bool getLastInstantiationPoint,
464 bool collectScopedOrigins);
465
467 void clearSourceCache() { getSourceCache.clear(); }
468
475 Source buildSourceAtDeclare(const Source::ScopedOrigin &so);
476
483 mlir::AliasResult aliasSources(Source lhsSrc, Source rhsSrc, mlir::Value lhs,
484 mlir::Value rhs);
485
491 bool mayAccessThroughArgument(mlir::Value arg, mlir::Value var,
492 const Source &varSrc);
493
499 mlir::Value getDeclarationScope(mlir::Operation *declareOp);
500
503 static bool isRecordWithPointerComponent(mlir::Type ty);
504
510 const mlir::SymbolTable *getNearestSymbolTable(mlir::Operation *from);
511
515 bool symbolMayHaveTargetAttr(mlir::SymbolRefAttr symbol,
516 mlir::Operation *from);
517
520 bool isCallToFortranUserProcedure(mlir::Operation *op);
521
525 mlir::ModRefResult getCallModRef(mlir::Operation *op, mlir::Value var);
526
540 llvm::DenseMap<mlir::Operation *, mlir::SymbolTable> symTabMap;
541
543 bool symbolLookupsDisabled = false;
544
558 llvm::DenseMap<mlir::Operation *, std::unique_ptr<mlir::DominanceInfo>>
559 domInfoCache;
560 llvm::DenseMap<mlir::Operation *, llvm::SmallVector<mlir::Operation *, 16>>
561 sortedScopeCache;
566 llvm::DenseMap<mlir::Operation *, bool> multiScopeCache;
567
573 llvm::DenseMap<std::pair<mlir::Value, unsigned>, Source> getSourceCache;
574
576 bool sourceCacheEnabled = false;
577
580 std::size_t sourceCacheHits = 0;
581 std::size_t sourceCacheMisses = 0;
582
584 AliasAnalysisRecursiveEffectsCache *cache = nullptr;
585};
586
589class AliasAnalysisRecursiveEffectsCache {
590public:
591 AliasAnalysisRecursiveEffectsCache() = default;
592 ~AliasAnalysisRecursiveEffectsCache() {
593 if (aa)
594 aa->cache = nullptr;
595 }
596
597 AliasAnalysisRecursiveEffectsCache(
598 const AliasAnalysisRecursiveEffectsCache &) = delete;
599 AliasAnalysisRecursiveEffectsCache &
600 operator=(const AliasAnalysisRecursiveEffectsCache &) = delete;
601 AliasAnalysisRecursiveEffectsCache(AliasAnalysisRecursiveEffectsCache &&) =
602 delete;
603 AliasAnalysisRecursiveEffectsCache &
604 operator=(AliasAnalysisRecursiveEffectsCache &&) = delete;
605
608 void clear() { summaries.clear(); }
609
611 std::size_t getSummaryCacheSizeForTesting() const { return summaries.size(); }
612
615 std::size_t getSummaryCacheHitsForTesting() const { return summaryHits; }
616 std::size_t getSummaryCacheMissesForTesting() const { return summaryMisses; }
617
618private:
619 friend struct AliasAnalysis;
620
621 struct CallInfo {
622 mlir::Operation *op;
627 bool isFortranUserProcedure;
628 };
629
630 struct Summary {
631 bool hasUnknownWrite = false;
632 bool hasUnknownRead = false;
633 llvm::SmallVector<mlir::Value, 16> writeLocations;
634 llvm::SmallVector<mlir::Value, 16> readLocations;
635 llvm::SmallVector<CallInfo, 4> calls;
636 };
637
641 void buildSummary(mlir::Operation *op, Summary &out);
642 void buildSummary(mlir::Region &region, Summary &out);
643
644 mlir::ModRefResult getModRefFromSummary(mlir::Operation *op,
645 mlir::Value location);
646
648 AliasAnalysis *aa = nullptr;
649 llvm::DenseMap<mlir::Operation *, Summary> summaries;
650
652 std::size_t summaryHits = 0;
653 std::size_t summaryMisses = 0;
654};
655
656inline bool operator==(const AliasAnalysis::Source::SourceOrigin &lhs,
658 return lhs.u == rhs.u && lhs.isData == rhs.isData;
659}
660inline bool operator!=(const AliasAnalysis::Source::SourceOrigin &lhs,
662 return !(lhs == rhs);
663}
664
665inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
666 const AliasAnalysis::Source &op) {
667 op.print(os);
668 return os;
669}
670
671} // namespace fir
672
673#endif // FORTRAN_OPTIMIZER_ANALYSIS_ALIASANALYSIS_H
Definition enum-set.h:28
Definition AliasAnalysis.h:589
std::size_t getSummaryCacheHitsForTesting() const
Definition AliasAnalysis.h:615
std::size_t getSummaryCacheSizeForTesting() const
Testing only: number of op summaries currently held.
Definition AliasAnalysis.h:611
void clear()
Definition AliasAnalysis.h:608
Definition OpenACC.h:20
Definition AbstractConverter.h:37
Definition AliasAnalysis.h:210
mlir::Operation * storageDecl
Definition AliasAnalysis.h:227
bool isApproximate
Definition AliasAnalysis.h:216
bool isIncomplete
Definition AliasAnalysis.h:221
bool mayHavePointerDeref() const
Definition AliasAnalysis.h:231
Definition AliasAnalysis.h:173
mlir::StringAttr component
Definition AliasAnalysis.h:187
mlir::Type recordType
Definition AliasAnalysis.h:190
Kind
Definition AliasAnalysis.h:174
@ Component
Named component access, e.g. xfield.
Definition AliasAnalysis.h:176
@ AllocDeref
Loading an ALLOCATABLE box (fir.load of !fir.box<!fir.heap<...>>).
Definition AliasAnalysis.h:181
@ PointerDeref
Definition AliasAnalysis.h:179
Definition AliasAnalysis.h:278
mlir::Value scope
Definition AliasAnalysis.h:282
AccessPath accessPath
Definition AliasAnalysis.h:287
bool isData
Definition AliasAnalysis.h:296
mlir::Value declValue
Result SSA value of the [hl]fir.declare op.
Definition AliasAnalysis.h:284
bool approximateSource
Whether the path is approximate at the moment of the snapshot.
Definition AliasAnalysis.h:293
Attributes attributes
Definition AliasAnalysis.h:291
Definition AliasAnalysis.h:151
mlir::Operation * instantiationPoint
Definition AliasAnalysis.h:164
SourceUnion u
Source definition of a value.
Definition AliasAnalysis.h:153
bool isData
Whether the source was reached following data or box reference.
Definition AliasAnalysis.h:167
Definition AliasAnalysis.h:147
bool isCrayPointer() const
Return true, if CrayPointer attribute is set.
Definition AliasAnalysis.cpp:489
bool isCapturedInInternalProcedure
Source object is used in an internal procedure via host association.
Definition AliasAnalysis.h:313
bool isFortranUserVariable() const
Is this source a variable from the Fortran source?
Definition AliasAnalysis.cpp:510
Attributes attributes
Attributes of the memory source object, e.g. Target.
Definition AliasAnalysis.h:306
bool isPointer() const
Return true, if Pointer attribute is set.
Definition AliasAnalysis.cpp:470
llvm::SmallVector< ScopedOrigin, 4 > scopedOrigins
Definition AliasAnalysis.h:318
SourceKind kind
Kind of the memory source.
Definition AliasAnalysis.h:302
bool isCrayPointee() const
Return true, if CrayPointee attribute is set.
Definition AliasAnalysis.cpp:485
void print(llvm::raw_ostream &os) const
Print information about the memory source to os.
Definition AliasAnalysis.cpp:427
bool mayBePtrDummyArgOrHostAssoc() const
mayBeDummyArgOrHostAssoc and the address of a pointer?
Definition AliasAnalysis.cpp:538
bool isTargetOrPointer() const
Return true, if Target or Pointer attribute is set.
Definition AliasAnalysis.cpp:461
bool mayBeDummyArgOrHostAssoc() const
Definition AliasAnalysis.cpp:533
AccessPath accessPath
The structured access path from the root variable.
Definition AliasAnalysis.h:311
bool approximateSource
Definition AliasAnalysis.h:309
bool mayBeActualArgWithPtr(const mlir::Value *val) const
Definition AliasAnalysis.cpp:553
mlir::Type valueType
Value type of the source definition.
Definition AliasAnalysis.h:304
bool isCrayPointerOrPointee() const
Return true, if CrayPointer or CrayPointee attribute is set.
Definition AliasAnalysis.cpp:493
bool isDeclaredAllocatable() const
Definition AliasAnalysis.cpp:474
bool isTarget() const
Return true, if Target attribute is set.
Definition AliasAnalysis.cpp:466
bool mayBeActualArg() const
The address of an actual argument of the current function?
Definition AliasAnalysis.cpp:549
std::size_t getSourceCacheSizeForTesting() const
Testing only: number of entries currently held in the getSource() cache.
Definition AliasAnalysis.h:432
void enableSourceCache()
Definition AliasAnalysis.cpp:1796
fir::AliasAnalysis::Source getSource(mlir::Value, bool getLastInstantiationPoint=false, bool collectScopedOrigins=true)
Definition AliasAnalysis.cpp:1803
mlir::AliasResult alias(Source lhsSrc, Source rhsSrc, mlir::Value lhs, mlir::Value rhs)
Given the values and their sources, return their aliasing behavior.
Definition AliasAnalysis.cpp:843
void disableSourceCache()
Disable getSource() memoization and drop any cached entries.
Definition AliasAnalysis.cpp:1798
static bool isPointerReference(mlir::Type ty)
Definition AliasAnalysis.cpp:453
ENUM_CLASS(SourceKind, Null, Allocate, Global, Argument, HostAssoc, Indirect, Unknown)
std::size_t getSourceCacheHitsForTesting() const
Testing only: cumulative getSource() cache hits / misses on this instance.
Definition AliasAnalysis.h:437
ENUM_CLASS(Attribute, Target, Pointer, IntentIn, CrayPointer, CrayPointee)
Attributes of the memory source object.
bool functionHasMultipleScopes(mlir::Value v)
Definition AliasAnalysis.cpp:2559
void disableSymbolLookups()
Definition AliasAnalysis.h:429
mlir::ModRefResult getModRef(mlir::Operation *op, mlir::Value location)
Return the modify-reference behavior of op on location.