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 &symbol0) {
26   const Symbol &symbol{ResolveAssociations(symbol0)};
27   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
28     if (symbol.attrs().test(semantics::Attr::PARAMETER) && details->init()) {
29       return details->shape().IsImpliedShape();
30     }
31   }
32   return false;
33 }
34 
35 bool IsExplicitShape(const Symbol &symbol0) {
36   const Symbol &symbol{ResolveAssociations(symbol0)};
37   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
38     const auto &shape{details->shape()};
39     return shape.Rank() == 0 || shape.IsExplicitShape(); // even if scalar
40   } else {
41     return false;
42   }
43 }
44 
45 Shape AsShape(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{extent}});
52   }
53   return result;
54 }
55 
56 std::optional<Shape> AsShape(FoldingContext &context, ExtentExpr &&arrayExpr) {
57   // Flatten any array expression into an array constructor if possible.
58   arrayExpr = Fold(context, std::move(arrayExpr));
59   if (const auto *constArray{UnwrapConstantValue<ExtentType>(arrayExpr)}) {
60     return AsShape(*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 std::optional<ExtentExpr> AsExtentArrayExpr(const Shape &shape) {
79   ArrayConstructorValues<ExtentType> values;
80   for (const auto &dim : shape) {
81     if (dim) {
82       values.Push(common::Clone(*dim));
83     } else {
84       return std::nullopt;
85     }
86   }
87   return ExtentExpr{ArrayConstructor<ExtentType>{std::move(values)}};
88 }
89 
90 std::optional<Constant<ExtentType>> AsConstantShape(
91     FoldingContext &context, const Shape &shape) {
92   if (auto shapeArray{AsExtentArrayExpr(shape)}) {
93     auto folded{Fold(context, std::move(*shapeArray))};
94     if (auto *p{UnwrapConstantValue<ExtentType>(folded)}) {
95       return std::move(*p);
96     }
97   }
98   return std::nullopt;
99 }
100 
101 Constant<SubscriptInteger> AsConstantShape(const ConstantSubscripts &shape) {
102   using IntType = Scalar<SubscriptInteger>;
103   std::vector<IntType> result;
104   for (auto dim : shape) {
105     result.emplace_back(dim);
106   }
107   return {std::move(result), ConstantSubscripts{GetRank(shape)}};
108 }
109 
110 ConstantSubscripts AsConstantExtents(const Constant<ExtentType> &shape) {
111   ConstantSubscripts result;
112   for (const auto &extent : shape.values()) {
113     result.push_back(extent.ToInt64());
114   }
115   return result;
116 }
117 
118 std::optional<ConstantSubscripts> AsConstantExtents(
119     FoldingContext &context, const Shape &shape) {
120   if (auto shapeConstant{AsConstantShape(context, shape)}) {
121     return AsConstantExtents(*shapeConstant);
122   } else {
123     return std::nullopt;
124   }
125 }
126 
127 static ExtentExpr ComputeTripCount(FoldingContext &context, ExtentExpr &&lower,
128     ExtentExpr &&upper, ExtentExpr &&stride) {
129   ExtentExpr strideCopy{common::Clone(stride)};
130   ExtentExpr span{
131       (std::move(upper) - std::move(lower) + std::move(strideCopy)) /
132       std::move(stride)};
133   ExtentExpr extent{
134       Extremum<ExtentType>{Ordering::Greater, std::move(span), ExtentExpr{0}}};
135   return Fold(context, std::move(extent));
136 }
137 
138 ExtentExpr CountTrips(FoldingContext &context, ExtentExpr &&lower,
139     ExtentExpr &&upper, ExtentExpr &&stride) {
140   return ComputeTripCount(
141       context, std::move(lower), std::move(upper), std::move(stride));
142 }
143 
144 ExtentExpr CountTrips(FoldingContext &context, const ExtentExpr &lower,
145     const ExtentExpr &upper, const ExtentExpr &stride) {
146   return ComputeTripCount(context, common::Clone(lower), common::Clone(upper),
147       common::Clone(stride));
148 }
149 
150 MaybeExtentExpr CountTrips(FoldingContext &context, MaybeExtentExpr &&lower,
151     MaybeExtentExpr &&upper, MaybeExtentExpr &&stride) {
152   std::function<ExtentExpr(ExtentExpr &&, ExtentExpr &&, ExtentExpr &&)> bound{
153       std::bind(ComputeTripCount, context, _1, _2, _3)};
154   return common::MapOptional(
155       std::move(bound), std::move(lower), std::move(upper), std::move(stride));
156 }
157 
158 MaybeExtentExpr GetSize(Shape &&shape) {
159   ExtentExpr extent{1};
160   for (auto &&dim : std::move(shape)) {
161     if (dim) {
162       extent = std::move(extent) * std::move(*dim);
163     } else {
164       return std::nullopt;
165     }
166   }
167   return extent;
168 }
169 
170 bool ContainsAnyImpliedDoIndex(const ExtentExpr &expr) {
171   struct MyVisitor : public AnyTraverse<MyVisitor> {
172     using Base = AnyTraverse<MyVisitor>;
173     MyVisitor() : Base{*this} {}
174     using Base::operator();
175     bool operator()(const ImpliedDoIndex &) { return true; }
176   };
177   return MyVisitor{}(expr);
178 }
179 
180 // Determines lower bound on a dimension.  This can be other than 1 only
181 // for a reference to a whole array object or component. (See LBOUND, 16.9.109).
182 // ASSOCIATE construct entities may require tranversal of their referents.
183 class GetLowerBoundHelper : public Traverse<GetLowerBoundHelper, ExtentExpr> {
184 public:
185   using Result = ExtentExpr;
186   using Base = Traverse<GetLowerBoundHelper, ExtentExpr>;
187   using Base::operator();
188   GetLowerBoundHelper(FoldingContext &c, int d)
189       : Base{*this}, context_{c}, dimension_{d} {}
190   static ExtentExpr Default() { return ExtentExpr{1}; }
191   static ExtentExpr Combine(Result &&, Result &&) { return Default(); }
192   ExtentExpr operator()(const Symbol &);
193   ExtentExpr operator()(const Component &);
194 
195 private:
196   FoldingContext &context_;
197   int dimension_;
198 };
199 
200 auto GetLowerBoundHelper::operator()(const Symbol &symbol0) -> Result {
201   const Symbol &symbol{symbol0.GetUltimate()};
202   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
203     int j{0};
204     for (const auto &shapeSpec : details->shape()) {
205       if (j++ == dimension_) {
206         if (const auto &bound{shapeSpec.lbound().GetExplicit()}) {
207           return Fold(context_, common::Clone(*bound));
208         } else if (semantics::IsDescriptor(symbol)) {
209           return ExtentExpr{DescriptorInquiry{NamedEntity{symbol0},
210               DescriptorInquiry::Field::LowerBound, dimension_}};
211         } else {
212           break;
213         }
214       }
215     }
216   } else if (const auto *assoc{
217                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
218     return (*this)(assoc->expr());
219   }
220   return Default();
221 }
222 
223 auto GetLowerBoundHelper::operator()(const Component &component) -> Result {
224   if (component.base().Rank() == 0) {
225     const Symbol &symbol{component.GetLastSymbol().GetUltimate()};
226     if (const auto *details{
227             symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
228       int j{0};
229       for (const auto &shapeSpec : details->shape()) {
230         if (j++ == dimension_) {
231           if (const auto &bound{shapeSpec.lbound().GetExplicit()}) {
232             return Fold(context_, common::Clone(*bound));
233           } else if (semantics::IsDescriptor(symbol)) {
234             return ExtentExpr{
235                 DescriptorInquiry{NamedEntity{common::Clone(component)},
236                     DescriptorInquiry::Field::LowerBound, dimension_}};
237           } else {
238             break;
239           }
240         }
241       }
242     }
243   }
244   return Default();
245 }
246 
247 ExtentExpr GetLowerBound(
248     FoldingContext &context, const NamedEntity &base, int dimension) {
249   return GetLowerBoundHelper{context, dimension}(base);
250 }
251 
252 Shape GetLowerBounds(FoldingContext &context, const NamedEntity &base) {
253   Shape result;
254   int rank{base.Rank()};
255   for (int dim{0}; dim < rank; ++dim) {
256     result.emplace_back(GetLowerBound(context, base, dim));
257   }
258   return result;
259 }
260 
261 MaybeExtentExpr GetExtent(
262     FoldingContext &context, const NamedEntity &base, int dimension) {
263   CHECK(dimension >= 0);
264   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
265   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
266     if (IsImpliedShape(symbol)) {
267       Shape shape{GetShape(context, symbol).value()};
268       return std::move(shape.at(dimension));
269     }
270     int j{0};
271     for (const auto &shapeSpec : details->shape()) {
272       if (j++ == dimension) {
273         if (shapeSpec.ubound().isExplicit()) {
274           if (const auto &ubound{shapeSpec.ubound().GetExplicit()}) {
275             if (const auto &lbound{shapeSpec.lbound().GetExplicit()}) {
276               return Fold(context,
277                   common::Clone(ubound.value()) -
278                       common::Clone(lbound.value()) + ExtentExpr{1});
279             } else {
280               return Fold(context, common::Clone(ubound.value()));
281             }
282           }
283         } else if (details->IsAssumedSize() && j == symbol.Rank()) {
284           return std::nullopt;
285         } else if (semantics::IsDescriptor(symbol)) {
286           return ExtentExpr{DescriptorInquiry{
287               NamedEntity{base}, DescriptorInquiry::Field::Extent, dimension}};
288         }
289       }
290     }
291   } else if (const auto *assoc{
292                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
293     if (auto shape{GetShape(context, assoc->expr())}) {
294       if (dimension < static_cast<int>(shape->size())) {
295         return std::move(shape->at(dimension));
296       }
297     }
298   }
299   return std::nullopt;
300 }
301 
302 MaybeExtentExpr GetExtent(FoldingContext &context, const Subscript &subscript,
303     const NamedEntity &base, int dimension) {
304   return std::visit(
305       common::visitors{
306           [&](const Triplet &triplet) -> MaybeExtentExpr {
307             MaybeExtentExpr upper{triplet.upper()};
308             if (!upper) {
309               upper = GetUpperBound(context, base, dimension);
310             }
311             MaybeExtentExpr lower{triplet.lower()};
312             if (!lower) {
313               lower = GetLowerBound(context, base, dimension);
314             }
315             return CountTrips(context, std::move(lower), std::move(upper),
316                 MaybeExtentExpr{triplet.stride()});
317           },
318           [&](const IndirectSubscriptIntegerExpr &subs) -> MaybeExtentExpr {
319             if (auto shape{GetShape(context, subs.value())}) {
320               if (GetRank(*shape) > 0) {
321                 CHECK(GetRank(*shape) == 1); // vector-valued subscript
322                 return std::move(shape->at(0));
323               }
324             }
325             return std::nullopt;
326           },
327       },
328       subscript.u);
329 }
330 
331 MaybeExtentExpr ComputeUpperBound(
332     FoldingContext &context, ExtentExpr &&lower, MaybeExtentExpr &&extent) {
333   if (extent) {
334     return Fold(context, std::move(*extent) - std::move(lower) + ExtentExpr{1});
335   } else {
336     return std::nullopt;
337   }
338 }
339 
340 MaybeExtentExpr GetUpperBound(
341     FoldingContext &context, const NamedEntity &base, int dimension) {
342   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
343   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
344     int j{0};
345     for (const auto &shapeSpec : details->shape()) {
346       if (j++ == dimension) {
347         if (const auto &bound{shapeSpec.ubound().GetExplicit()}) {
348           return Fold(context, common::Clone(*bound));
349         } else if (details->IsAssumedSize() && dimension + 1 == symbol.Rank()) {
350           break;
351         } else {
352           return ComputeUpperBound(context,
353               GetLowerBound(context, base, dimension),
354               GetExtent(context, base, dimension));
355         }
356       }
357     }
358   } else if (const auto *assoc{
359                  symbol.detailsIf<semantics::AssocEntityDetails>()}) {
360     if (auto shape{GetShape(context, assoc->expr())}) {
361       if (dimension < static_cast<int>(shape->size())) {
362         return ComputeUpperBound(context,
363             GetLowerBound(context, base, dimension),
364             std::move(shape->at(dimension)));
365       }
366     }
367   }
368   return std::nullopt;
369 }
370 
371 Shape GetUpperBounds(FoldingContext &context, const NamedEntity &base) {
372   const Symbol &symbol{ResolveAssociations(base.GetLastSymbol())};
373   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
374     Shape result;
375     int dim{0};
376     for (const auto &shapeSpec : details->shape()) {
377       if (const auto &bound{shapeSpec.ubound().GetExplicit()}) {
378         result.emplace_back(Fold(context, common::Clone(*bound)));
379       } else if (details->IsAssumedSize()) {
380         CHECK(dim + 1 == base.Rank());
381         result.emplace_back(std::nullopt); // UBOUND folding replaces with -1
382       } else {
383         result.emplace_back(ComputeUpperBound(context,
384             GetLowerBound(context, base, dim), GetExtent(context, base, dim)));
385       }
386       ++dim;
387     }
388     CHECK(GetRank(result) == symbol.Rank());
389     return result;
390   } else {
391     return std::move(GetShape(context, base).value());
392   }
393 }
394 
395 auto GetShapeHelper::operator()(const Symbol &symbol) const -> Result {
396   return std::visit(
397       common::visitors{
398           [&](const semantics::ObjectEntityDetails &object) {
399             if (IsImpliedShape(symbol)) {
400               return (*this)(object.init());
401             } else {
402               int n{object.shape().Rank()};
403               NamedEntity base{symbol};
404               return Result{CreateShape(n, base)};
405             }
406           },
407           [](const semantics::EntityDetails &) {
408             return Scalar(); // no dimensions seen
409           },
410           [&](const semantics::ProcEntityDetails &proc) {
411             if (const Symbol * interface{proc.interface().symbol()}) {
412               return (*this)(*interface);
413             } else {
414               return Scalar();
415             }
416           },
417           [&](const semantics::AssocEntityDetails &assoc) {
418             if (!assoc.rank()) {
419               return (*this)(assoc.expr());
420             } else {
421               int n{assoc.rank().value()};
422               NamedEntity base{symbol};
423               return Result{CreateShape(n, base)};
424             }
425           },
426           [&](const semantics::SubprogramDetails &subp) {
427             if (subp.isFunction()) {
428               return (*this)(subp.result());
429             } else {
430               return Result{};
431             }
432           },
433           [&](const semantics::ProcBindingDetails &binding) {
434             return (*this)(binding.symbol());
435           },
436           [&](const semantics::UseDetails &use) {
437             return (*this)(use.symbol());
438           },
439           [&](const semantics::HostAssocDetails &assoc) {
440             return (*this)(assoc.symbol());
441           },
442           [](const auto &) { return Result{}; },
443       },
444       symbol.details());
445 }
446 
447 auto GetShapeHelper::operator()(const Component &component) const -> Result {
448   const Symbol &symbol{component.GetLastSymbol()};
449   int rank{symbol.Rank()};
450   if (rank == 0) {
451     return (*this)(component.base());
452   } else if (symbol.has<semantics::ObjectEntityDetails>()) {
453     NamedEntity base{Component{component}};
454     return CreateShape(rank, base);
455   } else if (symbol.has<semantics::AssocEntityDetails>()) {
456     NamedEntity base{Component{component}};
457     return Result{CreateShape(rank, base)};
458   } else {
459     return (*this)(symbol);
460   }
461 }
462 
463 auto GetShapeHelper::operator()(const ArrayRef &arrayRef) const -> Result {
464   Shape shape;
465   int dimension{0};
466   const NamedEntity &base{arrayRef.base()};
467   for (const Subscript &ss : arrayRef.subscript()) {
468     if (ss.Rank() > 0) {
469       shape.emplace_back(GetExtent(context_, ss, base, dimension));
470     }
471     ++dimension;
472   }
473   if (shape.empty()) {
474     if (const Component * component{base.UnwrapComponent()}) {
475       return (*this)(component->base());
476     }
477   }
478   return shape;
479 }
480 
481 auto GetShapeHelper::operator()(const CoarrayRef &coarrayRef) const -> Result {
482   NamedEntity base{coarrayRef.GetBase()};
483   if (coarrayRef.subscript().empty()) {
484     return (*this)(base);
485   } else {
486     Shape shape;
487     int dimension{0};
488     for (const Subscript &ss : coarrayRef.subscript()) {
489       if (ss.Rank() > 0) {
490         shape.emplace_back(GetExtent(context_, ss, base, dimension));
491       }
492       ++dimension;
493     }
494     return shape;
495   }
496 }
497 
498 auto GetShapeHelper::operator()(const Substring &substring) const -> Result {
499   return (*this)(substring.parent());
500 }
501 
502 auto GetShapeHelper::operator()(const ProcedureRef &call) const -> Result {
503   if (call.Rank() == 0) {
504     return Scalar();
505   } else if (call.IsElemental()) {
506     for (const auto &arg : call.arguments()) {
507       if (arg && arg->Rank() > 0) {
508         return (*this)(*arg);
509       }
510     }
511     return Scalar();
512   } else if (const Symbol * symbol{call.proc().GetSymbol()}) {
513     return (*this)(*symbol);
514   } else if (const auto *intrinsic{call.proc().GetSpecificIntrinsic()}) {
515     if (intrinsic->name == "shape" || intrinsic->name == "lbound" ||
516         intrinsic->name == "ubound") {
517       // These are the array-valued cases for LBOUND and UBOUND (no DIM=).
518       const auto *expr{call.arguments().front().value().UnwrapExpr()};
519       CHECK(expr);
520       return Shape{MaybeExtentExpr{ExtentExpr{expr->Rank()}}};
521     } else if (intrinsic->name == "all" || intrinsic->name == "any" ||
522         intrinsic->name == "count" || intrinsic->name == "iall" ||
523         intrinsic->name == "iany" || intrinsic->name == "iparity" ||
524         intrinsic->name == "maxloc" || intrinsic->name == "maxval" ||
525         intrinsic->name == "minloc" || intrinsic->name == "minval" ||
526         intrinsic->name == "norm2" || intrinsic->name == "parity" ||
527         intrinsic->name == "product" || intrinsic->name == "sum") {
528       // Reduction with DIM=
529       if (call.arguments().size() >= 2) {
530         auto arrayShape{
531             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
532         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
533         if (arrayShape && dimArg) {
534           if (auto dim{ToInt64(*dimArg)}) {
535             if (*dim >= 1 &&
536                 static_cast<std::size_t>(*dim) <= arrayShape->size()) {
537               arrayShape->erase(arrayShape->begin() + (*dim - 1));
538               return std::move(*arrayShape);
539             }
540           }
541         }
542       }
543     } else if (intrinsic->name == "cshift" || intrinsic->name == "eoshift") {
544       if (!call.arguments().empty()) {
545         return (*this)(call.arguments()[0]);
546       }
547     } else if (intrinsic->name == "reshape") {
548       if (call.arguments().size() >= 2 && call.arguments().at(1)) {
549         // SHAPE(RESHAPE(array,shape)) -> shape
550         if (const auto *shapeExpr{
551                 call.arguments().at(1).value().UnwrapExpr()}) {
552           auto shape{std::get<Expr<SomeInteger>>(shapeExpr->u)};
553           return AsShape(context_, ConvertToType<ExtentType>(std::move(shape)));
554         }
555       }
556     } else if (intrinsic->name == "pack") {
557       if (call.arguments().size() >= 3 && call.arguments().at(2)) {
558         // SHAPE(PACK(,,VECTOR=v)) -> SHAPE(v)
559         return (*this)(call.arguments().at(2));
560       } else if (call.arguments().size() >= 2) {
561         if (auto maskShape{(*this)(call.arguments().at(1))}) {
562           if (maskShape->size() == 0) {
563             // Scalar MASK= -> [MERGE(SIZE(ARRAY=), 0, mask)]
564             if (auto arrayShape{(*this)(call.arguments().at(0))}) {
565               auto arraySize{GetSize(std::move(*arrayShape))};
566               CHECK(arraySize);
567               ActualArguments toMerge{
568                   ActualArgument{AsGenericExpr(std::move(*arraySize))},
569                   ActualArgument{AsGenericExpr(ExtentExpr{0})},
570                   common::Clone(call.arguments().at(1))};
571               auto specific{context_.intrinsics().Probe(
572                   CallCharacteristics{"merge"}, toMerge, context_)};
573               CHECK(specific);
574               return Shape{ExtentExpr{FunctionRef<ExtentType>{
575                   ProcedureDesignator{std::move(specific->specificIntrinsic)},
576                   std::move(specific->arguments)}}};
577             }
578           } else {
579             // Non-scalar MASK= -> [COUNT(mask)]
580             ActualArguments toCount{ActualArgument{common::Clone(
581                 DEREF(call.arguments().at(1).value().UnwrapExpr()))}};
582             auto specific{context_.intrinsics().Probe(
583                 CallCharacteristics{"count"}, toCount, context_)};
584             CHECK(specific);
585             return Shape{ExtentExpr{FunctionRef<ExtentType>{
586                 ProcedureDesignator{std::move(specific->specificIntrinsic)},
587                 std::move(specific->arguments)}}};
588           }
589         }
590       }
591     } else if (intrinsic->name == "spread") {
592       // SHAPE(SPREAD(ARRAY,DIM,NCOPIES)) = SHAPE(ARRAY) with NCOPIES inserted
593       // at position DIM.
594       if (call.arguments().size() == 3) {
595         auto arrayShape{
596             (*this)(UnwrapExpr<Expr<SomeType>>(call.arguments().at(0)))};
597         const auto *dimArg{UnwrapExpr<Expr<SomeType>>(call.arguments().at(1))};
598         const auto *nCopies{
599             UnwrapExpr<Expr<SomeInteger>>(call.arguments().at(2))};
600         if (arrayShape && dimArg && nCopies) {
601           if (auto dim{ToInt64(*dimArg)}) {
602             if (*dim >= 1 &&
603                 static_cast<std::size_t>(*dim) <= arrayShape->size() + 1) {
604               arrayShape->emplace(arrayShape->begin() + *dim - 1,
605                   ConvertToType<ExtentType>(common::Clone(*nCopies)));
606               return std::move(*arrayShape);
607             }
608           }
609         }
610       }
611     } else if (intrinsic->name == "transpose") {
612       if (call.arguments().size() >= 1) {
613         if (auto shape{(*this)(call.arguments().at(0))}) {
614           if (shape->size() == 2) {
615             std::swap((*shape)[0], (*shape)[1]);
616             return shape;
617           }
618         }
619       }
620     } else if (intrinsic->characteristics.value().attrs.test(characteristics::
621                        Procedure::Attr::NullPointer)) { // NULL(MOLD=)
622       return (*this)(call.arguments());
623     } else {
624       // TODO: shapes of other non-elemental intrinsic results
625     }
626   }
627   return std::nullopt;
628 }
629 
630 bool CheckConformance(parser::ContextualMessages &messages, const Shape &left,
631     const Shape &right, const char *leftIs, const char *rightIs) {
632   if (!left.empty() && !right.empty()) {
633     int n{GetRank(left)};
634     int rn{GetRank(right)};
635     if (n != rn) {
636       messages.Say("Rank of %1$s is %2$d, but %3$s has rank %4$d"_err_en_US,
637           leftIs, n, rightIs, rn);
638       return false;
639     } else {
640       for (int j{0}; j < n; ++j) {
641         if (auto leftDim{ToInt64(left[j])}) {
642           if (auto rightDim{ToInt64(right[j])}) {
643             if (*leftDim != *rightDim) {
644               messages.Say("Dimension %1$d of %2$s has extent %3$jd, "
645                            "but %4$s has extent %5$jd"_err_en_US,
646                   j + 1, leftIs, *leftDim, rightIs, *rightDim);
647               return false;
648             }
649           }
650         }
651       }
652     }
653   }
654   return true;
655 }
656 } // namespace Fortran::evaluate
657