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/fold.h"
14 #include "flang/Evaluate/intrinsics.h"
15 #include "flang/Evaluate/tools.h"
16 #include "flang/Evaluate/type.h"
17 #include "flang/Parser/message.h"
18 #include "flang/Semantics/symbol.h"
19 #include <functional>
20 
21 using namespace std::placeholders; // _1, _2, &c. for std::bind()
22 
23 namespace Fortran::evaluate {
24 
25 bool IsImpliedShape(const Symbol &original) {
26   const Symbol &symbol{ResolveAssociations(original)};
27   const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()};
28   return details && symbol.attrs().test(semantics::Attr::PARAMETER) &&
29       details->shape().IsImpliedShape();
30 }
31 
32 bool IsExplicitShape(const Symbol &original) {
33   const Symbol &symbol{ResolveAssociations(original)};
34   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
35     const auto &shape{details->shape()};
36     return shape.Rank() == 0 ||
37         shape.IsExplicitShape(); // true when scalar, too
38   } else {
39     return symbol
40         .has<semantics::AssocEntityDetails>(); // exprs have explicit shape
41   }
42 }
43 
44 Shape GetShapeHelper::ConstantShape(const Constant<ExtentType> &arrayConstant) {
45   CHECK(arrayConstant.Rank() == 1);
46   Shape result;
47   std::size_t dimensions{arrayConstant.size()};
48   for (std::size_t j{0}; j < dimensions; ++j) {
49     Scalar<ExtentType> extent{arrayConstant.values().at(j)};
50     result.emplace_back(MaybeExtentExpr{ExtentExpr{std::move(extent)}});
51   }
52   return result;
53 }
54 
55 auto GetShapeHelper::AsShape(ExtentExpr &&arrayExpr) const -> Result {
56   if (context_) {
57     arrayExpr = Fold(*context_, std::move(arrayExpr));
58   }
59   if (const auto *constArray{UnwrapConstantValue<ExtentType>(arrayExpr)}) {
60     return ConstantShape(*constArray);
61   }
62   if (auto *constructor{UnwrapExpr<ArrayConstructor<ExtentType>>(arrayExpr)}) {
63     Shape result;
64     for (auto &value : *constructor) {
65       if (auto *expr{std::get_if<ExtentExpr>(&value.u)}) {
66         if (expr->Rank() == 0) {
67           result.emplace_back(std::move(*expr));
68           continue;
69         }
70       }
71       return std::nullopt;
72     }
73     return result;
74   }
75   return std::nullopt;
76 }
77 
78 Shape GetShapeHelper::CreateShape(int rank, NamedEntity &base) {
79   Shape shape;
80   for (int dimension{0}; dimension < rank; ++dimension) {
81     shape.emplace_back(GetExtent(base, dimension));
82   }
83   return shape;
84 }
85 
86 std::optional<ExtentExpr> AsExtentArrayExpr(const Shape &shape) {
87   ArrayConstructorValues<ExtentType> values;
88   for (const auto &dim : shape) {
89     if (dim) {
90       values.Push(common::Clone(*dim));
91     } else {
92       return std::nullopt;
93     }
94   }
95   return ExtentExpr{ArrayConstructor<ExtentType>{std::move(values)}};
96 }
97 
98 std::optional<Constant<ExtentType>> AsConstantShape(
99     FoldingContext &context, const Shape &shape) {
100   if (auto shapeArray{AsExtentArrayExpr(shape)}) {
101     auto folded{Fold(context, std::move(*shapeArray))};
102     if (auto *p{UnwrapConstantValue<ExtentType>(folded)}) {
103       return std::move(*p);
104     }
105   }
106   return std::nullopt;
107 }
108 
109 Constant<SubscriptInteger> AsConstantShape(const ConstantSubscripts &shape) {
110   using IntType = Scalar<SubscriptInteger>;
111   std::vector<IntType> result;
112   for (auto dim : shape) {
113     result.emplace_back(dim);
114   }
115   return {std::move(result), ConstantSubscripts{GetRank(shape)}};
116 }
117 
118 ConstantSubscripts AsConstantExtents(const Constant<ExtentType> &shape) {
119   ConstantSubscripts result;
120   for (const auto &extent : shape.values()) {
121     result.push_back(extent.ToInt64());
122   }
123   return result;
124 }
125 
126 std::optional<ConstantSubscripts> AsConstantExtents(
127     FoldingContext &context, const Shape &shape) {
128   if (auto shapeConstant{AsConstantShape(context, shape)}) {
129     return AsConstantExtents(*shapeConstant);
130   } else {
131     return std::nullopt;
132   }
133 }
134 
135 Shape AsShape(const ConstantSubscripts &shape) {
136   Shape result;
137   for (const auto &extent : shape) {
138     result.emplace_back(ExtentExpr{extent});
139   }
140   return result;
141 }
142 
143 std::optional<Shape> AsShape(const std::optional<ConstantSubscripts> &shape) {
144   if (shape) {
145     return AsShape(*shape);
146   } else {
147     return std::nullopt;
148   }
149 }
150 
151 Shape Fold(FoldingContext &context, Shape &&shape) {
152   for (auto &dim : shape) {
153     dim = Fold(context, std::move(dim));
154   }
155   return std::move(shape);
156 }
157 
158 std::optional<Shape> Fold(
159     FoldingContext &context, std::optional<Shape> &&shape) {
160   if (shape) {
161     return Fold(context, std::move(*shape));
162   } else {
163     return std::nullopt;
164   }
165 }
166 
167 static ExtentExpr ComputeTripCount(
168     ExtentExpr &&lower, ExtentExpr &&upper, ExtentExpr &&stride) {
169   ExtentExpr strideCopy{common::Clone(stride)};
170   ExtentExpr span{
171       (std::move(upper) - std::move(lower) + std::move(strideCopy)) /
172       std::move(stride)};
173   return ExtentExpr{
174       Extremum<ExtentType>{Ordering::Greater, std::move(span), ExtentExpr{0}}};
175 }
176 
177 ExtentExpr CountTrips(
178     ExtentExpr &&lower, ExtentExpr &&upper, ExtentExpr &&stride) {
179   return ComputeTripCount(
180       std::move(lower), std::move(upper), std::move(stride));
181 }
182 
183 ExtentExpr CountTrips(const ExtentExpr &lower, const ExtentExpr &upper,
184     const ExtentExpr &stride) {
185   return ComputeTripCount(
186       common::Clone(lower), common::Clone(upper), common::Clone(stride));
187 }
188 
189 MaybeExtentExpr CountTrips(MaybeExtentExpr &&lower, MaybeExtentExpr &&upper,
190     MaybeExtentExpr &&stride) {
191   std::function<ExtentExpr(ExtentExpr &&, ExtentExpr &&, ExtentExpr &&)> bound{
192       std::bind(ComputeTripCount, _1, _2, _3)};
193   return common::MapOptional(
194       std::move(bound), std::move(lower), std::move(upper), std::move(stride));
195 }
196 
197 MaybeExtentExpr GetSize(Shape &&shape) {
198   ExtentExpr extent{1};
199   for (auto &&dim : std::move(shape)) {
200     if (dim) {
201       extent = std::move(extent) * std::move(*dim);
202     } else {
203       return std::nullopt;
204     }
205   }
206   return extent;
207 }
208 
209 ConstantSubscript GetSize(const ConstantSubscripts &shape) {
210   ConstantSubscript size{1};
211   for (auto dim : std::move(shape)) {
212     size *= dim;
213   }
214   return size;
215 }
216 
217 bool ContainsAnyImpliedDoIndex(const ExtentExpr &expr) {
218   struct MyVisitor : public AnyTraverse<MyVisitor> {
219     using Base = AnyTraverse<MyVisitor>;
220     MyVisitor() : Base{*this} {}
221     using Base::operator();
222     bool operator()(const ImpliedDoIndex &) { return true; }
223   };
224   return MyVisitor{}(expr);
225 }
226 
227 // Determines lower bound on a dimension.  This can be other than 1 only
228 // for a reference to a whole array object or component. (See LBOUND, 16.9.109).
229 // ASSOCIATE construct entities may require tranversal of their referents.
230 class GetLowerBoundHelper : public Traverse<GetLowerBoundHelper, ExtentExpr> {
231 public:
232   using Result = ExtentExpr;
233   using Base = Traverse<GetLowerBoundHelper, ExtentExpr>;
234   using Base::operator();
235   explicit GetLowerBoundHelper(int d) : Base{*this}, dimension_{d} {}
236   static ExtentExpr Default() { return ExtentExpr{1}; }
237   static ExtentExpr Combine(Result &&, Result &&) { return Default(); }
238   ExtentExpr operator()(const Symbol &);
239   ExtentExpr operator()(const Component &);
240 
241 private:
242   int dimension_;
243 };
244 
245 auto GetLowerBoundHelper::operator()(const Symbol &symbol0) -> Result {
246   const Symbol &symbol{symbol0.GetUltimate()};
247   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
248     int j{0};
249     for (const auto &shapeSpec : details->shape()) {
250       if (j++ == dimension_) {
251         if (const auto &bound{shapeSpec.lbound().GetExplicit()}) {
252           return *bound;
253         } else if (IsDescriptor(symbol)) {
254           return ExtentExpr{DescriptorInquiry{NamedEntity{symbol0},
255               DescriptorInquiry::Field::LowerBound, dimension_}};
256         } else {
257           break;
258         }
259       }
260     }
261   } else if (const auto *assoc{
262                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
263     return (*this)(assoc->expr());
264   }
265   return Default();
266 }
267 
268 auto GetLowerBoundHelper::operator()(const Component &component) -> Result {
269   if (component.base().Rank() == 0) {
270     const Symbol &symbol{component.GetLastSymbol().GetUltimate()};
271     if (const auto *details{
272             symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
273       int j{0};
274       for (const auto &shapeSpec : details->shape()) {
275         if (j++ == dimension_) {
276           if (const auto &bound{shapeSpec.lbound().GetExplicit()}) {
277             return *bound;
278           } else if (IsDescriptor(symbol)) {
279             return ExtentExpr{
280                 DescriptorInquiry{NamedEntity{common::Clone(component)},
281                     DescriptorInquiry::Field::LowerBound, dimension_}};
282           } else {
283             break;
284           }
285         }
286       }
287     }
288   }
289   return Default();
290 }
291 
292 ExtentExpr GetLowerBound(const NamedEntity &base, int dimension) {
293   return GetLowerBoundHelper{dimension}(base);
294 }
295 
296 ExtentExpr GetLowerBound(
297     FoldingContext &context, const NamedEntity &base, int dimension) {
298   return Fold(context, GetLowerBound(base, dimension));
299 }
300 
301 Shape GetLowerBounds(const NamedEntity &base) {
302   Shape result;
303   int rank{base.Rank()};
304   for (int dim{0}; dim < rank; ++dim) {
305     result.emplace_back(GetLowerBound(base, dim));
306   }
307   return result;
308 }
309 
310 Shape GetLowerBounds(FoldingContext &context, const NamedEntity &base) {
311   Shape result;
312   int rank{base.Rank()};
313   for (int dim{0}; dim < rank; ++dim) {
314     result.emplace_back(GetLowerBound(context, base, dim));
315   }
316   return result;
317 }
318 
319 MaybeExtentExpr GetExtent(const NamedEntity &base, int dimension) {
320   CHECK(dimension >= 0);
321   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
322   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
323     if (IsImpliedShape(symbol) && details->init()) {
324       if (auto shape{GetShape(symbol)}) {
325         if (dimension < static_cast<int>(shape->size())) {
326           return std::move(shape->at(dimension));
327         }
328       }
329     } else {
330       int j{0};
331       for (const auto &shapeSpec : details->shape()) {
332         if (j++ == dimension) {
333           if (shapeSpec.ubound().isExplicit()) {
334             if (const auto &ubound{shapeSpec.ubound().GetExplicit()}) {
335               if (const auto &lbound{shapeSpec.lbound().GetExplicit()}) {
336                 return common::Clone(ubound.value()) -
337                     common::Clone(lbound.value()) + ExtentExpr{1};
338               } else {
339                 return ubound.value();
340               }
341             }
342           } else if (details->IsAssumedSize() && j == symbol.Rank()) {
343             return std::nullopt;
344           } else if (semantics::IsDescriptor(symbol)) {
345             return ExtentExpr{DescriptorInquiry{NamedEntity{base},
346                 DescriptorInquiry::Field::Extent, dimension}};
347           }
348         }
349       }
350     }
351   } else if (const auto *assoc{
352                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
353     if (auto shape{GetShape(assoc->expr())}) {
354       if (dimension < static_cast<int>(shape->size())) {
355         return std::move(shape->at(dimension));
356       }
357     }
358   }
359   return std::nullopt;
360 }
361 
362 MaybeExtentExpr GetExtent(
363     FoldingContext &context, const NamedEntity &base, int dimension) {
364   return Fold(context, GetExtent(base, dimension));
365 }
366 
367 MaybeExtentExpr GetExtent(
368     const Subscript &subscript, const NamedEntity &base, int dimension) {
369   return std::visit(
370       common::visitors{
371           [&](const Triplet &triplet) -> MaybeExtentExpr {
372             MaybeExtentExpr upper{triplet.upper()};
373             if (!upper) {
374               upper = GetUpperBound(base, dimension);
375             }
376             MaybeExtentExpr lower{triplet.lower()};
377             if (!lower) {
378               lower = GetLowerBound(base, dimension);
379             }
380             return CountTrips(std::move(lower), std::move(upper),
381                 MaybeExtentExpr{triplet.stride()});
382           },
383           [&](const IndirectSubscriptIntegerExpr &subs) -> MaybeExtentExpr {
384             if (auto shape{GetShape(subs.value())}) {
385               if (GetRank(*shape) > 0) {
386                 CHECK(GetRank(*shape) == 1); // vector-valued subscript
387                 return std::move(shape->at(0));
388               }
389             }
390             return std::nullopt;
391           },
392       },
393       subscript.u);
394 }
395 
396 MaybeExtentExpr GetExtent(FoldingContext &context, const Subscript &subscript,
397     const NamedEntity &base, int dimension) {
398   return Fold(context, GetExtent(subscript, base, dimension));
399 }
400 
401 MaybeExtentExpr ComputeUpperBound(
402     ExtentExpr &&lower, MaybeExtentExpr &&extent) {
403   if (extent) {
404     return std::move(*extent) + std::move(lower) - ExtentExpr{1};
405   } else {
406     return std::nullopt;
407   }
408 }
409 
410 MaybeExtentExpr ComputeUpperBound(
411     FoldingContext &context, ExtentExpr &&lower, MaybeExtentExpr &&extent) {
412   return Fold(context, ComputeUpperBound(std::move(lower), std::move(extent)));
413 }
414 
415 MaybeExtentExpr GetUpperBound(const NamedEntity &base, int dimension) {
416   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
417   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
418     int j{0};
419     for (const auto &shapeSpec : details->shape()) {
420       if (j++ == dimension) {
421         if (const auto &bound{shapeSpec.ubound().GetExplicit()}) {
422           return *bound;
423         } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
424           break;
425         } else {
426           return ComputeUpperBound(
427               GetLowerBound(base, dimension), GetExtent(base, dimension));
428         }
429       }
430     }
431   } else if (const auto *assoc{
432                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
433     if (auto shape{GetShape(assoc->expr())}) {
434       if (dimension < static_cast<int>(shape->size())) {
435         return ComputeUpperBound(
436             GetLowerBound(base, dimension), std::move(shape->at(dimension)));
437       }
438     }
439   }
440   return std::nullopt;
441 }
442 
443 MaybeExtentExpr GetUpperBound(
444     FoldingContext &context, const NamedEntity &base, int dimension) {
445   return Fold(context, GetUpperBound(base, dimension));
446 }
447 
448 Shape GetUpperBounds(const NamedEntity &base) {
449   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
450   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
451     Shape result;
452     int dim{0};
453     for (const auto &shapeSpec : details->shape()) {
454       if (const auto &bound{shapeSpec.ubound().GetExplicit()}) {
455         result.push_back(*bound);
456       } else if (details->IsAssumedSize()) {
457         CHECK(dim + 1 == base.Rank());
458         result.emplace_back(std::nullopt); // UBOUND folding replaces with -1
459       } else {
460         result.emplace_back(
461             ComputeUpperBound(GetLowerBound(base, dim), GetExtent(base, dim)));
462       }
463       ++dim;
464     }
465     CHECK(GetRank(result) == symbol.Rank());
466     return result;
467   } else {
468     return std::move(GetShape(symbol).value());
469   }
470 }
471 
472 Shape GetUpperBounds(FoldingContext &context, const NamedEntity &base) {
473   return Fold(context, GetUpperBounds(base));
474 }
475 
476 auto GetShapeHelper::operator()(const Symbol &symbol) const -> Result {
477   return std::visit(
478       common::visitors{
479           [&](const semantics::ObjectEntityDetails &object) {
480             if (IsImpliedShape(symbol) && object.init()) {
481               return (*this)(object.init());
482             } else {
483               int n{object.shape().Rank()};
484               NamedEntity base{symbol};
485               return Result{CreateShape(n, base)};
486             }
487           },
488           [](const semantics::EntityDetails &) {
489             return ScalarShape(); // no dimensions seen
490           },
491           [&](const semantics::ProcEntityDetails &proc) {
492             if (const Symbol * interface{proc.interface().symbol()}) {
493               return (*this)(*interface);
494             } else {
495               return ScalarShape();
496             }
497           },
498           [&](const semantics::AssocEntityDetails &assoc) {
499             if (!assoc.rank()) {
500               return (*this)(assoc.expr());
501             } else {
502               int n{assoc.rank().value()};
503               NamedEntity base{symbol};
504               return Result{CreateShape(n, base)};
505             }
506           },
507           [&](const semantics::SubprogramDetails &subp) {
508             if (subp.isFunction()) {
509               return (*this)(subp.result());
510             } else {
511               return Result{};
512             }
513           },
514           [&](const semantics::ProcBindingDetails &binding) {
515             return (*this)(binding.symbol());
516           },
517           [&](const semantics::UseDetails &use) {
518             return (*this)(use.symbol());
519           },
520           [&](const semantics::HostAssocDetails &assoc) {
521             return (*this)(assoc.symbol());
522           },
523           [](const semantics::TypeParamDetails &) { return ScalarShape(); },
524           [](const auto &) { return Result{}; },
525       },
526       symbol.details());
527 }
528 
529 auto GetShapeHelper::operator()(const Component &component) const -> Result {
530   const Symbol &symbol{component.GetLastSymbol()};
531   int rank{symbol.Rank()};
532   if (rank == 0) {
533     return (*this)(component.base());
534   } else if (symbol.has<semantics::ObjectEntityDetails>()) {
535     NamedEntity base{Component{component}};
536     return CreateShape(rank, base);
537   } else if (symbol.has<semantics::AssocEntityDetails>()) {
538     NamedEntity base{Component{component}};
539     return Result{CreateShape(rank, base)};
540   } else {
541     return (*this)(symbol);
542   }
543 }
544 
545 auto GetShapeHelper::operator()(const ArrayRef &arrayRef) const -> Result {
546   Shape shape;
547   int dimension{0};
548   const NamedEntity &base{arrayRef.base()};
549   for (const Subscript &ss : arrayRef.subscript()) {
550     if (ss.Rank() > 0) {
551       shape.emplace_back(GetExtent(ss, base, dimension));
552     }
553     ++dimension;
554   }
555   if (shape.empty()) {
556     if (const Component * component{base.UnwrapComponent()}) {
557       return (*this)(component->base());
558     }
559   }
560   return shape;
561 }
562 
563 auto GetShapeHelper::operator()(const CoarrayRef &coarrayRef) const -> Result {
564   NamedEntity base{coarrayRef.GetBase()};
565   if (coarrayRef.subscript().empty()) {
566     return (*this)(base);
567   } else {
568     Shape shape;
569     int dimension{0};
570     for (const Subscript &ss : coarrayRef.subscript()) {
571       if (ss.Rank() > 0) {
572         shape.emplace_back(GetExtent(ss, base, dimension));
573       }
574       ++dimension;
575     }
576     return shape;
577   }
578 }
579 
580 auto GetShapeHelper::operator()(const Substring &substring) const -> Result {
581   return (*this)(substring.parent());
582 }
583 
584 auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
585   if (call.Rank() == 0) {
586     return ScalarShape();
587   } else if (call.IsElemental()) {
588     for (const auto &arg : call.arguments()) {
589       if (arg && arg->Rank() > 0) {
590         return (*this)(*arg);
591       }
592     }
593     return ScalarShape();
594   } else if (const Symbol * symbol{call.proc().GetSymbol()}) {
595     return (*this)(*symbol);
596   } else if (const auto *intrinsic{call.proc().GetSpecificIntrinsic()}) {
597     if (intrinsic->name == "shape" || intrinsic->name == "lbound" ||
598         intrinsic->name == "ubound") {
599       // These are the array-valued cases for LBOUND and UBOUND (no DIM=).
600       const auto *expr{call.arguments().front().value().UnwrapExpr()};
601       CHECK(expr);
602       return Shape{MaybeExtentExpr{ExtentExpr{expr->Rank()}}};
603     } else if (intrinsic->name == "all" || intrinsic->name == "any" ||
604         intrinsic->name == "count" || intrinsic->name == "iall" ||
605         intrinsic->name == "iany" || intrinsic->name == "iparity" ||
606         intrinsic->name == "maxval" || intrinsic->name == "minval" ||
607         intrinsic->name == "norm2" || intrinsic->name == "parity" ||
608         intrinsic->name == "product" || intrinsic->name == "sum") {
609       // Reduction with DIM=
610       if (call.arguments().size() >= 2) {
611         auto arrayShape{
612             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
613         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
614         if (arrayShape && dimArg) {
615           if (auto dim{ToInt64(*dimArg)}) {
616             if (*dim >= 1 &&
617                 static_cast<std::size_t>(*dim) <= arrayShape->size()) {
618               arrayShape->erase(arrayShape->begin() + (*dim - 1));
619               return std::move(*arrayShape);
620             }
621           }
622         }
623       }
624     } else if (intrinsic->name == "maxloc" || intrinsic->name == "minloc") {
625       // TODO: FINDLOC
626       if (call.arguments().size() >= 2) {
627         if (auto arrayShape{
628                 (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))}) {
629           auto rank{static_cast<int>(arrayShape->size())};
630           if (const auto *dimArg{
631                   UnwrapExpr<Expr<SomeType>>(call.arguments()[1])}) {
632             auto dim{ToInt64(*dimArg)};
633             if (dim && *dim >= 1 && *dim <= rank) {
634               arrayShape->erase(arrayShape->begin() + (*dim - 1));
635               return std::move(*arrayShape);
636             }
637           } else {
638             // xxxLOC(no DIM=) result is vector(1:RANK(ARRAY=))
639             return Shape{ExtentExpr{rank}};
640           }
641         }
642       }
643     } else if (intrinsic->name == "cshift" || intrinsic->name == "eoshift") {
644       if (!call.arguments().empty()) {
645         return (*this)(call.arguments()[0]);
646       }
647     } else if (intrinsic->name == "matmul") {
648       if (call.arguments().size() == 2) {
649         if (auto ashape{(*this)(call.arguments()[0])}) {
650           if (auto bshape{(*this)(call.arguments()[1])}) {
651             if (ashape->size() == 1 && bshape->size() == 2) {
652               bshape->erase(bshape->begin());
653               return std::move(*bshape); // matmul(vector, matrix)
654             } else if (ashape->size() == 2 && bshape->size() == 1) {
655               ashape->pop_back();
656               return std::move(*ashape); // matmul(matrix, vector)
657             } else if (ashape->size() == 2 && bshape->size() == 2) {
658               (*ashape)[1] = std::move((*bshape)[1]);
659               return std::move(*ashape); // matmul(matrix, matrix)
660             }
661           }
662         }
663       }
664     } else if (intrinsic->name == "reshape") {
665       if (call.arguments().size() >= 2 && call.arguments().at(1)) {
666         // SHAPE(RESHAPE(array,shape)) -> shape
667         if (const auto *shapeExpr{
668                 call.arguments().at(1).value().UnwrapExpr()}) {
669           auto shape{std::get<Expr<SomeInteger>>(shapeExpr->u)};
670           return AsShape(ConvertToType<ExtentType>(std::move(shape)));
671         }
672       }
673     } else if (intrinsic->name == "pack") {
674       if (call.arguments().size() >= 3 && call.arguments().at(2)) {
675         // SHAPE(PACK(,,VECTOR=v)) -> SHAPE(v)
676         return (*this)(call.arguments().at(2));
677       } else if (call.arguments().size() >= 2 && context_) {
678         if (auto maskShape{(*this)(call.arguments().at(1))}) {
679           if (maskShape->size() == 0) {
680             // Scalar MASK= -> [MERGE(SIZE(ARRAY=), 0, mask)]
681             if (auto arrayShape{(*this)(call.arguments().at(0))}) {
682               auto arraySize{GetSize(std::move(*arrayShape))};
683               CHECK(arraySize);
684               ActualArguments toMerge{
685                   ActualArgument{AsGenericExpr(std::move(*arraySize))},
686                   ActualArgument{AsGenericExpr(ExtentExpr{0})},
687                   common::Clone(call.arguments().at(1))};
688               auto specific{context_->intrinsics().Probe(
689                   CallCharacteristics{"merge"}, toMerge, *context_)};
690               CHECK(specific);
691               return Shape{ExtentExpr{FunctionRef<ExtentType>{
692                   ProcedureDesignator{std::move(specific->specificIntrinsic)},
693                   std::move(specific->arguments)}}};
694             }
695           } else {
696             // Non-scalar MASK= -> [COUNT(mask)]
697             ActualArguments toCount{ActualArgument{common::Clone(
698                 DEREF(call.arguments().at(1).value().UnwrapExpr()))}};
699             auto specific{context_->intrinsics().Probe(
700                 CallCharacteristics{"count"}, toCount, *context_)};
701             CHECK(specific);
702             return Shape{ExtentExpr{FunctionRef<ExtentType>{
703                 ProcedureDesignator{std::move(specific->specificIntrinsic)},
704                 std::move(specific->arguments)}}};
705           }
706         }
707       }
708     } else if (intrinsic->name == "spread") {
709       // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
710       // at position DIM.
711       if (call.arguments().size() == 3) {
712         auto arrayShape{
713             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
714         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
715         const auto *nCopies{
716             UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))};
717         if (arrayShape && dimArg && nCopies) {
718           if (auto dim{ToInt64(*dimArg)}) {
719             if (*dim >= 1 &&
720                 static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
721               arrayShape->emplace(arrayShape->begin() + *dim - 1,
722                   ConvertToType<ExtentType>(common::Clone(*nCopies)));
723               return std::move(*arrayShape);
724             }
725           }
726         }
727       }
728     } else if (intrinsic->name == "transfer") {
729       if (call.arguments().size() == 3 && call.arguments().at(2)) {
730         // SIZE= is present; shape is vector [SIZE=]
731         if (const auto *size{
732                 UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))}) {
733           return Shape{
734               MaybeExtentExpr{ConvertToType<ExtentType>(common::Clone(*size))}};
735         }
736       } else if (context_) {
737         if (auto moldTypeAndShape{characteristics::TypeAndShape::Characterize(
738                 call.arguments().at(1), *context_)}) {
739           if (GetRank(moldTypeAndShape->shape()) == 0) {
740             // SIZE= is absent and MOLD= is scalar: result is scalar
741             return ScalarShape();
742           } else {
743             // SIZE= is absent and MOLD= is array: result is vector whose
744             // length is determined by sizes of types.  See 16.9.193p4 case(ii).
745             if (auto sourceTypeAndShape{
746                     characteristics::TypeAndShape::Characterize(
747                         call.arguments().at(0), *context_)}) {
748               auto sourceBytes{
749                   sourceTypeAndShape->MeasureSizeInBytes(*context_)};
750               auto moldElementBytes{
751                   moldTypeAndShape->MeasureElementSizeInBytes(*context_, true)};
752               if (sourceBytes && moldElementBytes) {
753                 ExtentExpr extent{Fold(*context_,
754                     (std::move(*sourceBytes) +
755                         common::Clone(*moldElementBytes) - ExtentExpr{1}) /
756                         common::Clone(*moldElementBytes))};
757                 return Shape{MaybeExtentExpr{std::move(extent)}};
758               }
759             }
760           }
761         }
762       }
763     } else if (intrinsic->name == "transpose") {
764       if (call.arguments().size() >= 1) {
765         if (auto shape{(*this)(call.arguments().at(0))}) {
766           if (shape->size() == 2) {
767             std::swap((*shape)[0], (*shape)[1]);
768             return shape;
769           }
770         }
771       }
772     } else if (intrinsic->name == "unpack") {
773       if (call.arguments().size() >= 2) {
774         return (*this)(call.arguments()[1]); // MASK=
775       }
776     } else if (intrinsic->characteristics.value().attrs.test(characteristics::
777                        Procedure::Attr::NullPointer)) { // NULL(MOLD=)
778       return (*this)(call.arguments());
779     } else {
780       // TODO: shapes of other non-elemental intrinsic results
781     }
782   }
783   return std::nullopt;
784 }
785 
786 // Check conformance of the passed shapes.
787 std::optional<bool> CheckConformance(parser::ContextualMessages &messages,
788     const Shape &left, const Shape &right, CheckConformanceFlags::Flags flags,
789     const char *leftIs, const char *rightIs) {
790   int n{GetRank(left)};
791   if (n == 0 && (flags & CheckConformanceFlags::LeftScalarExpandable)) {
792     return true;
793   }
794   int rn{GetRank(right)};
795   if (rn == 0 && (flags & CheckConformanceFlags::RightScalarExpandable)) {
796     return true;
797   }
798   if (n != rn) {
799     messages.Say("Rank of %1$s is %2$d, but %3$s has rank %4$d"_err_en_US,
800         leftIs, n, rightIs, rn);
801     return false;
802   }
803   for (int j{0}; j < n; ++j) {
804     if (auto leftDim{ToInt64(left[j])}) {
805       if (auto rightDim{ToInt64(right[j])}) {
806         if (*leftDim != *rightDim) {
807           messages.Say("Dimension %1$d of %2$s has extent %3$jd, "
808                        "but %4$s has extent %5$jd"_err_en_US,
809               j + 1, leftIs, *leftDim, rightIs, *rightDim);
810           return false;
811         }
812       } else if (!(flags & CheckConformanceFlags::RightIsDeferredShape)) {
813         return std::nullopt;
814       }
815     } else if (!(flags & CheckConformanceFlags::LeftIsDeferredShape)) {
816       return std::nullopt;
817     }
818   }
819   return true;
820 }
821 
822 bool IncrementSubscripts(
823     ConstantSubscripts &indices, const ConstantSubscripts &extents) {
824   std::size_t rank(indices.size());
825   CHECK(rank <= extents.size());
826   for (std::size_t j{0}; j < rank; ++j) {
827     if (extents[j] < 1) {
828       return false;
829     }
830   }
831   for (std::size_t j{0}; j < rank; ++j) {
832     if (indices[j]++ < extents[j]) {
833       return true;
834     }
835     indices[j] = 1;
836   }
837   return false;
838 }
839 
840 } // namespace Fortran::evaluate
841