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
50 ENUM_CLASS(SourceKind,
53 Allocate,
55 Global,
58 Argument,
61 HostAssoc,
65 Indirect,
68 Unknown);
69
71 ENUM_CLASS(Attribute, Target, Pointer, IntentIn, CrayPointer, CrayPointee);
72
73 // See
74 // https://discourse.llvm.org/t/rfc-distinguish-between-data-and-non-data-in-fir-alias-analysis/78759/1
75 //
76 // It is possible, while following the source of a memory reference through
77 // the use-def chain, to arrive at the same origin, even though the starting
78 // points were known to not alias.
79 //
80 // clang-format off
81 // Example:
82 // ------------------- test.f90 --------------------
83 // module top
84 // real, pointer :: a(:)
85 // end module
86 //
87 // subroutine test()
88 // use top
89 // a(1) = 1
90 // end subroutine
91 // -------------------------------------------------
92 //
93 // flang -fc1 -emit-fir test.f90 -o test.fir
94 //
95 // ------------------- test.fir --------------------
96 // fir.global @_QMtopEa : !fir.box<!fir.ptr<!fir.array<?xf32>>>
97 //
98 // func.func @_QPtest() {
99 // %c1 = arith.constant 1 : index
100 // %cst = arith.constant 1.000000e+00 : f32
101 // %0 = fir.address_of(@_QMtopEa) : !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>
102 // %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>>>>
103 // %2 = fir.load %1 : !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>>
104 // ...
105 // %5 = fir.array_coor %2 %c1 : (!fir.box<!fir.ptr<!fir.array<?xf32>>>, !fir.shift<1>, index) -> !fir.ref<f32>
106 // fir.store %cst to %5 : !fir.ref<f32>
107 // return
108 // }
109 // -------------------------------------------------
110 //
111 // With high level operations, such as fir.array_coor, it is possible to
112 // reach into the data wrapped by the box (the descriptor). Therefore when
113 // asking about the memory source of %5, we are really asking about the
114 // source of the data of box %2.
115 //
116 // When asking about the source of %0 which is the address of the box, we
117 // reach the same source as in the first case: the global @_QMtopEa. Yet one
118 // source refers to the data while the other refers to the address of the box
119 // itself.
120 //
121 // To distinguish between the two, the isData flag has been added, whereby
122 // data is defined as any memory reference that is not a box reference.
123 // Additionally, because it is relied on in HLFIR lowering, we allow querying
124 // on a box SSA value, which is interpreted as querying on its data.
125 //
126 // So in the above example, !fir.ref<f32> and !fir.box<!fir.ptr<!fir.array<?xf32>>> is data,
127 // while !fir.ref<!fir.box<!fir.ptr<!fir.array<?xf32>>>> is not data.
128
129 // This also applies to function arguments. In the example below, %arg0
130 // is data, %arg1 is not data but a load of %arg1 is.
131 //
132 // func.func @_QFPtest2(%arg0: !fir.ref<f32>, %arg1: !fir.ref<!fir.box<!fir.ptr<f32>>> ) {
133 // %0 = fir.load %arg1 : !fir.ref<!fir.box<!fir.ptr<f32>>>
134 // ... }
135 //
136 // clang-format on
137
138 struct Source {
139 using SourceUnion = llvm::PointerUnion<mlir::SymbolRefAttr, mlir::Value>;
141
144 SourceUnion u;
145
155 mlir::Operation *instantiationPoint;
156
158 bool isData{false};
159 };
160
164 struct PathStep {
174 Kind kind;
178 mlir::StringAttr component;
179
180 bool operator==(const PathStep &o) const {
181 return kind == o.kind && component == o.component;
182 }
183 bool operator!=(const PathStep &o) const { return !(*this == o); }
184 };
185
197 struct AccessPath {
199
203 bool isApproximate{false};
204
206 bool hasPointerDeref() const {
207 return llvm::any_of(steps, [](const PathStep &s) {
208 return s.kind == PathStep::Kind::PointerDeref;
209 });
210 }
211
212 bool operator==(const AccessPath &o) const {
213 return isApproximate == o.isApproximate && steps == o.steps;
214 }
215 bool operator!=(const AccessPath &o) const { return !(*this == o); }
216
217 void print(llvm::raw_ostream &os) const;
218 };
219
255 mlir::Value scope;
257 mlir::Value declValue;
264 Attributes attributes;
266 bool approximateSource{false};
269 bool isData{false};
270 };
271
272 SourceOrigin origin;
273
275 SourceKind kind;
277 mlir::Type valueType;
279 Attributes attributes;
292
294 void print(llvm::raw_ostream &os) const;
295
297 bool isTargetOrPointer() const;
298
300 bool isTarget() const;
301
303 bool isPointer() const;
304
307 bool isDeclaredAllocatable() const;
308
310 bool isCrayPointer() const;
311
313 bool isCrayPointee() const;
314
316 bool isCrayPointerOrPointee() const;
317
318 bool isDummyArgument() const;
319 bool isData() const;
320 bool isBoxData() const;
321
323 bool isFortranUserVariable() const;
324
331
335 bool mayBeDummyArgOrHostAssoc() const;
337 bool mayBePtrDummyArgOrHostAssoc() const;
339 bool mayBeActualArg() const;
342 bool mayBeActualArgWithPtr(const mlir::Value *val) const;
344
345 mlir::Type getType() const;
346 };
347
348 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
349 const AliasAnalysis::Source &op);
350
352 mlir::AliasResult alias(Source lhsSrc, Source rhsSrc, mlir::Value lhs,
353 mlir::Value rhs);
354
356 mlir::AliasResult alias(mlir::Value lhs, mlir::Value rhs);
357
359 mlir::ModRefResult getModRef(mlir::Operation *op, mlir::Value location);
360
365 mlir::ModRefResult getModRef(mlir::Region &region, mlir::Value location);
366
385 bool getLastInstantiationPoint = false,
386 bool collectScopedOrigins = true);
387
392 void enableSourceCache();
393
395 void disableSourceCache();
396
398 std::size_t getSourceCacheSizeForTesting() const {
399 return getSourceCache.size();
400 }
401
403 std::size_t getSourceCacheHitsForTesting() const { return sourceCacheHits; }
404 std::size_t getSourceCacheMissesForTesting() const {
405 return sourceCacheMisses;
406 }
407
410 static bool isPointerReference(mlir::Type ty);
411
420 bool functionHasMultipleScopes(mlir::Value v);
421
422private:
423 friend class AliasAnalysisRecursiveEffectsCache;
424
428 fir::AliasAnalysis::Source getSourceImpl(mlir::Value v,
429 bool getLastInstantiationPoint,
430 bool collectScopedOrigins);
431
433 void clearSourceCache() { getSourceCache.clear(); }
434
441 Source buildSourceAtDeclare(const Source::ScopedOrigin &so);
442
448 mlir::Value getDeclarationScope(mlir::Operation *declareOp);
449
452 static bool isRecordWithPointerComponent(mlir::Type ty);
453
457 const mlir::SymbolTable *getNearestSymbolTable(mlir::Operation *from);
458
462 bool symbolMayHaveTargetAttr(mlir::SymbolRefAttr symbol,
463 mlir::Operation *from);
464
467 bool isCallToFortranUserProcedure(mlir::Operation *op);
468
472 mlir::ModRefResult getCallModRef(mlir::Operation *op, mlir::Value var);
473
487 llvm::DenseMap<mlir::Operation *, mlir::SymbolTable> symTabMap;
488
502 llvm::DenseMap<mlir::Operation *, std::unique_ptr<mlir::DominanceInfo>>
503 domInfoCache;
504 llvm::DenseMap<mlir::Operation *, llvm::SmallVector<mlir::Operation *, 16>>
505 sortedScopeCache;
510 llvm::DenseMap<mlir::Operation *, bool> multiScopeCache;
511
517 llvm::DenseMap<std::pair<mlir::Value, unsigned>, Source> getSourceCache;
518
520 bool sourceCacheEnabled = false;
521
524 std::size_t sourceCacheHits = 0;
525 std::size_t sourceCacheMisses = 0;
526
528 AliasAnalysisRecursiveEffectsCache *cache = nullptr;
529};
530
533class AliasAnalysisRecursiveEffectsCache {
534public:
535 AliasAnalysisRecursiveEffectsCache() = default;
536 ~AliasAnalysisRecursiveEffectsCache() {
537 if (aa)
538 aa->cache = nullptr;
539 }
540
541 AliasAnalysisRecursiveEffectsCache(
542 const AliasAnalysisRecursiveEffectsCache &) = delete;
543 AliasAnalysisRecursiveEffectsCache &
544 operator=(const AliasAnalysisRecursiveEffectsCache &) = delete;
545 AliasAnalysisRecursiveEffectsCache(AliasAnalysisRecursiveEffectsCache &&) =
546 delete;
547 AliasAnalysisRecursiveEffectsCache &
548 operator=(AliasAnalysisRecursiveEffectsCache &&) = delete;
549
552 void clear() { summaries.clear(); }
553
555 std::size_t getSummaryCacheSizeForTesting() const { return summaries.size(); }
556
559 std::size_t getSummaryCacheHitsForTesting() const { return summaryHits; }
560 std::size_t getSummaryCacheMissesForTesting() const { return summaryMisses; }
561
562private:
563 friend struct AliasAnalysis;
564
565 struct CallInfo {
566 mlir::Operation *op;
571 bool isFortranUserProcedure;
572 };
573
574 struct Summary {
575 bool hasUnknownWrite = false;
576 bool hasUnknownRead = false;
577 llvm::SmallVector<mlir::Value, 16> writeLocations;
578 llvm::SmallVector<mlir::Value, 16> readLocations;
579 llvm::SmallVector<CallInfo, 4> calls;
580 };
581
585 void buildSummary(mlir::Operation *op, Summary &out);
586 void buildSummary(mlir::Region &region, Summary &out);
587
588 mlir::ModRefResult getModRefFromSummary(mlir::Operation *op,
589 mlir::Value location);
590
592 AliasAnalysis *aa = nullptr;
593 llvm::DenseMap<mlir::Operation *, Summary> summaries;
594
596 std::size_t summaryHits = 0;
597 std::size_t summaryMisses = 0;
598};
599
600inline bool operator==(const AliasAnalysis::Source::SourceOrigin &lhs,
602 return lhs.u == rhs.u && lhs.isData == rhs.isData;
603}
604inline bool operator!=(const AliasAnalysis::Source::SourceOrigin &lhs,
606 return !(lhs == rhs);
607}
608
609inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
610 const AliasAnalysis::Source &op) {
611 op.print(os);
612 return os;
613}
614
615} // namespace fir
616
617#endif // FORTRAN_OPTIMIZER_ANALYSIS_ALIASANALYSIS_H
Definition enum-set.h:28
Definition AliasAnalysis.h:533
std::size_t getSummaryCacheHitsForTesting() const
Definition AliasAnalysis.h:559
std::size_t getSummaryCacheSizeForTesting() const
Testing only: number of op summaries currently held.
Definition AliasAnalysis.h:555
void clear()
Definition AliasAnalysis.h:552
Definition OpenACC.h:20
Definition AbstractConverter.h:37
Definition AliasAnalysis.h:197
bool hasPointerDeref() const
Return true if any step is a PointerDeref.
Definition AliasAnalysis.h:206
bool isApproximate
Definition AliasAnalysis.h:203
Definition AliasAnalysis.h:164
mlir::StringAttr component
Definition AliasAnalysis.h:178
Kind
Definition AliasAnalysis.h:165
@ Component
Named component access, e.g. xfield.
Definition AliasAnalysis.h:167
@ AllocDeref
Loading an ALLOCATABLE box (fir.load of !fir.box<!fir.heap<...>>).
Definition AliasAnalysis.h:172
@ PointerDeref
Definition AliasAnalysis.h:170
Definition AliasAnalysis.h:251
mlir::Value scope
Definition AliasAnalysis.h:255
AccessPath accessPath
Definition AliasAnalysis.h:260
bool isData
Definition AliasAnalysis.h:269
mlir::Value declValue
Result SSA value of the [hl]fir.declare op.
Definition AliasAnalysis.h:257
bool approximateSource
Whether the path is approximate at the moment of the snapshot.
Definition AliasAnalysis.h:266
Attributes attributes
Definition AliasAnalysis.h:264
Definition AliasAnalysis.h:142
mlir::Operation * instantiationPoint
Definition AliasAnalysis.h:155
SourceUnion u
Source definition of a value.
Definition AliasAnalysis.h:144
bool isData
Whether the source was reached following data or box reference.
Definition AliasAnalysis.h:158
Definition AliasAnalysis.h:138
bool isCrayPointer() const
Return true, if CrayPointer attribute is set.
Definition AliasAnalysis.cpp:445
bool isCapturedInInternalProcedure
Source object is used in an internal procedure via host association.
Definition AliasAnalysis.h:286
bool isFortranUserVariable() const
Is this source a variable from the Fortran source?
Definition AliasAnalysis.cpp:466
Attributes attributes
Attributes of the memory source object, e.g. Target.
Definition AliasAnalysis.h:279
bool isPointer() const
Return true, if Pointer attribute is set.
Definition AliasAnalysis.cpp:426
llvm::SmallVector< ScopedOrigin, 4 > scopedOrigins
Definition AliasAnalysis.h:291
SourceKind kind
Kind of the memory source.
Definition AliasAnalysis.h:275
bool isCrayPointee() const
Return true, if CrayPointee attribute is set.
Definition AliasAnalysis.cpp:441
void print(llvm::raw_ostream &os) const
Print information about the memory source to os.
Definition AliasAnalysis.cpp:383
bool mayBePtrDummyArgOrHostAssoc() const
mayBeDummyArgOrHostAssoc and the address of a pointer?
Definition AliasAnalysis.cpp:481
bool isTargetOrPointer() const
Return true, if Target or Pointer attribute is set.
Definition AliasAnalysis.cpp:417
bool mayBeDummyArgOrHostAssoc() const
Definition AliasAnalysis.cpp:477
AccessPath accessPath
The structured access path from the root variable.
Definition AliasAnalysis.h:284
bool approximateSource
Definition AliasAnalysis.h:282
bool mayBeActualArgWithPtr(const mlir::Value *val) const
Definition AliasAnalysis.cpp:496
mlir::Type valueType
Value type of the source definition.
Definition AliasAnalysis.h:277
bool isCrayPointerOrPointee() const
Return true, if CrayPointer or CrayPointee attribute is set.
Definition AliasAnalysis.cpp:449
bool isDeclaredAllocatable() const
Definition AliasAnalysis.cpp:430
bool isTarget() const
Return true, if Target attribute is set.
Definition AliasAnalysis.cpp:422
bool mayBeActualArg() const
The address of an actual argument of the current function?
Definition AliasAnalysis.cpp:492
std::size_t getSourceCacheSizeForTesting() const
Testing only: number of entries currently held in the getSource() cache.
Definition AliasAnalysis.h:398
void enableSourceCache()
Definition AliasAnalysis.cpp:1426
fir::AliasAnalysis::Source getSource(mlir::Value, bool getLastInstantiationPoint=false, bool collectScopedOrigins=true)
Definition AliasAnalysis.cpp:1433
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:666
void disableSourceCache()
Disable getSource() memoization and drop any cached entries.
Definition AliasAnalysis.cpp:1428
static bool isPointerReference(mlir::Type ty)
Definition AliasAnalysis.cpp:409
std::size_t getSourceCacheHitsForTesting() const
Testing only: cumulative getSource() cache hits / misses on this instance.
Definition AliasAnalysis.h:403
ENUM_CLASS(Attribute, Target, Pointer, IntentIn, CrayPointer, CrayPointee)
Attributes of the memory source object.
bool functionHasMultipleScopes(mlir::Value v)
Definition AliasAnalysis.cpp:2148
ENUM_CLASS(SourceKind, Allocate, Global, Argument, HostAssoc, Indirect, Unknown)
Kind of the memory source referenced by a value.
mlir::ModRefResult getModRef(mlir::Operation *op, mlir::Value location)
Return the modify-reference behavior of op on location.