[TargetVersion] Only enable on RISC-V and AArch64 (#115991)
[llvm-project.git] / flang / docs / Aliasing.md
blob652b766541fd467755d784f4f15c938a9379d7a4
1 <!--===- docs/Aliasing.md
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
7 -->
9 # Aliasing in Fortran
11 ```{contents}
12 ---
13 local:
14 ---
15 ```
17 ## Introduction
19 References to the ISO Fortran language standard here are given by subclause number
20 or constraint number and pertain to Fortran 2018.
22 ## Dummy Arguments
24 ### Basic rule
26 Fortran famously passes actual arguments by reference, and forbids callers
27 from associating multiple arguments on a call to conflicting storage when
28 doing so would cause the called subprogram to write to a bit of that
29 storage by means of one dummy argument and read or write that same bit
30 by means of another.
31 For example:
32 ```
33 function f(a,b,j,k)
34   real a(*), b(*)
35   a(j) = 1.
36   b(k) = 2.
37   f = a(j) ! can optimize to: f = 1.
38 end function
39 ```
41 This prohibition applies to programs (or programmers) and has been in place
42 since Fortran acquired subroutines and functions in Fortran II.
44 A Fortran compiler is free to assume that a program conforms with this rule
45 when optimizing; and while obvious violations should of course be diagnosed,
46 the programmer bears the responsibility to understand and comply with this rule.
48 It should be noted that this restriction on dummy argument aliasing works
49 "both ways", in general.
50 Modifications to a dummy argument cannot affect other names by which that
51 bit of storage may be known;
52 conversely, modifications to anything other than a dummy argument cannot
53 affect that dummy argument.
55 When a subprogram modifies storage by means of a particular dummy argument,
56 Fortran's prohibition against dummy argument aliasing is not limited just to other
57 dummy arguments, but to any other name by which that storage might be visible.
58 For example:
59 ```
60 module m
61   real x
62  contains
63   function f(y)
64     real y
65     x = 1.
66     y = 2.
67     f = x ! can optimize to: f = 1.
68   end function
69   subroutine bad
70     print *, f(x) ! nonconforming usage!
71   end subroutine
72 end module
73 ```
75 Similar examples can be written using variables in `COMMON` blocks, host-association
76 in internal subprograms, and so forth.
78 Further, the general rule that a dummy argument by which some particular bit
79 of storage has been modified must be the only means by which that storage is
80 referenced during the lifetime of a subprogram extends to cover any associations
81 with that dummy argument via pointer association, argument association in
82 procedure references deeper on the call chain, and so on.
84 ### Complications
86 Subclause 15.5.2.13 ("Restrictions on entities associated with dummy arguments"),
87 which the reader is encouraged to try to understand despite its opacity,
88 formalizes the rules for aliasing of dummy arguments.
90 In addition to the "basic rule" above, Fortran imposes these additional
91 requirements on programs.
93 1. When a dummy argument is `ALLOCATABLE` or `POINTER`, it can be deallocated
94    or reallocated only through the dummy argument during the life of the
95    subprogram.
96 1. When a dummy argument has a derived type with a component, possibly nested,
97    that is `ALLOCATABLE` or `POINTER`, the same restriction applies.
98 1. If a subprogram ever deallocates or reallocates a dummy argument or one of its
99    components, the program cannot access that data by any other means, even
100    before the change in allocation.
102 That subclause also *relaxes* the rules against dummy argument aliasing in
103 some situations.
105 1. When a dummy argument is a `POINTER`, it is essentially treated like any
106    other pointer for the purpose of alias analysis (see below), and its
107    status as a dummy argument is reduced to being relevant only for
108    deallocation and reallocation (see above).
109 1. When a dummy argument is a `TARGET`, the actual argument is really
110    a variable (not an expression or something that needs to be passed via
111    a temporary), and that variable could be a valid data target in a pointer
112    assignment statement, then the compiler has to worry about aliasing
113    between that dummy argument and pointers if some other circumstances
114    apply.  (See the standard, this one is weird and complicated!)
115 1. Aliasing doesn't extend its restrictions to what other images might do
116    to a coarray dummy argument's associated local storage during the lifetime
117    of a subprogram -- i.e., other images don't have to worry about avoiding
118    accesses to the local image's storage when its coarray nature is explicit
119    in the declaration of the dummy argument.
120    (But when the local image's storage is associated with a non-coarray dummy
121    argument, the rules still apply.
122    In other words, the compiler doesn't have to worry about corrays unless
123    it sees coarrays.)
125 ### Implications for inlining
127 A naive implementation of inlining might rewrite a procedure reference
128 something like this:
130 module m
131  contains
132   function addto(x, y)
133     real, intent(in out) :: x
134     real, intent(in) :: y
135     x = x + y
136     addto = y
137   end function
138   function f(a,j,k)
139     real a(*)
140     a(k) = 1.
141     f = addto(a(j), a(k)) ! optimizable to 1.
142   end function
143 end module
146 becoming, after inline expansion at the Fortran language level,
149 function f(a,j,k)
150   real a(*)
151   a(k) = 1.
152   a(j) = a(j) + a(k)
153   f = a(k) ! no longer optimizable to 1.
154 end function
157 The problem for a compiler is this: at the Fortran language level, no
158 language construct has the same useful guarantees against aliasing as
159 dummy arguments have.
160 A program transformation that changes dummy arguments into something
161 else needs to implement in its internal or intermediate representations
162 some kind of metadata that preserves assumptions against aliasing.
164 ### `INTENT(IN)`
166 A dummy argument may have an`INTENT` attribute.
167 The relevant case for alias analysis is `INTENT(IN)`, as constraint
168 C844 prohibits the appearance of an `INTENT(IN)` non-pointer dummy
169 argument in any "variable definition context" (19.6.7), which is
170 Fortran's way of saying that it might be at risk of modification.
172 It would be great if the compiler could assume that an actual argument
173 that corresponds to an `INTENT(IN)` dummy argument is unchanged after
174 the called subprogram returns.
175 Unfortunately, the language has holes that admit ways by which an
176 `INTENT(IN)` dummy argument may change, even in a conforming program
177 (paragraph 2 and note 4 in subclause 8.5.10 notwithstanding).
178 In particular, Fortran nowhere states that a non-pointer `INTENT(IN)`
179 dummy argument is not "definable".
181 1. `INTENT(IN)` does not prevent the same variable from also being
182    associated with another dummy argument in the same call *without*
183    `INTENT(IN)` and being modified thereby, which is conforming so
184    long as the subprogram never references the dummy argument that
185    has `INTENT(IN)`.
186    In other words, `INTENT(IN)` is necessary but not sufficient to
187    guarantee safety from modification.
188 1. A dummy argument may have `INTENT(IN)` and `TARGET` attributes,
189    and in a non-`PURE` subprogram this would allow modification of
190    its effective argument by means of a local pointer.
191 1. An `INTENT(IN)` dummy argument may be forwarded to another
192    procedure's dummy argument with no `INTENT` attribute, and is
193    susceptible to being modified during that call.
194    This case includes references to procedures with implicit
195    interfaces.
197 So, for the purposes of use/def/kill analysis, associating a variable with
198 a non-`PURE` procedure's non-pointer dummy argument may be fraught
199 even when `INTENT(IN)` is present without `VALUE`.
201 Arguing the other side of this:
202 an interoperable procedure's `INTENT(IN)` dummy
203 arguments are forbidden from being modified, and it would be odd
204 for calls to foreign C functions to be safer than native calls (18.7).
206 ### `VALUE`
208 A dummy argument with the `VALUE` attribute is effectively meant to
209 be copied into a temporary for a call and not copied back into
210 its original variable (if any).
211 A `VALUE` dummy argument is therefore as safe from aliasing as
212 a local variable of the subprogram is.
214 ## Pointers and targets
216 Modern Fortran's pointers can't associate with arbitrary data.
217 They can be pointed only at objects that have the explicit `TARGET`
218 attribute, or at the targets of other pointers.
220 A variable that does not have the `TARGET` attribute is generally
221 safe from aliasing with pointers (but see exceptions below).
222 And generally, pointers must be assumed to alias all other pointers and
223 all `TARGET` data (perhaps reduced with data flow analysis).
225 A `VOLATILE` pointer can only point to a `VOLATILE` target, and
226 a non-`VOLATILE` pointer cannot.
227 A clever programmer might try to exploit this requirement to
228 clarify alias analysis, but I have not encountered such usage
229 so far.
231 ### The `TARGET` hole for dummy arguments
233 An actual argument that doesn't have the `TARGET` attribute can still be
234 associated with a dummy argument that *is* a target.
235 This allows a non-target variable to become a target during the lifetime
236 of a call.
237 In a non-`PURE` subprogram (15.7), a pointer may be assigned to such a
238 dummy argument or to a portion of it.
239 Such a pointer has a valid lifetime that ends when the subprogram does.
241 ### Valid lifetimes of pointers to dummy arguments
243 The Fortran standard doesn't mention compiler-generated and -populated
244 temporary storage in the context of argument association in 15.5.2,
245 apart from `VALUE`, but instead tries to name all of the circumstances
246 in which an actual argument's value may have to be transmitted by means
247 of a temporary in each of the paragraphs that constrain the usable
248 lifetimes of a pointer that has been pointed to a dummy argument
249 during a call.
250 It would be more clear, I think, had the standard simply described
251 the reasons for which an actual argument might have to occupy temporary
252 storage, and then just said that pointers to temporaries must not be
253 used once those temporaries no longer exist.
255 ### Lack of pointer target `INTENT`
257 `INTENT` attributes for dummy pointer arguments apply to the pointer
258 itself, not to the data to which the pointer points.
259 Fortran still has no means of declaring a read-only pointer.
260 Fortran also has no rule against associating read-only data with a pointer.
262 ### Cray pointers
264 Cray pointers are, or were, an extension that attempted to provide
265 some of the capabilities of modern pointers and allocatables before those
266 features were standardized.
267 They had some aliasing restrictions; in particular, Cray pointers were
268 not allowed to alias each other.
270 They are now more or less obsolete and we have no plan in place to
271 support them.
273 ## Type considerations
275 Pointers with distinct types may alias so long as their types are
276 compatible in the sense of the standard.
278 Pointers to derived types and `COMPLEX` may alias with pointers to the
279 types of their components.
280 For example:
282 complex, pointer :: pz(:)
283 real, pointer :: pa(:)
284 pa => z(:)%re ! points to all of the real components
287 ### Shape and rank
289 Array rank is not a material consideration to alias analysis.
290 Two pointers may alias even if their ranks or shapes differ.
291 For example, a pointer may associate with a column in a matrix
292 to which another pointer associates;
293 or a matrix pointer with only one column or one row may associate
294 with a vector.
296 It is also possible in Fortran to "remap" target data by establishing
297 a pointer of arbitrary rank as a view of a storage sequence.
298 For example:
300 real, target :: vector(100)
301 real, pointer :: matrix(:,:)
302 matrix(1:10,1:10) => v ! now vector's elements look like a matrix
305 ## Selectors in `ASSOCIATE`, `SELECT TYPE`, and `CHANGE TEAM`
307 Selectors in `ASSOCIATE` and related constructs may associate with
308 either expression values or variables.
309 In the case of variables, the language imposes no restriction on
310 aliasing during the lifetime of the construct, and the compiler must
311 not assume that a selector works in a manner that is analogous to
312 that of a dummy argument.
314 ## Allocatables
316 There really isn't anything special about `ALLOCATABLE` objects
317 from the perspective of aliasing, apart from rules (above) that requiring
318 `ALLOCATABLE` dummy arguments be (de)allocated only by way of the dummy
319 argument.
321 Because an `ALLOCATABLE` dummy argument preserves the values of lower
322 bounds and can be assumed to be contiguous, some programmers advocate
323 the use of explicitly `ALLOCATABLE` dummy arguments even when subprograms
324 do not modify their allocation status.
325 The usual aliasing restrictions still apply, even when the same `ALLOCATABLE`
326 is associated with two or more dummy arguments on a call.
328 ## `ASYNCHRONOUS` and `VOLATILE`
330 These attributes can, unlike any other, be scoped in Fortran by means of
331 redeclaration in a `BLOCK` construct or nested procedure.
333 `ASYNCHRONOUS` data must be assumed to be read or written by some other
334 agent during its lifetime.
335 For example, Fortran's asynchronous I/O capabilities might be implemented
336 in a runtime support library by means of threading or explicitly asynchronous
337 system calls.
338 An MPI implementation might use `ASYNCHRONOUS` dummy arguments to indicate
339 that data transfers may take place during program execution in some way that
340 is not visible to the Fortran compiler.
342 The optimizer must handle `ASYNCHRONOUS` and `VOLATILE` data with great care.
343 Reads and writes of `ASYNCHRONOUS` data cannot be moved across statements
344 that might initiate or complete background operations.
345 Reads and writes of `VOLATILE` data should be treated like `volatile` in C:
346 there are no "dead" writes, reads cannot be CSE'd, and both operations should
347 be properly fenced.
349 ## Storage assocation via `EQUIVALENCE`
351 A non-allocatable object, or parts of one, may have multiple names in Fortran
352 via `EQUIVALENCE`.
353 These objects cannot be have the `POINTER` or `TARGET` attributes.
354 Their offsets in static, stack, or `COMMON` storage is resolved by semantics
355 prior to lowering.