xref: /llvm-project/flang/lib/Evaluate/shape.cpp (revision 635656f4ff1e0b74761af109f50d33287477d1db)
1 //===-- lib/Evaluate/shape.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/shape.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Common/template.h"
12 #include "flang/Evaluate/characteristics.h"
13 #include "flang/Evaluate/check-expression.h"
14 #include "flang/Evaluate/fold.h"
15 #include "flang/Evaluate/intrinsics.h"
16 #include "flang/Evaluate/tools.h"
17 #include "flang/Evaluate/type.h"
18 #include "flang/Parser/message.h"
19 #include "flang/Semantics/symbol.h"
20 #include <functional>
21 
22 using namespace std::placeholders; // _1, _2, &c. for std::bind()
23 
24 namespace Fortran::evaluate {
25 
26 bool IsImpliedShape(const Symbol &original) {
27   const Symbol &symbol{ResolveAssociations(original)};
28   const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()};
29   return details && symbol.attrs().test(semantics::Attr::PARAMETER) &&
30       details->shape().CanBeImpliedShape();
31 }
32 
33 bool IsExplicitShape(const Symbol &original) {
34   const Symbol &symbol{ResolveAssociations(original)};
35   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
36     const auto &shape{details->shape()};
37     return shape.Rank() == 0 ||
38         shape.IsExplicitShape(); // true when scalar, too
39   } else {
40     return symbol
41         .has<semantics::AssocEntityDetails>(); // exprs have explicit shape
42   }
43 }
44 
45 Shape GetShapeHelper::ConstantShape(const Constant<ExtentType> &arrayConstant) {
46   CHECK(arrayConstant.Rank() == 1);
47   Shape result;
48   std::size_t dimensions{arrayConstant.size()};
49   for (std::size_t j{0}; j < dimensions; ++j) {
50     Scalar<ExtentType> extent{arrayConstant.values().at(j)};
51     result.emplace_back(MaybeExtentExpr{ExtentExpr{std::move(extent)}});
52   }
53   return result;
54 }
55 
56 auto GetShapeHelper::AsShapeResult(ExtentExpr &&arrayExpr) const -> Result {
57   if (context_) {
58     arrayExpr = Fold(*context_, std::move(arrayExpr));
59   }
60   if (const auto *constArray{UnwrapConstantValue<ExtentType>(arrayExpr)}) {
61     return ConstantShape(*constArray);
62   }
63   if (auto *constructor{UnwrapExpr<ArrayConstructor<ExtentType>>(arrayExpr)}) {
64     Shape result;
65     for (auto &value : *constructor) {
66       auto *expr{std::get_if<ExtentExpr>(&value.u)};
67       if (expr && expr->Rank() == 0) {
68         result.emplace_back(std::move(*expr));
69       } else {
70         return std::nullopt;
71       }
72     }
73     return result;
74   } else {
75     return std::nullopt;
76   }
77 }
78 
79 Shape GetShapeHelper::CreateShape(int rank, NamedEntity &base) {
80   Shape shape;
81   for (int dimension{0}; dimension < rank; ++dimension) {
82     shape.emplace_back(GetExtent(base, dimension));
83   }
84   return shape;
85 }
86 
87 std::optional<ExtentExpr> AsExtentArrayExpr(const Shape &shape) {
88   ArrayConstructorValues<ExtentType> values;
89   for (const auto &dim : shape) {
90     if (dim) {
91       values.Push(common::Clone(*dim));
92     } else {
93       return std::nullopt;
94     }
95   }
96   return ExtentExpr{ArrayConstructor<ExtentType>{std::move(values)}};
97 }
98 
99 std::optional<Constant<ExtentType>> AsConstantShape(
100     FoldingContext &context, const Shape &shape) {
101   if (auto shapeArray{AsExtentArrayExpr(shape)}) {
102     auto folded{Fold(context, std::move(*shapeArray))};
103     if (auto *p{UnwrapConstantValue<ExtentType>(folded)}) {
104       return std::move(*p);
105     }
106   }
107   return std::nullopt;
108 }
109 
110 Constant<SubscriptInteger> AsConstantShape(const ConstantSubscripts &shape) {
111   using IntType = Scalar<SubscriptInteger>;
112   std::vector<IntType> result;
113   for (auto dim : shape) {
114     result.emplace_back(dim);
115   }
116   return {std::move(result), ConstantSubscripts{GetRank(shape)}};
117 }
118 
119 ConstantSubscripts AsConstantExtents(const Constant<ExtentType> &shape) {
120   ConstantSubscripts result;
121   for (const auto &extent : shape.values()) {
122     result.push_back(extent.ToInt64());
123   }
124   return result;
125 }
126 
127 std::optional<ConstantSubscripts> AsConstantExtents(
128     FoldingContext &context, const Shape &shape) {
129   if (auto shapeConstant{AsConstantShape(context, shape)}) {
130     return AsConstantExtents(*shapeConstant);
131   } else {
132     return std::nullopt;
133   }
134 }
135 
136 Shape AsShape(const ConstantSubscripts &shape) {
137   Shape result;
138   for (const auto &extent : shape) {
139     result.emplace_back(ExtentExpr{extent});
140   }
141   return result;
142 }
143 
144 std::optional<Shape> AsShape(const std::optional<ConstantSubscripts> &shape) {
145   if (shape) {
146     return AsShape(*shape);
147   } else {
148     return std::nullopt;
149   }
150 }
151 
152 Shape Fold(FoldingContext &context, Shape &&shape) {
153   for (auto &dim : shape) {
154     dim = Fold(context, std::move(dim));
155   }
156   return std::move(shape);
157 }
158 
159 std::optional<Shape> Fold(
160     FoldingContext &context, std::optional<Shape> &&shape) {
161   if (shape) {
162     return Fold(context, std::move(*shape));
163   } else {
164     return std::nullopt;
165   }
166 }
167 
168 static ExtentExpr ComputeTripCount(
169     ExtentExpr &&lower, ExtentExpr &&upper, ExtentExpr &&stride) {
170   ExtentExpr strideCopy{common::Clone(stride)};
171   ExtentExpr span{
172       (std::move(upper) - std::move(lower) + std::move(strideCopy)) /
173       std::move(stride)};
174   return ExtentExpr{
175       Extremum<ExtentType>{Ordering::Greater, std::move(span), ExtentExpr{0}}};
176 }
177 
178 ExtentExpr CountTrips(
179     ExtentExpr &&lower, ExtentExpr &&upper, ExtentExpr &&stride) {
180   return ComputeTripCount(
181       std::move(lower), std::move(upper), std::move(stride));
182 }
183 
184 ExtentExpr CountTrips(const ExtentExpr &lower, const ExtentExpr &upper,
185     const ExtentExpr &stride) {
186   return ComputeTripCount(
187       common::Clone(lower), common::Clone(upper), common::Clone(stride));
188 }
189 
190 MaybeExtentExpr CountTrips(MaybeExtentExpr &&lower, MaybeExtentExpr &&upper,
191     MaybeExtentExpr &&stride) {
192   std::function<ExtentExpr(ExtentExpr &&, ExtentExpr &&, ExtentExpr &&)> bound{
193       std::bind(ComputeTripCount, _1, _2, _3)};
194   return common::MapOptional(
195       std::move(bound), std::move(lower), std::move(upper), std::move(stride));
196 }
197 
198 MaybeExtentExpr GetSize(Shape &&shape) {
199   ExtentExpr extent{1};
200   for (auto &&dim : std::move(shape)) {
201     if (dim) {
202       extent = std::move(extent) * std::move(*dim);
203     } else {
204       return std::nullopt;
205     }
206   }
207   return extent;
208 }
209 
210 ConstantSubscript GetSize(const ConstantSubscripts &shape) {
211   ConstantSubscript size{1};
212   for (auto dim : shape) {
213     CHECK(dim >= 0);
214     size *= dim;
215   }
216   return size;
217 }
218 
219 bool ContainsAnyImpliedDoIndex(const ExtentExpr &expr) {
220   struct MyVisitor : public AnyTraverse<MyVisitor> {
221     using Base = AnyTraverse<MyVisitor>;
222     MyVisitor() : Base{*this} {}
223     using Base::operator();
224     bool operator()(const ImpliedDoIndex &) { return true; }
225   };
226   return MyVisitor{}(expr);
227 }
228 
229 // Determines lower bound on a dimension.  This can be other than 1 only
230 // for a reference to a whole array object or component. (See LBOUND, 16.9.109).
231 // ASSOCIATE construct entities may require traversal of their referents.
232 template <typename RESULT, bool LBOUND_SEMANTICS>
233 class GetLowerBoundHelper
234     : public Traverse<GetLowerBoundHelper<RESULT, LBOUND_SEMANTICS>, RESULT> {
235 public:
236   using Result = RESULT;
237   using Base = Traverse<GetLowerBoundHelper, RESULT>;
238   using Base::operator();
239   explicit GetLowerBoundHelper(int d, FoldingContext *context)
240       : Base{*this}, dimension_{d}, context_{context} {}
241   static Result Default() { return Result{1}; }
242   static Result Combine(Result &&, Result &&) {
243     // Operator results and array references always have lower bounds == 1
244     return Result{1};
245   }
246 
247   Result GetLowerBound(const Symbol &symbol0, NamedEntity &&base) const {
248     const Symbol &symbol{symbol0.GetUltimate()};
249     if (const auto *details{
250             symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
251       int rank{details->shape().Rank()};
252       if (dimension_ < rank) {
253         const semantics::ShapeSpec &shapeSpec{details->shape()[dimension_]};
254         if (shapeSpec.lbound().isExplicit()) {
255           if (const auto &lbound{shapeSpec.lbound().GetExplicit()}) {
256             if constexpr (LBOUND_SEMANTICS) {
257               bool ok{false};
258               auto lbValue{ToInt64(*lbound)};
259               if (dimension_ == rank - 1 && details->IsAssumedSize()) {
260                 // last dimension of assumed-size dummy array: don't worry
261                 // about handling an empty dimension
262                 ok = IsScopeInvariantExpr(*lbound);
263               } else if (lbValue.value_or(0) == 1) {
264                 // Lower bound is 1, regardless of extent
265                 ok = true;
266               } else if (const auto &ubound{shapeSpec.ubound().GetExplicit()}) {
267                 // If we can't prove that the dimension is nonempty,
268                 // we must be conservative.
269                 // TODO: simple symbolic math in expression rewriting to
270                 // cope with cases like A(J:J)
271                 if (context_) {
272                   auto extent{ToInt64(Fold(*context_,
273                       ExtentExpr{*ubound} - ExtentExpr{*lbound} +
274                           ExtentExpr{1}))};
275                   if (extent) {
276                     if (extent <= 0) {
277                       return Result{1};
278                     }
279                     ok = true;
280                   } else {
281                     ok = false;
282                   }
283                 } else {
284                   auto ubValue{ToInt64(*ubound)};
285                   if (lbValue && ubValue) {
286                     if (*lbValue > *ubValue) {
287                       return Result{1};
288                     }
289                     ok = true;
290                   } else {
291                     ok = false;
292                   }
293                 }
294               }
295               return ok ? *lbound : Result{};
296             } else {
297               return *lbound;
298             }
299           } else {
300             return Result{1};
301           }
302         }
303         if (IsDescriptor(symbol)) {
304           return ExtentExpr{DescriptorInquiry{std::move(base),
305               DescriptorInquiry::Field::LowerBound, dimension_}};
306         }
307       }
308     } else if (const auto *assoc{
309                    symbol.detailsIf<semantics::AssocEntityDetails>()}) {
310       if (assoc->rank()) { // SELECT RANK case
311         const Symbol &resolved{ResolveAssociations(symbol)};
312         if (IsDescriptor(resolved) && dimension_ < *assoc->rank()) {
313           return ExtentExpr{DescriptorInquiry{std::move(base),
314               DescriptorInquiry::Field::LowerBound, dimension_}};
315         }
316       } else {
317         auto exprLowerBound{((*this)(assoc->expr()))};
318         if (IsActuallyConstant(exprLowerBound)) {
319           return std::move(exprLowerBound);
320         } else {
321           // If the lower bound of the associated entity is not resolved to
322           // constant expression at the time of the association, it is unsafe
323           // to re-evaluate it later in the associate construct. Statements
324           // in-between may have modified its operands value.
325           return ExtentExpr{DescriptorInquiry{std::move(base),
326               DescriptorInquiry::Field::LowerBound, dimension_}};
327         }
328       }
329     }
330     if constexpr (LBOUND_SEMANTICS) {
331       return Result{};
332     } else {
333       return Result{1};
334     }
335   }
336 
337   Result operator()(const Symbol &symbol0) const {
338     return GetLowerBound(symbol0, NamedEntity{symbol0});
339   }
340 
341   Result operator()(const Component &component) const {
342     if (component.base().Rank() == 0) {
343       return GetLowerBound(
344           component.GetLastSymbol(), NamedEntity{common::Clone(component)});
345     }
346     return Result{1};
347   }
348 
349 private:
350   int dimension_;
351   FoldingContext *context_{nullptr};
352 };
353 
354 ExtentExpr GetRawLowerBound(const NamedEntity &base, int dimension) {
355   return GetLowerBoundHelper<ExtentExpr, false>{dimension, nullptr}(base);
356 }
357 
358 ExtentExpr GetRawLowerBound(
359     FoldingContext &context, const NamedEntity &base, int dimension) {
360   return Fold(context,
361       GetLowerBoundHelper<ExtentExpr, false>{dimension, &context}(base));
362 }
363 
364 MaybeExtentExpr GetLBOUND(const NamedEntity &base, int dimension) {
365   return GetLowerBoundHelper<MaybeExtentExpr, true>{dimension, nullptr}(base);
366 }
367 
368 MaybeExtentExpr GetLBOUND(
369     FoldingContext &context, const NamedEntity &base, int dimension) {
370   return Fold(context,
371       GetLowerBoundHelper<MaybeExtentExpr, true>{dimension, &context}(base));
372 }
373 
374 Shape GetRawLowerBounds(const NamedEntity &base) {
375   Shape result;
376   int rank{base.Rank()};
377   for (int dim{0}; dim < rank; ++dim) {
378     result.emplace_back(GetRawLowerBound(base, dim));
379   }
380   return result;
381 }
382 
383 Shape GetRawLowerBounds(FoldingContext &context, const NamedEntity &base) {
384   Shape result;
385   int rank{base.Rank()};
386   for (int dim{0}; dim < rank; ++dim) {
387     result.emplace_back(GetRawLowerBound(context, base, dim));
388   }
389   return result;
390 }
391 
392 Shape GetLBOUNDs(const NamedEntity &base) {
393   Shape result;
394   int rank{base.Rank()};
395   for (int dim{0}; dim < rank; ++dim) {
396     result.emplace_back(GetLBOUND(base, dim));
397   }
398   return result;
399 }
400 
401 Shape GetLBOUNDs(FoldingContext &context, const NamedEntity &base) {
402   Shape result;
403   int rank{base.Rank()};
404   for (int dim{0}; dim < rank; ++dim) {
405     result.emplace_back(GetLBOUND(context, base, dim));
406   }
407   return result;
408 }
409 
410 // If the upper and lower bounds are constant, return a constant expression for
411 // the extent.  In particular, if the upper bound is less than the lower bound,
412 // return zero.
413 static MaybeExtentExpr GetNonNegativeExtent(
414     const semantics::ShapeSpec &shapeSpec) {
415   const auto &ubound{shapeSpec.ubound().GetExplicit()};
416   const auto &lbound{shapeSpec.lbound().GetExplicit()};
417   std::optional<ConstantSubscript> uval{ToInt64(ubound)};
418   std::optional<ConstantSubscript> lval{ToInt64(lbound)};
419   if (uval && lval) {
420     if (*uval < *lval) {
421       return ExtentExpr{0};
422     } else {
423       return ExtentExpr{*uval - *lval + 1};
424     }
425   } else if (lbound && ubound && IsScopeInvariantExpr(*lbound) &&
426       IsScopeInvariantExpr(*ubound)) {
427     // Apply effective IDIM (MAX calculation with 0) so thet the
428     // result is never negative
429     if (lval.value_or(0) == 1) {
430       return ExtentExpr{Extremum<SubscriptInteger>{
431           Ordering::Greater, ExtentExpr{0}, common::Clone(*ubound)}};
432     } else {
433       return ExtentExpr{
434           Extremum<SubscriptInteger>{Ordering::Greater, ExtentExpr{0},
435               common::Clone(*ubound) - common::Clone(*lbound) + ExtentExpr{1}}};
436     }
437   } else {
438     return std::nullopt;
439   }
440 }
441 
442 MaybeExtentExpr GetAssociatedExtent(const NamedEntity &base,
443     const semantics::AssocEntityDetails &assoc, int dimension) {
444   if (auto shape{GetShape(assoc.expr())}) {
445     if (dimension < static_cast<int>(shape->size())) {
446       auto &extent{shape->at(dimension)};
447       if (extent && IsActuallyConstant(*extent)) {
448         return std::move(extent);
449       } else {
450         // Otherwise, evaluating the associated expression extent expression
451         // after the associate statement is unsafe given statements inside the
452         // associate may have modified the associated expression operands
453         // values.
454         return ExtentExpr{DescriptorInquiry{
455             NamedEntity{base}, DescriptorInquiry::Field::Extent, dimension}};
456       }
457     }
458   }
459   return std::nullopt;
460 }
461 
462 MaybeExtentExpr GetExtent(const NamedEntity &base, int dimension) {
463   CHECK(dimension >= 0);
464   const Symbol &last{base.GetLastSymbol()};
465   const Symbol &symbol{ResolveAssociations(last)};
466   if (const auto *assoc{last.detailsIf<semantics::AssocEntityDetails>()}) {
467     if (assoc->rank()) { // SELECT RANK case
468       if (semantics::IsDescriptor(symbol) && dimension < *assoc->rank()) {
469         return ExtentExpr{DescriptorInquiry{
470             NamedEntity{base}, DescriptorInquiry::Field::Extent, dimension}};
471       }
472     } else {
473       return GetAssociatedExtent(base, *assoc, dimension);
474     }
475   }
476   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
477     if (IsImpliedShape(symbol) && details->init()) {
478       if (auto shape{GetShape(symbol)}) {
479         if (dimension < static_cast<int>(shape->size())) {
480           return std::move(shape->at(dimension));
481         }
482       }
483     } else {
484       int j{0};
485       for (const auto &shapeSpec : details->shape()) {
486         if (j++ == dimension) {
487           if (auto extent{GetNonNegativeExtent(shapeSpec)}) {
488             return extent;
489           } else if (details->IsAssumedSize() && j == symbol.Rank()) {
490             return std::nullopt;
491           } else if (semantics::IsDescriptor(symbol)) {
492             return ExtentExpr{DescriptorInquiry{NamedEntity{base},
493                 DescriptorInquiry::Field::Extent, dimension}};
494           } else {
495             break;
496           }
497         }
498       }
499     }
500   }
501   return std::nullopt;
502 }
503 
504 MaybeExtentExpr GetExtent(
505     FoldingContext &context, const NamedEntity &base, int dimension) {
506   return Fold(context, GetExtent(base, dimension));
507 }
508 
509 MaybeExtentExpr GetExtent(
510     const Subscript &subscript, const NamedEntity &base, int dimension) {
511   return common::visit(
512       common::visitors{
513           [&](const Triplet &triplet) -> MaybeExtentExpr {
514             MaybeExtentExpr upper{triplet.upper()};
515             if (!upper) {
516               upper = GetUBOUND(base, dimension);
517             }
518             MaybeExtentExpr lower{triplet.lower()};
519             if (!lower) {
520               lower = GetLBOUND(base, dimension);
521             }
522             return CountTrips(std::move(lower), std::move(upper),
523                 MaybeExtentExpr{triplet.stride()});
524           },
525           [&](const IndirectSubscriptIntegerExpr &subs) -> MaybeExtentExpr {
526             if (auto shape{GetShape(subs.value())}) {
527               if (GetRank(*shape) > 0) {
528                 CHECK(GetRank(*shape) == 1); // vector-valued subscript
529                 return std::move(shape->at(0));
530               }
531             }
532             return std::nullopt;
533           },
534       },
535       subscript.u);
536 }
537 
538 MaybeExtentExpr GetExtent(FoldingContext &context, const Subscript &subscript,
539     const NamedEntity &base, int dimension) {
540   return Fold(context, GetExtent(subscript, base, dimension));
541 }
542 
543 MaybeExtentExpr ComputeUpperBound(
544     ExtentExpr &&lower, MaybeExtentExpr &&extent) {
545   if (extent) {
546     if (ToInt64(lower).value_or(0) == 1) {
547       return std::move(*extent);
548     } else {
549       return std::move(*extent) + std::move(lower) - ExtentExpr{1};
550     }
551   } else {
552     return std::nullopt;
553   }
554 }
555 
556 MaybeExtentExpr ComputeUpperBound(
557     FoldingContext &context, ExtentExpr &&lower, MaybeExtentExpr &&extent) {
558   return Fold(context, ComputeUpperBound(std::move(lower), std::move(extent)));
559 }
560 
561 MaybeExtentExpr GetRawUpperBound(const NamedEntity &base, int dimension) {
562   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
563   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
564     int rank{details->shape().Rank()};
565     if (dimension < rank) {
566       const auto &bound{details->shape()[dimension].ubound().GetExplicit()};
567       if (bound && IsScopeInvariantExpr(*bound)) {
568         return *bound;
569       } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
570         return std::nullopt;
571       } else {
572         return ComputeUpperBound(
573             GetRawLowerBound(base, dimension), GetExtent(base, dimension));
574       }
575     }
576   } else if (const auto *assoc{
577                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
578     if (auto extent{GetAssociatedExtent(base, *assoc, dimension)}) {
579       return ComputeUpperBound(
580           GetRawLowerBound(base, dimension), std::move(extent));
581     }
582   }
583   return std::nullopt;
584 }
585 
586 MaybeExtentExpr GetRawUpperBound(
587     FoldingContext &context, const NamedEntity &base, int dimension) {
588   return Fold(context, GetRawUpperBound(base, dimension));
589 }
590 
591 static MaybeExtentExpr GetExplicitUBOUND(
592     FoldingContext *context, const semantics::ShapeSpec &shapeSpec) {
593   const auto &ubound{shapeSpec.ubound().GetExplicit()};
594   if (ubound && IsScopeInvariantExpr(*ubound)) {
595     if (auto extent{GetNonNegativeExtent(shapeSpec)}) {
596       if (auto cstExtent{ToInt64(
597               context ? Fold(*context, std::move(*extent)) : *extent)}) {
598         if (cstExtent > 0) {
599           return *ubound;
600         } else if (cstExtent == 0) {
601           return ExtentExpr{0};
602         }
603       }
604     }
605   }
606   return std::nullopt;
607 }
608 
609 static MaybeExtentExpr GetUBOUND(
610     FoldingContext *context, const NamedEntity &base, int dimension) {
611   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
612   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
613     int rank{details->shape().Rank()};
614     if (dimension < rank) {
615       const semantics::ShapeSpec &shapeSpec{details->shape()[dimension]};
616       if (auto ubound{GetExplicitUBOUND(context, shapeSpec)}) {
617         return *ubound;
618       } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
619         return std::nullopt;
620       } else if (auto lb{GetLBOUND(base, dimension)}) {
621         return ComputeUpperBound(std::move(*lb), GetExtent(base, dimension));
622       }
623     }
624   } else if (const auto *assoc{
625                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
626     if (auto extent{GetAssociatedExtent(base, *assoc, dimension)}) {
627       if (auto lb{GetLBOUND(base, dimension)}) {
628         return ComputeUpperBound(std::move(*lb), std::move(extent));
629       }
630     }
631   }
632   return std::nullopt;
633 }
634 
635 MaybeExtentExpr GetUBOUND(const NamedEntity &base, int dimension) {
636   return GetUBOUND(nullptr, base, dimension);
637 }
638 
639 MaybeExtentExpr GetUBOUND(
640     FoldingContext &context, const NamedEntity &base, int dimension) {
641   return Fold(context, GetUBOUND(&context, base, dimension));
642 }
643 
644 static Shape GetUBOUNDs(FoldingContext *context, const NamedEntity &base) {
645   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
646   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
647     Shape result;
648     int dim{0};
649     for (const auto &shapeSpec : details->shape()) {
650       if (auto ubound{GetExplicitUBOUND(context, shapeSpec)}) {
651         result.emplace_back(*ubound);
652       } else if (details->IsAssumedSize() && dim + 1 == base.Rank()) {
653         result.emplace_back(std::nullopt); // UBOUND folding replaces with -1
654       } else if (auto lb{GetLBOUND(base, dim)}) {
655         result.emplace_back(
656             ComputeUpperBound(std::move(*lb), GetExtent(base, dim)));
657       } else {
658         result.emplace_back(); // unknown
659       }
660       ++dim;
661     }
662     CHECK(GetRank(result) == symbol.Rank());
663     return result;
664   } else {
665     return std::move(GetShape(symbol).value());
666   }
667 }
668 
669 Shape GetUBOUNDs(FoldingContext &context, const NamedEntity &base) {
670   return Fold(context, GetUBOUNDs(&context, base));
671 }
672 
673 Shape GetUBOUNDs(const NamedEntity &base) { return GetUBOUNDs(nullptr, base); }
674 
675 auto GetShapeHelper::operator()(const Symbol &symbol) const -> Result {
676   return common::visit(
677       common::visitors{
678           [&](const semantics::ObjectEntityDetails &object) {
679             if (IsImpliedShape(symbol) && object.init()) {
680               return (*this)(object.init());
681             } else if (IsAssumedRank(symbol)) {
682               return Result{};
683             } else {
684               int n{object.shape().Rank()};
685               NamedEntity base{symbol};
686               return Result{CreateShape(n, base)};
687             }
688           },
689           [](const semantics::EntityDetails &) {
690             return ScalarShape(); // no dimensions seen
691           },
692           [&](const semantics::ProcEntityDetails &proc) {
693             if (const Symbol * interface{proc.procInterface()}) {
694               return (*this)(*interface);
695             } else {
696               return ScalarShape();
697             }
698           },
699           [&](const semantics::AssocEntityDetails &assoc) {
700             NamedEntity base{symbol};
701             if (assoc.rank()) { // SELECT RANK case
702               int n{assoc.rank().value()};
703               return Result{CreateShape(n, base)};
704             } else {
705               auto exprShape{((*this)(assoc.expr()))};
706               if (exprShape) {
707                 int rank{static_cast<int>(exprShape->size())};
708                 for (int dimension{0}; dimension < rank; ++dimension) {
709                   auto &extent{(*exprShape)[dimension]};
710                   if (extent && !IsActuallyConstant(*extent)) {
711                     extent = GetExtent(base, dimension);
712                   }
713                 }
714               }
715               return exprShape;
716             }
717           },
718           [&](const semantics::SubprogramDetails &subp) -> Result {
719             if (subp.isFunction()) {
720               auto resultShape{(*this)(subp.result())};
721               if (resultShape && !useResultSymbolShape_) {
722                 // Ensure the shape is constant. Otherwise, it may be referring
723                 // to symbols that belong to the subroutine scope and are
724                 // meaningless on the caller side without the related call
725                 // expression.
726                 for (auto &extent : *resultShape) {
727                   if (extent && !IsActuallyConstant(*extent)) {
728                     extent.reset();
729                   }
730                 }
731               }
732               return resultShape;
733             } else {
734               return Result{};
735             }
736           },
737           [&](const semantics::ProcBindingDetails &binding) {
738             return (*this)(binding.symbol());
739           },
740           [](const semantics::TypeParamDetails &) { return ScalarShape(); },
741           [](const auto &) { return Result{}; },
742       },
743       symbol.GetUltimate().details());
744 }
745 
746 auto GetShapeHelper::operator()(const Component &component) const -> Result {
747   const Symbol &symbol{component.GetLastSymbol()};
748   int rank{symbol.Rank()};
749   if (rank == 0) {
750     return (*this)(component.base());
751   } else if (symbol.has<semantics::ObjectEntityDetails>()) {
752     NamedEntity base{Component{component}};
753     return CreateShape(rank, base);
754   } else if (symbol.has<semantics::AssocEntityDetails>()) {
755     NamedEntity base{Component{component}};
756     return Result{CreateShape(rank, base)};
757   } else {
758     return (*this)(symbol);
759   }
760 }
761 
762 auto GetShapeHelper::operator()(const ArrayRef &arrayRef) const -> Result {
763   Shape shape;
764   int dimension{0};
765   const NamedEntity &base{arrayRef.base()};
766   for (const Subscript &ss : arrayRef.subscript()) {
767     if (ss.Rank() > 0) {
768       shape.emplace_back(GetExtent(ss, base, dimension));
769     }
770     ++dimension;
771   }
772   if (shape.empty()) {
773     if (const Component * component{base.UnwrapComponent()}) {
774       return (*this)(component->base());
775     }
776   }
777   return shape;
778 }
779 
780 auto GetShapeHelper::operator()(const CoarrayRef &coarrayRef) const -> Result {
781   NamedEntity base{coarrayRef.GetBase()};
782   if (coarrayRef.subscript().empty()) {
783     return (*this)(base);
784   } else {
785     Shape shape;
786     int dimension{0};
787     for (const Subscript &ss : coarrayRef.subscript()) {
788       if (ss.Rank() > 0) {
789         shape.emplace_back(GetExtent(ss, base, dimension));
790       }
791       ++dimension;
792     }
793     return shape;
794   }
795 }
796 
797 auto GetShapeHelper::operator()(const Substring &substring) const -> Result {
798   return (*this)(substring.parent());
799 }
800 
801 auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
802   if (call.Rank() == 0) {
803     return ScalarShape();
804   } else if (call.IsElemental()) {
805     for (const auto &arg : call.arguments()) {
806       if (arg && arg->Rank() > 0) {
807         return (*this)(*arg);
808       }
809     }
810     return ScalarShape();
811   } else if (const Symbol * symbol{call.proc().GetSymbol()}) {
812     return (*this)(*symbol);
813   } else if (const auto *intrinsic{call.proc().GetSpecificIntrinsic()}) {
814     if (intrinsic->name == "shape" || intrinsic->name == "lbound" ||
815         intrinsic->name == "ubound") {
816       // For LBOUND/UBOUND, these are the array-valued cases (no DIM=)
817       if (!call.arguments().empty() && call.arguments().front()) {
818         return Shape{
819             MaybeExtentExpr{ExtentExpr{call.arguments().front()->Rank()}}};
820       }
821     } else if (intrinsic->name == "all" || intrinsic->name == "any" ||
822         intrinsic->name == "count" || intrinsic->name == "iall" ||
823         intrinsic->name == "iany" || intrinsic->name == "iparity" ||
824         intrinsic->name == "maxval" || intrinsic->name == "minval" ||
825         intrinsic->name == "norm2" || intrinsic->name == "parity" ||
826         intrinsic->name == "product" || intrinsic->name == "sum") {
827       // Reduction with DIM=
828       if (call.arguments().size() >= 2) {
829         auto arrayShape{
830             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
831         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
832         if (arrayShape && dimArg) {
833           if (auto dim{ToInt64(*dimArg)}) {
834             if (*dim >= 1 &&
835                 static_cast<std::size_t>(*dim) <= arrayShape->size()) {
836               arrayShape->erase(arrayShape->begin() + (*dim - 1));
837               return std::move(*arrayShape);
838             }
839           }
840         }
841       }
842     } else if (intrinsic->name == "findloc" || intrinsic->name == "maxloc" ||
843         intrinsic->name == "minloc") {
844       std::size_t dimIndex{intrinsic->name == "findloc" ? 2u : 1u};
845       if (call.arguments().size() > dimIndex) {
846         if (auto arrayShape{
847                 (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))}) {
848           auto rank{static_cast<int>(arrayShape->size())};
849           if (const auto *dimArg{
850                   UnwrapExpr<Expr<SomeType>>(call.arguments()[dimIndex])}) {
851             auto dim{ToInt64(*dimArg)};
852             if (dim && *dim >= 1 && *dim <= rank) {
853               arrayShape->erase(arrayShape->begin() + (*dim - 1));
854               return std::move(*arrayShape);
855             }
856           } else {
857             // xxxLOC(no DIM=) result is vector(1:RANK(ARRAY=))
858             return Shape{ExtentExpr{rank}};
859           }
860         }
861       }
862     } else if (intrinsic->name == "cshift" || intrinsic->name == "eoshift") {
863       if (!call.arguments().empty()) {
864         return (*this)(call.arguments()[0]);
865       }
866     } else if (intrinsic->name == "matmul") {
867       if (call.arguments().size() == 2) {
868         if (auto ashape{(*this)(call.arguments()[0])}) {
869           if (auto bshape{(*this)(call.arguments()[1])}) {
870             if (ashape->size() == 1 && bshape->size() == 2) {
871               bshape->erase(bshape->begin());
872               return std::move(*bshape); // matmul(vector, matrix)
873             } else if (ashape->size() == 2 && bshape->size() == 1) {
874               ashape->pop_back();
875               return std::move(*ashape); // matmul(matrix, vector)
876             } else if (ashape->size() == 2 && bshape->size() == 2) {
877               (*ashape)[1] = std::move((*bshape)[1]);
878               return std::move(*ashape); // matmul(matrix, matrix)
879             }
880           }
881         }
882       }
883     } else if (intrinsic->name == "pack") {
884       if (call.arguments().size() >= 3 && call.arguments().at(2)) {
885         // SHAPE(PACK(,,VECTOR=v)) -> SHAPE(v)
886         return (*this)(call.arguments().at(2));
887       } else if (call.arguments().size() >= 2 && context_) {
888         if (auto maskShape{(*this)(call.arguments().at(1))}) {
889           if (maskShape->size() == 0) {
890             // Scalar MASK= -> [MERGE(SIZE(ARRAY=), 0, mask)]
891             if (auto arrayShape{(*this)(call.arguments().at(0))}) {
892               auto arraySize{GetSize(std::move(*arrayShape))};
893               CHECK(arraySize);
894               ActualArguments toMerge{
895                   ActualArgument{AsGenericExpr(std::move(*arraySize))},
896                   ActualArgument{AsGenericExpr(ExtentExpr{0})},
897                   common::Clone(call.arguments().at(1))};
898               auto specific{context_->intrinsics().Probe(
899                   CallCharacteristics{"merge"}, toMerge, *context_)};
900               CHECK(specific);
901               return Shape{ExtentExpr{FunctionRef<ExtentType>{
902                   ProcedureDesignator{std::move(specific->specificIntrinsic)},
903                   std::move(specific->arguments)}}};
904             }
905           } else {
906             // Non-scalar MASK= -> [COUNT(mask)]
907             ActualArguments toCount{ActualArgument{common::Clone(
908                 DEREF(call.arguments().at(1).value().UnwrapExpr()))}};
909             auto specific{context_->intrinsics().Probe(
910                 CallCharacteristics{"count"}, toCount, *context_)};
911             CHECK(specific);
912             return Shape{ExtentExpr{FunctionRef<ExtentType>{
913                 ProcedureDesignator{std::move(specific->specificIntrinsic)},
914                 std::move(specific->arguments)}}};
915           }
916         }
917       }
918     } else if (intrinsic->name == "reshape") {
919       if (call.arguments().size() >= 2 && call.arguments().at(1)) {
920         // SHAPE(RESHAPE(array,shape)) -> shape
921         if (const auto *shapeExpr{
922                 call.arguments().at(1).value().UnwrapExpr()}) {
923           auto shapeArg{std::get<Expr<SomeInteger>>(shapeExpr->u)};
924           if (auto result{AsShapeResult(
925                   ConvertToType<ExtentType>(std::move(shapeArg)))}) {
926             return result;
927           }
928         }
929       }
930     } else if (intrinsic->name == "spread") {
931       // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
932       // at position DIM.
933       if (call.arguments().size() == 3) {
934         auto arrayShape{
935             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
936         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
937         const auto *nCopies{
938             UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))};
939         if (arrayShape && dimArg && nCopies) {
940           if (auto dim{ToInt64(*dimArg)}) {
941             if (*dim >= 1 &&
942                 static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
943               arrayShape->emplace(arrayShape->begin() + *dim - 1,
944                   ConvertToType<ExtentType>(common::Clone(*nCopies)));
945               return std::move(*arrayShape);
946             }
947           }
948         }
949       }
950     } else if (intrinsic->name == "transfer") {
951       if (call.arguments().size() == 3 && call.arguments().at(2)) {
952         // SIZE= is present; shape is vector [SIZE=]
953         if (const auto *size{
954                 UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))}) {
955           return Shape{
956               MaybeExtentExpr{ConvertToType<ExtentType>(common::Clone(*size))}};
957         }
958       } else if (context_) {
959         if (auto moldTypeAndShape{characteristics::TypeAndShape::Characterize(
960                 call.arguments().at(1), *context_)}) {
961           if (GetRank(moldTypeAndShape->shape()) == 0) {
962             // SIZE= is absent and MOLD= is scalar: result is scalar
963             return ScalarShape();
964           } else {
965             // SIZE= is absent and MOLD= is array: result is vector whose
966             // length is determined by sizes of types.  See 16.9.193p4 case(ii).
967             // Note that if sourceBytes is not known to be empty, we
968             // can fold only when moldElementBytes is known to not be zero;
969             // the most general case risks a division by zero otherwise.
970             if (auto sourceTypeAndShape{
971                     characteristics::TypeAndShape::Characterize(
972                         call.arguments().at(0), *context_)}) {
973               if (auto sourceBytes{
974                       sourceTypeAndShape->MeasureSizeInBytes(*context_)}) {
975                 *sourceBytes = Fold(*context_, std::move(*sourceBytes));
976                 if (auto sourceBytesConst{ToInt64(*sourceBytes)}) {
977                   if (*sourceBytesConst == 0) {
978                     return Shape{ExtentExpr{0}};
979                   }
980                 }
981                 if (auto moldElementBytes{
982                         moldTypeAndShape->MeasureElementSizeInBytes(
983                             *context_, true)}) {
984                   *moldElementBytes =
985                       Fold(*context_, std::move(*moldElementBytes));
986                   auto moldElementBytesConst{ToInt64(*moldElementBytes)};
987                   if (moldElementBytesConst && *moldElementBytesConst != 0) {
988                     ExtentExpr extent{Fold(*context_,
989                         (std::move(*sourceBytes) +
990                             common::Clone(*moldElementBytes) - ExtentExpr{1}) /
991                             common::Clone(*moldElementBytes))};
992                     return Shape{MaybeExtentExpr{std::move(extent)}};
993                   }
994                 }
995               }
996             }
997           }
998         }
999       }
1000     } else if (intrinsic->name == "transpose") {
1001       if (call.arguments().size() >= 1) {
1002         if (auto shape{(*this)(call.arguments().at(0))}) {
1003           if (shape->size() == 2) {
1004             std::swap((*shape)[0], (*shape)[1]);
1005             return shape;
1006           }
1007         }
1008       }
1009     } else if (intrinsic->name == "unpack") {
1010       if (call.arguments().size() >= 2) {
1011         return (*this)(call.arguments()[1]); // MASK=
1012       }
1013     } else if (intrinsic->characteristics.value().attrs.test(characteristics::
1014                        Procedure::Attr::NullPointer)) { // NULL(MOLD=)
1015       return (*this)(call.arguments());
1016     } else {
1017       // TODO: shapes of other non-elemental intrinsic results
1018     }
1019   }
1020   // The rank is always known even if the extents are not.
1021   return Shape(static_cast<std::size_t>(call.Rank()), MaybeExtentExpr{});
1022 }
1023 
1024 void GetShapeHelper::AccumulateExtent(
1025     ExtentExpr &result, ExtentExpr &&n) const {
1026   result = std::move(result) + std::move(n);
1027   if (context_) {
1028     // Fold during expression creation to avoid creating an expression so
1029     // large we can't evalute it without overflowing the stack.
1030     result = Fold(*context_, std::move(result));
1031   }
1032 }
1033 
1034 // Check conformance of the passed shapes.
1035 std::optional<bool> CheckConformance(parser::ContextualMessages &messages,
1036     const Shape &left, const Shape &right, CheckConformanceFlags::Flags flags,
1037     const char *leftIs, const char *rightIs) {
1038   int n{GetRank(left)};
1039   if (n == 0 && (flags & CheckConformanceFlags::LeftScalarExpandable)) {
1040     return true;
1041   }
1042   int rn{GetRank(right)};
1043   if (rn == 0 && (flags & CheckConformanceFlags::RightScalarExpandable)) {
1044     return true;
1045   }
1046   if (n != rn) {
1047     messages.Say("Rank of %1$s is %2$d, but %3$s has rank %4$d"_err_en_US,
1048         leftIs, n, rightIs, rn);
1049     return false;
1050   }
1051   for (int j{0}; j < n; ++j) {
1052     if (auto leftDim{ToInt64(left[j])}) {
1053       if (auto rightDim{ToInt64(right[j])}) {
1054         if (*leftDim != *rightDim) {
1055           messages.Say("Dimension %1$d of %2$s has extent %3$jd, "
1056                        "but %4$s has extent %5$jd"_err_en_US,
1057               j + 1, leftIs, *leftDim, rightIs, *rightDim);
1058           return false;
1059         }
1060       } else if (!(flags & CheckConformanceFlags::RightIsDeferredShape)) {
1061         return std::nullopt;
1062       }
1063     } else if (!(flags & CheckConformanceFlags::LeftIsDeferredShape)) {
1064       return std::nullopt;
1065     }
1066   }
1067   return true;
1068 }
1069 
1070 bool IncrementSubscripts(
1071     ConstantSubscripts &indices, const ConstantSubscripts &extents) {
1072   std::size_t rank(indices.size());
1073   CHECK(rank <= extents.size());
1074   for (std::size_t j{0}; j < rank; ++j) {
1075     if (extents[j] < 1) {
1076       return false;
1077     }
1078   }
1079   for (std::size_t j{0}; j < rank; ++j) {
1080     if (indices[j]++ < extents[j]) {
1081       return true;
1082     }
1083     indices[j] = 1;
1084   }
1085   return false;
1086 }
1087 
1088 } // namespace Fortran::evaluate
1089