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