1 //===-- lib/Evaluate/check-expression.cpp ---------------------------------===//
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 #include "flang/Evaluate/check-expression.h"
10 #include "flang/Evaluate/traverse.h"
11 #include "flang/Evaluate/type.h"
12 #include "flang/Semantics/symbol.h"
13 #include "flang/Semantics/tools.h"
14 
15 namespace Fortran::evaluate {
16 
17 // Constant expression predicate IsConstantExpr().
18 // This code determines whether an expression is a "constant expression"
19 // in the sense of section 10.1.12.  This is not the same thing as being
20 // able to fold it (yet) into a known constant value; specifically,
21 // the expression may reference derived type kind parameters whose values
22 // are not yet known.
23 class IsConstantExprHelper : public AllTraverse<IsConstantExprHelper, true> {
24 public:
25   using Base = AllTraverse<IsConstantExprHelper, true>;
26   IsConstantExprHelper() : Base{*this} {}
27   using Base::operator();
28 
29   template <int KIND> bool operator()(const TypeParamInquiry<KIND> &inq) const {
30     return IsKindTypeParameter(inq.parameter());
31   }
32   bool operator()(const semantics::Symbol &symbol) const {
33     return IsNamedConstant(symbol) || IsImpliedDoIndex(symbol);
34   }
35   bool operator()(const CoarrayRef &) const { return false; }
36   bool operator()(const semantics::ParamValue &param) const {
37     return param.isExplicit() && (*this)(param.GetExplicit());
38   }
39   template <typename T> bool operator()(const FunctionRef<T> &call) const {
40     if (const auto *intrinsic{std::get_if<SpecificIntrinsic>(&call.proc().u)}) {
41       return intrinsic->name == "kind";
42       // TODO: other inquiry intrinsics
43     } else {
44       return false;
45     }
46   }
47   bool operator()(const StructureConstructor &constructor) const {
48     for (const auto &[symRef, expr] : constructor) {
49       if (IsAllocatable(*symRef)) {
50         return IsNullPointer(expr.value());
51       } else if (IsPointer(*symRef)) {
52         return IsNullPointer(expr.value()) || IsInitialDataTarget(expr.value());
53       } else if (!(*this)(expr.value())) {
54         return false;
55       }
56     }
57     return true;
58   }
59 
60   // Forbid integer division by zero in constants.
61   template <int KIND>
62   bool operator()(
63       const Divide<Type<TypeCategory::Integer, KIND>> &division) const {
64     using T = Type<TypeCategory::Integer, KIND>;
65     if (const auto divisor{GetScalarConstantValue<T>(division.right())}) {
66       return !divisor->IsZero();
67     } else {
68       return false;
69     }
70   }
71 };
72 
73 template <typename A> bool IsConstantExpr(const A &x) {
74   return IsConstantExprHelper{}(x);
75 }
76 template bool IsConstantExpr(const Expr<SomeType> &);
77 template bool IsConstantExpr(const Expr<SomeInteger> &);
78 template bool IsConstantExpr(const Expr<SubscriptInteger> &);
79 
80 // Object pointer initialization checking predicate IsInitialDataTarget().
81 // This code determines whether an expression is allowable as the static
82 // data address used to initialize a pointer with "=> x".  See C765.
83 // If messages are requested, errors may be generated without returning
84 // a false result.
85 class IsInitialDataTargetHelper
86     : public AllTraverse<IsInitialDataTargetHelper, true> {
87 public:
88   using Base = AllTraverse<IsInitialDataTargetHelper, true>;
89   using Base::operator();
90   explicit IsInitialDataTargetHelper(parser::ContextualMessages *m)
91       : Base{*this}, messages_{m} {}
92 
93   bool operator()(const BOZLiteralConstant &) const { return false; }
94   bool operator()(const NullPointer &) const { return true; }
95   template <typename T> bool operator()(const Constant<T> &) const {
96     return false;
97   }
98   bool operator()(const semantics::Symbol &symbol) const {
99     const Symbol &ultimate{symbol.GetUltimate()};
100     if (IsAllocatable(ultimate)) {
101       if (messages_) {
102         messages_->Say(
103             "An initial data target may not be a reference to an ALLOCATABLE '%s'"_err_en_US,
104             ultimate.name());
105       } else {
106         return false;
107       }
108     } else if (ultimate.Corank() > 0) {
109       if (messages_) {
110         messages_->Say(
111             "An initial data target may not be a reference to a coarray '%s'"_err_en_US,
112             ultimate.name());
113       } else {
114         return false;
115       }
116     } else if (!ultimate.attrs().test(semantics::Attr::TARGET)) {
117       if (messages_) {
118         messages_->Say(
119             "An initial data target may not be a reference to an object '%s' that lacks the TARGET attribute"_err_en_US,
120             ultimate.name());
121       } else {
122         return false;
123       }
124     } else if (!IsSaved(ultimate)) {
125       if (messages_) {
126         messages_->Say(
127             "An initial data target may not be a reference to an object '%s' that lacks the SAVE attribute"_err_en_US,
128             ultimate.name());
129       } else {
130         return false;
131       }
132     }
133     return true;
134   }
135   bool operator()(const StaticDataObject &) const { return false; }
136   template <int KIND> bool operator()(const TypeParamInquiry<KIND> &) const {
137     return false;
138   }
139   bool operator()(const Triplet &x) const {
140     return IsConstantExpr(x.lower()) && IsConstantExpr(x.upper()) &&
141         IsConstantExpr(x.stride());
142   }
143   bool operator()(const Subscript &x) const {
144     return std::visit(common::visitors{
145                           [&](const Triplet &t) { return (*this)(t); },
146                           [&](const auto &y) {
147                             return y.value().Rank() == 0 &&
148                                 IsConstantExpr(y.value());
149                           },
150                       },
151         x.u);
152   }
153   bool operator()(const CoarrayRef &) const { return false; }
154   bool operator()(const Substring &x) const {
155     return IsConstantExpr(x.lower()) && IsConstantExpr(x.upper()) &&
156         (*this)(x.parent());
157   }
158   bool operator()(const DescriptorInquiry &) const { return false; }
159   template <typename T> bool operator()(const ArrayConstructor<T> &) const {
160     return false;
161   }
162   bool operator()(const StructureConstructor &) const { return false; }
163   template <typename T> bool operator()(const FunctionRef<T> &) {
164     return false;
165   }
166   template <typename D, typename R, typename... O>
167   bool operator()(const Operation<D, R, O...> &) const {
168     return false;
169   }
170   template <typename T> bool operator()(const Parentheses<T> &x) const {
171     return (*this)(x.left());
172   }
173   bool operator()(const Relational<SomeType> &) const { return false; }
174 private:
175   parser::ContextualMessages *messages_;
176 };
177 
178 bool IsInitialDataTarget(
179     const Expr<SomeType> &x, parser::ContextualMessages *messages) {
180   return IsInitialDataTargetHelper{messages}(x);
181 }
182 
183 // Specification expression validation (10.1.11(2), C1010)
184 class CheckSpecificationExprHelper
185     : public AnyTraverse<CheckSpecificationExprHelper,
186           std::optional<std::string>> {
187 public:
188   using Result = std::optional<std::string>;
189   using Base = AnyTraverse<CheckSpecificationExprHelper, Result>;
190   explicit CheckSpecificationExprHelper(const semantics::Scope &s)
191       : Base{*this}, scope_{s} {}
192   using Base::operator();
193 
194   Result operator()(const ProcedureDesignator &) const {
195     return "dummy procedure argument";
196   }
197   Result operator()(const CoarrayRef &) const { return "coindexed reference"; }
198 
199   Result operator()(const semantics::Symbol &symbol) const {
200     if (semantics::IsNamedConstant(symbol)) {
201       return std::nullopt;
202     } else if (symbol.IsDummy()) {
203       if (symbol.attrs().test(semantics::Attr::OPTIONAL)) {
204         return "reference to OPTIONAL dummy argument '"s +
205             symbol.name().ToString() + "'";
206       } else if (symbol.attrs().test(semantics::Attr::INTENT_OUT)) {
207         return "reference to INTENT(OUT) dummy argument '"s +
208             symbol.name().ToString() + "'";
209       } else if (symbol.has<semantics::ObjectEntityDetails>()) {
210         return std::nullopt;
211       } else {
212         return "dummy procedure argument";
213       }
214     } else if (symbol.has<semantics::UseDetails>() ||
215         symbol.has<semantics::HostAssocDetails>() ||
216         symbol.owner().kind() == semantics::Scope::Kind::Module) {
217       return std::nullopt;
218     } else if (const auto *object{
219                    symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
220       // TODO: what about EQUIVALENCE with data in COMMON?
221       // TODO: does this work for blank COMMON?
222       if (object->commonBlock()) {
223         return std::nullopt;
224       }
225     }
226     for (const semantics::Scope *s{&scope_}; !s->IsGlobal();) {
227       s = &s->parent();
228       if (s == &symbol.owner()) {
229         return std::nullopt;
230       }
231     }
232     return "reference to local entity '"s + symbol.name().ToString() + "'";
233   }
234 
235   Result operator()(const Component &x) const {
236     // Don't look at the component symbol.
237     return (*this)(x.base());
238   }
239   Result operator()(const DescriptorInquiry &) const {
240     // Subtle: Uses of SIZE(), LBOUND(), &c. that are valid in specification
241     // expressions will have been converted to expressions over descriptor
242     // inquiries by Fold().
243     return std::nullopt;
244   }
245 
246   template <typename T> Result operator()(const FunctionRef<T> &x) const {
247     if (const auto *symbol{x.proc().GetSymbol()}) {
248       if (!semantics::IsPureProcedure(*symbol)) {
249         return "reference to impure function '"s + symbol->name().ToString() +
250             "'";
251       }
252       // TODO: other checks for standard module procedures
253     } else {
254       const SpecificIntrinsic &intrin{DEREF(x.proc().GetSpecificIntrinsic())};
255       if (intrin.name == "present") {
256         return std::nullopt; // no need to check argument(s)
257       }
258       if (IsConstantExpr(x)) {
259         // inquiry functions may not need to check argument(s)
260         return std::nullopt;
261       }
262     }
263     return (*this)(x.arguments());
264   }
265 
266 private:
267   const semantics::Scope &scope_;
268 };
269 
270 template <typename A>
271 void CheckSpecificationExpr(const A &x, parser::ContextualMessages &messages,
272     const semantics::Scope &scope) {
273   if (auto why{CheckSpecificationExprHelper{scope}(x)}) {
274     messages.Say("Invalid specification expression: %s"_err_en_US, *why);
275   }
276 }
277 
278 template void CheckSpecificationExpr(const Expr<SomeType> &,
279     parser::ContextualMessages &, const semantics::Scope &);
280 template void CheckSpecificationExpr(const Expr<SomeInteger> &,
281     parser::ContextualMessages &, const semantics::Scope &);
282 template void CheckSpecificationExpr(const Expr<SubscriptInteger> &,
283     parser::ContextualMessages &, const semantics::Scope &);
284 template void CheckSpecificationExpr(const std::optional<Expr<SomeType>> &,
285     parser::ContextualMessages &, const semantics::Scope &);
286 template void CheckSpecificationExpr(const std::optional<Expr<SomeInteger>> &,
287     parser::ContextualMessages &, const semantics::Scope &);
288 template void CheckSpecificationExpr(
289     const std::optional<Expr<SubscriptInteger>> &, parser::ContextualMessages &,
290     const semantics::Scope &);
291 
292 // IsSimplyContiguous() -- 9.5.4
293 class IsSimplyContiguousHelper
294     : public AnyTraverse<IsSimplyContiguousHelper, std::optional<bool>> {
295 public:
296   using Result = std::optional<bool>; // tri-state
297   using Base = AnyTraverse<IsSimplyContiguousHelper, Result>;
298   explicit IsSimplyContiguousHelper(const IntrinsicProcTable &t)
299       : Base{*this}, table_{t} {}
300   using Base::operator();
301 
302   Result operator()(const semantics::Symbol &symbol) const {
303     if (symbol.attrs().test(semantics::Attr::CONTIGUOUS) ||
304         symbol.Rank() == 0) {
305       return true;
306     } else if (semantics::IsPointer(symbol)) {
307       return false;
308     } else if (const auto *details{
309                    symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
310       // N.B. ALLOCATABLEs are deferred shape, not assumed, and
311       // are obviously contiguous.
312       return !details->IsAssumedShape() && !details->IsAssumedRank();
313     } else {
314       return false;
315     }
316   }
317 
318   Result operator()(const ArrayRef &x) const {
319     const auto &symbol{x.GetLastSymbol()};
320     if (!(*this)(symbol)) {
321       return false;
322     } else if (auto rank{CheckSubscripts(x.subscript())}) {
323       // a(:)%b(1,1) is not contiguous; a(1)%b(:,:) is
324       return *rank > 0 || x.Rank() == 0;
325     } else {
326       return false;
327     }
328   }
329   Result operator()(const CoarrayRef &x) const {
330     return CheckSubscripts(x.subscript()).has_value();
331   }
332   Result operator()(const Component &x) const {
333     return x.base().Rank() == 0 && (*this)(x.GetLastSymbol());
334   }
335   Result operator()(const ComplexPart &) const { return false; }
336   Result operator()(const Substring &) const { return false; }
337 
338   template <typename T> Result operator()(const FunctionRef<T> &x) const {
339     if (auto chars{
340             characteristics::Procedure::Characterize(x.proc(), table_)}) {
341       if (chars->functionResult) {
342         const auto &result{*chars->functionResult};
343         return !result.IsProcedurePointer() &&
344             result.attrs.test(characteristics::FunctionResult::Attr::Pointer) &&
345             result.attrs.test(
346                 characteristics::FunctionResult::Attr::Contiguous);
347       }
348     }
349     return false;
350   }
351 
352 private:
353   // If the subscripts can possibly be on a simply-contiguous array reference,
354   // return the rank.
355   static std::optional<int> CheckSubscripts(
356       const std::vector<Subscript> &subscript) {
357     bool anyTriplet{false};
358     int rank{0};
359     for (auto j{subscript.size()}; j-- > 0;) {
360       if (const auto *triplet{std::get_if<Triplet>(&subscript[j].u)}) {
361         if (!triplet->IsStrideOne()) {
362           return std::nullopt;
363         } else if (anyTriplet) {
364           if (triplet->lower() || triplet->upper()) {
365             // all triplets before the last one must be just ":"
366             return std::nullopt;
367           }
368         } else {
369           anyTriplet = true;
370         }
371         ++rank;
372       } else if (anyTriplet || subscript[j].Rank() > 0) {
373         return std::nullopt;
374       }
375     }
376     return rank;
377   }
378 
379   const IntrinsicProcTable &table_;
380 };
381 
382 template <typename A>
383 bool IsSimplyContiguous(const A &x, const IntrinsicProcTable &table) {
384   if (IsVariable(x)) {
385     auto known{IsSimplyContiguousHelper{table}(x)};
386     return known && *known;
387   } else {
388     return true; // not a variable
389   }
390 }
391 
392 template bool IsSimplyContiguous(
393     const Expr<SomeType> &, const IntrinsicProcTable &);
394 
395 } // namespace Fortran::evaluate
396