xref: /llvm-project/flang/lib/Evaluate/shape.cpp (revision 7db4c583db634ca4f16cd7aadb967dcb209bad5d)
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{ResolveAssociationsExceptSelectRank(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{
563       ResolveAssociationsExceptSelectRank(base.GetLastSymbol())};
564   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
565     int rank{details->shape().Rank()};
566     if (dimension < rank) {
567       const auto &bound{details->shape()[dimension].ubound().GetExplicit()};
568       if (bound && IsScopeInvariantExpr(*bound)) {
569         return *bound;
570       } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
571         return std::nullopt;
572       } else {
573         return ComputeUpperBound(
574             GetRawLowerBound(base, dimension), GetExtent(base, dimension));
575       }
576     }
577   } else if (const auto *assoc{
578                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
579     if (auto extent{GetAssociatedExtent(base, *assoc, dimension)}) {
580       return ComputeUpperBound(
581           GetRawLowerBound(base, dimension), std::move(extent));
582     }
583   }
584   return std::nullopt;
585 }
586 
587 MaybeExtentExpr GetRawUpperBound(
588     FoldingContext &context, const NamedEntity &base, int dimension) {
589   return Fold(context, GetRawUpperBound(base, dimension));
590 }
591 
592 static MaybeExtentExpr GetExplicitUBOUND(
593     FoldingContext *context, const semantics::ShapeSpec &shapeSpec) {
594   const auto &ubound{shapeSpec.ubound().GetExplicit()};
595   if (ubound && IsScopeInvariantExpr(*ubound)) {
596     if (auto extent{GetNonNegativeExtent(shapeSpec)}) {
597       if (auto cstExtent{ToInt64(
598               context ? Fold(*context, std::move(*extent)) : *extent)}) {
599         if (cstExtent > 0) {
600           return *ubound;
601         } else if (cstExtent == 0) {
602           return ExtentExpr{0};
603         }
604       }
605     }
606   }
607   return std::nullopt;
608 }
609 
610 static MaybeExtentExpr GetUBOUND(
611     FoldingContext *context, const NamedEntity &base, int dimension) {
612   const Symbol &symbol{
613       ResolveAssociationsExceptSelectRank(base.GetLastSymbol())};
614   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
615     int rank{details->shape().Rank()};
616     if (dimension < rank) {
617       const semantics::ShapeSpec &shapeSpec{details->shape()[dimension]};
618       if (auto ubound{GetExplicitUBOUND(context, shapeSpec)}) {
619         return *ubound;
620       } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
621         return std::nullopt;
622       } else if (auto lb{GetLBOUND(base, dimension)}) {
623         return ComputeUpperBound(std::move(*lb), GetExtent(base, dimension));
624       }
625     }
626   } else if (const auto *assoc{
627                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
628     if (auto extent{GetAssociatedExtent(base, *assoc, dimension)}) {
629       if (auto lb{GetLBOUND(base, dimension)}) {
630         return ComputeUpperBound(std::move(*lb), std::move(extent));
631       }
632     }
633   }
634   return std::nullopt;
635 }
636 
637 MaybeExtentExpr GetUBOUND(const NamedEntity &base, int dimension) {
638   return GetUBOUND(nullptr, base, dimension);
639 }
640 
641 MaybeExtentExpr GetUBOUND(
642     FoldingContext &context, const NamedEntity &base, int dimension) {
643   return Fold(context, GetUBOUND(&context, base, dimension));
644 }
645 
646 static Shape GetUBOUNDs(FoldingContext *context, const NamedEntity &base) {
647   const Symbol &symbol{
648       ResolveAssociationsExceptSelectRank(base.GetLastSymbol())};
649   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
650     Shape result;
651     int dim{0};
652     for (const auto &shapeSpec : details->shape()) {
653       if (auto ubound{GetExplicitUBOUND(context, shapeSpec)}) {
654         result.emplace_back(*ubound);
655       } else if (details->IsAssumedSize() && dim + 1 == base.Rank()) {
656         result.emplace_back(std::nullopt); // UBOUND folding replaces with -1
657       } else if (auto lb{GetLBOUND(base, dim)}) {
658         result.emplace_back(
659             ComputeUpperBound(std::move(*lb), GetExtent(base, dim)));
660       } else {
661         result.emplace_back(); // unknown
662       }
663       ++dim;
664     }
665     CHECK(GetRank(result) == symbol.Rank());
666     return result;
667   } else {
668     return std::move(GetShape(symbol).value());
669   }
670 }
671 
672 Shape GetUBOUNDs(FoldingContext &context, const NamedEntity &base) {
673   return Fold(context, GetUBOUNDs(&context, base));
674 }
675 
676 Shape GetUBOUNDs(const NamedEntity &base) { return GetUBOUNDs(nullptr, base); }
677 
678 auto GetShapeHelper::operator()(const Symbol &symbol) const -> Result {
679   return common::visit(
680       common::visitors{
681           [&](const semantics::ObjectEntityDetails &object) {
682             if (IsImpliedShape(symbol) && object.init()) {
683               return (*this)(object.init());
684             } else if (IsAssumedRank(symbol)) {
685               return Result{};
686             } else {
687               int n{object.shape().Rank()};
688               NamedEntity base{symbol};
689               return Result{CreateShape(n, base)};
690             }
691           },
692           [](const semantics::EntityDetails &) {
693             return ScalarShape(); // no dimensions seen
694           },
695           [&](const semantics::ProcEntityDetails &proc) {
696             if (const Symbol * interface{proc.procInterface()}) {
697               return (*this)(*interface);
698             } else {
699               return ScalarShape();
700             }
701           },
702           [&](const semantics::AssocEntityDetails &assoc) {
703             NamedEntity base{symbol};
704             if (assoc.rank()) { // SELECT RANK case
705               int n{assoc.rank().value()};
706               return Result{CreateShape(n, base)};
707             } else {
708               auto exprShape{((*this)(assoc.expr()))};
709               if (exprShape) {
710                 int rank{static_cast<int>(exprShape->size())};
711                 for (int dimension{0}; dimension < rank; ++dimension) {
712                   auto &extent{(*exprShape)[dimension]};
713                   if (extent && !IsActuallyConstant(*extent)) {
714                     extent = GetExtent(base, dimension);
715                   }
716                 }
717               }
718               return exprShape;
719             }
720           },
721           [&](const semantics::SubprogramDetails &subp) -> Result {
722             if (subp.isFunction()) {
723               auto resultShape{(*this)(subp.result())};
724               if (resultShape && !useResultSymbolShape_) {
725                 // Ensure the shape is constant. Otherwise, it may be referring
726                 // to symbols that belong to the subroutine scope and are
727                 // meaningless on the caller side without the related call
728                 // expression.
729                 for (auto &extent : *resultShape) {
730                   if (extent && !IsActuallyConstant(*extent)) {
731                     extent.reset();
732                   }
733                 }
734               }
735               return resultShape;
736             } else {
737               return Result{};
738             }
739           },
740           [&](const semantics::ProcBindingDetails &binding) {
741             return (*this)(binding.symbol());
742           },
743           [](const semantics::TypeParamDetails &) { return ScalarShape(); },
744           [](const auto &) { return Result{}; },
745       },
746       symbol.GetUltimate().details());
747 }
748 
749 auto GetShapeHelper::operator()(const Component &component) const -> Result {
750   const Symbol &symbol{component.GetLastSymbol()};
751   int rank{symbol.Rank()};
752   if (rank == 0) {
753     return (*this)(component.base());
754   } else if (symbol.has<semantics::ObjectEntityDetails>()) {
755     NamedEntity base{Component{component}};
756     return CreateShape(rank, base);
757   } else if (symbol.has<semantics::AssocEntityDetails>()) {
758     NamedEntity base{Component{component}};
759     return Result{CreateShape(rank, base)};
760   } else {
761     return (*this)(symbol);
762   }
763 }
764 
765 auto GetShapeHelper::operator()(const ArrayRef &arrayRef) const -> Result {
766   Shape shape;
767   int dimension{0};
768   const NamedEntity &base{arrayRef.base()};
769   for (const Subscript &ss : arrayRef.subscript()) {
770     if (ss.Rank() > 0) {
771       shape.emplace_back(GetExtent(ss, base, dimension));
772     }
773     ++dimension;
774   }
775   if (shape.empty()) {
776     if (const Component * component{base.UnwrapComponent()}) {
777       return (*this)(component->base());
778     }
779   }
780   return shape;
781 }
782 
783 auto GetShapeHelper::operator()(const CoarrayRef &coarrayRef) const -> Result {
784   NamedEntity base{coarrayRef.GetBase()};
785   if (coarrayRef.subscript().empty()) {
786     return (*this)(base);
787   } else {
788     Shape shape;
789     int dimension{0};
790     for (const Subscript &ss : coarrayRef.subscript()) {
791       if (ss.Rank() > 0) {
792         shape.emplace_back(GetExtent(ss, base, dimension));
793       }
794       ++dimension;
795     }
796     return shape;
797   }
798 }
799 
800 auto GetShapeHelper::operator()(const Substring &substring) const -> Result {
801   return (*this)(substring.parent());
802 }
803 
804 auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
805   if (call.Rank() == 0) {
806     return ScalarShape();
807   } else if (call.IsElemental()) {
808     // Use the shape of an actual array argument associated with a
809     // non-OPTIONAL dummy object argument.
810     if (context_) {
811       if (auto chars{characteristics::Procedure::FromActuals(
812               call.proc(), call.arguments(), *context_)}) {
813         std::size_t j{0};
814         for (const auto &arg : call.arguments()) {
815           if (arg && arg->Rank() > 0 && j < chars->dummyArguments.size() &&
816               !chars->dummyArguments[j].IsOptional()) {
817             return (*this)(*arg);
818           }
819           ++j;
820         }
821       }
822     }
823     return ScalarShape();
824   } else if (const Symbol * symbol{call.proc().GetSymbol()}) {
825     return (*this)(*symbol);
826   } else if (const auto *intrinsic{call.proc().GetSpecificIntrinsic()}) {
827     if (intrinsic->name == "shape" || intrinsic->name == "lbound" ||
828         intrinsic->name == "ubound") {
829       // For LBOUND/UBOUND, these are the array-valued cases (no DIM=)
830       if (!call.arguments().empty() && call.arguments().front()) {
831         return Shape{
832             MaybeExtentExpr{ExtentExpr{call.arguments().front()->Rank()}}};
833       }
834     } else if (intrinsic->name == "all" || intrinsic->name == "any" ||
835         intrinsic->name == "count" || intrinsic->name == "iall" ||
836         intrinsic->name == "iany" || intrinsic->name == "iparity" ||
837         intrinsic->name == "maxval" || intrinsic->name == "minval" ||
838         intrinsic->name == "norm2" || intrinsic->name == "parity" ||
839         intrinsic->name == "product" || intrinsic->name == "sum") {
840       // Reduction with DIM=
841       if (call.arguments().size() >= 2) {
842         auto arrayShape{
843             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
844         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
845         if (arrayShape && dimArg) {
846           if (auto dim{ToInt64(*dimArg)}) {
847             if (*dim >= 1 &&
848                 static_cast<std::size_t>(*dim) <= arrayShape->size()) {
849               arrayShape->erase(arrayShape->begin() + (*dim - 1));
850               return std::move(*arrayShape);
851             }
852           }
853         }
854       }
855     } else if (intrinsic->name == "findloc" || intrinsic->name == "maxloc" ||
856         intrinsic->name == "minloc") {
857       std::size_t dimIndex{intrinsic->name == "findloc" ? 2u : 1u};
858       if (call.arguments().size() > dimIndex) {
859         if (auto arrayShape{
860                 (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))}) {
861           auto rank{static_cast<int>(arrayShape->size())};
862           if (const auto *dimArg{
863                   UnwrapExpr<Expr<SomeType>>(call.arguments()[dimIndex])}) {
864             auto dim{ToInt64(*dimArg)};
865             if (dim && *dim >= 1 && *dim <= rank) {
866               arrayShape->erase(arrayShape->begin() + (*dim - 1));
867               return std::move(*arrayShape);
868             }
869           } else {
870             // xxxLOC(no DIM=) result is vector(1:RANK(ARRAY=))
871             return Shape{ExtentExpr{rank}};
872           }
873         }
874       }
875     } else if (intrinsic->name == "cshift" || intrinsic->name == "eoshift") {
876       if (!call.arguments().empty()) {
877         return (*this)(call.arguments()[0]);
878       }
879     } else if (intrinsic->name == "matmul") {
880       if (call.arguments().size() == 2) {
881         if (auto ashape{(*this)(call.arguments()[0])}) {
882           if (auto bshape{(*this)(call.arguments()[1])}) {
883             if (ashape->size() == 1 && bshape->size() == 2) {
884               bshape->erase(bshape->begin());
885               return std::move(*bshape); // matmul(vector, matrix)
886             } else if (ashape->size() == 2 && bshape->size() == 1) {
887               ashape->pop_back();
888               return std::move(*ashape); // matmul(matrix, vector)
889             } else if (ashape->size() == 2 && bshape->size() == 2) {
890               (*ashape)[1] = std::move((*bshape)[1]);
891               return std::move(*ashape); // matmul(matrix, matrix)
892             }
893           }
894         }
895       }
896     } else if (intrinsic->name == "pack") {
897       if (call.arguments().size() >= 3 && call.arguments().at(2)) {
898         // SHAPE(PACK(,,VECTOR=v)) -> SHAPE(v)
899         return (*this)(call.arguments().at(2));
900       } else if (call.arguments().size() >= 2 && context_) {
901         if (auto maskShape{(*this)(call.arguments().at(1))}) {
902           if (maskShape->size() == 0) {
903             // Scalar MASK= -> [MERGE(SIZE(ARRAY=), 0, mask)]
904             if (auto arrayShape{(*this)(call.arguments().at(0))}) {
905               if (auto arraySize{GetSize(std::move(*arrayShape))}) {
906                 ActualArguments toMerge{
907                     ActualArgument{AsGenericExpr(std::move(*arraySize))},
908                     ActualArgument{AsGenericExpr(ExtentExpr{0})},
909                     common::Clone(call.arguments().at(1))};
910                 auto specific{context_->intrinsics().Probe(
911                     CallCharacteristics{"merge"}, toMerge, *context_)};
912                 CHECK(specific);
913                 return Shape{ExtentExpr{FunctionRef<ExtentType>{
914                     ProcedureDesignator{std::move(specific->specificIntrinsic)},
915                     std::move(specific->arguments)}}};
916               }
917             }
918           } else {
919             // Non-scalar MASK= -> [COUNT(mask)]
920             ActualArguments toCount{ActualArgument{common::Clone(
921                 DEREF(call.arguments().at(1).value().UnwrapExpr()))}};
922             auto specific{context_->intrinsics().Probe(
923                 CallCharacteristics{"count"}, toCount, *context_)};
924             CHECK(specific);
925             return Shape{ExtentExpr{FunctionRef<ExtentType>{
926                 ProcedureDesignator{std::move(specific->specificIntrinsic)},
927                 std::move(specific->arguments)}}};
928           }
929         }
930       }
931     } else if (intrinsic->name == "reshape") {
932       if (call.arguments().size() >= 2 && call.arguments().at(1)) {
933         // SHAPE(RESHAPE(array,shape)) -> shape
934         if (const auto *shapeExpr{
935                 call.arguments().at(1).value().UnwrapExpr()}) {
936           auto shapeArg{std::get<Expr<SomeInteger>>(shapeExpr->u)};
937           if (auto result{AsShapeResult(
938                   ConvertToType<ExtentType>(std::move(shapeArg)))}) {
939             return result;
940           }
941         }
942       }
943     } else if (intrinsic->name == "spread") {
944       // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
945       // at position DIM.
946       if (call.arguments().size() == 3) {
947         auto arrayShape{
948             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
949         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
950         const auto *nCopies{
951             UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))};
952         if (arrayShape && dimArg && nCopies) {
953           if (auto dim{ToInt64(*dimArg)}) {
954             if (*dim >= 1 &&
955                 static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
956               arrayShape->emplace(arrayShape->begin() + *dim - 1,
957                   ConvertToType<ExtentType>(common::Clone(*nCopies)));
958               return std::move(*arrayShape);
959             }
960           }
961         }
962       }
963     } else if (intrinsic->name == "transfer") {
964       if (call.arguments().size() == 3 && call.arguments().at(2)) {
965         // SIZE= is present; shape is vector [SIZE=]
966         if (const auto *size{
967                 UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))}) {
968           return Shape{
969               MaybeExtentExpr{ConvertToType<ExtentType>(common::Clone(*size))}};
970         }
971       } else if (context_) {
972         if (auto moldTypeAndShape{characteristics::TypeAndShape::Characterize(
973                 call.arguments().at(1), *context_)}) {
974           if (GetRank(moldTypeAndShape->shape()) == 0) {
975             // SIZE= is absent and MOLD= is scalar: result is scalar
976             return ScalarShape();
977           } else {
978             // SIZE= is absent and MOLD= is array: result is vector whose
979             // length is determined by sizes of types.  See 16.9.193p4 case(ii).
980             // Note that if sourceBytes is not known to be empty, we
981             // can fold only when moldElementBytes is known to not be zero;
982             // the most general case risks a division by zero otherwise.
983             if (auto sourceTypeAndShape{
984                     characteristics::TypeAndShape::Characterize(
985                         call.arguments().at(0), *context_)}) {
986               if (auto sourceBytes{
987                       sourceTypeAndShape->MeasureSizeInBytes(*context_)}) {
988                 *sourceBytes = Fold(*context_, std::move(*sourceBytes));
989                 if (auto sourceBytesConst{ToInt64(*sourceBytes)}) {
990                   if (*sourceBytesConst == 0) {
991                     return Shape{ExtentExpr{0}};
992                   }
993                 }
994                 if (auto moldElementBytes{
995                         moldTypeAndShape->MeasureElementSizeInBytes(
996                             *context_, true)}) {
997                   *moldElementBytes =
998                       Fold(*context_, std::move(*moldElementBytes));
999                   auto moldElementBytesConst{ToInt64(*moldElementBytes)};
1000                   if (moldElementBytesConst && *moldElementBytesConst != 0) {
1001                     ExtentExpr extent{Fold(*context_,
1002                         (std::move(*sourceBytes) +
1003                             common::Clone(*moldElementBytes) - ExtentExpr{1}) /
1004                             common::Clone(*moldElementBytes))};
1005                     return Shape{MaybeExtentExpr{std::move(extent)}};
1006                   }
1007                 }
1008               }
1009             }
1010           }
1011         }
1012       }
1013     } else if (intrinsic->name == "transpose") {
1014       if (call.arguments().size() >= 1) {
1015         if (auto shape{(*this)(call.arguments().at(0))}) {
1016           if (shape->size() == 2) {
1017             std::swap((*shape)[0], (*shape)[1]);
1018             return shape;
1019           }
1020         }
1021       }
1022     } else if (intrinsic->name == "unpack") {
1023       if (call.arguments().size() >= 2) {
1024         return (*this)(call.arguments()[1]); // MASK=
1025       }
1026     } else if (intrinsic->characteristics.value().attrs.test(characteristics::
1027                        Procedure::Attr::NullPointer)) { // NULL(MOLD=)
1028       return (*this)(call.arguments());
1029     } else {
1030       // TODO: shapes of other non-elemental intrinsic results
1031     }
1032   }
1033   // The rank is always known even if the extents are not.
1034   return Shape(static_cast<std::size_t>(call.Rank()), MaybeExtentExpr{});
1035 }
1036 
1037 void GetShapeHelper::AccumulateExtent(
1038     ExtentExpr &result, ExtentExpr &&n) const {
1039   result = std::move(result) + std::move(n);
1040   if (context_) {
1041     // Fold during expression creation to avoid creating an expression so
1042     // large we can't evalute it without overflowing the stack.
1043     result = Fold(*context_, std::move(result));
1044   }
1045 }
1046 
1047 // Check conformance of the passed shapes.
1048 std::optional<bool> CheckConformance(parser::ContextualMessages &messages,
1049     const Shape &left, const Shape &right, CheckConformanceFlags::Flags flags,
1050     const char *leftIs, const char *rightIs) {
1051   int n{GetRank(left)};
1052   if (n == 0 && (flags & CheckConformanceFlags::LeftScalarExpandable)) {
1053     return true;
1054   }
1055   int rn{GetRank(right)};
1056   if (rn == 0 && (flags & CheckConformanceFlags::RightScalarExpandable)) {
1057     return true;
1058   }
1059   if (n != rn) {
1060     messages.Say("Rank of %1$s is %2$d, but %3$s has rank %4$d"_err_en_US,
1061         leftIs, n, rightIs, rn);
1062     return false;
1063   }
1064   for (int j{0}; j < n; ++j) {
1065     if (auto leftDim{ToInt64(left[j])}) {
1066       if (auto rightDim{ToInt64(right[j])}) {
1067         if (*leftDim != *rightDim) {
1068           messages.Say("Dimension %1$d of %2$s has extent %3$jd, "
1069                        "but %4$s has extent %5$jd"_err_en_US,
1070               j + 1, leftIs, *leftDim, rightIs, *rightDim);
1071           return false;
1072         }
1073       } else if (!(flags & CheckConformanceFlags::RightIsDeferredShape)) {
1074         return std::nullopt;
1075       }
1076     } else if (!(flags & CheckConformanceFlags::LeftIsDeferredShape)) {
1077       return std::nullopt;
1078     }
1079   }
1080   return true;
1081 }
1082 
1083 bool IncrementSubscripts(
1084     ConstantSubscripts &indices, const ConstantSubscripts &extents) {
1085   std::size_t rank(indices.size());
1086   CHECK(rank <= extents.size());
1087   for (std::size_t j{0}; j < rank; ++j) {
1088     if (extents[j] < 1) {
1089       return false;
1090     }
1091   }
1092   for (std::size_t j{0}; j < rank; ++j) {
1093     if (indices[j]++ < extents[j]) {
1094       return true;
1095     }
1096     indices[j] = 1;
1097   }
1098   return false;
1099 }
1100 
1101 } // namespace Fortran::evaluate
1102