xref: /llvm-project/flang/lib/Semantics/pointer-assignment.cpp (revision d5285fef00f6c5a725a515118192dd117fc3c665)
1 //===-- lib/Semantics/pointer-assignment.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 "pointer-assignment.h"
10 #include "definable.h"
11 #include "flang/Common/idioms.h"
12 #include "flang/Common/restorer.h"
13 #include "flang/Common/template.h"
14 #include "flang/Evaluate/characteristics.h"
15 #include "flang/Evaluate/expression.h"
16 #include "flang/Evaluate/fold.h"
17 #include "flang/Evaluate/tools.h"
18 #include "flang/Parser/message.h"
19 #include "flang/Parser/parse-tree-visitor.h"
20 #include "flang/Parser/parse-tree.h"
21 #include "flang/Semantics/expression.h"
22 #include "flang/Semantics/symbol.h"
23 #include "flang/Semantics/tools.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <optional>
26 #include <set>
27 #include <string>
28 #include <type_traits>
29 
30 // Semantic checks for pointer assignment.
31 
32 namespace Fortran::semantics {
33 
34 using namespace parser::literals;
35 using evaluate::characteristics::DummyDataObject;
36 using evaluate::characteristics::FunctionResult;
37 using evaluate::characteristics::Procedure;
38 using evaluate::characteristics::TypeAndShape;
39 using parser::MessageFixedText;
40 using parser::MessageFormattedText;
41 
42 class PointerAssignmentChecker {
43 public:
44   PointerAssignmentChecker(SemanticsContext &context, const Scope &scope,
45       parser::CharBlock source, const std::string &description)
46       : context_{context}, scope_{scope}, source_{source}, description_{
47                                                                description} {}
48   PointerAssignmentChecker(
49       SemanticsContext &context, const Scope &scope, const Symbol &lhs)
50       : context_{context}, scope_{scope}, source_{lhs.name()},
51         description_{"pointer '"s + lhs.name().ToString() + '\''}, lhs_{&lhs} {
52     set_lhsType(TypeAndShape::Characterize(lhs, foldingContext_));
53     set_isContiguous(lhs.attrs().test(Attr::CONTIGUOUS));
54     set_isVolatile(lhs.attrs().test(Attr::VOLATILE));
55   }
56   PointerAssignmentChecker &set_lhsType(std::optional<TypeAndShape> &&);
57   PointerAssignmentChecker &set_isContiguous(bool);
58   PointerAssignmentChecker &set_isVolatile(bool);
59   PointerAssignmentChecker &set_isBoundsRemapping(bool);
60   PointerAssignmentChecker &set_isAssumedRank(bool);
61   PointerAssignmentChecker &set_pointerComponentLHS(const Symbol *);
62   bool CheckLeftHandSide(const SomeExpr &);
63   bool Check(const SomeExpr &);
64 
65 private:
66   bool CharacterizeProcedure();
67   template <typename T> bool Check(const T &);
68   template <typename T> bool Check(const evaluate::Expr<T> &);
69   template <typename T> bool Check(const evaluate::FunctionRef<T> &);
70   template <typename T> bool Check(const evaluate::Designator<T> &);
71   bool Check(const evaluate::NullPointer &);
72   bool Check(const evaluate::ProcedureDesignator &);
73   bool Check(const evaluate::ProcedureRef &);
74   // Target is a procedure
75   bool Check(parser::CharBlock rhsName, bool isCall,
76       const Procedure * = nullptr,
77       const evaluate::SpecificIntrinsic *specific = nullptr);
78   bool LhsOkForUnlimitedPoly() const;
79   template <typename... A> parser::Message *Say(A &&...);
80 
81   SemanticsContext &context_;
82   evaluate::FoldingContext &foldingContext_{context_.foldingContext()};
83   const Scope &scope_;
84   const parser::CharBlock source_;
85   const std::string description_;
86   const Symbol *lhs_{nullptr};
87   std::optional<TypeAndShape> lhsType_;
88   std::optional<Procedure> procedure_;
89   bool characterizedProcedure_{false};
90   bool isContiguous_{false};
91   bool isVolatile_{false};
92   bool isBoundsRemapping_{false};
93   bool isAssumedRank_{false};
94   const Symbol *pointerComponentLHS_{nullptr};
95 };
96 
97 PointerAssignmentChecker &PointerAssignmentChecker::set_lhsType(
98     std::optional<TypeAndShape> &&lhsType) {
99   lhsType_ = std::move(lhsType);
100   return *this;
101 }
102 
103 PointerAssignmentChecker &PointerAssignmentChecker::set_isContiguous(
104     bool isContiguous) {
105   isContiguous_ = isContiguous;
106   return *this;
107 }
108 
109 PointerAssignmentChecker &PointerAssignmentChecker::set_isVolatile(
110     bool isVolatile) {
111   isVolatile_ = isVolatile;
112   return *this;
113 }
114 
115 PointerAssignmentChecker &PointerAssignmentChecker::set_isBoundsRemapping(
116     bool isBoundsRemapping) {
117   isBoundsRemapping_ = isBoundsRemapping;
118   return *this;
119 }
120 
121 PointerAssignmentChecker &PointerAssignmentChecker::set_isAssumedRank(
122     bool isAssumedRank) {
123   isAssumedRank_ = isAssumedRank;
124   return *this;
125 }
126 
127 PointerAssignmentChecker &PointerAssignmentChecker::set_pointerComponentLHS(
128     const Symbol *symbol) {
129   pointerComponentLHS_ = symbol;
130   return *this;
131 }
132 
133 bool PointerAssignmentChecker::CharacterizeProcedure() {
134   if (!characterizedProcedure_) {
135     characterizedProcedure_ = true;
136     if (lhs_ && IsProcedure(*lhs_)) {
137       procedure_ = Procedure::Characterize(*lhs_, foldingContext_);
138     }
139   }
140   return procedure_.has_value();
141 }
142 
143 bool PointerAssignmentChecker::CheckLeftHandSide(const SomeExpr &lhs) {
144   if (auto whyNot{WhyNotDefinable(foldingContext_.messages().at(), scope_,
145           DefinabilityFlags{DefinabilityFlag::PointerDefinition}, lhs)}) {
146     if (auto *msg{Say(
147             "The left-hand side of a pointer assignment is not definable"_err_en_US)}) {
148       msg->Attach(std::move(whyNot->set_severity(parser::Severity::Because)));
149     }
150     return false;
151   } else if (evaluate::IsAssumedRank(lhs)) {
152     Say("The left-hand side of a pointer assignment must not be an assumed-rank dummy argument"_err_en_US);
153     return false;
154   } else {
155     return true;
156   }
157 }
158 
159 template <typename T> bool PointerAssignmentChecker::Check(const T &) {
160   // Catch-all case for really bad target expression
161   Say("Target associated with %s must be a designator or a call to a"
162       " pointer-valued function"_err_en_US,
163       description_);
164   return false;
165 }
166 
167 template <typename T>
168 bool PointerAssignmentChecker::Check(const evaluate::Expr<T> &x) {
169   return common::visit([&](const auto &x) { return Check(x); }, x.u);
170 }
171 
172 bool PointerAssignmentChecker::Check(const SomeExpr &rhs) {
173   if (HasVectorSubscript(rhs)) { // C1025
174     Say("An array section with a vector subscript may not be a pointer target"_err_en_US);
175     return false;
176   }
177   if (ExtractCoarrayRef(rhs)) { // C1026
178     Say("A coindexed object may not be a pointer target"_err_en_US);
179     return false;
180   }
181   if (!common::visit([&](const auto &x) { return Check(x); }, rhs.u)) {
182     return false;
183   }
184   if (IsNullPointer(rhs)) {
185     return true;
186   }
187   if (lhs_ && IsProcedure(*lhs_)) {
188     return true;
189   }
190   if (const auto *pureProc{FindPureProcedureContaining(scope_)}) {
191     if (pointerComponentLHS_) { // C1594(4) is a hard error
192       if (const Symbol * object{FindExternallyVisibleObject(rhs, *pureProc)}) {
193         if (auto *msg{Say(
194                 "Externally visible object '%s' may not be associated with pointer component '%s' in a pure procedure"_err_en_US,
195                 object->name(), pointerComponentLHS_->name())}) {
196           msg->Attach(object->name(), "Object declaration"_en_US)
197               .Attach(
198                   pointerComponentLHS_->name(), "Pointer declaration"_en_US);
199         }
200         return false;
201       }
202     } else if (const Symbol * base{GetFirstSymbol(rhs)}) {
203       if (const char *why{WhyBaseObjectIsSuspicious(
204               base->GetUltimate(), scope_)}) { // C1594(3)
205         evaluate::SayWithDeclaration(foldingContext_.messages(), *base,
206             "A pure subprogram may not use '%s' as the target of pointer assignment because it is %s"_err_en_US,
207             base->name(), why);
208         return false;
209       }
210     }
211   }
212   if (isContiguous_) {
213     if (auto contiguous{evaluate::IsContiguous(rhs, foldingContext_)}) {
214       if (!*contiguous) {
215         Say("CONTIGUOUS pointer may not be associated with a discontiguous target"_err_en_US);
216         return false;
217       }
218     } else if (context_.ShouldWarn(
219                    common::UsageWarning::PointerToPossibleNoncontiguous)) {
220       Say("Target of CONTIGUOUS pointer association is not known to be contiguous"_warn_en_US);
221     }
222   }
223   // Warn about undefinable data targets
224   if (context_.ShouldWarn(common::UsageWarning::PointerToUndefinable)) {
225     if (auto because{WhyNotDefinable(
226             foldingContext_.messages().at(), scope_, {}, rhs)}) {
227       if (auto *msg{
228               Say("Pointer target is not a definable variable"_warn_en_US)}) {
229         msg->Attach(
230             std::move(because->set_severity(parser::Severity::Because)));
231       }
232       return false;
233     }
234   }
235   return true;
236 }
237 
238 bool PointerAssignmentChecker::Check(const evaluate::NullPointer &) {
239   return true; // P => NULL() without MOLD=; always OK
240 }
241 
242 template <typename T>
243 bool PointerAssignmentChecker::Check(const evaluate::FunctionRef<T> &f) {
244   std::string funcName;
245   const auto *symbol{f.proc().GetSymbol()};
246   if (symbol) {
247     funcName = symbol->name().ToString();
248   } else if (const auto *intrinsic{f.proc().GetSpecificIntrinsic()}) {
249     funcName = intrinsic->name;
250   }
251   auto proc{
252       Procedure::Characterize(f.proc(), foldingContext_, /*emitError=*/true)};
253   if (!proc) {
254     return false;
255   }
256   std::optional<MessageFixedText> msg;
257   const auto &funcResult{proc->functionResult}; // C1025
258   if (!funcResult) {
259     msg = "%s is associated with the non-existent result of reference to"
260           " procedure"_err_en_US;
261   } else if (CharacterizeProcedure()) {
262     // Shouldn't be here in this function unless lhs is an object pointer.
263     msg = "Procedure %s is associated with the result of a reference to"
264           " function '%s' that does not return a procedure pointer"_err_en_US;
265   } else if (funcResult->IsProcedurePointer()) {
266     msg = "Object %s is associated with the result of a reference to"
267           " function '%s' that is a procedure pointer"_err_en_US;
268   } else if (!funcResult->attrs.test(FunctionResult::Attr::Pointer)) {
269     msg = "%s is associated with the result of a reference to function '%s'"
270           " that is a not a pointer"_err_en_US;
271   } else if (isContiguous_ &&
272       !funcResult->attrs.test(FunctionResult::Attr::Contiguous)) {
273     if (context_.ShouldWarn(
274             common::UsageWarning::PointerToPossibleNoncontiguous)) {
275       msg =
276           "CONTIGUOUS %s is associated with the result of reference to function '%s' that is not known to be contiguous"_warn_en_US;
277     }
278   } else if (lhsType_) {
279     const auto *frTypeAndShape{funcResult->GetTypeAndShape()};
280     CHECK(frTypeAndShape);
281     if (!lhsType_->IsCompatibleWith(foldingContext_.messages(), *frTypeAndShape,
282             "pointer", "function result",
283             /*omitShapeConformanceCheck=*/isBoundsRemapping_ || isAssumedRank_,
284             evaluate::CheckConformanceFlags::BothDeferredShape)) {
285       return false; // IsCompatibleWith() emitted message
286     }
287   }
288   if (msg) {
289     auto restorer{common::ScopedSet(lhs_, symbol)};
290     Say(*msg, description_, funcName);
291     return false;
292   }
293   return true;
294 }
295 
296 template <typename T>
297 bool PointerAssignmentChecker::Check(const evaluate::Designator<T> &d) {
298   const Symbol *last{d.GetLastSymbol()};
299   const Symbol *base{d.GetBaseObject().symbol()};
300   if (!last || !base) {
301     // P => "character literal"(1:3)
302     Say("Pointer target is not a named entity"_err_en_US);
303     return false;
304   }
305   std::optional<std::variant<MessageFixedText, MessageFormattedText>> msg;
306   if (CharacterizeProcedure()) {
307     // Shouldn't be here in this function unless lhs is an object pointer.
308     msg = "In assignment to procedure %s, the target is not a procedure or"
309           " procedure pointer"_err_en_US;
310   } else if (!evaluate::GetLastTarget(GetSymbolVector(d))) { // C1025
311     msg = "In assignment to object %s, the target '%s' is not an object with"
312           " POINTER or TARGET attributes"_err_en_US;
313   } else if (auto rhsType{TypeAndShape::Characterize(d, foldingContext_)}) {
314     if (!lhsType_) {
315       msg = "%s associated with object '%s' with incompatible type or"
316             " shape"_err_en_US;
317     } else if (rhsType->corank() > 0 &&
318         (isVolatile_ != last->attrs().test(Attr::VOLATILE))) { // C1020
319       // TODO: what if A is VOLATILE in A%B%C?  need a better test here
320       if (isVolatile_) {
321         msg = "Pointer may not be VOLATILE when target is a"
322               " non-VOLATILE coarray"_err_en_US;
323       } else {
324         msg = "Pointer must be VOLATILE when target is a"
325               " VOLATILE coarray"_err_en_US;
326       }
327     } else if (rhsType->type().IsUnlimitedPolymorphic()) {
328       if (!LhsOkForUnlimitedPoly()) {
329         msg = "Pointer type must be unlimited polymorphic or non-extensible"
330               " derived type when target is unlimited polymorphic"_err_en_US;
331       }
332     } else {
333       if (!lhsType_->type().IsTkLenCompatibleWith(rhsType->type())) {
334         msg = MessageFormattedText{
335             "Target type %s is not compatible with pointer type %s"_err_en_US,
336             rhsType->type().AsFortran(), lhsType_->type().AsFortran()};
337 
338       } else if (!isBoundsRemapping_ &&
339           !lhsType_->attrs().test(TypeAndShape::Attr::AssumedRank)) {
340         int lhsRank{lhsType_->Rank()};
341         int rhsRank{rhsType->Rank()};
342         if (lhsRank != rhsRank) {
343           msg = MessageFormattedText{
344               "Pointer has rank %d but target has rank %d"_err_en_US, lhsRank,
345               rhsRank};
346         }
347       }
348     }
349   }
350   if (msg) {
351     auto restorer{common::ScopedSet(lhs_, last)};
352     if (auto *m{std::get_if<MessageFixedText>(&*msg)}) {
353       std::string buf;
354       llvm::raw_string_ostream ss{buf};
355       d.AsFortran(ss);
356       Say(*m, description_, ss.str());
357     } else {
358       Say(std::get<MessageFormattedText>(*msg));
359     }
360     return false;
361   }
362   return true;
363 }
364 
365 // Common handling for procedure pointer right-hand sides
366 bool PointerAssignmentChecker::Check(parser::CharBlock rhsName, bool isCall,
367     const Procedure *rhsProcedure,
368     const evaluate::SpecificIntrinsic *specific) {
369   std::string whyNot;
370   std::optional<std::string> warning;
371   CharacterizeProcedure();
372   if (std::optional<MessageFixedText> msg{evaluate::CheckProcCompatibility(
373           isCall, procedure_, rhsProcedure, specific, whyNot, warning,
374           /*ignoreImplicitVsExplicit=*/isCall)}) {
375     Say(std::move(*msg), description_, rhsName, whyNot);
376     return false;
377   }
378   if (context_.ShouldWarn(common::UsageWarning::ProcDummyArgShapes) &&
379       warning) {
380     Say("%s and %s may not be completely compatible procedures: %s"_warn_en_US,
381         description_, rhsName, std::move(*warning));
382   }
383   return true;
384 }
385 
386 bool PointerAssignmentChecker::Check(const evaluate::ProcedureDesignator &d) {
387   const Symbol *symbol{d.GetSymbol()};
388   if (symbol) {
389     if (const auto *subp{
390             symbol->GetUltimate().detailsIf<SubprogramDetails>()}) {
391       if (subp->stmtFunction()) {
392         evaluate::SayWithDeclaration(foldingContext_.messages(), *symbol,
393             "Statement function '%s' may not be the target of a pointer assignment"_err_en_US,
394             symbol->name());
395         return false;
396       }
397     } else if (symbol->has<ProcBindingDetails>() &&
398         context_.ShouldWarn(common::LanguageFeature::BindingAsProcedure)) {
399       evaluate::SayWithDeclaration(foldingContext_.messages(), *symbol,
400           "Procedure binding '%s' used as target of a pointer assignment"_port_en_US,
401           symbol->name());
402     }
403   }
404   if (auto chars{
405           Procedure::Characterize(d, foldingContext_, /*emitError=*/true)}) {
406     // Disregard the elemental attribute of RHS intrinsics.
407     if (symbol && symbol->GetUltimate().attrs().test(Attr::INTRINSIC)) {
408       chars->attrs.reset(Procedure::Attr::Elemental);
409     }
410     return Check(d.GetName(), false, &*chars, d.GetSpecificIntrinsic());
411   } else {
412     return Check(d.GetName(), false);
413   }
414 }
415 
416 bool PointerAssignmentChecker::Check(const evaluate::ProcedureRef &ref) {
417   auto chars{Procedure::Characterize(ref, foldingContext_)};
418   return Check(ref.proc().GetName(), true, common::GetPtrFromOptional(chars));
419 }
420 
421 // The target can be unlimited polymorphic if the pointer is, or if it is
422 // a non-extensible derived type.
423 bool PointerAssignmentChecker::LhsOkForUnlimitedPoly() const {
424   const auto &type{lhsType_->type()};
425   if (type.category() != TypeCategory::Derived || type.IsAssumedType()) {
426     return false;
427   } else if (type.IsUnlimitedPolymorphic()) {
428     return true;
429   } else {
430     return !IsExtensibleType(&type.GetDerivedTypeSpec());
431   }
432 }
433 
434 template <typename... A>
435 parser::Message *PointerAssignmentChecker::Say(A &&...x) {
436   auto *msg{foldingContext_.messages().Say(std::forward<A>(x)...)};
437   if (msg) {
438     if (lhs_) {
439       return evaluate::AttachDeclaration(msg, *lhs_);
440     }
441     if (!source_.empty()) {
442       msg->Attach(source_, "Declaration of %s"_en_US, description_);
443     }
444   }
445   return msg;
446 }
447 
448 // Verify that any bounds on the LHS of a pointer assignment are valid.
449 // Return true if it is a bound-remapping so we can perform further checks.
450 static bool CheckPointerBounds(
451     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
452   auto &messages{context.messages()};
453   const SomeExpr &lhs{assignment.lhs};
454   const SomeExpr &rhs{assignment.rhs};
455   bool isBoundsRemapping{false};
456   std::size_t numBounds{common::visit(
457       common::visitors{
458           [&](const evaluate::Assignment::BoundsSpec &bounds) {
459             return bounds.size();
460           },
461           [&](const evaluate::Assignment::BoundsRemapping &bounds) {
462             isBoundsRemapping = true;
463             evaluate::ExtentExpr lhsSizeExpr{1};
464             for (const auto &bound : bounds) {
465               lhsSizeExpr = std::move(lhsSizeExpr) *
466                   (common::Clone(bound.second) - common::Clone(bound.first) +
467                       evaluate::ExtentExpr{1});
468             }
469             if (std::optional<std::int64_t> lhsSize{evaluate::ToInt64(
470                     evaluate::Fold(context, std::move(lhsSizeExpr)))}) {
471               if (auto shape{evaluate::GetShape(context, rhs)}) {
472                 if (std::optional<std::int64_t> rhsSize{
473                         evaluate::ToInt64(evaluate::Fold(
474                             context, evaluate::GetSize(std::move(*shape))))}) {
475                   if (*lhsSize > *rhsSize) {
476                     messages.Say(
477                         "Pointer bounds require %d elements but target has"
478                         " only %d"_err_en_US,
479                         *lhsSize, *rhsSize); // 10.2.2.3(9)
480                   }
481                 }
482               }
483             }
484             return bounds.size();
485           },
486           [](const auto &) -> std::size_t {
487             DIE("not valid for pointer assignment");
488           },
489       },
490       assignment.u)};
491   if (numBounds > 0) {
492     if (lhs.Rank() != static_cast<int>(numBounds)) {
493       messages.Say("Pointer '%s' has rank %d but the number of bounds specified"
494                    " is %d"_err_en_US,
495           lhs.AsFortran(), lhs.Rank(), numBounds); // C1018
496     }
497   }
498   if (isBoundsRemapping && rhs.Rank() != 1 &&
499       !evaluate::IsSimplyContiguous(rhs, context)) {
500     messages.Say("Pointer bounds remapping target must have rank 1 or be"
501                  " simply contiguous"_err_en_US); // 10.2.2.3(9)
502   }
503   return isBoundsRemapping;
504 }
505 
506 bool CheckPointerAssignment(SemanticsContext &context,
507     const evaluate::Assignment &assignment, const Scope &scope) {
508   return CheckPointerAssignment(context, assignment.lhs, assignment.rhs, scope,
509       CheckPointerBounds(context.foldingContext(), assignment),
510       /*isAssumedRank=*/false);
511 }
512 
513 bool CheckPointerAssignment(SemanticsContext &context, const SomeExpr &lhs,
514     const SomeExpr &rhs, const Scope &scope, bool isBoundsRemapping,
515     bool isAssumedRank) {
516   const Symbol *pointer{GetLastSymbol(lhs)};
517   if (!pointer) {
518     return false; // error was reported
519   }
520   PointerAssignmentChecker checker{context, scope, *pointer};
521   checker.set_isBoundsRemapping(isBoundsRemapping);
522   checker.set_isAssumedRank(isAssumedRank);
523   bool lhsOk{checker.CheckLeftHandSide(lhs)};
524   bool rhsOk{checker.Check(rhs)};
525   return lhsOk && rhsOk; // don't short-circuit
526 }
527 
528 bool CheckStructConstructorPointerComponent(SemanticsContext &context,
529     const Symbol &lhs, const SomeExpr &rhs, const Scope &scope) {
530   return PointerAssignmentChecker{context, scope, lhs}
531       .set_pointerComponentLHS(&lhs)
532       .Check(rhs);
533 }
534 
535 bool CheckPointerAssignment(SemanticsContext &context, parser::CharBlock source,
536     const std::string &description, const DummyDataObject &lhs,
537     const SomeExpr &rhs, const Scope &scope, bool isAssumedRank) {
538   return PointerAssignmentChecker{context, scope, source, description}
539       .set_lhsType(common::Clone(lhs.type))
540       .set_isContiguous(lhs.attrs.test(DummyDataObject::Attr::Contiguous))
541       .set_isVolatile(lhs.attrs.test(DummyDataObject::Attr::Volatile))
542       .set_isAssumedRank(isAssumedRank)
543       .Check(rhs);
544 }
545 
546 bool CheckInitialDataPointerTarget(SemanticsContext &context,
547     const SomeExpr &pointer, const SomeExpr &init, const Scope &scope) {
548   return evaluate::IsInitialDataTarget(
549              init, &context.foldingContext().messages()) &&
550       CheckPointerAssignment(context, pointer, init, scope,
551           /*isBoundsRemapping=*/false,
552           /*isAssumedRank=*/false);
553 }
554 
555 } // namespace Fortran::semantics
556