FLANG
constant.h
1//===-- include/flang/Evaluate/constant.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_CONSTANT_H_
10#define FORTRAN_EVALUATE_CONSTANT_H_
11
12#include "formatting.h"
13#include "type.h"
14#include "flang/Common/reference.h"
15#include "flang/Support/default-kinds.h"
16#include <map>
17#include <vector>
18
19namespace llvm {
20class raw_ostream;
21}
22
23namespace Fortran::semantics {
24class Symbol;
25}
26
27namespace Fortran::evaluate {
28
29using semantics::Symbol;
30using SymbolRef = common::Reference<const Symbol>;
31
32// Wraps a constant value in a class templated by its resolved type.
33// This Constant<> template class should be instantiated only for
34// concrete intrinsic types and Type<TypeCategory::Derived>. There is no
35// instance Constant<SomeType> since there is no way to constrain each element
36// of its array to hold the same type. To represent a generic constant, use a
37// generic expression like Expr<Type<TypeCategory::Integer>> or Expr<SomeType>)
38// to wrap the appropriate instantiation of Constant<>.
39
40template <typename> class Constant;
41
42// When describing shapes of constants or specifying 1-based subscript
43// values as indices into constants, use a vector of integers.
44using ConstantSubscripts = std::vector<ConstantSubscript>;
45inline int GetRank(const ConstantSubscripts &s) {
46 return static_cast<int>(s.size());
47}
48
49// Returns the number of elements of shape, if no overflow occurs.
50std::optional<uint64_t> TotalElementCount(const ConstantSubscripts &shape);
51
52// Validate dimension re-ordering like ORDER in RESHAPE.
53// On success, return a vector that can be used as dimOrder in
54// ConstantBounds::IncrementSubscripts().
55std::optional<std::vector<int>> ValidateDimensionOrder(
56 int rank, const std::vector<int> &order);
57
58bool HasNegativeExtent(const ConstantSubscripts &);
59
60class ConstantBounds {
61public:
62 ConstantBounds() = default;
63 explicit ConstantBounds(const ConstantSubscripts &shape);
64 explicit ConstantBounds(ConstantSubscripts &&shape);
65 ~ConstantBounds();
66 const ConstantSubscripts &shape() const { return shape_; }
67 int Rank() const { return GetRank(shape_); }
68 static constexpr int Corank() { return 0; }
69 Constant<SubscriptInteger> SHAPE() const;
70
71 // It is possible in this representation for a constant array to have
72 // lower bounds other than 1, which is of course not expressible in
73 // Fortran. This case arises only from definitions of named constant
74 // arrays with such bounds, as in:
75 // REAL, PARAMETER :: NAMED(0:1) = [1.,2.]
76 // Bundling the lower bounds of the named constant with its
77 // constant value allows folding of subscripted array element
78 // references, LBOUND, and UBOUND without having to thread the named
79 // constant or its bounds throughout folding.
80 const ConstantSubscripts &lbounds() const { return lbounds_; }
81 ConstantSubscripts ComputeUbounds(std::optional<int> dim) const;
82 void set_lbounds(ConstantSubscripts &&);
83 void SetLowerBoundsToOne();
84 bool HasNonDefaultLowerBound() const;
85
86 // If no optional dimension order argument is passed, increments a vector of
87 // subscripts in Fortran array order (first dimension varying most quickly).
88 // Otherwise, increments the vector of subscripts according to the given
89 // dimension order (dimension dimOrder[0] varying most quickly; dimension
90 // indexing is zero based here). Returns false when last element was visited.
91 bool IncrementSubscripts(
92 ConstantSubscripts &, const std::vector<int> *dimOrder = nullptr) const;
93
94protected:
95 ConstantSubscript SubscriptsToOffset(const ConstantSubscripts &) const;
96
97private:
98 ConstantSubscripts shape_;
99 ConstantSubscripts lbounds_;
100};
101
102// Constant<> is specialized for Character kinds and
103// Type<TypeCategory::Derived>. The non-Character intrinsic types, and
104// Type<TypeCategory::Derived>, share enough common behavior that they use this
105// common base class.
106template <typename RESULT, typename ELEMENT = Scalar<RESULT>>
107class ConstantBase : public ConstantBounds {
108 static_assert(RESULT::category != TypeCategory::Character);
109
110public:
111 using Result = RESULT;
112 using Element = ELEMENT;
113
114 constexpr int kind() const { return kind_; }
115
116 // Constructor for creating ConstantBase from an actual value (i.e.
117 // literals, etc.)
118 template <typename A>
119 ConstantBase(int kind, const A &x, Result res)
120 : kind_{kind}, result_{res}, values_{Element{kind, x}} {
121 CHECK_KIND(kind, RESULT);
122 if constexpr (IsLengthlessIntrinsicType<Result>) {
123 CHECK(res.kind() == kind);
124 }
125 }
126 ConstantBase(int kind, ELEMENT &&x)
127 : kind_{kind}, result_{Result{kind}}, values_{std::move(x)} {
128 CHECK_KIND(kind, RESULT);
129 if constexpr (IsLengthlessIntrinsicType<Result>) {
130 CHECK(values_.front().kind() == kind);
131 }
132 }
133
134 template <typename A>
135 ConstantBase(int kind, const A &x)
136 : kind_{kind}, result_{Result{kind}}, values_{Element{kind, x}} {
137 CHECK_KIND(kind, RESULT);
138 }
139 ConstantBase(int kind, ELEMENT &&x, Result res)
140 : kind_{kind}, result_{res}, values_{std::move(x)} {
141 CHECK_KIND(kind, RESULT);
142 if constexpr (IsLengthlessIntrinsicType<Result>) {
143 CHECK(res.kind() == kind);
144 }
145 }
146
147 ConstantBase(int kind, std::vector<Element> &&x, ConstantSubscripts &&sh)
148 : ConstantBase{kind, std::move(x), std::move(sh), Result{kind}} {}
149 ConstantBase(
150 int kind, std::vector<Element> &&, ConstantSubscripts &&, Result);
151 template <typename A, typename B, typename C>
152 ConstantBase(int kind, const std::map<A, B, C> &x, Result res)
153 : kind_{kind}, result_{res}, values_{x} {
154 CHECK_KIND(kind, RESULT);
155 }
156
157 DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(ConstantBase)
158 ~ConstantBase();
159
160 bool operator==(const ConstantBase &) const;
161 bool empty() const { return values_.empty(); }
162 std::size_t size() const { return values_.size(); }
163 const std::vector<Element> &values() const { return values_; }
164 Result &result() { return result_; }
165 const Result &result() const { return result_; }
166
167 constexpr DynamicType GetType() const { return result_.GetType(); }
168 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
169 std::string AsFortran() const;
170
171protected:
172 std::vector<Element> Reshape(const ConstantSubscripts &) const;
173 std::size_t CopyFrom(const ConstantBase &source, std::size_t count,
174 ConstantSubscripts &resultSubscripts, const std::vector<int> *dimOrder);
175
176 int kind_;
177 Result result_; // usually empty except for Real & Complex
178 std::vector<Element> values_;
179};
180
181template <typename T> class Constant : public ConstantBase<T> {
182public:
183 using Result = T;
184 using Base = ConstantBase<T>;
185 using Element = Scalar<T>;
186
187 using Base::Base;
188 CLASS_BOILERPLATE(Constant)
189
190 std::optional<Scalar<T>> GetScalarValue() const {
191 if (ConstantBounds::Rank() == 0) {
192 return Base::values_.at(0);
193 } else {
194 return std::nullopt;
195 }
196 }
197
198 // Apply subscripts. Excess subscripts are ignored, including the
199 // case of a scalar.
200 Element At(const ConstantSubscripts &) const;
201
202 Constant Reshape(ConstantSubscripts &&) const;
203 std::size_t CopyFrom(const Constant &source, std::size_t count,
204 ConstantSubscripts &resultSubscripts, const std::vector<int> *dimOrder);
205};
206
207template <>
208class Constant<Type<TypeCategory::Character>> : public ConstantBounds {
209public:
210 using Result = Type<TypeCategory::Character>;
211 using Element = Scalar<Result>;
212
213 constexpr int kind() const { return kind_; }
214
215 CLASS_BOILERPLATE(Constant)
216 explicit Constant(int kind, const Scalar<Result> &);
217 explicit Constant(int kind, Scalar<Result> &&);
218 Constant(int kind, ConstantSubscript length, std::vector<Element> &&,
219 ConstantSubscripts &&);
220 ~Constant();
221
222 bool operator==(const Constant &that) const {
223 return kind() == that.kind() && LEN() == that.LEN() &&
224 shape() == that.shape() && values_ == that.values_;
225 }
226 bool empty() const;
227 std::size_t size() const;
228
229 const Scalar<Result> &values() const { return values_; }
230 ConstantSubscript LEN() const { return length_; }
231 bool wasHollerith() const { return wasHollerith_; }
232 void set_wasHollerith(bool yes = true) { wasHollerith_ = yes; }
233
234 std::optional<Scalar<Result>> GetScalarValue() const {
235 if (Rank() == 0) {
236 return values_;
237 } else {
238 return std::nullopt;
239 }
240 }
241
242 // Apply subscripts, if any.
243 Scalar<Result> At(const ConstantSubscripts &) const;
244
245 // Extract substring(s); returns nullopt for errors.
246 std::optional<Constant> Substring(ConstantSubscript, ConstantSubscript) const;
247
248 Constant Reshape(ConstantSubscripts &&) const;
249 llvm::raw_ostream &AsFortran(llvm::raw_ostream &) const;
250 std::string AsFortran() const;
251 DynamicType GetType() const { return {kind_, length_}; }
252 std::size_t CopyFrom(const Constant &source, std::size_t count,
253 ConstantSubscripts &resultSubscripts, const std::vector<int> *dimOrder);
254
255private:
256 int kind_;
257 Scalar<Result> values_; // one contiguous string
258 ConstantSubscript length_;
259 bool wasHollerith_{false};
260};
261
264 bool operator()(SymbolRef x, SymbolRef y) const;
265};
266using StructureConstructorValues = std::map<SymbolRef,
267 common::CopyableIndirection<Expr<SomeType>>, ComponentCompare>;
268
269template <>
270class Constant<Type<TypeCategory::Derived>>
271 : public ConstantBase<Type<TypeCategory::Derived>,
272 StructureConstructorValues> {
273public:
274 using Result = Type<TypeCategory::Derived>;
275 using Element = StructureConstructorValues;
276 using Base =
277 ConstantBase<Type<TypeCategory::Derived>, StructureConstructorValues>;
278
279 Constant(const StructureConstructor &);
280 Constant(StructureConstructor &&);
281 Constant(int kind, const StructureConstructor &v) : Constant(v) {
282 CHECK(kind == 0);
283 }
284 Constant(int kind, StructureConstructor &&v) : Constant(std::move(v)) {
285 CHECK(kind == 0);
286 }
287 Constant(const semantics::DerivedTypeSpec &,
288 std::vector<StructureConstructorValues> &&, ConstantSubscripts &&);
289 Constant(const semantics::DerivedTypeSpec &,
290 std::vector<StructureConstructor> &&, ConstantSubscripts &&);
291 CLASS_BOILERPLATE(Constant)
292
293 std::optional<StructureConstructor> GetScalarValue() const;
294 StructureConstructor At(const ConstantSubscripts &) const;
295
296 bool operator==(const Constant &) const;
297 Constant Reshape(ConstantSubscripts &&) const;
298 std::size_t CopyFrom(const Constant &source, std::size_t count,
299 ConstantSubscripts &resultSubscripts, const std::vector<int> *dimOrder);
300};
301
302inline Constant<SubscriptInteger> MakeSubscriptIntConstant(int64_t v) {
304 SubscriptIntegerKind, Scalar<SubscriptInteger>{SubscriptIntegerKind, v}};
305}
306
307inline Constant<CInteger> MakeCIntegerConstant(int32_t v) {
308 return Constant<CInteger>{CIntegerKind, Scalar<CInteger>{CIntegerKind, v}};
309}
310
311inline Constant<LogicalResult> MakeLogicalResultConstant(bool v) {
313 LogicalResultKind, Scalar<LogicalResult>{LogicalResultKind, v}};
314}
315
316template <typename T, typename CharT,
317 typename =
318 std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Character>>>>
319inline Constant<T> MakeConstant(int kind, const std::basic_string<CharT> &v) {
320 return Constant<T>{kind, value::CharacterValue{kind, v}};
321}
322
323template <typename T, typename CharT,
324 typename =
325 std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Character>>>>
326inline Constant<T> MakeConstant(int kind, std::basic_string<CharT> &&v) {
327 return Constant<T>{kind, value::CharacterValue{kind, std::move(v)}};
328}
329
330template <typename T,
331 typename = std::enable_if_t<std::is_same_v<T, Type<TypeCategory::Integer>>>>
332inline Constant<T> MakeConstant(int kind, int64_t v) {
333 return Constant<T>{kind, value::IntegerValue{kind, v}};
334}
335
336FOR_EACH_LENGTHLESS_INTRINSIC_KIND(extern template class ConstantBase, )
337extern template class ConstantBase<Type<TypeCategory::Derived>,
338 StructureConstructorValues>;
339FOR_EACH_INTRINSIC_KIND(extern template class Constant, )
340
341#define INSTANTIATE_CONSTANT_TEMPLATES \
342 FOR_EACH_LENGTHLESS_INTRINSIC_KIND(template class ConstantBase, ) \
343 template class ConstantBase<Type<TypeCategory::Derived>, \
344 StructureConstructorValues>; \
345 FOR_EACH_INTRINSIC_KIND(template class Constant, )
346} // namespace Fortran::evaluate
347#endif // FORTRAN_EVALUATE_CONSTANT_H_
Definition constant.h:107
Definition constant.h:181
Definition type.h:101
Definition expression.h:853
Definition type.h:61
Definition character-value.h:34
Definition integer-value.h:35
Definition symbol.h:911
Definition call.h:34
Definition constant.h:263