FLANG
variable.h
1//===-- include/flang/Evaluate/variable.h -----------------------*- 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_EVALUATE_VARIABLE_H_
10#define FORTRAN_EVALUATE_VARIABLE_H_
11
12// Defines data structures to represent data access and function calls
13// for use in expressions and assignment statements. Both copy and move
14// semantics are supported. The representation adheres closely to the
15// Fortran 2018 language standard (q.v.) and uses strong typing to ensure
16// that only admissable combinations can be constructed.
17
18#include "call.h"
19#include "common.h"
20#include "formatting.h"
21#include "static-data.h"
22#include "type.h"
23#include "flang/Common/idioms.h"
24#include "flang/Common/reference.h"
25#include "flang/Common/template.h"
26#include "flang/Parser/char-block.h"
27#include <optional>
28#include <variant>
29#include <vector>
30
31namespace llvm {
32class raw_ostream;
33}
34
35namespace Fortran::semantics {
36class Symbol;
37}
38
39namespace Fortran::evaluate {
40
41using semantics::Symbol;
42using SymbolRef = common::Reference<const Symbol>;
43using SymbolVector = std::vector<SymbolRef>;
44
45// Forward declarations
46struct DataRef;
47
48// Reference a base object in memory. This can be a Fortran symbol,
49// static data (e.g., CHARACTER literal), or compiler-created temporary.
50struct BaseObject {
51 EVALUATE_UNION_CLASS_BOILERPLATE(BaseObject)
52 int Rank() const;
53 int Corank() const;
54 std::optional<Expr<SubscriptInteger>> LEN() const;
55 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
56 const Symbol *symbol() const {
57 if (const auto *result{std::get_if<SymbolRef>(&u)}) {
58 return &result->get();
59 } else {
60 return nullptr;
61 }
62 }
63 std::variant<SymbolRef, StaticDataObject::Pointer> u;
64};
65
66// R913 structure-component & C920: Defined to be a multi-part
67// data-ref whose last part has no subscripts (or image-selector, although
68// that isn't explicit in the document). Pointer and allocatable components
69// are not explicitly indirected in this representation.
70// Complex components (%RE, %IM) are isolated below in ComplexPart.
71// (Type parameter inquiries look like component references but are distinct
72// constructs and not represented by this class.)
73class Component {
74public:
75 CLASS_BOILERPLATE(Component)
76 Component(const DataRef &b, const Symbol &c) : base_{b}, symbol_{c} {}
77 Component(DataRef &&b, const Symbol &c) : base_{std::move(b)}, symbol_{c} {}
78 Component(common::CopyableIndirection<DataRef> &&b, const Symbol &c)
79 : base_{std::move(b)}, symbol_{c} {}
80
81 const DataRef &base() const { return base_.value(); }
82 DataRef &base() { return base_.value(); }
83 const SymbolRef &symbol() const { return symbol_; }
84 SymbolRef &symbol() { return symbol_; }
85
86 int Rank() const;
87 int Corank() const;
88 const Symbol &GetFirstSymbol() const;
89 const Symbol &GetLastSymbol() const { return symbol_; }
90 std::optional<Expr<SubscriptInteger>> LEN() const;
91 bool operator==(const Component &) const;
92 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
93
94private:
95 common::CopyableIndirection<DataRef> base_;
96 SymbolRef symbol_;
97};
98
99// A NamedEntity is either a whole Symbol or a component in an instance
100// of a derived type. It may be a descriptor.
101class NamedEntity {
102public:
103 CLASS_BOILERPLATE(NamedEntity)
104 explicit NamedEntity(const Symbol &symbol) : u_{symbol} {}
105 explicit NamedEntity(Component &&c) : u_{std::move(c)} {}
106
107 bool IsSymbol() const { return std::holds_alternative<SymbolRef>(u_); }
108 const Symbol &GetFirstSymbol() const;
109 const Symbol &GetLastSymbol() const;
110 const Component &GetComponent() const { return std::get<Component>(u_); }
111 Component &GetComponent() { return std::get<Component>(u_); }
112 const SymbolRef *UnwrapSymbolRef() const; // null if a Component
113 SymbolRef *UnwrapSymbolRef();
114 const Component *UnwrapComponent() const; // null if not a Component
115 Component *UnwrapComponent();
116
117 int Rank() const;
118 int Corank() const;
119 std::optional<Expr<SubscriptInteger>> LEN() const;
120 bool operator==(const NamedEntity &) const;
121 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
122
123private:
124 std::variant<SymbolRef, Component> u_;
125};
126
127// R916 type-param-inquiry
128// N.B. x%LEN for CHARACTER is rewritten in semantics to LEN(x), which is
129// then handled via LEN() member functions in the various classes;
130// it becomes a DescriptorInquiry with Field::Len for assumed-length
131// CHARACTER objects.
132// x%KIND for intrinsic types is similarly rewritten in semantics to
133// KIND(x), which is then folded to a constant value.
134// "Bare" type parameter references within a derived type definition do
135// not have base objects.
136class TypeParamInquiry {
137public:
138 using Result = SubscriptInteger;
139 static constexpr int ResultKind{SubscriptIntegerKind};
140 static constexpr int kind() { return SubscriptIntegerKind; }
141 static constexpr DynamicType GetType() {
142 return DynamicType{TypeCategory::Integer, SubscriptIntegerKind};
143 }
144 CLASS_BOILERPLATE(TypeParamInquiry)
145 TypeParamInquiry(NamedEntity &&x, const Symbol &param)
146 : base_{std::move(x)}, parameter_{param} {}
147 TypeParamInquiry(std::optional<NamedEntity> &&x, const Symbol &param)
148 : base_{std::move(x)}, parameter_{param} {}
149
150 const std::optional<NamedEntity> &base() const { return base_; }
151 std::optional<NamedEntity> &base() { return base_; }
152 const Symbol &parameter() const { return parameter_; }
153
154 static constexpr int Rank() { return 0; } // always scalar
155 static constexpr int Corank() { return 0; }
156 bool operator==(const TypeParamInquiry &) const;
157 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
158
159private:
160 std::optional<NamedEntity> base_;
161 SymbolRef parameter_;
162};
163
164// R921 subscript-triplet
165class Triplet {
166public:
167 Triplet();
168 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Triplet)
169 Triplet(std::optional<Expr<SubscriptInteger>> &&,
170 std::optional<Expr<SubscriptInteger>> &&,
171 std::optional<Expr<SubscriptInteger>> &&);
172
173 std::optional<Expr<SubscriptInteger>> lower() const;
174 const Expr<SubscriptInteger> *GetLower() const {
175 return lower_.has_value() ? &lower_->value() : nullptr;
176 }
177 Triplet &set_lower(Expr<SubscriptInteger> &&);
178 std::optional<Expr<SubscriptInteger>> upper() const;
179 const Expr<SubscriptInteger> *GetUpper() const {
180 return upper_.has_value() ? &upper_->value() : nullptr;
181 }
182 Triplet &set_upper(Expr<SubscriptInteger> &&);
183 Expr<SubscriptInteger> stride() const; // N.B. result is not optional<>
184 const Expr<SubscriptInteger> &GetStride() const { return stride_.value(); }
185 Triplet &set_stride(Expr<SubscriptInteger> &&);
186
187 bool operator==(const Triplet &) const;
188 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
189
190private:
191 std::optional<IndirectSubscriptIntegerExpr> lower_, upper_;
192 IndirectSubscriptIntegerExpr stride_;
193};
194
195// R919 subscript when rank 0, R923 vector-subscript when rank 1
196struct Subscript {
197 EVALUATE_UNION_CLASS_BOILERPLATE(Subscript)
198 explicit Subscript(Expr<SubscriptInteger> &&);
199 int Rank() const;
200 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
201 std::variant<IndirectSubscriptIntegerExpr, Triplet> u;
202};
203
204// R917 array-element, R918 array-section; however, the case of an
205// array-section that is a complex-part-designator is represented here
206// as a ComplexPart instead. C919 & C925 require that at most one set of
207// subscripts have rank greater than 0, but that is not explicit in
208// these types.
209class ArrayRef {
210public:
211 CLASS_BOILERPLATE(ArrayRef)
212 ArrayRef(const Symbol &symbol, std::vector<Subscript> &&ss)
213 : base_{symbol}, subscript_(std::move(ss)) {}
214 ArrayRef(Component &&c, std::vector<Subscript> &&ss)
215 : base_{std::move(c)}, subscript_(std::move(ss)) {}
216 ArrayRef(NamedEntity &&base, std::vector<Subscript> &&ss)
217 : base_{std::move(base)}, subscript_(std::move(ss)) {}
218
219 NamedEntity &base() { return base_; }
220 const NamedEntity &base() const { return base_; }
221 std::vector<Subscript> &subscript() { return subscript_; }
222 const std::vector<Subscript> &subscript() const { return subscript_; }
223
224 int size() const { return static_cast<int>(subscript_.size()); }
225 Subscript &at(int n) { return subscript_.at(n); }
226 const Subscript &at(int n) const { return subscript_.at(n); }
227 template <typename A> common::IfNoLvalue<Subscript &, A> emplace_back(A &&x) {
228 return subscript_.emplace_back(std::move(x));
229 }
230
231 int Rank() const;
232 int Corank() const;
233 const Symbol &GetFirstSymbol() const;
234 const Symbol &GetLastSymbol() const;
235 std::optional<Expr<SubscriptInteger>> LEN() const;
236 bool operator==(const ArrayRef &) const;
237 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
238
239private:
240 NamedEntity base_;
241 std::vector<Subscript> subscript_;
242};
243
244// A coindexed data-ref. The base is represented as a general
245// DataRef, but the base may not contain a CoarrayRef and may
246// have rank > 0 only in an uppermost ArrayRef.
247class CoarrayRef {
248public:
249 CLASS_BOILERPLATE(CoarrayRef)
250 CoarrayRef(DataRef &&, std::vector<Expr<SubscriptInteger>> &&);
251
252 const DataRef &base() const { return base_.value(); }
253 DataRef &base() { return base_.value(); }
254 const std::vector<Expr<SubscriptInteger>> &cosubscript() const {
255 return cosubscript_;
256 }
257 std::vector<Expr<SubscriptInteger>> &cosubscript() { return cosubscript_; }
258
259 // These integral expressions for STAT= and TEAM= must be variables
260 // (i.e., Designator or pointer-valued FunctionRef).
261 std::optional<Expr<Type<TypeCategory::Integer>>> stat() const;
262 CoarrayRef &set_stat(Expr<Type<TypeCategory::Integer>> &&);
263 // When team() is Expr<Type<TypeCategory::Integer>>, it's TEAM_NUMBER=;
264 // otherwise, it's TEAM=.
265 std::optional<Expr<SomeType>> team() const;
266 CoarrayRef &set_team(Expr<SomeType> &&);
267 // When notify() is Expr<Some>, it's NOTIFY=.
268 std::optional<Expr<SomeType>> notify() const;
269 CoarrayRef &set_notify(Expr<SomeType> &&);
270
271 int Rank() const;
272 int Corank() const { return 0; }
273 const Symbol &GetFirstSymbol() const;
274 const Symbol &GetLastSymbol() const;
275 std::optional<Expr<SubscriptInteger>> LEN() const;
276 bool operator==(const CoarrayRef &) const;
277 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
278
279private:
280 common::CopyableIndirection<DataRef> base_;
281 std::vector<Expr<SubscriptInteger>> cosubscript_;
282 std::optional<common::CopyableIndirection<Expr<SomeType>>> notify_;
283 std::optional<common::CopyableIndirection<Expr<Type<TypeCategory::Integer>>>>
284 stat_;
285 std::optional<common::CopyableIndirection<Expr<SomeType>>> team_;
286};
287
288// R911 data-ref is defined syntactically as a series of part-refs, which
289// would be far too expressive if the constraints were ignored. Here, the
290// possible outcomes are spelled out. Note that a data-ref cannot include
291// a terminal substring range or complex component designator; use
292// R901 designator for that.
293struct DataRef {
294 EVALUATE_UNION_CLASS_BOILERPLATE(DataRef)
295 int Rank() const;
296 int Corank() const;
297 const Symbol &GetFirstSymbol() const;
298 const Symbol &GetLastSymbol() const;
299 std::optional<Expr<SubscriptInteger>> LEN() const;
300 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
301
302 std::variant<SymbolRef, Component, ArrayRef, CoarrayRef> u;
303};
304
305// R908 substring, R909 parent-string, R910 substring-range.
306// The base object of a substring can be a literal.
307// In the F2018 standard, substrings of array sections are parsed as
308// variants of sections instead.
309class Substring {
310 using Parent = std::variant<DataRef, StaticDataObject::Pointer>;
311
312public:
313 CLASS_BOILERPLATE(Substring)
314 Substring(DataRef &&parent, std::optional<Expr<SubscriptInteger>> &&lower,
315 std::optional<Expr<SubscriptInteger>> &&upper)
316 : parent_{std::move(parent)} {
317 SetBounds(lower, upper);
318 }
319 Substring(StaticDataObject::Pointer &&parent,
320 std::optional<Expr<SubscriptInteger>> &&lower,
321 std::optional<Expr<SubscriptInteger>> &&upper)
322 : parent_{std::move(parent)} {
323 SetBounds(lower, upper);
324 }
325
326 Expr<SubscriptInteger> lower() const;
327 const Expr<SubscriptInteger> *GetLower() const {
328 return lower_.has_value() ? &lower_->value() : nullptr;
329 }
330 Substring &set_lower(Expr<SubscriptInteger> &&);
331 std::optional<Expr<SubscriptInteger>> upper() const;
332 const Expr<SubscriptInteger> *GetUpper() const {
333 return upper_.has_value() ? &upper_->value() : nullptr;
334 }
335 Substring &set_upper(Expr<SubscriptInteger> &&);
336 const Parent &parent() const { return parent_; }
337 Parent &parent() { return parent_; }
338
339 int Rank() const;
340 int Corank() const;
341 template <typename A> const A *GetParentIf() const {
342 return std::get_if<A>(&parent_);
343 }
344 BaseObject GetBaseObject() const;
345 const Symbol *GetLastSymbol() const;
346 std::optional<Expr<SubscriptInteger>> LEN() const;
347 bool operator==(const Substring &) const;
348 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
349
350 std::optional<Expr<Type<TypeCategory::Character>>> Fold(FoldingContext &);
351
352private:
353 void SetBounds(std::optional<Expr<SubscriptInteger>> &,
354 std::optional<Expr<SubscriptInteger>> &);
355 Parent parent_;
356 std::optional<IndirectSubscriptIntegerExpr> lower_, upper_;
357};
358
359// R915 complex-part-designator
360// In the F2018 standard, complex parts of array sections are parsed as
361// variants of sections instead.
362class ComplexPart {
363public:
364 ENUM_CLASS(Part, RE, IM)
365 CLASS_BOILERPLATE(ComplexPart)
366 ComplexPart(DataRef &&z, Part p) : complex_{std::move(z)}, part_{p} {}
367 DataRef &complex() { return complex_; }
368 const DataRef &complex() const { return complex_; }
369 Part part() const { return part_; }
370 int Rank() const;
371 int Corank() const;
372 const Symbol &GetFirstSymbol() const { return complex_.GetFirstSymbol(); }
373 const Symbol &GetLastSymbol() const { return complex_.GetLastSymbol(); }
374 bool operator==(const ComplexPart &) const;
375 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
376
377private:
378 DataRef complex_;
379 Part part_;
380};
381
382// R901 designator is the most general data reference object, apart from
383// calls to pointer-valued functions. Its variant holds everything that
384// a DataRef can, and possibly also a substring reference or a
385// complex component (%RE/%IM) reference.
386template <typename T> class Designator {
387 using DataRefs = std::decay_t<decltype(DataRef::u)>;
388 using MaybeSubstring =
389 std::conditional_t<T::category == TypeCategory::Character,
390 std::variant<Substring>, std::variant<>>;
391 using MaybeComplexPart = std::conditional_t<T::category == TypeCategory::Real,
392 std::variant<ComplexPart>, std::variant<>>;
393 using Variant =
394 common::CombineVariants<DataRefs, MaybeSubstring, MaybeComplexPart>;
395
396public:
397 using Result = T;
398 static_assert(IsSpecificIntrinsicType<Result> ||
399 std::is_same_v<Result, Type<TypeCategory::Derived>>);
400
401 constexpr int kind() const { return kind_; }
402
403 CLASS_BOILERPLATE(Designator)
404 template <typename A>
405 explicit Designator(int kind, const A &x) : u{x}, kind_{kind} {
406 CHECK_KIND(kind, T);
407 }
408 template <typename A, typename = common::NoLvalue<A>>
409 explicit Designator(int kind, A &&x) : u(std::move(x)), kind_{kind} {
410 CHECK_KIND(kind, T);
411 }
412 template <typename A, typename U = T,
413 typename =
414 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
415 explicit Designator(const A &x) : Designator(0, x) {}
416 template <typename A, typename U = T, typename = common::NoLvalue<A>,
417 typename =
418 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
419 explicit Designator(A &&x) : Designator(0, std::move(x)) {}
420 bool operator==(const Designator &) const;
421 Designator(int kind, const DataRef &that)
422 : u{common::CopyVariant<Variant>(that.u)}, kind_{kind} {
423 CHECK_KIND(kind, T);
424 }
425 Designator(int kind, DataRef &&that)
426 : u{common::MoveVariant<Variant>(std::move(that.u))}, kind_{kind} {
427 CHECK_KIND(kind, T);
428 }
429 template <typename U = T,
430 typename =
431 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
432 Designator(const DataRef &that) : Designator(0, that) {}
433 template <typename U = T,
434 typename =
435 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
436 Designator(DataRef &&that) : Designator(0, std::move(that)) {}
437
438 std::optional<DynamicType> GetType() const;
439 int Rank() const;
440 int Corank() const;
441 BaseObject GetBaseObject() const;
442 const Symbol *GetLastSymbol() const;
443 std::optional<Expr<SubscriptInteger>> LEN() const;
444 llvm::raw_ostream &AsFortran(llvm::raw_ostream &o) const;
445
446 Variant u;
447
448private:
449 int kind_;
450};
451
452extern template class Designator<Type<TypeCategory::Character>>;
453
454class DescriptorInquiry {
455public:
456 using Result = SubscriptInteger;
457 static constexpr int ResultKind{SubscriptIntegerKind};
458 static constexpr int kind() { return SubscriptIntegerKind; }
459 static constexpr DynamicType GetType() {
460 return DynamicType{TypeCategory::Integer, SubscriptIntegerKind};
461 }
462 ENUM_CLASS(Field, LowerBound, Extent, Stride, Rank, Len)
463
464 CLASS_BOILERPLATE(DescriptorInquiry)
465 DescriptorInquiry(const NamedEntity &, Field, int = 0);
466 DescriptorInquiry(NamedEntity &&, Field, int = 0);
467
468 NamedEntity &base() { return base_; }
469 const NamedEntity &base() const { return base_; }
470 Field field() const { return field_; }
471 int dimension() const { return dimension_; }
472
473 static constexpr int Rank() { return 0; } // always scalar
474 static constexpr int Corank() { return 0; }
475 bool operator==(const DescriptorInquiry &) const;
476 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
477
478private:
479 NamedEntity base_;
480 Field field_;
481 int dimension_{0}; // zero-based
482};
483
484// Represents the extraction of a single scalar element from a rank-1
485// integer array expression used as an explicit-shape array bound (F2023).
486// The inner expression is rank-1; this node is scalar (Rank() == 0).
487// dimension_ is zero-based.
488class RankOneBoundElement {
489public:
490 using Result = SubscriptInteger;
491 static constexpr int ResultKind{SubscriptIntegerKind};
492 CLASS_BOILERPLATE(RankOneBoundElement)
493 RankOneBoundElement(
494 common::CopyableIndirection<Expr<SubscriptInteger>> &&e, int dim)
495 : base_{std::move(e)}, dimension_{dim} {}
496 RankOneBoundElement(Expr<SubscriptInteger> &&e, int dim)
497 : base_{std::move(e)}, dimension_{dim} {}
498
499 const Expr<SubscriptInteger> &base() const { return base_.value(); }
500 Expr<SubscriptInteger> &base() { return base_.value(); }
501 static constexpr int kind() { return ResultKind; }
502 int dimension() const { return dimension_; }
503
504 // Optional provenance. When this element was produced by folding an
505 // UBOUND()/LBOUND() inquiry of an explicit-shape array whose shape came from
506 // a rank-1 array bound, record the originating array and bound side so the
507 // mod-file writer can serialize it as the real ubound(a,dim)/lbound(a,dim)
508 // intrinsic instead of the synthetic %ROBE spelling.
509 // Declaration-time elements carry no provenance. Provenance is metadata for
510 // serialization only: it is excluded from operator== and hashing so that the
511 // builtin reuse/deduplication optimizations are unaffected.
512 const std::optional<NamedEntity> &originatingArray() const {
513 return originatingArray_;
514 }
515 bool isUpperBound() const { return isUpperBound_; }
516 void set_provenance(const NamedEntity &array, bool isUpper) {
517 originatingArray_ = array;
518 isUpperBound_ = isUpper;
519 }
520
521 static constexpr int Rank() { return 0; } // always scalar
522 static constexpr int Corank() { return 0; }
523 bool operator==(const RankOneBoundElement &) const;
524 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
525
526private:
527 common::CopyableIndirection<Expr<SubscriptInteger>> base_;
528 int dimension_{0}; // zero-based
529 std::optional<NamedEntity> originatingArray_;
530 bool isUpperBound_{false};
531};
532
533#define INSTANTIATE_VARIABLE_TEMPLATES \
534 FOR_EACH_SPECIFIC_TYPE(template class Designator, )
535} // namespace Fortran::evaluate
536#endif // FORTRAN_EVALUATE_VARIABLE_H_
Definition variable.h:73
Definition variable.h:386
Definition type.h:101
Definition common.h:222
Definition common.h:224
Definition variable.h:101
Definition type.h:61
Definition symbol.h:905
Definition call.h:34
Definition variable.h:50
Definition variable.h:293
Definition variable.h:196