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