xref: /llvm-project/flang/lib/Semantics/pointer-assignment.cpp (revision d5dd7d230ecaf8242f4429a5e3653e16bf55bcd6)
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_, buf);
357     } else {
358       Say(std::get<MessageFormattedText>(*msg));
359     }
360     return false;
361   } else {
362     context_.NoteDefinedSymbol(*base);
363     return true;
364   }
365 }
366 
367 // Common handling for procedure pointer right-hand sides
368 bool PointerAssignmentChecker::Check(parser::CharBlock rhsName, bool isCall,
369     const Procedure *rhsProcedure,
370     const evaluate::SpecificIntrinsic *specific) {
371   std::string whyNot;
372   std::optional<std::string> warning;
373   CharacterizeProcedure();
374   if (std::optional<MessageFixedText> msg{evaluate::CheckProcCompatibility(
375           isCall, procedure_, rhsProcedure, specific, whyNot, warning,
376           /*ignoreImplicitVsExplicit=*/isCall)}) {
377     Say(std::move(*msg), description_, rhsName, whyNot);
378     return false;
379   }
380   if (context_.ShouldWarn(common::UsageWarning::ProcDummyArgShapes) &&
381       warning) {
382     Say("%s and %s may not be completely compatible procedures: %s"_warn_en_US,
383         description_, rhsName, std::move(*warning));
384   }
385   return true;
386 }
387 
388 bool PointerAssignmentChecker::Check(const evaluate::ProcedureDesignator &d) {
389   const Symbol *symbol{d.GetSymbol()};
390   if (symbol) {
391     if (const auto *subp{
392             symbol->GetUltimate().detailsIf<SubprogramDetails>()}) {
393       if (subp->stmtFunction()) {
394         evaluate::SayWithDeclaration(foldingContext_.messages(), *symbol,
395             "Statement function '%s' may not be the target of a pointer assignment"_err_en_US,
396             symbol->name());
397         return false;
398       }
399     } else if (symbol->has<ProcBindingDetails>() &&
400         context_.ShouldWarn(common::LanguageFeature::BindingAsProcedure)) {
401       evaluate::SayWithDeclaration(foldingContext_.messages(), *symbol,
402           "Procedure binding '%s' used as target of a pointer assignment"_port_en_US,
403           symbol->name());
404     }
405   }
406   if (auto chars{
407           Procedure::Characterize(d, foldingContext_, /*emitError=*/true)}) {
408     // Disregard the elemental attribute of RHS intrinsics.
409     if (symbol && symbol->GetUltimate().attrs().test(Attr::INTRINSIC)) {
410       chars->attrs.reset(Procedure::Attr::Elemental);
411     }
412     return Check(d.GetName(), false, &*chars, d.GetSpecificIntrinsic());
413   } else {
414     return Check(d.GetName(), false);
415   }
416 }
417 
418 bool PointerAssignmentChecker::Check(const evaluate::ProcedureRef &ref) {
419   auto chars{Procedure::Characterize(ref, foldingContext_)};
420   return Check(ref.proc().GetName(), true, common::GetPtrFromOptional(chars));
421 }
422 
423 // The target can be unlimited polymorphic if the pointer is, or if it is
424 // a non-extensible derived type.
425 bool PointerAssignmentChecker::LhsOkForUnlimitedPoly() const {
426   const auto &type{lhsType_->type()};
427   if (type.category() != TypeCategory::Derived || type.IsAssumedType()) {
428     return false;
429   } else if (type.IsUnlimitedPolymorphic()) {
430     return true;
431   } else {
432     return !IsExtensibleType(&type.GetDerivedTypeSpec());
433   }
434 }
435 
436 template <typename... A>
437 parser::Message *PointerAssignmentChecker::Say(A &&...x) {
438   auto *msg{foldingContext_.messages().Say(std::forward<A>(x)...)};
439   if (msg) {
440     if (lhs_) {
441       return evaluate::AttachDeclaration(msg, *lhs_);
442     }
443     if (!source_.empty()) {
444       msg->Attach(source_, "Declaration of %s"_en_US, description_);
445     }
446   }
447   return msg;
448 }
449 
450 // Verify that any bounds on the LHS of a pointer assignment are valid.
451 // Return true if it is a bound-remapping so we can perform further checks.
452 static bool CheckPointerBounds(
453     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
454   auto &messages{context.messages()};
455   const SomeExpr &lhs{assignment.lhs};
456   const SomeExpr &rhs{assignment.rhs};
457   bool isBoundsRemapping{false};
458   std::size_t numBounds{common::visit(
459       common::visitors{
460           [&](const evaluate::Assignment::BoundsSpec &bounds) {
461             return bounds.size();
462           },
463           [&](const evaluate::Assignment::BoundsRemapping &bounds) {
464             isBoundsRemapping = true;
465             evaluate::ExtentExpr lhsSizeExpr{1};
466             for (const auto &bound : bounds) {
467               lhsSizeExpr = std::move(lhsSizeExpr) *
468                   (common::Clone(bound.second) - common::Clone(bound.first) +
469                       evaluate::ExtentExpr{1});
470             }
471             if (std::optional<std::int64_t> lhsSize{evaluate::ToInt64(
472                     evaluate::Fold(context, std::move(lhsSizeExpr)))}) {
473               if (auto shape{evaluate::GetShape(context, rhs)}) {
474                 if (std::optional<std::int64_t> rhsSize{
475                         evaluate::ToInt64(evaluate::Fold(
476                             context, evaluate::GetSize(std::move(*shape))))}) {
477                   if (*lhsSize > *rhsSize) {
478                     messages.Say(
479                         "Pointer bounds require %d elements but target has"
480                         " only %d"_err_en_US,
481                         *lhsSize, *rhsSize); // 10.2.2.3(9)
482                   }
483                 }
484               }
485             }
486             return bounds.size();
487           },
488           [](const auto &) -> std::size_t {
489             DIE("not valid for pointer assignment");
490           },
491       },
492       assignment.u)};
493   if (numBounds > 0) {
494     if (lhs.Rank() != static_cast<int>(numBounds)) {
495       messages.Say("Pointer '%s' has rank %d but the number of bounds specified"
496                    " is %d"_err_en_US,
497           lhs.AsFortran(), lhs.Rank(), numBounds); // C1018
498     }
499   }
500   if (isBoundsRemapping && rhs.Rank() != 1 &&
501       !evaluate::IsSimplyContiguous(rhs, context)) {
502     messages.Say("Pointer bounds remapping target must have rank 1 or be"
503                  " simply contiguous"_err_en_US); // 10.2.2.3(9)
504   }
505   return isBoundsRemapping;
506 }
507 
508 bool CheckPointerAssignment(SemanticsContext &context,
509     const evaluate::Assignment &assignment, const Scope &scope) {
510   return CheckPointerAssignment(context, assignment.lhs, assignment.rhs, scope,
511       CheckPointerBounds(context.foldingContext(), assignment),
512       /*isAssumedRank=*/false);
513 }
514 
515 bool CheckPointerAssignment(SemanticsContext &context, const SomeExpr &lhs,
516     const SomeExpr &rhs, const Scope &scope, bool isBoundsRemapping,
517     bool isAssumedRank) {
518   const Symbol *pointer{GetLastSymbol(lhs)};
519   if (!pointer) {
520     return false; // error was reported
521   }
522   PointerAssignmentChecker checker{context, scope, *pointer};
523   checker.set_isBoundsRemapping(isBoundsRemapping);
524   checker.set_isAssumedRank(isAssumedRank);
525   bool lhsOk{checker.CheckLeftHandSide(lhs)};
526   bool rhsOk{checker.Check(rhs)};
527   return lhsOk && rhsOk; // don't short-circuit
528 }
529 
530 bool CheckStructConstructorPointerComponent(SemanticsContext &context,
531     const Symbol &lhs, const SomeExpr &rhs, const Scope &scope) {
532   return PointerAssignmentChecker{context, scope, lhs}
533       .set_pointerComponentLHS(&lhs)
534       .Check(rhs);
535 }
536 
537 bool CheckPointerAssignment(SemanticsContext &context, parser::CharBlock source,
538     const std::string &description, const DummyDataObject &lhs,
539     const SomeExpr &rhs, const Scope &scope, bool isAssumedRank) {
540   return PointerAssignmentChecker{context, scope, source, description}
541       .set_lhsType(common::Clone(lhs.type))
542       .set_isContiguous(lhs.attrs.test(DummyDataObject::Attr::Contiguous))
543       .set_isVolatile(lhs.attrs.test(DummyDataObject::Attr::Volatile))
544       .set_isAssumedRank(isAssumedRank)
545       .Check(rhs);
546 }
547 
548 bool CheckInitialDataPointerTarget(SemanticsContext &context,
549     const SomeExpr &pointer, const SomeExpr &init, const Scope &scope) {
550   return evaluate::IsInitialDataTarget(
551              init, &context.foldingContext().messages()) &&
552       CheckPointerAssignment(context, pointer, init, scope,
553           /*isBoundsRemapping=*/false,
554           /*isAssumedRank=*/false);
555 }
556 
557 } // namespace Fortran::semantics
558